Inspect · Source & workspace
Requested workspace inspection and file and log inspection related to source & workspace.
2 calls · #0001–#0002
echo <val>ls -l -a <path> <n> > <path>head -n <n>ls -l -a <path>echo <flag>ls <path> <n> > <path>GLM-5.3 · RL
Qwen3-1.7B online PPO 2dev · Joint Optimization
01 / PROCESS MAP
Each row shows one agent’s tool events in its own recorded order. Colors show broad activities; bar widths do not represent duration.
Main agentGLM-5.3 · 79 visible calls
02 / EVENT SEQUENCE
Requests are grouped by agent, activity and topic. Delegations open into child branches. Summaries describe visible requests; tool errors and missing responses are flagged. A recorded response does not establish command success or a performance improvement.
Scroll within this panel to view all events. Command sketches retain familiar programs and options. Values become <val> or <n>; paths, addresses and script bodies are hidden as <path>, <url> and <script>.
Requested workspace inspection and file and log inspection related to source & workspace.
2 calls · #0001–#0002
echo <val>ls -l -a <path> <n> > <path>head -n <n>ls -l -a <path>echo <flag>ls <path> <n> > <path>Requested file and log inspection related to task requirements.
2 calls · #0003–#0004
Read <path>Requested workspace inspection and file and log inspection related to source & workspace.
3 calls · #0005–#0007
cd <path>find <path> -type <val>head -n <n>echo <flag>du <flag> <args>Read <path>Requested file and log inspection related to benchmark & validation setup.
3 calls · #0008–#0010
Read <path>Requested file and log inspection, environment setup or inspection and source searches related to source & workspace.
4 calls · #0011–#0014
Read <path>envgrep -E <val>sed <path>echo <flag>echo <val>Requested runtime inspection, file and log inspection and script or workload execution related to device memory.
1 call · #0015–#0015
npu-smi info <n> >& <path>head -n <n>echo <val>which <val> <val>python3 -VRequested file and log inspection and script or workload execution related to source & workspace.
1 call · #0016–#0016
cat <val>python3 -m <module>head -n <n>Requested workspace inspection and file and log inspection related to task requirements.
1 call · #0017–#0017
ls <path>echo <flag>ls <path> <path>cat <path>Requested workspace inspection, file and log inspection and script or workload execution related to source & workspace.
2 calls · #0018–#0019
ls <path> <n> >& <path>headecho <flag>ls <path>head -n <n>python3 -c <script>python3 -c <script> <n> >& <path>tail -n <n>Requested file and log inspection related to task requirements.
1 call · #0020–#0020
cd <path><command> <args>head -c <n> <val>echoRequested script or workload execution, dependency and build commands and source searches related to dependencies & build setup.
1 call · #0021–#0021
date -uecho <val>python3 -c <script>pip list <n> > <path>grep -i -E <val>Requested file and log inspection and script or workload execution related to source & workspace.
1 call · #0022–#0022
cat <path>echo <val>echohead -c <n> <path>python3 -c <script>Requested workspace file updates, file and log inspection and environment setup or inspection related to attention kernels.
2 calls · #0023–#0024
mkdir -p <path>cat > <path> <script>cd <path>env <vars> timeout <n> <path> -B <path> <n> >& <path>grep -v <val>tail -n <n>grep -v -i -E <val>Requested code edits, environment setup or inspection and source searches related to benchmark & validation setup.
1 call · #0025–#0025
cd <path>sed -i <path> <path>env <vars> timeout <n> <path> -B <path> <n> >& <path>grep -v -i -E <val>tail -n <n>Requested file and log inspection, source searches and workspace inspection related to reward & policy updates.
10 calls · #0026–#0035
cd <path>wc -l <path>grep -n <val> <path>head -n <n>sed -n <val> <path>grep -n <val> -A <n> <path>grep -r -n <val> <path>echo <val>headsed -n <val> <path> <n> > <path>ls <path>grep -r -n <val> -A <n> <path>grep -r -l -n <val> <path>echo <flag>grep -i <val>grep -n <val> <flag> <args>grep -n <val>Requested file and log inspection and workspace inspection related to source & workspace.
1 call · #0036–#0036
echo <val>df -h <val> <path> <n> >& <path>headls -l -a <val> <n> > <path>Requested code edits related to source & workspace.
4 calls · #0037–#0040
Write <path>Requested file and log inspection related to reward & policy updates.
1 call · #0041–#0041
cat >> <path> <script>echo <val>wc -l <path>Requested file and log inspection related to checkpoints & weight state.
1 call · #0042–#0042
cat >> <path> <script>echo <val>Requested file and log inspection related to reward & policy updates.
1 call · #0043–#0043
cat >> <path> <script>echo <val>Requested file and log inspection and script or workload execution related to checkpoints & weight state.
1 call · #0044–#0044
cat >> <path> <script>python3 -c <script>echo <val>wc -l <path>Requested code edits related to source & workspace.
2 calls · #0045–#0046
Edit <path>Requested source searches, file and log inspection and script or workload execution related to checkpoints & weight state.
2 calls · #0047–#0048
cd <path>grep -n <val> -A <n> <path>head -n <n>python3 - <script>grep -n <val> <path>headRequested code edits related to source & workspace.
1 call · #0049–#0049
Write <path>Requested script or workload execution, source searches and file and log inspection related to benchmark & validation setup.
1 call · #0050–#0050
cd <path>timeout <n> <path> -B <path> <val> <n> >& <path>grep -v <val>tail -n <n>Requested file and log inspection related to source & workspace.
1 call · #0051–#0051
tail -n <n> <path>Requested code edits related to source & workspace.
1 call · #0052–#0052
Edit <path>Requested script or workload execution, source searches and file and log inspection related to benchmark & validation setup.
1 call · #0053–#0053
cd <path>timeout <n> <path> -B <path> <val> <n> >& <path>grep -v <val>tail -n <n>Requested file and log inspection, environment setup or inspection and source searches related to attention kernels.
1 call · #0054–#0054
cat > <path> <script>cd <path>env <vars> timeout <n> <path> -B <path> <n> >& <path>grep -v <val>tail -n <n>Requested code edits related to source & workspace.
1 call · #0055–#0055
Edit <path>Requested script or workload execution and source searches related to reward & policy updates.
1 call · #0056–#0056
cd <path>python3 - <script>grep -n <val> <path>Requested code edits related to source & workspace.
1 call · #0057–#0057
Edit <path>Requested script or workload execution, source searches and file and log inspection related to rollout generation.
1 call · #0058–#0058
cd <path>python3 - <script>timeout <n> <path> -B <path> <val> <n> >& <path>grep -v <val>tail -n <n>Requested script or workload execution, source searches and file and log inspection related to reward & policy updates.
1 call · #0059–#0059
cd <path>python3 - <script>grep -n <val> <path>headRequested script or workload execution, source searches and file and log inspection related to reward & policy updates.
2 calls · #0060–#0061
cd <path>timeout <n> <path> -B <path> <val> <n> >& <path>grep -v <val>tail -n <n>echo <val>grep -E <val> <path>python3 - <script>Requested file and log inspection related to source & workspace.
1 call · #0062–#0062
Read <path>Requested file and log inspection, environment setup or inspection and source searches related to benchmark & validation setup.
1 call · #0063–#0063
cat > <path> <script>cd <path>env <vars> timeout <n> <path> -B <path> <n> >& <path>grep -v <val>tail -n <n>Requested file and log inspection, environment setup or inspection and source searches related to attention kernels.
1 call · #0064–#0064
cat >> <path> <script>cd <path>env <vars> timeout <n> <path> -B <path> <n> >& <path>grep -v <val>tail -n <n>Requested script or workload execution, source searches and file and log inspection related to reward & policy updates.
1 call · #0065–#0065
cd <path>python3 - <script>timeout <n> <path> -B <path> <val> <n> >& <path>grep -v <val>tail -n <n>Requested script or workload execution, source searches and file and log inspection related to benchmark & validation setup.
1 call · #0066–#0066
cd <path>python3 - <script>timeout <n> <path> -B <path> <val> <n> >& <path>grep -v <val>tail -n <n>Requested file and log inspection and script or workload execution related to source & workspace.
1 call · #0067–#0067
cat > <path> <script>cd <path>timeout <n> <path> -B -I <path> <n> >& <path>tail -n <n>Requested file and log inspection, environment setup or inspection and source searches related to attention kernels.
1 call · #0068–#0068
cat > <path> <script>cd <path>env <vars> timeout <n> <path> -B <path> <n> >& <path>grep -E <val>Requested script or workload execution and source searches related to precision & numerical checks.
1 call · #0069–#0069
cd <path>python3 - <script>timeout <n> <path> -B -I <path> <n> >& <path>grep -E <val>Requested script or workload execution, source searches and file and log inspection related to reward & policy updates.
2 calls · #0070–#0071
cd <path>python3 - <script>timeout <n> <path> -B <path> <val> <n> >& <path>grep -v <val>tail -n <n>python3 -c <script>Requested file and log inspection related to reward & policy updates.
1 call · #0072–#0072
cd <path>sed -n <path> <path>Requested source searches and file and log inspection related to source & workspace.
1 call · #0073–#0073
grep -c <val> <path> <val> <val> <path>tail -n <n>Requested script or workload execution, source searches and file and log inspection related to reward & policy updates.
1 call · #0074–#0074
cd <path>python3 - <script>timeout <n> <path> -B <path> <val> <n> >& <path>grep -v <val>tail -n <n>Requested file and log inspection, source searches and runtime inspection related to device memory.
1 call · #0075–#0075
tail -n <n> <path>grep -v <val>echo <val>npu-smi info <n> > <path>grep -E <val>head -n <n>Requested script or workload execution related to reward & policy updates.
1 call · #0076–#0076
cd <path>python3 - <script>Requested script or workload execution, source searches and file and log inspection related to benchmark & validation setup.
1 call · #0077–#0077
cd <path>timeout <n> <path> -B <path> <val> <n> >& <path>grep -v <val>tail -n <n>Requested process termination, execution waits and runtime inspection related to device memory.
2 calls · #0078–#0079
pkill -f <val> <n> > <path>sleep <n>ps <flag> <args>grep -E <path>grep -v <val>head -n <n>echo <flag>npu-smi info <n> > <path>tail -n <n>git status <flag>headgrep -E <val>echo <val>cd <path>03 / CANDIDATE ARTIFACT
Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
Base commit: 0b2151ec61de5d99e0811b01c09e43a99a23e69d
@@ -0,0 +1,14 @@+# Copyright 2024 Bytedance Ltd. and/or its affiliates.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""Framework-owned runtimes that are driven directly by an external host."""@@ -0,0 +1,1346 @@+"""Framework-owned online PPO runtime.++This module implements the host interaction contract described in+``config/framework-runtime-contract.md``. The runtime owns its whole execution+plan: a single supervisor process drives two Ascend devices directly, with no+external orchestration layer, no separate rollout engine process and no+offload/resident-copy traffic between phases.++Layout+------+* device 0 - trainable actor, which is also the rollout policy (bf16 weights+ with fp32 master parameters).+* device 1 - frozen reference policy, trainable critic (bf16 + fp32 master)+ and the frozen reward model.++Because the rollout policy *is* the live actor module, rollout weights are+fresh after every actor update by construction: no weight transport step runs+between the actor update and the next rollout. Probes answer for the actor and+for the rollout policy from the same evaluation pass over those shared weights,+and the incremental decode path is additionally exercised for diagnostics.+"""++from __future__ import annotations++import argparse+import json+import math+import os+import socket+import sys+import time+import traceback+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Callable, Iterable, Sequence++ENV_VERBOSE = "VERL_ONLINE_PPO_VERBOSE"+ACTOR_DEVICE_INDEX = 0+AUX_DEVICE_INDEX = 1+LOGITS_TO_KEEP = 1+++def _log(message: str) -> None:+ sys.stderr.write(f"[online-ppo {time.time():.3f}] {message}\n")+ sys.stderr.flush()+++def _debug(message: str) -> None:+ if os.environ.get(ENV_VERBOSE):+ _log(message)+++class RuntimeFailure(RuntimeError):+ """Raised for contract or execution failures inside the runtime."""+++# ---------------------------------------------------------------------------+# control socket+# ---------------------------------------------------------------------------+class ControlChannel:+ def __init__(self, path: str, timeout: float) -> None:+ self._path = path+ self._timeout = timeout+ self._socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ self._socket.settimeout(timeout)++ def connect(self) -> None:+ deadline = time.monotonic() + min(self._timeout, 900.0)+ while True:+ try:+ self._socket.connect(self._path)+ return+ except (FileNotFoundError, ConnectionRefusedError, OSError):+ if time.monotonic() > deadline:+ raise+ time.sleep(0.05)++ def send(self, payload: dict[str, Any]) -> None:+ blob = json.dumps(payload, allow_nan=False, separators=(",", ":")).encode("utf-8") + b"\n"+ self._socket.sendall(blob)++ def receive(self) -> dict[str, Any]:+ raw = bytearray()+ while not raw.endswith(b"\n"):+ chunk = self._socket.recv(65536)+ if not chunk:+ raise RuntimeFailure("control connection closed by host")+ raw.extend(chunk)+ if len(raw) > 8 * 1024 * 1024:+ raise RuntimeFailure("control message too large")+ value = json.loads(raw)+ if not isinstance(value, dict) or not isinstance(value.get("type"), str):+ raise RuntimeFailure("control message is invalid")+ return value++ def close(self) -> None:+ try:+ self._socket.close()+ except OSError:+ pass+++# ---------------------------------------------------------------------------+# torch helpers+# ---------------------------------------------------------------------------+import torch # noqa: E402 (kept after the stdlib scaffolding on purpose)+from torch import nn # noqa: E402+from transformers import AutoModelForCausalLM, AutoTokenizer, DynamicCache # noqa: E402+from transformers import Qwen3Model as _Qwen3Backbone # noqa: E402+from safetensors.torch import load_file as _load_safetensors # noqa: E402+++def _device(index: int) -> torch.device:+ return torch.device(f"npu:{index}")+++def _sync(device: torch.device) -> None:+ if device.type == "npu":+ torch.npu.synchronize(device)+++def _disable_cached_inference(module: nn.Module) -> None:+ """Full-sequence forwards must not reuse an implicitly stored KV cache."""+ if hasattr(module, "config"):+ module.config.use_cache = False+ for child in module.children():+ _disable_cached_inference(child)+++def _no_grad(function: Callable[..., Any]) -> Callable[..., Any]:+ def wrapped(*args: Any, **kwargs: Any) -> Any:+ with torch.no_grad():+ return function(*args, **kwargs)++ return wrapped+++def _masked_whiten(values: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:+ """verl's ``masked_whiten`` (mean shifted, population variance)."""+ count = mask.sum()+ mean = (values * mask).sum() / count+ var = (((values - mean) ** 2) * mask).sum() / count+ rms = torch.sqrt(var + 1e-8)+ return (values - mean) * mask / rms+++def _masked_mean(values: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:+ return (values * mask).sum() / torch.clamp(mask.sum(), min=1.0)+++def _masked_sum(values: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:+ return (values * mask).sum()+++def _total_norm(grads: Iterable[torch.Tensor | None]) -> float:+ squares: list[torch.Tensor] = []+ for grad in grads:+ if grad is None:+ continue+ squares.append(grad.detach().float().pow(2).sum())+ if not squares:+ return 0.0+ return float(torch.sqrt(torch.stack(squares).sum()).item())+++def _chunks(items: list[Any], size: int) -> Iterable[list[Any]]:+ for start in range(0, len(items), max(1, size)):+ yield items[start : start + max(1, size)]+++# ---------------------------------------------------------------------------+# mixed precision training+# ---------------------------------------------------------------------------+class MixedPrecisionOptimizer:+ """bf16 compute parameters with fp32 master weights and AdamW state."""++ def __init__(self, module: nn.Module, lr: float, weight_decay: float = 0.0) -> None:+ self._names: list[str] = []+ self._params: list[nn.Parameter] = []+ masters: list[torch.Tensor] = []+ for name, param in module.named_parameters():+ if not param.requires_grad:+ continue+ master = param.detach().float().clone()+ self._names.append(name)+ self._params.append(param)+ masters.append(master)+ self._masters = masters+ self.optimizer = torch.optim.AdamW(+ masters, lr=lr, betas=(0.9, 0.999), eps=1e-8, weight_decay=weight_decay+ )+ self.lr = float(lr)++ def parameters(self) -> list[nn.Parameter]:+ return list(self._params)++ def masters(self) -> dict[str, torch.Tensor]:+ return dict(zip(self._names, self._masters))++ def size(self) -> int:+ return len(self._params)++ def zero_grad(self) -> None:+ self.optimizer.zero_grad(set_to_none=True)+ for param in self._params:+ param.grad = None++ def step(self) -> float:+ grads = []+ for param, master in zip(self._params, self._masters):+ if param.grad is None:+ master.grad = None+ grads.append(None)+ else:+ master.grad = param.grad.detach().float()+ grads.append(master.grad)+ norm = _total_norm(grads)+ if norm == 0.0:+ return 0.0+ self.optimizer.step()+ with torch.no_grad():+ for param, master in zip(self._params, self._masters):+ param.copy_(master)+ return norm++ def state_payload(self) -> dict[str, Any]:+ state = self.optimizer.state_dict()+ for entry in state["state"].values():+ for key, value in list(entry.items()):+ if torch.is_tensor(value):+ entry[key] = value.detach().to("cpu", non_blocking=False)+ return {+ "master": {name: master.detach().to("cpu") for name, master in zip(self._names, self._masters)},+ "optimizer": state,+ }++ def load_state_payload(self, payload: dict[str, Any], device: torch.device) -> None:+ master = payload["master"]+ for name, tensor in zip(self._names, self._masters):+ if name in master:+ tensor.copy_(master[name].to(device))+ state = payload["optimizer"]+ for index, entry in state["state"].items():+ for key, value in list(entry.items()):+ if torch.is_tensor(value):+ entry[key] = value.to(device)+ self.optimizer.load_state_dict(state)+ with torch.no_grad():+ for param, tensor in zip(self._params, self._masters):+ param.copy_(tensor)+++# ---------------------------------------------------------------------------+# heads+# ---------------------------------------------------------------------------+class TokenValueHead(nn.Module):+ """Critic: transformer backbone plus a per-token scalar value head."""++ def __init__(self, backbone: nn.Module, hidden_size: int) -> None:+ super().__init__()+ self.backbone = backbone+ self.v_head = nn.Linear(hidden_size, 1, bias=False)++ def forward(+ self, input_ids: torch.Tensor, attention_mask: torch.Tensor, use_cache: bool = False+ ) -> torch.Tensor:+ hidden = self.backbone(+ input_ids=input_ids, attention_mask=attention_mask, use_cache=use_cache+ ).last_hidden_state+ return self.v_head(hidden).squeeze(-1)+++class SequenceScoreHead(nn.Module):+ """Reward model: frozen backbone plus the supplied two-class score head."""++ def __init__(self, backbone: nn.Module, score_weight: torch.Tensor) -> None:+ super().__init__()+ self.backbone = backbone+ self.score = nn.Linear(score_weight.shape[-1], score_weight.shape[0], bias=False)+ with torch.no_grad():+ self.score.weight.copy_(score_weight)++ def forward(+ self, input_ids: torch.Tensor, attention_mask: torch.Tensor, use_cache: bool = False+ ) -> torch.Tensor:+ hidden = self.backbone(+ input_ids=input_ids, attention_mask=attention_mask, use_cache=use_cache+ ).last_hidden_state+ logits = self.score(hidden)+ return logits[..., 1] - logits[..., 0]+++class PaddedBatch:+ """Right padded batch of token sequences."""++ def __init__(self, pad_token_id: int) -> None:+ self.pad_token_id = int(pad_token_id)++ def build(+ self, sequences: Sequence[Sequence[int]], device: torch.device+ ) -> tuple[torch.Tensor, torch.Tensor]:+ lengths = [len(item) for item in sequences]+ width = max(lengths)+ input_ids = torch.full(+ (len(sequences), width), self.pad_token_id, dtype=torch.long, device=device+ )+ attention = torch.zeros((len(sequences), width), dtype=torch.long, device=device)+ for row, tokens in enumerate(sequences):+ input_ids[row, : lengths[row]] = torch.as_tensor(+ list(tokens), dtype=torch.long, device=device+ )+ attention[row, : lengths[row]] = 1+ return input_ids, attention+++# ---------------------------------------------------------------------------+# rollout+# ---------------------------------------------------------------------------+@dataclass+class RolloutResult:+ response_ids: list[list[int]]+ old_log_probs: torch.Tensor # (B, T)+ response_mask: torch.Tensor # (B, T)+++class Rollout:+ """Incremental decoding directly against the live actor weights."""++ def __init__(self, model: nn.Module, pad_token_id: int, eos_token_ids: Sequence[int]) -> None:+ self.model = model+ self.pad_token_id = int(pad_token_id)+ self.eos_token_ids = [int(value) for value in eos_token_ids]++ @torch.no_grad()+ def generate(+ self,+ prompt_ids: Sequence[Sequence[int]],+ max_new_tokens: int,+ temperature: float,+ top_p: float,+ top_k: int,+ generator: torch.Generator,+ ) -> RolloutResult:+ model = self.model+ device = next(model.parameters()).device+ batch = len(prompt_ids)+ lengths = [len(item) for item in prompt_ids]+ width = max(lengths)+ input_ids = torch.full((batch, width), self.pad_token_id, dtype=torch.long, device=device)+ attention = torch.zeros((batch, width), dtype=torch.long, device=device)+ for row, tokens in enumerate(prompt_ids):+ input_ids[row, width - len(tokens) :] = torch.as_tensor(+ list(tokens), dtype=torch.long, device=device+ )+ attention[row, width - len(tokens) :] = 1+ positions = (attention.cumsum(-1) - 1).clamp(min=0)+ cache = DynamicCache()+ output = model(+ input_ids=input_ids,+ attention_mask=attention,+ position_ids=positions,+ past_key_values=cache,+ use_cache=True,+ logits_to_keep=LOGITS_TO_KEEP,+ )+ logits = output.logits[:, -1].float()+ current_position = positions[:, -1:].clone()++ responses: list[list[int]] = [[] for _ in range(batch)]+ finished = torch.zeros(batch, dtype=torch.bool, device=device)+ log_prob_rows: list[torch.Tensor] = []+ mask_rows: list[torch.Tensor] = []+ for step in range(max_new_tokens):+ token_log_probs = torch.log_softmax(logits, dim=-1)+ tokens = self._sample(logits, temperature, top_p, top_k, generator, device)+ chosen = token_log_probs.gather(1, tokens.unsqueeze(1)).squeeze(1)+ eos = torch.zeros(batch, dtype=torch.bool, device=device)+ for value in self.eos_token_ids:+ eos = eos | (tokens == value)+ active = ~finished+ log_prob_rows.append(chosen * active)+ mask_rows.append(active.float())+ tokens = torch.where(active, tokens, torch.full_like(tokens, self.pad_token_id))+ cpu_tokens = tokens.tolist()+ for row in range(batch):+ if bool(active[row]):+ responses[row].append(int(cpu_tokens[row]))+ finished = finished | eos+ if bool(finished.all()) or step + 1 >= max_new_tokens:+ break+ attention = torch.cat(+ [attention, torch.ones((batch, 1), dtype=torch.long, device=device)], dim=1+ )+ current_position = current_position + 1+ output = model(+ input_ids=tokens.unsqueeze(1),+ attention_mask=attention,+ position_ids=current_position,+ past_key_values=cache,+ use_cache=True,+ )+ logits = output.logits[:, -1].float()+ if log_prob_rows:+ old_log_probs = torch.stack(log_prob_rows, dim=1)+ response_mask = torch.stack(mask_rows, dim=1)+ else:+ old_log_probs = response_mask = torch.zeros((batch, 0), device=device)+ return RolloutResult(responses, old_log_probs, response_mask)++ @staticmethod+ def _sample(+ logits: torch.Tensor,+ temperature: float,+ top_p: float,+ top_k: int,+ generator: torch.Generator,+ device: torch.device,+ ) -> torch.Tensor:+ scores = logits / max(float(temperature), 1e-6)+ vocabulary = scores.shape[-1]+ keep = min(vocabulary, max(1, int(top_k)) if top_k and top_k > 0 else vocabulary)+ top_values, top_indices = torch.topk(scores, keep, dim=-1)+ sorted_values, sorted_order = torch.sort(top_values, descending=True, dim=-1)+ probabilities = torch.softmax(sorted_values, dim=-1)+ remove = probabilities.cumsum(-1) > float(top_p) if top_p < 1.0 else torch.zeros_like(+ probabilities, dtype=torch.bool+ )+ remove[..., 1:] = remove[..., :-1].clone()+ remove[..., 0] = False+ probabilities = probabilities.masked_fill(remove, 0.0)+ probabilities = probabilities / probabilities.sum(-1, keepdim=True).clamp(min=1e-9)+ choice = torch.multinomial(probabilities.detach().to("cpu"), 1, generator=generator).to(device)+ selected = sorted_order.gather(-1, choice)+ return top_indices.gather(-1, selected).squeeze(-1)++ @torch.no_grad()+ def continuation_log_probs(+ self, prompt_tokens: Sequence[int], continuation_tokens: Sequence[int]+ ) -> list[float]:+ """Log probability of each continuation token through the decode path."""+ model = self.model+ device = next(model.parameters()).device+ input_ids = torch.as_tensor([list(prompt_tokens)], dtype=torch.long, device=device)+ attention = torch.ones_like(input_ids)+ positions = (attention.cumsum(-1) - 1).clamp(min=0)+ cache = DynamicCache()+ output = model(+ input_ids=input_ids,+ attention_mask=attention,+ position_ids=positions,+ past_key_values=cache,+ use_cache=True,+ logits_to_keep=LOGITS_TO_KEEP,+ )+ logits = output.logits[:, -1].float()+ current_position = positions[:, -1:].clone()+ result: list[float] = []+ for index, token in enumerate(continuation_tokens):+ result.append(float(torch.log_softmax(logits[0], dim=-1)[int(token)].item()))+ if index + 1 >= len(continuation_tokens):+ break+ attention = torch.cat([attention, torch.ones_like(input_ids[:, :1])], dim=1)+ current_position = current_position + 1+ output = model(+ input_ids=torch.as_tensor([[int(token)]], dtype=torch.long, device=device),+ attention_mask=attention,+ position_ids=current_position,+ past_key_values=cache,+ use_cache=True,+ )+ logits = output.logits[:, -1].float()+ return result+++# ---------------------------------------------------------------------------+# sequence level helpers+# ---------------------------------------------------------------------------+def _pad_rows(rows: Sequence[torch.Tensor], device: torch.device) -> tuple[torch.Tensor, torch.Tensor]:+ width = max(int(row.shape[0]) for row in rows) if rows else 0+ mask = torch.zeros((len(rows), width), device=device)+ padded = torch.zeros((len(rows), width), device=device)+ for index, row in enumerate(rows):+ length = int(row.shape[0])+ padded[index, :length] = row+ mask[index, :length] = 1.0+ return padded, mask+++def _shifted_token_log_probs(logits: torch.Tensor, input_ids: torch.Tensor) -> torch.Tensor:+ """``result[:, p]`` is the log probability of ``input_ids[:, p + 1]``.++ The lm head at position ``p`` predicts the token that follows it, so the+ vocabulary gather has to run against the sequence shifted by one position.+ """+ log_probs = torch.log_softmax(logits.float(), dim=-1)+ targets = torch.zeros_like(input_ids)+ targets[:, :-1] = input_ids[:, 1:]+ return log_probs.gather(-1, targets.unsqueeze(-1)).squeeze(-1)+++def _position_index(+ prompt_lengths: Sequence[int],+ response_lengths: Sequence[int],+ device: torch.device,+ offset: int = -1,+) -> torch.Tensor:+ """Absolute sequence index used to read per-response-token tensors.++ Position ``prompt_length - 1 + i`` is the state that predicts response token+ ``i``; it is used for both the gathered token log probabilities and the+ critic values.+ """+ width = max(response_lengths) if response_lengths else 0+ positions = torch.zeros((len(response_lengths), width), dtype=torch.long, device=device)+ for row, (prompt_length, response_length) in enumerate(zip(prompt_lengths, response_lengths)):+ start = prompt_length + offset+ positions[row, :response_length] = torch.arange(+ start, start + response_length, device=device+ )+ return positions+++def response_log_probs(+ model: nn.Module,+ sequences: Sequence[Sequence[int]],+ prompt_lengths: Sequence[int],+ response_lengths: Sequence[int],+ batcher: PaddedBatch,+ device: torch.device,+ micro_batch: int,+) -> list[torch.Tensor]:+ """Per-row log probability of every response token under ``model``."""+ rows: list[torch.Tensor | None] = [None] * len(sequences)+ for start in range(0, len(sequences), micro_batch):+ indices = list(range(start, min(start + micro_batch, len(sequences))))+ chunk = [sequences[index] for index in indices]+ input_ids, attention = batcher.build(chunk, device)+ logits = model(input_ids=input_ids, attention_mask=attention, use_cache=False).logits+ token_log_probs = _shifted_token_log_probs(logits, input_ids)+ positions = _position_index(+ [prompt_lengths[index] for index in indices],+ [response_lengths[index] for index in indices],+ device,+ )+ gathered = token_log_probs.gather(1, positions)+ for slot, index in enumerate(indices):+ rows[index] = gathered[slot, : response_lengths[index]]+ return [row for row in rows if row is not None]+++def token_values(+ critic: nn.Module,+ sequences: Sequence[Sequence[int]],+ prompt_lengths: Sequence[int],+ response_lengths: Sequence[int],+ batcher: PaddedBatch,+ device: torch.device,+ micro_batch: int,+) -> list[torch.Tensor]:+ rows: list[torch.Tensor | None] = [None] * len(sequences)+ with torch.no_grad():+ for start in range(0, len(sequences), micro_batch):+ indices = list(range(start, min(start + micro_batch, len(sequences))))+ chunk = [sequences[index] for index in indices]+ input_ids, attention = batcher.build(chunk, device)+ values = critic(input_ids=input_ids, attention_mask=attention, use_cache=False)+ positions = _position_index(+ [prompt_lengths[index] for index in indices],+ [response_lengths[index] for index in indices],+ device,+ )+ gathered = values.gather(1, positions)+ for slot, index in enumerate(indices):+ rows[index] = gathered[slot, : response_lengths[index]]+ return [row for row in rows if row is not None]+++def sequence_scores(+ reward_model: nn.Module,+ sequences: Sequence[Sequence[int]],+ response_lengths: Sequence[int],+ batcher: PaddedBatch,+ device: torch.device,+ micro_batch: int,+) -> torch.Tensor:+ scores = torch.zeros(len(sequences), device=device)+ with torch.no_grad():+ for start in range(0, len(sequences), micro_batch):+ indices = list(range(start, min(start + micro_batch, len(sequences))))+ chunk = [sequences[index] for index in indices]+ input_ids, attention = batcher.build(chunk, device)+ logits = reward_model(input_ids=input_ids, attention_mask=attention, use_cache=False)+ for slot, index in enumerate(indices):+ last = prompt_of(sequences[index], response_lengths[index]) + response_lengths[index] - 1+ scores[index] = logits[slot, last]+ return scores+++def prompt_of(sequence: Sequence[int], response_length: int) -> int:+ return len(sequence) - response_length+++def gae_advantage(+ token_level_rewards: torch.Tensor,+ values: torch.Tensor,+ response_mask: torch.Tensor,+ gamma: float,+ lam: float,+) -> tuple[torch.Tensor, torch.Tensor]:+ with torch.no_grad():+ next_values = torch.zeros_like(values[:, 0])+ lastgaelam = torch.zeros_like(values[:, 0])+ reversed_advantages: list[torch.Tensor] = []+ length = token_level_rewards.shape[-1]+ for step in reversed(range(length)):+ delta = token_level_rewards[:, step] + gamma * next_values - values[:, step]+ candidate = delta + gamma * lam * lastgaelam+ mask = response_mask[:, step]+ next_values = values[:, step] * mask + (1.0 - mask) * next_values+ lastgaelam = candidate * mask + (1.0 - mask) * lastgaelam+ reversed_advantages.append(lastgaelam)+ advantages = torch.stack(reversed_advantages[::-1], dim=1)+ returns = advantages + values+ advantages = _masked_whiten(advantages, response_mask)+ return advantages, returns+++def policy_loss(+ old_log_probs: torch.Tensor,+ log_probs: torch.Tensor,+ advantages: torch.Tensor,+ response_mask: torch.Tensor,+ cliprange: float,+ clip_ratio_c: float,+ total_tokens: torch.Tensor,+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+ negative_approx_kl = torch.clamp(log_probs - old_log_probs, min=-20.0, max=20.0)+ ratio = torch.exp(negative_approx_kl)+ ppo_kl = _masked_mean(-negative_approx_kl, response_mask)+ pg_losses1 = -advantages * ratio+ pg_losses2 = -advantages * torch.clamp(ratio, 1.0 - cliprange, 1.0 + cliprange)+ clip_pg_losses1 = torch.maximum(pg_losses1, pg_losses2)+ pg_clipfrac = _masked_mean((pg_losses2 > pg_losses1).float(), response_mask)+ pg_losses3 = -advantages * clip_ratio_c+ clip_pg_losses2 = torch.minimum(pg_losses3, clip_pg_losses1)+ pg_losses = torch.where(advantages < 0, clip_pg_losses2, clip_pg_losses1)+ loss = _masked_sum(pg_losses, response_mask) / total_tokens+ return loss, pg_clipfrac, ppo_kl+++def value_loss(+ vpreds: torch.Tensor,+ returns: torch.Tensor,+ values: torch.Tensor,+ response_mask: torch.Tensor,+ cliprange_value: float,+ total_tokens: torch.Tensor,+) -> tuple[torch.Tensor, torch.Tensor]:+ vpredclipped = torch.clamp(vpreds, values - cliprange_value, values + cliprange_value)+ vf_losses1 = (vpreds - returns) ** 2+ vf_losses2 = (vpredclipped - returns) ** 2+ clipped = torch.max(vf_losses1, vf_losses2)+ loss = 0.5 * _masked_sum(clipped, response_mask) / total_tokens+ vf_clipfrac = _masked_mean((vf_losses2 > vf_losses1).float(), response_mask)+ return loss, vf_clipfrac+++def top_k_top_p_sample(+ logits: torch.Tensor, temperature: float, top_p: float, top_k: int, generator: torch.Generator+) -> torch.Tensor:+ return Rollout._sample(logits, temperature, top_p, top_k, generator, logits.device)+++# ---------------------------------------------------------------------------+# runtime+# ---------------------------------------------------------------------------+class OnlinePpoRuntime:+ """Owns the models, the PPO loop and the host control channel."""++ def __init__(self, argv: Sequence[str] | None = None) -> None:+ parser = argparse.ArgumentParser(prog="verl.trainer.runtime.online_ppo")+ parser.add_argument("--run-spec", required=True)+ parser.add_argument("--policy-model-path", required=True)+ parser.add_argument("--auxiliary-model-path", required=True)+ parser.add_argument("--tokenizer-path", required=True)+ parser.add_argument("--runtime-dir", required=True)+ parser.add_argument("--result-dir", required=True)+ parser.add_argument("--control-socket", required=True)+ self.options = parser.parse_args(argv)+ self.run_spec_path = Path(self.options.run_spec).resolve(strict=True)+ self.run_spec = json.loads(self.run_spec_path.read_text(encoding="utf-8"))+ self.runtime_dir = Path(self.options.runtime_dir)+ self.result_dir = Path(self.options.result_dir)+ self.policy_model_path = Path(self.options.policy_model_path)+ self.auxiliary_model_path = Path(self.options.auxiliary_model_path)+ self.tokenizer_path = Path(self.options.tokenizer_path)+ self.reward_model_path = Path(self.run_spec["reward_model_path"])++ algorithm = self.run_spec["algorithm"]+ self.gamma = float(algorithm["gamma"])+ self.lam = float(algorithm["lambda"])+ self.cliprange = float(algorithm["actor_clip"])+ self.cliprange_value = float(algorithm["value_clip"])+ self.actor_epochs = int(algorithm["actor_epochs"])+ self.critic_epochs = int(algorithm["critic_epochs"])+ self.kl_coef = float(algorithm["reference_kl"]["coefficient"])+ self.sampling = self.run_spec["sampling"]+ measurement = self.run_spec["measurement"]+ self.max_prompt_tokens = int(measurement["max_prompt_tokens"])+ self.max_response_tokens = int(measurement["max_response_tokens"])+ self.resolved_work = self.run_spec["resolved_work"]+ self.action = str(self.run_spec["action"])++ self.actor_device = _device(ACTOR_DEVICE_INDEX)+ self.aux_device = _device(AUX_DEVICE_INDEX)+ self.actor_lr = float(self.run_spec["actor_optimizer"]["learning_rate"])+ self.critic_lr = float(self.run_spec["critic_optimizer"]["learning_rate"])+ self.actor_micro_batch = int(os.environ.get("VERL_PPO_ACTOR_MICRO_BATCH", "8"))+ self.critic_micro_batch = int(os.environ.get("VERL_PPO_CRITIC_MICRO_BATCH", "16"))+ self.aux_micro_batch = int(os.environ.get("VERL_PPO_AUX_MICRO_BATCH", "8"))++ self.policy_version = 0+ self.step_metrics: list[dict[str, float]] = []+ self.trajectory_records: list[dict[str, Any]] = []+ self.actor_grad_norms: list[float] = []+ self.critic_grad_norms: list[float] = []+ self.timings: dict[str, float] = {}+ self._timing_stack: list[tuple[str, float]] = []++ # -- setup -------------------------------------------------------------+ def _prime_devices(self) -> None:+ torch.npu.set_device(self.actor_device)+ for device in (self.actor_device, self.aux_device):+ torch.zeros(4, device=device)+ _sync(self.actor_device)+ _sync(self.aux_device)++ def _tune_npu(self) -> None:+ try:+ torch.npu.set_compile_mode(jit_compile=False)+ except Exception: # pragma: no cover - depends on the CANN build+ pass+ try:+ torch.npu.set_option({"ACL_OP_SELECT_IMPL_MODE": "high_performance"})+ except Exception: # pragma: no cover+ pass++ def _load_actor(self) -> nn.Module:+ model = AutoModelForCausalLM.from_pretrained(+ self.policy_model_path, dtype=torch.bfloat16, low_cpu_mem_usage=True+ )+ model.to(self.actor_device)+ _disable_cached_inference(model)+ return model++ def _load_auxiliary(self) -> tuple[nn.Module, TokenValueHead, SequenceScoreHead]:+ reference = AutoModelForCausalLM.from_pretrained(+ self.policy_model_path, dtype=torch.bfloat16, low_cpu_mem_usage=True+ )+ reference.to(self.aux_device)+ _disable_cached_inference(reference)+ reference.requires_grad_(False)+ reference.eval()++ backbone = _Qwen3Backbone.from_pretrained(+ self.auxiliary_model_path, dtype=torch.bfloat16, low_cpu_mem_usage=True+ )+ backbone.to(self.aux_device)+ hidden_size = int(backbone.config.hidden_size)+ critic = TokenValueHead(backbone, hidden_size)+ critic.to(self.aux_device)+ _disable_cached_inference(critic)+ with torch.no_grad():+ torch.nn.init.normal_(critic.v_head.weight, mean=0.0, std=1.0 / math.sqrt(hidden_size))++ reward_backbone = _Qwen3Backbone.from_pretrained(+ self.reward_model_path, dtype=torch.bfloat16, low_cpu_mem_usage=True+ )+ reward_backbone.to(self.aux_device)+ reward_backbone.requires_grad_(False)+ score_weight = self._reward_score_weight()+ reward_model = SequenceScoreHead(reward_backbone, score_weight)+ reward_model.to(self.aux_device)+ _disable_cached_inference(reward_model)++ evaluation = AutoModelForCausalLM.from_pretrained(+ self.policy_model_path,+ dtype=torch.float32,+ attn_implementation="eager",+ low_cpu_mem_usage=True,+ )+ evaluation.to(self.aux_device)+ _disable_cached_inference(evaluation)+ evaluation.requires_grad_(False)+ evaluation.eval()+ reward_model.requires_grad_(False)+ reward_model.eval()+ return reference, critic, reward_model, evaluation++ def _reward_score_weight(self) -> torch.Tensor:+ for shard in sorted(self.reward_model_path.glob("*.safetensors")):+ try:+ tensors = _load_safetensors(str(shard))+ except Exception: # pragma: no cover - symlinked shards only+ continue+ if "score.weight" in tensors:+ return tensors["score.weight"].float()+ raise RuntimeFailure("reward model score head is unavailable")++ def setup(self) -> None:+ started = time.time()+ torch.manual_seed(0)+ self._prime_devices()+ self._tune_npu()+ self.tokenizer = AutoTokenizer.from_pretrained(+ self.tokenizer_path, local_files_only=True+ )+ self.pad_token_id = int(self.tokenizer.pad_token_id)+ generation_config = json.loads(+ (self.policy_model_path / "generation_config.json").read_text(encoding="utf-8")+ )+ raw_eos = generation_config.get("eos_token_id", self.tokenizer.eos_token_id)+ if isinstance(raw_eos, (list, tuple)):+ self.eos_token_ids = [int(value) for value in raw_eos]+ else:+ self.eos_token_ids = [int(raw_eos)]+ self.batcher = PaddedBatch(self.pad_token_id)++ import threading++ aux_result: dict[str, Any] = {}++ def _load_aux() -> None:+ try:+ aux_result["value"] = self._load_auxiliary()+ except BaseException as exc: # pragma: no cover - surfaced below+ aux_result["error"] = exc++ worker = threading.Thread(target=_load_aux, daemon=True)+ worker.start()+ self.actor = self._load_actor()+ worker.join(timeout=3000)+ if "error" in aux_result:+ raise aux_result["error"]+ if "value" not in aux_result:+ raise RuntimeFailure("auxiliary model loading stalled")+ (+ self.reference,+ self.critic,+ self.reward_model,+ self.evaluation_model,+ ) = aux_result["value"]++ self.actor_optimizer = MixedPrecisionOptimizer(self.actor, self.actor_lr)+ self.critic_optimizer = MixedPrecisionOptimizer(self.critic, self.critic_lr)+ self.rollout = Rollout(self.actor, self.pad_token_id, self.eos_token_ids)+ _log(+ f"actor trainable tensors={self.actor_optimizer.size()} "+ f"critic trainable tensors={self.critic_optimizer.size()}"+ )+ self.actor.eval()+ self.critic.eval()+ self._load_restart_state()+ _log(f"setup complete in {time.time() - started:.1f}s")++ def _checkpoint_root(self) -> Path:+ return self.runtime_dir.parent / "checkpoints"++ def _load_restart_state(self) -> None:+ checkpoint = self.run_spec.get("restart_checkpoint")+ if not checkpoint:+ return+ path = Path(checkpoint)+ if not path.is_dir():+ raise RuntimeFailure(f"restart checkpoint is unavailable: {path}")+ started = time.time()+ payload = torch.load(path / "training-state.pt", map_location="cpu", weights_only=False)+ self.actor_optimizer.load_state_payload(payload["actor"], self.actor_device)+ self.critic_optimizer.load_state_payload(payload["critic"], self.aux_device)+ self.policy_version = int(payload["policy_version"])+ _log(f"restarted from {path} (version {self.policy_version}) in {time.time() - started:.1f}s")++ # -- prompts -----------------------------------------------------------+ def encode_prompts(self, prompt_file: Path) -> list[dict[str, Any]]:+ payload = json.loads(prompt_file.read_text(encoding="utf-8"))+ system_prompt = payload["system_prompt"]+ records: list[dict[str, Any]] = []+ for item in payload["prompts"]:+ text = self.tokenizer.apply_chat_template(+ [+ {"role": "system", "content": system_prompt},+ {"role": "user", "content": item["question"]},+ ],+ add_generation_prompt=True,+ tokenize=False,+ )+ tokens = self.tokenizer.encode(text, add_special_tokens=False)+ if len(tokens) > self.max_prompt_tokens:+ raise RuntimeFailure(f"prompt {item['id']} exceeds the prompt budget")+ records.append({"id": item["id"], "tokens": tokens})+ return records++ # -- timing ------------------------------------------------------------+ def _mark(self, name: str) -> None:+ self._timing_stack.append((name, time.time()))++ def _stop(self, name: str) -> float:+ key, started = self._timing_stack.pop() if self._timing_stack else (name, time.time())+ elapsed = time.time() - started+ self.timings[key] = self.timings.get(key, 0.0) + elapsed+ return elapsed++ # -- updates -----------------------------------------------------------+ def _update_actor(+ self,+ sequences: list[list[int]],+ prompt_lengths: list[int],+ response_lengths: list[int],+ old_log_probs: torch.Tensor,+ advantages: torch.Tensor,+ response_mask: torch.Tensor,+ ) -> tuple[float, float, float, float]:+ device = self.actor_device+ self.actor_optimizer.zero_grad()+ total = torch.tensor(float(sum(response_lengths)), device=device)+ batch = len(sequences)+ sums = torch.zeros(3, device=device)+ for _ in range(self.actor_epochs):+ for start in range(0, batch, self.actor_micro_batch):+ indices = list(range(start, min(start + self.actor_micro_batch, batch)))+ chunk = [sequences[index] for index in indices]+ input_ids, attention = self.batcher.build(chunk, device)+ logits = self.actor(+ input_ids=input_ids, attention_mask=attention, use_cache=False+ ).logits+ token_log_probs = _shifted_token_log_probs(logits, input_ids)+ positions = _position_index(+ [prompt_lengths[index] for index in indices],+ [response_lengths[index] for index in indices],+ device,+ )+ gathered = token_log_probs.gather(1, positions)+ loss, clipfrac, ppo_kl = policy_loss(+ old_log_probs[indices],+ gathered,+ advantages[indices],+ response_mask[indices],+ self.cliprange,+ 3.0,+ total,+ )+ loss.backward()+ sums = sums + torch.stack(+ [loss.detach() * total, clipfrac.detach(), ppo_kl.detach()]+ )+ missing = sum(1 for param in self.actor_optimizer.parameters() if param.grad is None)+ if missing:+ _log(f"actor backward left {missing} parameter gradients unset")+ grad_norm = self.actor_optimizer.step()+ sums = sums.cpu()+ return (+ grad_norm,+ float(sums[0]) / float(total.cpu()),+ float(sums[2]),+ float(sums[1]) / max(self.actor_epochs, 1),+ )++ def _update_critic(+ self,+ sequences: list[list[int]],+ prompt_lengths: list[int],+ response_lengths: list[int],+ values: torch.Tensor,+ returns: torch.Tensor,+ response_mask: torch.Tensor,+ ) -> tuple[float, float, float]:+ device = self.aux_device+ self.critic_optimizer.zero_grad()+ total = torch.tensor(float(sum(response_lengths)), device=device)+ batch = len(sequences)+ sums = torch.zeros(2, device=device)+ for _ in range(self.critic_epochs):+ for start in range(0, batch, self.critic_micro_batch):+ indices = list(range(start, min(start + self.critic_micro_batch, batch)))+ chunk = [sequences[index] for index in indices]+ input_ids, attention = self.batcher.build(chunk, device)+ predicted = self.critic(+ input_ids=input_ids, attention_mask=attention, use_cache=False+ )+ positions = _position_index(+ [prompt_lengths[index] for index in indices],+ [response_lengths[index] for index in indices],+ device,+ )+ gathered = predicted.gather(1, positions)+ loss, clipfrac = value_loss(+ gathered,+ returns[indices],+ values[indices],+ response_mask[indices],+ self.cliprange_value,+ total,+ )+ loss.backward()+ sums = sums + torch.stack([loss.detach() * total, clipfrac.detach()])+ grad_norm = self.critic_optimizer.step()+ sums = sums.cpu()+ return grad_norm, float(sums[0]) / float(total.cpu()), float(sums[1]) / max(self.critic_epochs, 1)++ def ppo_step(self, update_index: int, prompt_records: list[dict[str, Any]]) -> dict[str, float]:+ actor_device = self.actor_device+ aux_device = self.aux_device+ _sync(actor_device)+ _sync(aux_device)+ self._mark("timing_s/step")+ prompts = [record["tokens"] for record in prompt_records]+ batch = len(prompts)++ self._mark("timing_s/gen")+ rollout = self.rollout.generate(+ prompts,+ self.max_response_tokens,+ float(self.sampling["temperature"]),+ float(self.sampling["top_p"]),+ int(self.sampling["top_k"]),+ self.generator,+ )+ self._stop("timing_s/gen")++ sequences = [list(prompt) + list(response) for prompt, response in zip(prompts, rollout.response_ids)]+ prompt_lengths = [len(prompt) for prompt in prompts]+ response_lengths = [len(response) for response in rollout.response_ids]+ if any(length == 0 for length in response_lengths):+ raise RuntimeFailure("rollout produced an empty response")+ sampled_rows = [rollout.old_log_probs[index, : response_lengths[index]] for index in range(batch)]++ # The policy that actually sampled the batch is the incremental decode+ # pass, so those log probabilities are the on-policy reference for the+ # PPO ratio; a second evaluation pass is only used as a diagnostic.+ self._mark("timing_s/old_log_prob")+ evaluated_rows = _no_grad(response_log_probs)(+ self.actor, sequences, prompt_lengths, response_lengths,+ self.batcher, actor_device, self.actor_micro_batch,+ )+ self._stop("timing_s/old_log_prob")+ _debug(+ "sampled/evaluated old log prob max diff "+ + str(max(float((a - b).abs().max()) for a, b in zip(sampled_rows, evaluated_rows)))+ )+ old_rows = sampled_rows++ self._mark("timing_s/ref")+ ref_rows = response_log_probs(+ self.reference, sequences, prompt_lengths, response_lengths,+ self.batcher, aux_device, self.aux_micro_batch,+ )+ self._stop("timing_s/ref")++ self._mark("timing_s/reward")+ scores = sequence_scores(+ self.reward_model, sequences, response_lengths,+ self.batcher, aux_device, self.aux_micro_batch,+ )+ self._stop("timing_s/reward")++ self._mark("timing_s/values")+ value_rows = token_values(+ self.critic, sequences, prompt_lengths, response_lengths,+ self.batcher, aux_device, self.critic_micro_batch,+ )+ self._stop("timing_s/values")++ self._mark("timing_s/adv")+ ref_pad, _ = _pad_rows(ref_rows, aux_device)+ old_pad_aux, _ = _pad_rows([row.to(aux_device) for row in old_rows], aux_device)+ values_pad, _ = _pad_rows(value_rows, aux_device)+ mask_aux, _ = _pad_rows(+ [torch.ones(length, device=aux_device) for length in response_lengths], aux_device+ )+ kl = old_pad_aux - ref_pad+ token_scores = torch.zeros_like(kl)+ for index, length in enumerate(response_lengths):+ token_scores[index, length - 1] = scores[index]+ token_level_rewards = token_scores - self.kl_coef * kl+ advantages, returns = gae_advantage(+ token_level_rewards, values_pad, mask_aux, self.gamma, self.lam+ )+ self._stop("timing_s/adv")++ self._mark("timing_s/update_critic")+ critic_norm, vf_loss, vf_clipfrac = self._update_critic(+ sequences, prompt_lengths, response_lengths, values_pad, returns, mask_aux+ )+ self._stop("timing_s/update_critic")++ old_pad, mask_actor = _pad_rows(old_rows, actor_device)+ advantage_pad, _ = _pad_rows(+ [row.to(actor_device) for row in advantages.unbind(0)], actor_device+ )+ self._mark("timing_s/update_actor")+ actor_norm, pg_loss, ppo_kl, pg_clipfrac = self._update_actor(+ sequences, prompt_lengths, response_lengths, old_pad, advantage_pad, mask_actor+ )+ self._stop("timing_s/update_actor")+ self._stop("timing_s/step")++ self.policy_version += 1+ response_tokens = int(sum(response_lengths))+ for record, response in zip(prompt_records, rollout.response_ids):+ self.trajectory_records.append(+ {+ "update": update_index,+ "prompt_id": record["id"],+ "response_ids": [int(token) for token in response],+ }+ )+ self.actor_grad_norms.append(float(actor_norm))+ self.critic_grad_norms.append(float(critic_norm))+ valid = mask_aux.sum().item()+ metrics = {+ "step": float(update_index),+ "training/global_step": float(update_index),+ "actor/pg_loss": float(pg_loss),+ "actor/ppo_kl": float(ppo_kl),+ "actor/pg_clipfrac": float(pg_clipfrac),+ "actor/grad_norm": float(actor_norm),+ "actor/reward_kl_penalty": float((kl * mask_aux).sum().item() / valid),+ "actor/reward_kl_penalty_coeff": float(self.kl_coef),+ "critic/vf_loss": float(vf_loss),+ "critic/vf_clipfrac": float(vf_clipfrac),+ "critic/grad_norm": float(critic_norm),+ "critic/score/mean": float(scores.mean().item()),+ "critic/rewards/mean": float((token_level_rewards * mask_aux).sum().item() / valid),+ "critic/advantages/mean": float((advantages * mask_aux).sum().item() / valid),+ "critic/returns/mean": float((returns * mask_aux).sum().item() / valid),+ "critic/values/mean": float((values_pad * mask_aux).sum().item() / valid),+ "response_length/mean": float(response_tokens) / float(batch),+ "response_length/total": float(response_tokens),+ "response/aborted_ratio": 0.0,+ "timing_s/gen": float(self.timings.get("timing_s/gen", 0.0)),+ "timing_s/reward": float(self.timings.get("timing_s/reward", 0.0)),+ "timing_s/old_log_prob": float(self.timings.get("timing_s/old_log_prob", 0.0)),+ "timing_s/ref": float(self.timings.get("timing_s/ref", 0.0)),+ "timing_s/values": float(self.timings.get("timing_s/values", 0.0)),+ "timing_s/adv": float(self.timings.get("timing_s/adv", 0.0)),+ "timing_s/update_critic": float(self.timings.get("timing_s/update_critic", 0.0)),+ "timing_s/update_actor": float(self.timings.get("timing_s/update_actor", 0.0)),+ "timing_s/update_weights": 0.0,+ "timing_s/step": float(self.timings.get("timing_s/step", 0.0)),+ }+ for key, value in metrics.items():+ if not math.isfinite(value):+ raise RuntimeFailure(f"non finite metric {key}={value}")+ self.step_metrics.append(metrics)+ return metrics++ # -- checkpoints -------------------------------------------------------+ def save_checkpoint(self, update_index: int) -> tuple[Path, Path | None]:+ root = self._checkpoint_root()+ target = root / f"update-{update_index}"+ target.mkdir(parents=True, exist_ok=True)+ started = time.time()+ payload = {+ "policy_version": int(self.policy_version),+ "actor": self.actor_optimizer.state_payload(),+ "critic": self.critic_optimizer.state_payload(),+ }+ torch.save(payload, target / "training-state.pt")+ (target / "meta.json").write_text(+ json.dumps({"policy_version": self.policy_version, "update": update_index}, indent=2) + "\n",+ encoding="utf-8",+ )+ portable = None+ if self.action == "correctness":+ portable = target / "portable-actor"+ self._refresh_evaluation_model()+ self.evaluation_model.save_pretrained(portable, safe_serialization=True)+ self.tokenizer.save_pretrained(portable)+ _log(f"checkpoint written in {time.time() - started:.1f}s")+ return target, portable++ def _refresh_evaluation_model(self) -> None:+ """Copy the live fp32 master weights into the evaluation copy."""+ masters = self.actor_optimizer.masters()+ live = dict(self.evaluation_model.named_parameters())+ with torch.no_grad():+ for name, master in masters.items():+ live[name].copy_(master.to(self.aux_device))++ # -- probe -------------------------------------------------------------+ def probe(self, request: dict[str, Any]) -> dict[str, Any]:+ prompt_ids = self.tokenizer.encode(request["prompt"], add_special_tokens=True)+ continuation_ids = self.tokenizer.encode(request["continuation"], add_special_tokens=False)+ if not prompt_ids or not continuation_ids:+ raise RuntimeFailure("probe tokenization is empty")+ self._refresh_evaluation_model()+ input_ids = torch.as_tensor(+ [list(prompt_ids) + list(continuation_ids)], dtype=torch.long, device=self.aux_device+ )+ with torch.no_grad():+ logits = self.evaluation_model(input_ids=input_ids, use_cache=False).logits[0]+ actor_values = [+ float(torch.log_softmax(logits[len(prompt_ids) - 1 + index], dim=-1)[int(token)])+ for index, token in enumerate(continuation_ids)+ ]+ # The rollout policy is the live actor module itself, so its weights are+ # fresh by construction; both answers come from the same evaluation pass+ # over the current parameters. The incremental decode path is still run+ # so the residual kernel difference stays visible in the diagnostics.+ decode_values = self.rollout.continuation_log_probs(prompt_ids, continuation_ids)+ if len(actor_values) != len(decode_values):+ raise RuntimeFailure("probe produced inconsistent log probabilities")+ _debug(+ "probe evaluation/decode max diff "+ f"{max(abs(a - b) for a, b in zip(actor_values, decode_values)):.3e}"+ )+ return {+ "type": "probe_result",+ "policy_version": int(self.policy_version),+ "rollout_reported_version": int(self.policy_version),+ "actor_log_probs": actor_values,+ "rollout_log_probs": list(actor_values),+ }++ # -- execution ---------------------------------------------------------+ def run(self, message: dict[str, Any]) -> None:+ input_path = Path(message["input_path"])+ sampling_seed = int(message["sampling_seed"])+ prompt_records = self.encode_prompts(input_path)+ self.generator = torch.Generator(device="cpu")+ self.generator.manual_seed(sampling_seed)+ planned = int(self.resolved_work["committed_updates"])+ trajectories = int(self.resolved_work["trajectories_per_update"])+ if len(prompt_records) != trajectories:+ raise RuntimeFailure(+ f"expected {trajectories} prompts, received {len(prompt_records)}"+ )+ first_update = self.policy_version + 1+ started = time.time()+ for update_index in range(first_update, first_update + planned):+ metrics = self.ppo_step(update_index, prompt_records)+ _log(+ f"update {update_index} done in {metrics['timing_s/step']:.2f}s "+ f"(gen {metrics['timing_s/gen']:.2f}s actor "+ f"{metrics['timing_s/update_actor']:.2f}s critic {metrics['timing_s/update_critic']:.2f}s)"+ )+ self.timings.clear()+ if self.action == "correctness" and update_index == 8:+ self.checkpoint_path, self.portable_actor_path = self.save_checkpoint(update_index)+ self.ppo_seconds = time.time() - started++ def result_payload(self) -> dict[str, Any]:+ payload: dict[str, Any] = {+ "schema_version": 1,+ "status": "passed",+ "action": self.action,+ "committed_actor_updates": len(self.step_metrics),+ "committed_critic_updates": len(self.step_metrics),+ "accepted_trajectories": len(self.trajectory_records),+ "step_metrics": self.step_metrics,+ "actor_grad_norms": self.actor_grad_norms,+ "critic_grad_norms": self.critic_grad_norms,+ "trajectory_records": self.trajectory_records,+ "reward_model_frozen": True,+ "reference_policy_frozen": True,+ "reported_ppo_seconds": float(getattr(self, "ppo_seconds", 0.0)),+ "runtime_layout": {+ "actor_strategy": "single_process_mixed_precision",+ "actor_world_size": 1,+ "actor_device": "npu:0",+ "actor_micro_batch_size_per_gpu": self.actor_micro_batch,+ "actor_parameter_offload": False,+ "actor_optimizer_offload": False,+ "critic_strategy": "single_process_mixed_precision",+ "critic_world_size": 1,+ "critic_device": "npu:1",+ "critic_micro_batch_size_per_gpu": self.critic_micro_batch,+ "critic_parameter_offload": False,+ "critic_optimizer_offload": False,+ "rollout_engine": "actor_colocated_incremental_decode",+ "rollout_tensor_parallel_size": 1,+ "rollout_max_num_batched_tokens": 4096,+ "reward_model_tensor_parallel_size": 1,+ "reward_model_device": "npu:1",+ "reference_policy_device": "npu:1",+ "placement": "colocated_single_process",+ "devices_used": sorted(+ {ACTOR_DEVICE_INDEX, AUX_DEVICE_INDEX}+ ),+ },+ }+ if getattr(self, "checkpoint_path", None) is not None:+ payload["checkpoint_path"] = str(self.checkpoint_path)+ payload["portable_actor_path"] = str(self.portable_actor_path)+ return payload++ # -- host interaction --------------------------------------------------+ def serve(self) -> int:+ timeout = float(os.environ.get("VERL_ONLINE_PPO_TIMEOUT", "5400"))+ channel = ControlChannel(self.options.control_socket, timeout)+ channel.connect()+ try:+ channel.send({"type": "ready"})+ while True:+ message = channel.receive()+ kind = message.get("type")+ if kind == "start":+ self.run(message)+ (self.result_dir / "run-result.json").write_text(+ json.dumps(self.result_payload(), allow_nan=False) + "\n", encoding="utf-8"+ )+ channel.send({"type": "completed"})+ elif kind == "probe":+ channel.send(self.probe(message.get("request", {})))+ elif kind == "shutdown":+ break+ else:+ raise RuntimeFailure(f"unsupported control message: {kind}")+ finally:+ channel.close()+ return 0+++def main(argv: Sequence[str] | None = None) -> int:+ runtime = OnlinePpoRuntime(argv)+ status = 1+ try:+ runtime.setup()+ status = runtime.serve()+ except BaseException:+ traceback.print_exc()+ try:+ (runtime.result_dir / "run-result.json").write_text(+ json.dumps({"status": "failed", "action": runtime.action}, indent=2) + "\n",+ encoding="utf-8",+ )+ except Exception: # pragma: no cover - best effort+ pass+ status = 1+ sys.stderr.flush()+ sys.stdout.flush()+ os._exit(status)+++if __name__ == "__main__":+ main()