Inspect · Source & workspace
Requested workspace inspection and file and log inspection related to source & workspace.
1 call · #0001–#0001
echo <val>ls -l -a <path> <n> > <path>head -n <n>GLM-5.3 · RL
Qwen3-1.7B online GRPO 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 · 178 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.
1 call · #0001–#0001
echo <val>ls -l -a <path> <n> > <path>head -n <n>Requested file and log inspection and workspace inspection related to task requirements.
3 calls · #0002–#0004
Read <path>cd <path>find <path> -type <val>head -n <n>echo <flag>du <flag> <args>wc -l <path> <path> <path> <path> <path> <n> > <path>Requested file and log inspection related to source & workspace.
1 call · #0005–#0005
Read <path>Requested file and log inspection related to reward & policy updates.
1 call · #0006–#0006
Read <path>Requested file and log inspection related to source & workspace.
2 calls · #0007–#0008
Read <path>Requested file and log inspection related to benchmark & validation setup.
1 call · #0009–#0009
cat <path> <path> <path> <path> <path> <path> <path> <n> > <path>Requested runtime inspection, file and log inspection and script or workload execution related to device memory.
1 call · #0010–#0010
npu-smi info <n> >& <path>head -n <n>echo <val>which <val> <val>python3 -VRequested file and log inspection related to benchmark & validation setup.
1 call · #0011–#0011
cd <path><command> <args>cat <val>Requested environment setup or inspection, source searches and file and log inspection related to source & workspace.
2 calls · #0012–#0013
envgrep -E <val>sortecho <val>cat <path> <n> > <path>head -n <n>cd <path>lsls -l -a <path> <n> > <path>ls <path>git log --oneline <flag>Requested script or workload execution related to benchmark & validation setup.
1 call · #0014–#0014
cd <path>timeout <n> <val> <path> > <path> <n> >& <path>echo <val> >> <path>Requested file and log inspection related to source & workspace.
1 call · #0015–#0015
Read <path>Requested script or workload execution, workspace inspection and file and log inspection related to source & workspace.
1 call · #0016–#0016
python3 -c <script>echo <val>ls <path> <n> > <path>head -n <n>Requested file and log inspection and workspace inspection related to checkpoints & weight state.
1 call · #0017–#0017
cd <path>wc -l <path> <path> <path> <path> <n> > <path>tail -n <n>echols <path> <path> <path> <n> > <path>Requested file and log inspection related to rollout generation.
1 call · #0018–#0018
Read <path>Requested file and log inspection and workspace inspection related to benchmark & validation setup.
1 call · #0019–#0019
tail -n <n> <path> <n> > <path>echo <val>ls -l -a <path> <n> > <path>Requested file and log inspection related to checkpoints & weight state.
1 call · #0020–#0020
Read <path>Requested file and log inspection related to source & workspace.
1 call · #0021–#0021
Read <path>Requested file and log inspection and workspace inspection related to benchmark & validation setup.
2 calls · #0022–#0023
tail -c <n> <path>echoecho <val>ls -l -a <path>Requested workspace inspection, file and log inspection and source searches related to rollout generation.
4 calls · #0024–#0027
ls -l -a <path> <path> <n> > <path>head -n <n>echo <val>sed -n <val> <path>cd <path>grep -n <val> <path>tail -c <n> <path>ls <path>Requested file and log inspection and source searches related to rollout generation.
1 call · #0028–#0028
tail -c <n> <path>echo <val>awk <val> <path>grep -n <val> <path>tail -n <n>Requested source searches and file and log inspection related to rollout generation.
3 calls · #0029–#0031
cd <path>grep -r -n <val> <path>head -n <n>echo <val>grep -n <val> <path>headecho <flag>sed -n <val> <path>Requested file and log inspection related to task requirements.
2 calls · #0032–#0033
cd <path>cat <val>echo <val>cat <path>head -n <n> <val>sed -n <val> <val>Requested workspace inspection and file and log inspection related to benchmark & validation setup.
1 call · #0034–#0034
ls -l -a <path>tail -c <n> <path>tr -d <val>Requested workspace inspection, source searches and file and log inspection related to checkpoints & weight state.
2 calls · #0035–#0036
cd <path>ls <path>grep -n <val> <path>head -n <n>sed -n <val> <path>Requested file and log inspection and source searches related to prefix caching.
1 call · #0037–#0037
cd <path>sed -n <path> <path>sed -n <val>echo <path>grep -n <val> <path>head -n <n>Requested workspace inspection and file and log inspection related to rollout generation.
2 calls · #0038–#0039
cd <path>ls <path>sed -n <val> <path>cat <path> <n> > <path>head -n <n>Requested workspace inspection, file and log inspection and source searches related to benchmark & validation setup.
1 call · #0040–#0040
ls -l -a <path> <n> > <path>tail -c <n> <path>echogrep -c <path> <path>Requested runtime inspection, source searches and file and log inspection related to device memory.
1 call · #0041–#0041
dateps <val>grep -c <val>tail -n <n> <path>npu-smi infotail -n <n>Requested workspace file updates and workspace inspection related to reward & policy updates.
1 call · #0042–#0042
mkdir -p <path>printf <val> > <path>ls <path>Requested file and log inspection and source searches related to source & workspace.
1 call · #0043–#0043
cd <path>sed -n <val> <path> <n> > <path>head -n <n>echo <val>grep -r -n <val> <path>Requested code edits related to source & workspace.
3 calls · #0044–#0046
Write <path>Edit <path>Requested script or workload execution and workspace inspection related to benchmark & validation setup.
1 call · #0047–#0047
cd <path>python3 -c <script>ls -l -a <path>dateRequested workspace inspection and script or workload execution related to source & workspace.
1 call · #0048–#0048
ls -l -a <path>python3 -c <script>Requested script or workload execution, file and log inspection and source searches related to benchmark & validation setup.
3 calls · #0049–#0051
cd <path>python3 -c <script>echo <val>tail -n <n> <val>python3 -c <script> <n> >& <path>head -n <n>grep -n <val> <val>tail -n <n>Requested script or workload execution related to reward & policy updates.
1 call · #0052–#0052
cd <path>python3 -c <script>Requested source searches and file and log inspection related to device memory.
1 call · #0053–#0053
cd <path>grep -n <val> <val>tail -n <n>Requested script or workload execution related to device memory.
2 calls · #0054–#0055
cd <path>python3 - <script>Requested file and log inspection, runtime inspection and source searches related to device memory.
1 call · #0056–#0056
<command> <args>cat <path>free -ghead -n <n>grep <flag> <args>cat <path> <n> > <path>Requested file and log inspection related to rollout generation.
1 call · #0057–#0057
cd <path>sed -n <val> <path>Requested code edits related to source & workspace.
11 calls · #0058–#0068
Edit <path>Requested source searches related to source & workspace.
1 call · #0069–#0069
cd <path>grep -n <val> <path>Requested script or workload execution and source searches related to source & workspace.
1 call · #0070–#0070
cd <path>python3 - <script>grep -n <val> <path>Requested script or workload execution and file and log inspection related to rollout generation.
1 call · #0071–#0071
cd <path>python3 -c <script> <n> >& <path>tail -n <n>Requested code edits related to source & workspace.
1 call · #0072–#0072
Edit <path>Requested code edits, script or workload execution and file and log inspection related to rollout generation.
1 call · #0073–#0073
cd <path>sed -i <path> <path>python3 -c <script> <n> >& <path>tail -n <n>grep -n <val> <path>Requested file and log inspection related to source & workspace.
1 call · #0074–#0074
Read <path>Requested code edits related to source & workspace.
2 calls · #0075–#0076
Edit <path>Requested file and log inspection related to source & workspace.
1 call · #0077–#0077
Read <path>Requested script or workload execution related to benchmark & validation setup.
1 call · #0078–#0078
cd <path>timeout <n> <val> <path> > <path> <n> >& <path>echo <val> >> <path>Requested task coordination related to benchmark & validation setup.
1 call · #0079–#0079
Create task <task>Requested execution waits, workspace inspection and file and log inspection related to benchmark & validation setup.
1 call · #0080–#0080
sleep <n>cd <path>ls -l -aecho <flag>tail -c <n> <val> <n> > <path>tr -d <val>Requested code edits related to source & workspace.
1 call · #0081–#0081
Edit <path>Requested script or workload execution and source searches related to source & workspace.
1 call · #0082–#0082
cd <path>python3 - <script>grep -n <val> <path>python3 -c <script>Requested workspace file updates, script or workload execution and execution waits related to benchmark & validation setup.
5 calls · #0083–#0087
rm -rf <path> <path> <path> <n> > <path>cd <path>timeout <n> <val> <path> > <path> <n> >& <path>echo <val> >> <path>sleep <n>ls -l -atail -n <n>echo <val>tail -c <n> <val> <n> > <path>tr -d <val>python3 -c <script> <n> >& <path>head -n <n>tail -c <n> <val>rm -f <val> <val> <val>rm -rf <path> <path> <path> <path>lsdateRequested code edits related to source & workspace.
1 call · #0088–#0088
Edit <path>Requested execution waits, workspace inspection and source searches related to device memory.
2 calls · #0089–#0090
sleep <n>cd <path>ls -l -agrep <val>echo <val>tail -c <n> <val> <n> > <path>tr -d <val>tail -n <n>echonpu-smi info <n> > <path>grep -E <val>head -n <n>Requested execution waits, workspace inspection and source searches related to benchmark & validation setup.
3 calls · #0091–#0093
sleep <n>cd <path>ls -l -agrep -c <val>tail -c <n> <val> <n> > <path>tr -d <val>tail -n <n>python3 - <script>dateRequested script or workload execution related to checkpoints & weight state.
1 call · #0094–#0094
cd <path>python3 - <script>Requested file and log inspection related to benchmark & validation setup.
1 call · #0095–#0095
cd <path>tail -c <n> <val>tr -d <val>tail -n <n>Requested code edits related to source & workspace.
1 call · #0096–#0096
Edit <path>Requested workspace file updates, script or workload execution and execution waits related to benchmark & validation setup.
3 calls · #0097–#0099
cd <path>rm -f <val> <val> <val>rm -rf <path> <path> <path>timeout <n> <val> <path> > <path> <n> >& <path>echo <val> >> <path>sleep <n>python3 - <script>dateRequested task coordination related to source & workspace.
1 call · #0100–#0100
Update task <task>Requested execution waits and script or workload execution related to benchmark & validation setup.
2 calls · #0101–#0102
sleep <n>cd <path>python3 - <script>dateRequested script or workload execution related to checkpoints & weight state.
1 call · #0103–#0103
cd <path>python3 - <script>Requested source searches and file and log inspection related to benchmark & validation setup.
1 call · #0104–#0104
cd <path>grep -n <val> -A <n> <val>tr -d <val>tail -n <n>Requested script or workload execution related to benchmark & validation setup.
2 calls · #0105–#0106
cd <path>python3 - <script>Requested file and log inspection related to benchmark & validation setup.
1 call · #0107–#0107
cd <path>tail -c <n> <val>tr -d <val>echoecho <val>tail -n <n> <val>cut <flag>Requested code edits related to source & workspace.
5 calls · #0108–#0112
Edit <path>Requested script or workload execution and workspace file updates related to reward & policy updates.
1 call · #0113–#0113
cd <path>python3 -c <script>rm -f <path>rm -f <val> <val> <val>rm -rf <path> <path> <path>timeout <n> <val> <path> > <path> <n> >& <path>echo <val> >> <path>Requested code edits related to reward & policy updates.
2 calls · #0114–#0115
Write <path>Requested workspace inspection related to device memory.
1 call · #0116–#0116
cd <path>ls<command> <args>Requested code edits related to device memory.
1 call · #0117–#0117
Write <path>Requested execution waits, file and log inspection and workspace inspection related to reward & policy updates.
1 call · #0118–#0118
sleep <n>cat <path> <n> > <path>tail -n <n>datels -l -a <path>grep -c <val>Requested execution waits, file and log inspection and runtime inspection related to reward & policy updates.
3 calls · #0119–#0121
sleep <n>cat <path> <n> > <path>tail -n <n>dateps <val>grep -c <val>Requested file and log inspection and script or workload execution related to reward & policy updates.
1 call · #0122–#0122
cat <path>echo <val>cd <path>python3 -c <script>python3 - <script>Requested source searches and file and log inspection related to rollout generation.
4 calls · #0123–#0126
cd <path>grep -n <val> <path> <path>head -n <n>sed -n <val> <path>echo <val>grep -r -n <val> -A <n> <path>grep -n <val> -A <n> <path>Requested code edits, source searches and file and log inspection related to reward & policy updates.
1 call · #0127–#0127
cd <path>sed -i <path> <path>grep -n <val> <path>head -n <n>rm -f <path>rm -f <val> <val> <val>rm -rf <path> <path> <path>Requested script or workload execution related to benchmark & validation setup.
1 call · #0128–#0128
cd <path>timeout <n> <val> <path> > <path> <n> >& <path>echo <val> >> <path>Requested execution waits and file and log inspection related to reward & policy updates.
4 calls · #0129–#0132
sleep <n>cat <path> <n> > <path>tail -n <n>dateRequested workspace inspection and script or workload execution related to benchmark & validation setup.
1 call · #0133–#0133
ls -d <path> <n> > <path>ls <path> <n> > <path>echo <val>python3 - <script>Requested script or workload execution, source searches and file and log inspection related to checkpoints & weight state.
1 call · #0134–#0134
cd <path>python3 - <script>grep -n <val> <path>head -n <n>Requested workspace file updates and script or workload execution related to reward & policy updates.
1 call · #0135–#0135
rm -f <path>cd <path>rm -f <val> <val> <val>rm -rf <path> <path>timeout <n> <val> <path> > <path> <n> >& <path>echo <val> >> <path>Requested source searches and file and log inspection related to benchmark & validation setup.
1 call · #0136–#0136
cd <path>grep -c <val> <val> <val> <n> > <path>grep -n <val> <val>head -n <n>Requested source searches and file and log inspection related to source & workspace.
1 call · #0137–#0137
cd <path>grep -n <val> <path>head -n <n>grep -r -n <val> <path>Requested file and log inspection and execution waits related to reward & policy updates.
5 calls · #0138–#0142
cd <path>sed -n <val> <path>sleep <n>cat <path> <n> > <path>tail -n <n>dateRequested file and log inspection and script or workload execution related to checkpoints & weight state.
1 call · #0143–#0143
cat <path>echo <val>cd <path>python3 - <script>Requested file and log inspection and script or workload execution related to benchmark & validation setup.
1 call · #0144–#0144
cd <path>wc -l <val>python3 - <script>Requested code edits related to source & workspace.
4 calls · #0145–#0148
Edit <path>Requested script or workload execution and workspace file updates related to reward & policy updates.
1 call · #0149–#0149
cd <path>python3 -c <script>rm -f <path> <path>rm -f <val> <val> <val>rm -rf <path> <path>timeout <n> <val> <path> > <path> <n> >& <path>echo <val> >> <path>Requested execution waits and file and log inspection related to reward & policy updates.
4 calls · #0150–#0153
sleep <n>cat <path> <n> > <path>tail -n <n>dateecho <flag>Requested script or workload execution related to benchmark & validation setup.
1 call · #0154–#0154
cd <path>python3 - <script>Requested source searches and file and log inspection related to benchmark & validation setup.
1 call · #0155–#0155
cd <path>grep -n <val> <val>head -n <n>Requested code edits related to source & workspace.
2 calls · #0156–#0157
Edit <path>Requested script or workload execution, source searches and file and log inspection related to runtime processes.
1 call · #0158–#0158
cd <path>python3 - <script>grep -n <val> <path>headRequested script or workload execution and workspace file updates related to reward & policy updates.
1 call · #0159–#0159
cd <path>python3 -c <script>rm -f <path> <path>rm -f <val> <val> <val>rm -rf <path> <path>timeout <n> <val> <path> > <path> <n> >& <path>echo <val> >> <path>Requested repository inspection and file and log inspection related to source & workspace.
1 call · #0160–#0160
cd <path>git status <flag>echo <val><command> <args>git -C <val> <val> <flag>head -n <n>tr <val> <val>echoRequested execution waits and file and log inspection related to reward & policy updates.
5 calls · #0161–#0165
sleep <n>cat <path> <n> > <path>tail -n <n>dateecho <flag>tail -n <n> <path> <n> > <path>Requested script or workload execution related to checkpoints & weight state.
1 call · #0166–#0166
cd <path>python3 - <script>Requested workspace inspection related to source & workspace.
1 call · #0167–#0167
ls -l -a <path> <n> > <path>find <path> -name <val> <n> > <path>Requested script or workload execution and source searches related to rollout generation.
1 call · #0168–#0168
cd <path>python3 - <script>grep -n <val> <path>python3 -c <script>Requested workspace file updates and script or workload execution related to reward & policy updates.
1 call · #0169–#0169
rm -f <path> <path>cd <path>rm -f <val> <val> <val>rm -rf <path> <path>timeout <n> <val> <path> > <path> <n> >& <path>echo <val> >> <path>Requested execution waits and file and log inspection related to reward & policy updates.
5 calls · #0170–#0174
sleep <n>cat <path> <n> > <path>tail -n <n>dateRequested script or workload execution and source searches related to benchmark & validation setup.
1 call · #0175–#0175
cd <path>python3 - <script>grep -n <val> <path>python3 -c <script>Requested file and log inspection related to source & workspace.
1 call · #0176–#0176
cd <path>sed -n <val> <path>echo <path>Requested task coordination related to source & workspace.
1 call · #0177–#0177
Update task <task>Requested file and log inspection, workspace inspection and repository inspection related to reward & policy updates.
1 call · #0178–#0178
cat <path>head -n <n>echo <path>ls <path>cd <path>git status <flag>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 @@+"""Framework-owned online GRPO runtime package."""@@ -0,0 +1,1391 @@+# Copyright 2025 Project Contributors+#+# 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 this license file, distributed under the License is+# distributed on an "ASIS" 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 runtime for the two-device online GRPO/RLVR workflow.++The process owns its whole internal execution plan: a colocated FSDP2 actor and+an async vLLM rollout replica share the two projected Ascend devices and the+runtime drives generation, scoring, the actor update, the full policy refresh+and the freshness probes from a single control loop.++Outer interaction (see ``config/framework-runtime-contract.md``):++ ready -> start -> run -> run-result.json -> completed -> probe -> shutdown+"""++from __future__ import annotations++import argparse+import asyncio+import hashlib+import json+import math+import os+import shutil+import socket+import sys+import time+import traceback+from collections.abc import Mapping+from dataclasses import dataclass+from decimal import Decimal, InvalidOperation+from pathlib import Path+from typing import Any+from urllib.parse import urlsplit+from urllib.request import Request, urlopen++MAX_PROMPT_TOKENS = 256+MAX_RESPONSE_TOKENS = 256+RESPONSES_PER_PROMPT = 4+PROMPT_GROUPS_PER_UPDATE = 8+TEMPERATURE = 0.7+TOP_P = 0.8+TOP_K = 20+COMMITTED_UPDATES = 8+OBSERVATION_UPDATES = (1, 4, 8)++# Tuning knobs. Defaults are the tuned configuration; the environment variables+# only exist so alternative layouts can be measured side by side.+_KNOBS = {+ "GRPO_RT_GRAD_CKPT": "1", # activation checkpointing on (matches the reference layout)+ "GRPO_RT_TOKEN_BUDGET": "2048", # max tokens per training micro-batch+ "GRPO_RT_LOGPROB_TOKEN_BUDGET": "2048",+ "GRPO_RT_FREE_CACHE": "1", # sleep/wake the rollout around training+ "GRPO_RT_GPU_MEM_UTIL": "0.32",+ "GRPO_RT_MAX_NUM_SEQS": "32",+ "GRPO_RT_MAX_BATCHED_TOKENS": "4096",+ "GRPO_RT_SYNC_BUCKET_MB": "1024",+ "GRPO_RT_ROLLOUT_TP": "2",+ "GRPO_RT_FSDP_SIZE": "2",+ "GRPO_RT_PROBE_ROWS": "4",+ "GRPO_RT_LOG_STATS": "0",+}+++def _knob(name: str) -> Any:+ raw = os.environ.get(name, _KNOBS[name])+ if name in {"GRPO_RT_GRAD_CKPT", "GRPO_RT_FREE_CACHE"}:+ return raw.strip().lower() not in {"0", "false", "no", "off"}+ if name == "GRPO_RT_GPU_MEM_UTIL":+ return float(raw)+ return int(raw)+++def _log(message: str) -> None:+ line = f"[online_grpo {time.strftime('%H:%M:%S')}] {message}"+ print(line, flush=True)+ try:+ with open(f"/tmp/online-grpo-{os.getpid()}.log", "a", encoding="utf-8") as handle:+ handle.write(line + "\n")+ except OSError: # pragma: no cover - diagnostics only+ pass+++def _enable_fault_handler() -> None:+ """Dump a Python traceback for native (SIGSEGV/SIGABRT) failures."""+ import faulthandler++ try:+ _fault_file = open("/tmp/online-grpo-fault.log", "a", encoding="utf-8")+ faulthandler.enable(file=_fault_file, all_threads=True)+ except (OSError, RuntimeError): # pragma: no cover - diagnostics only+ pass+++_SAFETENSORS_TO_TORCH = {+ "BOOL": "bool",+ "U8": "uint8",+ "I8": "int8",+ "I16": "int16",+ "I32": "int32",+ "I64": "int64",+ "F16": "float16",+ "BF16": "bfloat16",+ "F32": "float32",+ "F64": "float64",+}+++def _torch_dtype(name: str):+ import torch++ mapped = _SAFETENSORS_TO_TORCH.get(str(name).upper(), str(name).lower())+ return getattr(torch, mapped)+++class ControlChannel:+ """Line-delimited JSON control channel towards the host supervisor."""++ def __init__(self, path: Path) -> None:+ self.path = path+ self._socket: socket.socket | None = None+ self._buffer = bytearray()++ def connect(self, timeout: float) -> None:+ deadline = time.monotonic() + timeout+ while True:+ client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ client.settimeout(max(1.0, deadline - time.monotonic()))+ try:+ client.connect(str(self.path))+ except (FileNotFoundError, ConnectionRefusedError, OSError):+ client.close()+ if time.monotonic() >= deadline:+ raise+ time.sleep(0.05)+ continue+ self._socket = client+ return++ def send(self, value: dict[str, Any]) -> None:+ assert self._socket is not None+ self._socket.sendall(+ json.dumps(value, allow_nan=False, separators=(",", ":")).encode("utf-8") + b"\n"+ )++ def recv(self) -> dict[str, Any]:+ assert self._socket is not None+ while not self._buffer.endswith(b"\n"):+ chunk = self._socket.recv(65536)+ if not chunk:+ raise RuntimeError("control connection closed by host")+ self._buffer.extend(chunk)+ if len(self._buffer) > 4 * 1024 * 1024:+ raise RuntimeError("control message is too large")+ raw = bytes(self._buffer)+ self._buffer.clear()+ value = json.loads(raw)+ if not isinstance(value, dict) or not isinstance(value.get("type"), str):+ raise RuntimeError("control message is invalid")+ return value++ def close(self) -> None:+ if self._socket is not None:+ self._socket.close()+ self._socket = None+++# --------------------------------------------------------------------------------------+# reward / advantage helpers (public numerical contract)+# --------------------------------------------------------------------------------------+++def _numeric_reward(text: str, expected: str) -> float:+ import re++ boxed = re.findall(r"\\boxed\{\s*([-+]?\d[\d,]*(?:\.\d+)?)\s*\}", text)+ candidates = boxed or re.findall(r"[-+]?\d[\d,]*(?:\.\d+)?", text)+ if not candidates:+ return 0.0+ try:+ return 1.0 if Decimal(candidates[-1].replace(",", "")) == Decimal(expected) else 0.0+ except InvalidOperation:+ return 0.0+++def _score_responses(endpoint: tuple[str, str], items: list[tuple[str, str]]) -> list[float]:+ request = Request(+ endpoint[0] + "/score_batch",+ data=json.dumps(+ {+ "items": [+ {"prompt_id": prompt_id, "response_text": response_text}+ for prompt_id, response_text in items+ ]+ },+ allow_nan=False,+ separators=(",", ":"),+ ).encode("utf-8"),+ headers={+ "Authorization": f"Bearer {endpoint[1]}",+ "Content-Type": "application/json",+ },+ method="POST",+ )+ with urlopen(request, timeout=300) as response:+ payload = json.loads(response.read())+ rewards = payload.get("rewards") if isinstance(payload, dict) else None+ if (+ not isinstance(rewards, list)+ or len(rewards) != len(items)+ or any(+ isinstance(value, bool) or not isinstance(value, (int, float)) or float(value) not in {0.0, 1.0}+ for value in rewards+ )+ ):+ raise RuntimeError("online reward endpoint returned invalid rewards")+ return [float(value) for value in rewards]+++def _numeric_metrics(raw: Any) -> dict[str, float]:+ if not hasattr(raw, "items"):+ raise RuntimeError("actor metrics are not a mapping")+ result: dict[str, float] = {}+ for name, value in raw.items():+ values = value if isinstance(value, list) else [value]+ numeric = []+ for item in values:+ if hasattr(item, "value"):+ item = item.value+ if hasattr(item, "item"):+ item = item.item()+ if isinstance(item, (int, float)) and not isinstance(item, bool):+ numeric.append(float(item))+ if numeric:+ result[str(name)] = math.fsum(numeric) / len(numeric)+ required = ("pg_loss", "ppo_kl", "clipfrac", "grad_norm")+ if not all(any(fragment in name for name in result) for fragment in required):+ raise RuntimeError(f"actor metrics are missing required values: {sorted(result)}")+ return result+++@dataclass+class Timing:+ """Accumulated phase timings for one committed update."""++ rollout_generation_seconds: float = 0.0+ rollout_sleep_seconds: float = 0.0+ scoring_seconds: float = 0.0+ actor_update_seconds: float = 0.0+ weight_sync_seconds: float = 0.0+ pre_update_log_prob_seconds: float = 0.0+ observation_seconds: float = 0.0+ probe_seconds: float = 0.0+++class OnlineGRPORuntime:+ def __init__(+ self,+ *,+ run_spec_path: Path,+ model_path: Path,+ tokenizer_path: Path,+ runtime_dir: Path,+ result_dir: Path,+ control_socket: Path,+ ) -> None:+ self.run_spec_path = run_spec_path+ self.model_path = model_path+ self.tokenizer_path = tokenizer_path+ self.runtime_dir = runtime_dir+ self.result_dir = result_dir+ self.control_path = control_socket+ self.run_spec = json.loads(run_spec_path.read_text(encoding="utf-8"))+ self.action = str(self.run_spec.get("action", "measurement"))+ if self.action not in {"smoke", "correctness", "measurement", "restart"}:+ raise RuntimeError(f"unsupported run action: {self.action}")+ self.restart_checkpoint = self.run_spec.get("restart_checkpoint")+ self.channel = ControlChannel(control_socket)+ self.checkpoint_root = runtime_dir.parent / "checkpoints"+ self.update8_dir = self.checkpoint_root / "update-8"++ # -- lifecycle ------------------------------------------------------------------++ def start(self) -> int:+ _enable_fault_handler()+ # Connect before building anything: if construction fails the host sees a+ # closed control connection instead of waiting on its accept() timeout.+ self.channel.connect(timeout=600.0)+ _log(f"action={self.action} building workers")+ self._build()+ try:+ self.channel.send({"type": "ready"})+ while True:+ message = self.channel.recv()+ kind = message.get("type")+ if kind == "start":+ self._run(message)+ self.channel.send({"type": "completed"})+ elif kind == "probe":+ if message.get("kind") != "freshness":+ raise RuntimeError(f"unsupported probe kind: {message.get('kind')}")+ self.channel.send(self._final_probe(message["request"]))+ elif kind == "shutdown":+ break+ else:+ raise RuntimeError(f"unexpected control message: {kind}")+ finally:+ self._teardown()+ self.channel.close()+ return 0++ # -- construction ---------------------------------------------------------------++ def _build(self) -> None:+ import ray+ from hydra import compose, initialize_config_dir+ from omegaconf import open_dict++ source_root = Path(__file__).resolve().parents[3]+ config_dir = source_root / "verl/trainer/config"+ with initialize_config_dir(version_base=None, config_dir=str(config_dir)):+ config = compose(config_name="ppo_trainer", overrides=["actor_rollout_ref.rollout.name=vllm"])+ free_cache = _knob("GRPO_RT_FREE_CACHE")+ with open_dict(config):+ config.trainer.n_gpus_per_node = 2+ config.trainer.nnodes = 1+ config.trainer.logger = ["console"]+ config.actor_rollout_ref.model.path = str(self.model_path)+ config.actor_rollout_ref.model.tokenizer_path = str(self.tokenizer_path)+ config.actor_rollout_ref.model.enable_gradient_checkpointing = _knob("GRPO_RT_GRAD_CKPT")+ config.actor_rollout_ref.model.use_remove_padding = True+ config.actor_rollout_ref.actor.strategy = "fsdp2"+ config.actor_rollout_ref.actor.ppo_mini_batch_size = PROMPT_GROUPS_PER_UPDATE * RESPONSES_PER_PROMPT+ config.actor_rollout_ref.actor.ppo_micro_batch_size = None+ config.actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu = None+ config.actor_rollout_ref.actor.ppo_max_token_len_per_gpu = _knob("GRPO_RT_TOKEN_BUDGET")+ config.actor_rollout_ref.actor.use_dynamic_bsz = True+ config.actor_rollout_ref.actor.use_torch_compile = False+ config.actor_rollout_ref.actor.ppo_epochs = 1+ config.actor_rollout_ref.actor.shuffle = False+ config.actor_rollout_ref.actor.loss_agg_mode = "token-mean"+ config.actor_rollout_ref.actor.entropy_coeff = 0.0+ config.actor_rollout_ref.actor.calculate_entropy = False+ config.actor_rollout_ref.actor.use_kl_loss = False+ config.actor_rollout_ref.actor.clip_ratio = 0.2+ config.actor_rollout_ref.actor.clip_ratio_low = 0.2+ config.actor_rollout_ref.actor.clip_ratio_high = 0.2+ config.actor_rollout_ref.actor.optim.lr = 0.000001+ config.actor_rollout_ref.actor.optim.weight_decay = 0.01+ config.actor_rollout_ref.actor.optim.betas = [0.9, 0.999]+ config.actor_rollout_ref.actor.optim.clip_grad = 1.0+ config.actor_rollout_ref.actor.optim.total_training_steps = COMMITTED_UPDATES+ config.actor_rollout_ref.actor.fsdp_config.strategy = "fsdp2"+ config.actor_rollout_ref.actor.fsdp_config.fsdp_size = _knob("GRPO_RT_FSDP_SIZE")+ config.actor_rollout_ref.actor.fsdp_config.forward_only = False+ config.actor_rollout_ref.actor.fsdp_config.model_dtype = "fp32"+ config.actor_rollout_ref.actor.fsdp_config.dtype = "bfloat16"+ config.actor_rollout_ref.actor.fsdp_config.param_offload = False+ config.actor_rollout_ref.actor.fsdp_config.optimizer_offload = False+ config.actor_rollout_ref.actor.fsdp_config.offload_policy = False+ config.actor_rollout_ref.actor.fsdp_config.use_torch_compile = False+ rollout = config.actor_rollout_ref.rollout+ rollout.name = "vllm"+ rollout.mode = "async"+ rollout.nnodes = 1+ rollout.n_gpus_per_node = 2+ rollout.tensor_model_parallel_size = _knob("GRPO_RT_ROLLOUT_TP")+ rollout.data_parallel_size = 1+ rollout.pipeline_model_parallel_size = 1+ rollout.prompt_length = MAX_PROMPT_TOKENS+ rollout.response_length = MAX_RESPONSE_TOKENS+ rollout.max_model_len = MAX_PROMPT_TOKENS + MAX_RESPONSE_TOKENS+ # A resident rollout engine only needs a small KV cache footprint;+ # a sleeping engine is sized by the trainer's peak instead.+ rollout.gpu_memory_utilization = 0.60 if free_cache else _knob("GRPO_RT_GPU_MEM_UTIL")+ rollout.free_cache_engine = free_cache+ rollout.max_num_seqs = _knob("GRPO_RT_MAX_NUM_SEQS")+ rollout.max_num_batched_tokens = _knob("GRPO_RT_MAX_BATCHED_TOKENS")+ rollout.enable_chunked_prefill = True+ rollout.enable_prefix_caching = True+ rollout.skip_tokenizer_init = False+ rollout.disable_log_stats = not _knob("GRPO_RT_LOG_STATS")+ rollout.load_format = "dummy"+ rollout.log_prob_use_dynamic_bsz = True+ rollout.log_prob_max_token_len_per_gpu = _knob("GRPO_RT_LOGPROB_TOKEN_BUDGET")+ rollout.log_prob_micro_batch_size = None+ rollout.log_prob_micro_batch_size_per_gpu = None+ rollout.checkpoint_engine.backend = "naive"+ rollout.checkpoint_engine.update_weights_bucket_megabytes = _knob("GRPO_RT_SYNC_BUCKET_MB")+ rollout.checkpoint_engine.engine_kwargs = {}+ self.config = config+ self.free_cache = free_cache++ from transformers import AutoTokenizer++ tokenizer = AutoTokenizer.from_pretrained(+ self.tokenizer_path, local_files_only=True, trust_remote_code=True+ )+ if tokenizer.pad_token_id is None:+ tokenizer.pad_token_id = tokenizer.eos_token_id+ self.tokenizer = tokenizer+ # Imported once here so no import happens inside the timed loop.+ from verl.utils import tensordict_utils as _tu_module++ self._tu_module = _tu_module++ # Ray opens AF_UNIX sockets inside its temp dir, so the path has to stay+ # well below the 107 byte kernel limit.+ temp_root = Path("/tmp") / f"vr-rt-{hashlib.sha256(str(self.runtime_dir).encode()).hexdigest()[:10]}"+ temp_root.mkdir(parents=True, exist_ok=True)+ self._ray_temp = temp_root+ ray.init(+ include_dashboard=False,+ _temp_dir=str(temp_root),+ runtime_env={+ "env_vars": {+ "TOKENIZERS_PARALLELISM": "false",+ "RAY_EXPERIMENTAL_NOSET_CUDA_VISIBLE_DEVICES": "1",+ "RAY_EXPERIMENTAL_NOSET_ASCEND_RT_VISIBLE_DEVICES": "1",+ "VLLM_USE_V1": "1",+ "HCCL_CONNECT_TIMEOUT": "1500",+ "HCCL_NPU_SOCKET_PORT_RANGE": os.environ.get(+ "HCCL_NPU_SOCKET_PORT_RANGE", "61000-61050"+ ),+ }+ },+ )++ from verl.checkpoint_engine import CheckpointEngineManager+ from verl.single_controller.ray import RayClassWithInitArgs, RayWorkerGroup+ from verl.single_controller.ray.base import create_colocated_worker_cls+ from verl.trainer.ppo.ray_trainer import ResourcePoolManager, Role+ from verl.utils import omega_conf_to_dataclass+ from verl.utils.device import get_device_name++ self._checkpoint_manager_cls = CheckpointEngineManager+ self._omega_conf_to_dataclass = omega_conf_to_dataclass+ self._get_device_name = get_device_name++ pool_id = "colocated_pool"+ actor_role = Role.ActorRollout+ role_name = str(actor_role)+ pool_manager = ResourcePoolManager(resource_pool_spec={pool_id: [2]}, mapping={actor_role: pool_id})+ pool_manager.create_resource_pool()+ actor_cls = RayClassWithInitArgs(+ cls=ray.remote(self._worker_class()),+ config=config.actor_rollout_ref,+ role=role_name,+ )+ colocated_cls = create_colocated_worker_cls(class_dict={role_name: actor_cls})+ self.actor_group = RayWorkerGroup(+ resource_pool=pool_manager.get_resource_pool(actor_role),+ ray_cls_with_init=colocated_cls,+ device_name=get_device_name(),+ ).spawn(prefix_set={role_name})[role_name]+ self.actor_group.init_model()++ self.rollout_tp = int(rollout.tensor_model_parallel_size)+ self.world_size = 2+ self.replicas_per_run = self.world_size // self.rollout_tp++ checkpoint_reloaded = self.action == "restart"+ self.checkpoint_reloaded = checkpoint_reloaded+ internal_dir = self.update8_dir / "internal" if checkpoint_reloaded else None+ if checkpoint_reloaded:+ state = self._load_runtime_state()+ if internal_dir is None or not internal_dir.is_dir():+ raise RuntimeError("update-eight actor checkpoint is unavailable")+ self.actor_group.load_checkpoint(str(internal_dir))+ else:+ state = {"actor_version": 0}+ self.initial_actor_version = int(state["actor_version"])++ self.initial_projection = self._aggregate_projection(self.actor_group.policy_projection())+ self.device_observations = {+ "actor": self._worker_results(self.actor_group.device_observation(), expected=2),+ }++ from verl.workers.rollout.llm_server import LLMServerManager++ self.llm_server_manager = LLMServerManager.create(+ config=config,+ worker_group=self.actor_group,+ rollout_resource_pool=pool_manager.get_resource_pool(actor_role),+ )+ self.rollout_replicas = self.llm_server_manager.get_replicas()+ if len(self.rollout_replicas) != self.replicas_per_run:+ raise RuntimeError(f"rollout created {len(self.rollout_replicas)} replicas")+ self.rollout_workers = [worker for replica in self.rollout_replicas for worker in replica.workers]+ if len(self.rollout_workers) != 2:+ raise RuntimeError("rollout did not place exactly two workers")++ import ray as _ray++ self.device_observations["rollout"] = list(+ _ray.get([worker.execute_with_func_generator.remote(self._observe_rollout_device)+ for worker in self.rollout_workers])+ )++ self.checkpoint_manager = CheckpointEngineManager(+ config=omega_conf_to_dataclass(rollout.checkpoint_engine),+ trainer=self.actor_group,+ replicas=self.rollout_replicas,+ )+ # The rollout model is materialised with dummy weights, so the initial+ # policy always has to be pushed once before the first generation.+ self.checkpoint_manager.sleep_replicas()+ self.checkpoint_manager.update_weights(global_steps=self.initial_actor_version)+ self.client = self.llm_server_manager.get_client()+ _log("workers ready")++ @staticmethod+ def _observe_rollout_device(worker) -> dict[str, Any]:+ import os++ import torch++ return {+ "role": "rollout",+ "current_device": int(torch.npu.current_device()),+ "visible_devices": os.environ.get("ASCEND_RT_VISIBLE_DEVICES", "not set"),+ }++ def _worker_class(self):+ from verl.single_controller.base.decorator import Dispatch, register+ from verl.workers.engine_workers import ActorRolloutRefWorker++ runtime = self++ class ObservedActorWorker(ActorRolloutRefWorker):+ @register(dispatch_mode=Dispatch.ONE_TO_ALL)+ def synchronize(self):+ import torch++ torch.npu.synchronize()+ return True++ @register(dispatch_mode=Dispatch.ONE_TO_ALL)+ def policy_projection(self):+ import torch++ parameter_count = 0+ tensor_count = 0+ picked_tensors = []+ weights: list[float] = []+ for ordinal, parameter in enumerate(self.actor.engine.module.parameters()):+ local = parameter.detach()+ if hasattr(local, "to_local"):+ local = local.to_local()+ flat = local.reshape(-1)+ parameter_count += flat.numel()+ tensor_count += 1+ if flat.numel():+ positions = sorted({0, flat.numel() // 2, flat.numel() - 1})+ picked_tensors.append(+ flat[torch.tensor(positions, device=flat.device)].float().reshape(-1)+ )+ weights.extend(((ordinal + position) % 31 + 1) / 31 for position in positions)+ # One packed device->host copy keeps the observation cheap; the+ # reported value is exactly the reference arithmetic.+ picks = torch.cat(picked_tensors).cpu().tolist() if picked_tensors else []+ return {+ "value": math.fsum(value * scale for value, scale in zip(picks, weights, strict=True)),+ "logical_parameter_count": parameter_count,+ "parameter_tensor_count": tensor_count,+ }++ @register(dispatch_mode=Dispatch.ONE_TO_ALL)+ def state_dtypes(self):+ import torch++ parameter_dtypes: dict[str, int] = {}+ optimizer_dtypes: dict[str, int] = {}+ for parameter in self.actor.engine.module.parameters():+ name = str(parameter.dtype).removeprefix("torch.")+ parameter_dtypes[name] = parameter_dtypes.get(name, 0) + parameter.numel()+ for state in self.actor.engine.optimizer.state.values():+ for value in state.values():+ if isinstance(value, torch.Tensor):+ name = str(value.dtype).removeprefix("torch.")+ optimizer_dtypes[name] = optimizer_dtypes.get(name, 0) + value.numel()+ return {"parameters": parameter_dtypes, "optimizer": optimizer_dtypes}++ @register(dispatch_mode=Dispatch.ONE_TO_ALL)+ def device_observation(self):+ import os++ import torch++ return {+ "role": "actor",+ "current_device": int(torch.npu.current_device()),+ "visible_devices": os.environ.get("ASCEND_RT_VISIBLE_DEVICES", "not set"),+ }++ @register(dispatch_mode=Dispatch.ONE_TO_ALL)+ def export_portable_actor(self, target_dir: str, dtypes: dict[str, str], shards: int):+ from safetensors.torch import save_file+ from torch.distributed.tensor import DTensor++ from verl.utils.model import convert_weight_keys++ module = self.actor.engine.module+ params = convert_weight_keys(module.state_dict(), getattr(module, "_fsdp_wrapped_module", module))+ ordered: list[tuple[str, Any]] = []+ for name, param in params.items():+ dtype = _SAFETENSORS_TO_TORCH.get(dtypes.get(name))+ if dtype is None:+ continue+ tensor = param.full_tensor() if isinstance(param, DTensor) else param+ tensor = tensor.detach().to(_torch_dtype(dtype)).contiguous().cpu()+ ordered.append((name, tensor))+ del params+ if not ordered:+ raise RuntimeError("portable actor export produced no tensors")+ limit = math.ceil(len(ordered) / shards)+ for shard in range(shards):+ chunk = dict(ordered[shard * limit : (shard + 1) * limit])+ if not chunk:+ continue+ if self.rank == 0:+ save_file(chunk, str(Path(target_dir) / f"model-{shard:05d}-of-{shards:05d}.safetensors"))+ return len(ordered)++ return ObservedActorWorker++ # -- run ------------------------------------------------------------------------++ def _run(self, message: dict[str, Any]) -> None:+ started = time.monotonic()+ prompt_path = Path(str(message["prompt_path"]))+ endpoint = message["reward_endpoint"]+ self.reward_endpoint = (str(endpoint["url"]).rstrip("/"), str(endpoint["token"]))+ self._prepare_prompts(prompt_path)+ result = self._train_loop()+ _log(f"gates: {result.get('gates')}")+ _log(+ "freshness: "+ + json.dumps(+ [+ {+ "version": probe["policy_version"],+ "reported": probe["rollout_reported_version"],+ "delta": probe["max_abs_logprob_difference"],+ }+ for probe in result.get("freshness_probes", [])+ ]+ )+ )+ result["end_to_end_seconds"] = time.monotonic() - started+ self.result_dir.mkdir(parents=True, exist_ok=True)+ (self.result_dir / "run-result.json").write_text(+ json.dumps(result, allow_nan=False, indent=2, sort_keys=True) + "\n", encoding="utf-8"+ )+ self.final_policy_version = result["policy_versions"][-1]["actor_after"]++ def _prepare_prompts(self, prompt_path: Path) -> None:+ import numpy as np++ prompt_asset = json.loads(prompt_path.read_text(encoding="utf-8"))+ prompt_records = prompt_asset["prompts"]+ self.system_prompt = prompt_asset["system_prompt"]+ self.base_seed = int(prompt_asset.get("seed", 20260817))+ if self.action == "smoke":+ prompt_records = prompt_records[:1]+ self.committed_updates = 1+ elif self.action == "restart":+ prompt_records = prompt_records[-PROMPT_GROUPS_PER_UPDATE:]+ self.committed_updates = 1+ else:+ self.committed_updates = COMMITTED_UPDATES++ tokenizer = self.tokenizer++ encoded = []+ for item in prompt_records:+ token_ids = tokenizer.apply_chat_template(+ [+ {"role": "system", "content": prompt_asset["system_prompt"]},+ {"role": "user", "content": item["question"]},+ ],+ tokenize=True,+ add_generation_prompt=True,+ enable_thinking=False,+ )+ if isinstance(token_ids, Mapping):+ token_ids = token_ids["input_ids"]+ if len(token_ids) > MAX_PROMPT_TOKENS:+ raise RuntimeError(f"prompt {item['id']} exceeds {MAX_PROMPT_TOKENS} tokens")+ encoded.append({**item, "token_ids": list(token_ids)})+ if self.action in {"smoke", "restart"}:+ self.prompt_batches = [encoded]+ else:+ if len(encoded) != 64:+ raise RuntimeError("a full run requires 64 distinct prompt groups")+ self.prompt_batches = [+ encoded[index : index + PROMPT_GROUPS_PER_UPDATE]+ for index in range(0, 64, PROMPT_GROUPS_PER_UPDATE)+ ]+ self.np = np++ def _generate_batch(self, batch_ordinal: int, policy_version: int):+ async def generate():+ requests = []+ metadata = []+ prompt_batch = self.prompt_batches[(batch_ordinal - 1) % len(self.prompt_batches)]+ for prompt_ordinal, prompt in enumerate(prompt_batch):+ for response_ordinal in range(RESPONSES_PER_PROMPT):+ seed = (+ self.base_seed+ + batch_ordinal * 100000+ + policy_version * 10000+ + prompt_ordinal * RESPONSES_PER_PROMPT+ + response_ordinal+ )+ request_id = f"b{batch_ordinal}-v{policy_version}-{prompt['id']}-{response_ordinal}"+ requests.append(+ self.client.generate(+ request_id,+ prompt_ids=prompt["token_ids"],+ sampling_params={+ "temperature": TEMPERATURE,+ "top_p": TOP_P,+ "top_k": TOP_K,+ "max_tokens": MAX_RESPONSE_TOKENS,+ "logprobs": True,+ "seed": seed,+ },+ )+ )+ metadata.append((prompt_ordinal, prompt, response_ordinal, seed))+ return metadata, await asyncio.gather(*requests), prompt_batch++ return asyncio.run(generate())++ def _build_batch(self, generated):+ from tensordict import TensorDict+ import torch++ from verl.utils import tensordict_utils as tu+ from verl.workers.utils.padding import left_right_2_no_padding++ metadata, outputs, prompt_batch = generated+ rows = []+ group_rewards: dict[int, list[float]] = {index: [] for index in range(len(prompt_batch))}+ group_texts: dict[int, list[str]] = {index: [] for index in range(len(prompt_batch))}+ policy_versions = set()+ decoded = []+ for (prompt_ordinal, prompt, response_ordinal, seed), output in zip(metadata, outputs, strict=True):+ if output.stop_reason != "completed" or not output.token_ids:+ raise RuntimeError(f"rollout {prompt['id']}/{response_ordinal} did not complete")+ if output.log_probs is None or len(output.log_probs) != len(output.token_ids):+ raise RuntimeError("rollout logprobs are incomplete")+ policy_versions.add(output.extra_fields.get("global_steps"))+ text = self.tokenizer.decode(output.token_ids, skip_special_tokens=True)+ decoded.append((prompt_ordinal, prompt, response_ordinal, seed, output, text))+ rewards = _score_responses(+ self.reward_endpoint,+ [(str(prompt["id"]), text) for _, prompt, _, _, _, text in decoded],+ )+ for (+ prompt_ordinal,+ prompt,+ response_ordinal,+ seed,+ output,+ text,+ ), reward in zip(decoded, rewards, strict=True):+ group_rewards[prompt_ordinal].append(reward)+ group_texts[prompt_ordinal].append(text)+ rows.append(+ {+ "prompt_ordinal": prompt_ordinal,+ "prompt_id": prompt["id"],+ "response_ordinal": response_ordinal,+ "seed": seed,+ "prompt_ids": prompt["token_ids"],+ "response_ids": list(output.token_ids),+ "old_log_probs": list(output.log_probs),+ "reward": reward,+ }+ )+ if len(policy_versions) != 1 or next(iter(policy_versions)) is None:+ raise RuntimeError(f"rollout policy version is ambiguous: {policy_versions}")+ advantages: dict[int, list[float]] = {}+ for group, group_values in group_rewards.items():+ mean = float(self.np.mean(group_values))+ std = float(self.np.std(group_values, ddof=1))+ advantages[group] = (+ [0.0] * len(group_values)+ if std == 0+ else [(reward - mean) / (std + 1e-6) for reward in group_values]+ )+ for row in rows:+ row["advantage"] = advantages[row["prompt_ordinal"]][row["response_ordinal"]]++ prompt_width = max(len(row["prompt_ids"]) for row in rows)+ response_width = max(len(row["response_ids"]) for row in rows)+ pad = self.tokenizer.pad_token_id+ input_ids, attention_mask, position_ids, responses, response_mask = [], [], [], [], []+ old_log_probs, advantage_values, prompts = [], [], []+ for row in rows:+ prompt_padding = prompt_width - len(row["prompt_ids"])+ response_padding = response_width - len(row["response_ids"])+ prompt_row = [pad] * prompt_padding + row["prompt_ids"]+ response_row = row["response_ids"] + [pad] * response_padding+ mask = (+ [0] * prompt_padding+ + [1] * len(row["prompt_ids"])+ + [1] * len(row["response_ids"])+ + [0] * response_padding+ )+ positions = []+ position = 0+ for active in mask:+ positions.append(position if active else 0)+ if active:+ position += 1+ prompts.append(prompt_row)+ responses.append(response_row)+ input_ids.append(prompt_row + response_row)+ attention_mask.append(mask)+ position_ids.append(positions)+ response_mask.append([1] * len(row["response_ids"]) + [0] * response_padding)+ old_log_probs.append(row["old_log_probs"] + [0.0] * response_padding)+ advantage_values.append([row["advantage"]] * len(row["response_ids"]) + [0.0] * response_padding)+ padded = TensorDict(+ {+ "input_ids": torch.tensor(input_ids, dtype=torch.long),+ "attention_mask": torch.tensor(attention_mask, dtype=torch.bool),+ "position_ids": torch.tensor(position_ids, dtype=torch.long),+ "prompts": torch.tensor(prompts, dtype=torch.long),+ "responses": torch.tensor(responses, dtype=torch.long),+ "response_mask": torch.tensor(response_mask, dtype=torch.bool),+ "old_log_probs": torch.tensor(old_log_probs, dtype=torch.float32),+ "advantages": torch.tensor(advantage_values, dtype=torch.float32),+ },+ batch_size=[len(rows)],+ )+ batch = left_right_2_no_padding(padded.clone())+ tu.assign_non_tensor(+ batch,+ calculate_entropy=False,+ compute_loss=True,+ temperature=TEMPERATURE,+ global_batch_size=len(rows),+ mini_batch_size=len(rows),+ epochs=1,+ seed=self.base_seed,+ dataloader_kwargs={"shuffle": False},+ )+ observation = {+ "policy_version": int(next(iter(policy_versions))),+ "prompt_ids": [prompt["id"] for prompt in prompt_batch],+ "rewards": [group_rewards[index] for index in range(len(prompt_batch))],+ "advantages": [advantages[index] for index in range(len(prompt_batch))],+ "response_lengths": [len(row["response_ids"]) for row in rows],+ "response_texts": [group_texts[index] for index in range(len(prompt_batch))],+ "consumed_response_tokens": sum(len(row["response_ids"]) for row in rows),+ "nonzero_advantage_groups": sum(+ any(abs(value) > 0 for value in values) for values in advantages.values()+ ),+ "trajectories": [+ {+ "prompt_id": row["prompt_id"],+ "response_ordinal": row["response_ordinal"],+ "seed": row["seed"],+ "response_ids": row["response_ids"],+ "old_log_probs": row["old_log_probs"],+ "response_text": group_texts[row["prompt_ordinal"]][row["response_ordinal"]],+ "reward": row["reward"],+ "advantage": row["advantage"],+ }+ for row in rows+ ],+ }+ return batch, padded, observation++ def _actor_log_probs(self, padded):+ import torch++ from verl.utils import tensordict_utils as tu+ from verl.workers.utils.padding import left_right_2_no_padding, no_padding_2_padding++ batch = left_right_2_no_padding(padded.clone())+ tu.assign_non_tensor(+ batch, calculate_entropy=False, compute_loss=False, temperature=TEMPERATURE+ )+ output = self.actor_group.compute_log_prob(batch)+ return no_padding_2_padding(tu.get(output, "log_probs"), batch).float().cpu()++ def _train_loop(self) -> dict[str, Any]:+ observations: dict[str, Any] = {"initial": {"parameter_projection": self.initial_projection}}+ freshness_probes = []+ step_metrics = []+ policy_versions = []+ trajectory_records = []+ total_tokens = 0+ accepted_trajectories = 0+ sync_count = 0+ state_dtypes = None+ current_actor_version = self.initial_actor_version+ timing = Timing()++ def sleep_rollout():+ started = time.monotonic()+ self.checkpoint_manager.sleep_replicas()+ return time.monotonic() - started++ if not self.free_cache:+ # A resident engine needs no sleep/wake handshake at all.+ sleep_rollout = lambda: 0.0++ generation_started = time.monotonic()+ generated = self._generate_batch(1, current_actor_version)+ timing.rollout_generation_seconds = time.monotonic() - generation_started+ for update in range(1, self.committed_updates + 1):+ _log(f"update {update}: start (rollout generated {timing.rollout_generation_seconds:.1f}s)")+ timing.rollout_sleep_seconds = sleep_rollout()+ scoring_started = time.monotonic()+ batch, padded, trajectory_observation = self._build_batch(generated)+ timing.scoring_seconds = time.monotonic() - scoring_started+ if self.action in {"correctness", "restart"}:+ pre_started = time.monotonic()+ pre_update_log_probs = self._actor_log_probs(padded)+ timing.pre_update_log_prob_seconds = time.monotonic() - pre_started+ for row_index, row in enumerate(trajectory_observation["trajectories"]):+ response_length = len(row["response_ids"])+ row["new_log_probs"] = [+ float(value)+ for value in pre_update_log_probs[row_index, :response_length].tolist()+ ]+ trajectory_version = trajectory_observation["policy_version"]+ lag = current_actor_version - trajectory_version+ if lag < 0 or lag > 1:+ raise RuntimeError(f"trajectory policy lag {lag} is outside [0, 1]")+ total_tokens += trajectory_observation["consumed_response_tokens"]+ trajectory_records.extend({"update": update, **row} for row in trajectory_observation["trajectories"])+ update_trajectories = (+ len(self.prompt_batches[(update - 1) % len(self.prompt_batches)]) * RESPONSES_PER_PROMPT+ )+ accepted_trajectories += update_trajectories++ self.actor_group.synchronize()+ actor_started = time.monotonic()+ actor_output = self.actor_group.update_actor(batch)+ self.actor_group.synchronize()+ timing.actor_update_seconds = time.monotonic() - actor_started+ _log(f"update {update}: actor {timing.actor_update_seconds:.1f}s")+ metrics = _numeric_metrics(self._tu_module.get(actor_output, "metrics"))+ _log(f"update {update}: metrics {sorted(metrics)[:3]}")+ if update == 1:+ state_dtypes = self._aggregate_state_dtypes(self.actor_group.state_dtypes())+ _log("state dtypes observed")+ current_actor_version += 1++ sync_started = time.monotonic()+ _log(f"update {update}: weight sync start (version {current_actor_version})")+ self.checkpoint_manager.update_weights(global_steps=current_actor_version)+ timing.weight_sync_seconds = time.monotonic() - sync_started+ sync_count += 1+ _log(f"update {update}: weight sync {timing.weight_sync_seconds:.1f}s")++ if update in {1, self.committed_updates}:+ probe_started = time.monotonic()+ probe = self._freshness_probe(current_actor_version)+ probe["seconds"] = time.monotonic() - probe_started+ freshness_probes.append(probe)++ observation_updates = (+ {1} if self.action in {"smoke", "restart"} else set(OBSERVATION_UPDATES)+ )+ if update in observation_updates:+ observation_started = time.monotonic()+ probe_rows = min(_knob("GRPO_RT_PROBE_ROWS"), padded.batch_size[0])+ current_log_probs = self._actor_log_probs(padded[:probe_rows])+ probe_positions = []+ for row in range(probe_rows):+ length = int(padded["response_mask"][row].sum())+ positions = sorted({0, length // 2, length - 1})+ probe_positions.append(+ [float(current_log_probs[row, position]) for position in positions]+ )+ observations[str(update)] = {+ "trajectory": trajectory_observation,+ "actor_metrics": metrics,+ "parameter_projection": self._aggregate_projection(+ self.actor_group.policy_projection()+ ),+ "selected_log_probs": probe_positions,+ }+ timing.observation_seconds = time.monotonic() - observation_started++ step_metrics.append(+ {+ "update": update,+ "trajectory_policy_version": trajectory_version,+ "actor_version_before_update": current_actor_version - 1,+ "actor_version_after_update": current_actor_version,+ "policy_lag": lag,+ "consumed_response_tokens": trajectory_observation["consumed_response_tokens"],+ "accepted_trajectories": update_trajectories,+ "scoring_seconds": timing.scoring_seconds,+ "rollout_generation_seconds": timing.rollout_generation_seconds,+ "rollout_sleep_seconds": timing.rollout_sleep_seconds,+ "actor_update_seconds": timing.actor_update_seconds,+ "weight_sync_seconds": timing.weight_sync_seconds,+ "pre_update_log_prob_seconds": timing.pre_update_log_prob_seconds,+ "observation_seconds": timing.observation_seconds,+ "freshness_probe_seconds": timing.probe_seconds,+ "actor_metrics": metrics,+ "nonzero_advantage_groups": trajectory_observation["nonzero_advantage_groups"],+ }+ )+ policy_versions.append(+ {+ "update": update,+ "trajectory": trajectory_version,+ "actor_before": current_actor_version - 1,+ "actor_after": current_actor_version,+ "rollout_after_sync": current_actor_version,+ "lag": lag,+ }+ )+ if update < self.committed_updates:+ generation_started = time.monotonic()+ generated = self._generate_batch(update + 1, current_actor_version)+ timing.rollout_generation_seconds = time.monotonic() - generation_started+ timing.rollout_sleep_seconds = sleep_rollout()++ self.current_actor_version = current_actor_version+ saved_checkpoint = None+ portable_actor_path = None+ if self.action == "correctness":+ saved_checkpoint, portable_actor_path = self._save_checkpoint()++ expected_trajectories = sum(len(batch) * RESPONSES_PER_PROMPT for batch in self.prompt_batches)+ final_projection = observations[str(self.committed_updates)]["parameter_projection"]+ freshness_valid = all(+ probe["rollout_reported_version"] == probe["policy_version"]+ and probe["max_abs_logprob_difference"] <= 0.5+ for probe in freshness_probes+ )+ metrics_finite = (+ len(step_metrics) > 0+ and all(+ item["actor_metrics"]+ and all(math.isfinite(value) for value in item["actor_metrics"].values())+ and item["actor_update_seconds"] > 0+ and item["weight_sync_seconds"] > 0+ for item in step_metrics+ )+ and set(state_dtypes["parameters"]) == {"float32"}+ and set(state_dtypes["optimizer"]).issubset({"float32"})+ and bool(state_dtypes["optimizer"])+ )+ observation_updates = {"1"} if self.action in {"smoke", "restart"} else set(+ str(update) for update in OBSERVATION_UPDATES+ )+ gates = {+ "actor_initialized": True,+ "rollout_initialized": True,+ "rollouts_complete": accepted_trajectories == expected_trajectories,+ "reward_advantage_valid": all(+ math.isfinite(value)+ for key in observation_updates+ for group in observations[str(key)]["trajectory"]["advantages"]+ for value in group+ ),+ "updates_complete": len(step_metrics) == self.committed_updates,+ "weights_synced": sync_count == self.committed_updates,+ "policy_lag_valid": all(0 <= item["lag"] <= 1 for item in policy_versions),+ "freshness_valid": freshness_valid,+ "parameters_changed": final_projection["value"] != self.initial_projection["value"],+ "metrics_finite": metrics_finite,+ "observations_complete": observation_updates.issubset(observations)+ and len(freshness_probes) == (1 if self.action in {"smoke", "restart"} else 2),+ }+ return {+ "schema_version": 1,+ "kind": "online_grpo_worker",+ "action": self.action,+ "status": "passed" if all(gates.values()) else "failed",+ "gates": gates,+ "committed_updates": self.committed_updates,+ "accepted_trajectories": accepted_trajectories,+ "consumed_response_tokens": total_tokens,+ "trajectory_records": trajectory_records,+ "end_to_end_seconds": 0.0,+ "policy_versions": policy_versions,+ "step_metrics": step_metrics,+ "observations": observations,+ "freshness_probes": freshness_probes,+ "device_observations": self.device_observations,+ "logical_parameter_count": self.initial_projection["logical_parameter_count"],+ "parameter_tensor_count": self.initial_projection["parameter_tensor_count"],+ "state_dtypes": state_dtypes,+ "checkpoint_path": saved_checkpoint,+ "checkpoint_reloaded": self.checkpoint_reloaded,+ "portable_actor_path": portable_actor_path,+ "runtime_layout": {+ "activation_checkpointing": _knob("GRPO_RT_GRAD_CKPT"),+ "actor_world_size": 2,+ "actor_strategy": "fsdp2",+ "dynamic_batching": True,+ "enable_chunked_prefill": True,+ "gpu_memory_utilization": float(self.config.actor_rollout_ref.rollout.gpu_memory_utilization),+ "free_cache_engine": self.free_cache,+ "log_prob_max_tokens_per_microbatch": _knob("GRPO_RT_LOGPROB_TOKEN_BUDGET"),+ "max_num_batched_tokens": _knob("GRPO_RT_MAX_BATCHED_TOKENS"),+ "max_num_seqs": _knob("GRPO_RT_MAX_NUM_SEQS"),+ "max_tokens_per_microbatch": _knob("GRPO_RT_TOKEN_BUDGET"),+ "optimizer_offload": False,+ "parameter_offload": False,+ "remove_padding": True,+ "rollout_tensor_parallel_size": self.rollout_tp,+ "rollout_replicas": self.replicas_per_run,+ "weight_sync_bucket_megabytes": _knob("GRPO_RT_SYNC_BUCKET_MB"),+ },+ }++ def _save_checkpoint(self):+ internal = self.update8_dir / "internal"+ internal.parent.mkdir(parents=True, exist_ok=True)+ self.actor_group.save_checkpoint(+ str(internal), global_step=self.committed_updates, max_ckpt_to_keep=1+ )+ self._write_runtime_state({"actor_version": self.current_actor_version})+ portable = self.update8_dir / "portable-actor"+ if portable.exists():+ shutil.rmtree(portable)+ portable.mkdir(parents=True, exist_ok=True)+ dtypes = self._portable_dtypes()+ count = self.actor_group.export_portable_actor(+ str(portable), dtypes, shards=min(4, max(1, len(dtypes) // 200))+ )+ if not count or not any(portable.glob("*.safetensors")):+ raise RuntimeError("portable actor export produced no weights")+ exported = set()+ for path in sorted(portable.glob("*.safetensors")):+ from safetensors import safe_open++ with safe_open(path, framework="pt", device="cpu") as handle:+ exported.update(handle.keys())+ missing = set(dtypes) - exported - {"lm_head.weight"}+ if missing:+ raise RuntimeError(f"portable actor export is incomplete: {sorted(missing)[:8]}")+ shutil.copyfile(self.model_path / "config.json", portable / "config.json")+ _log(f"checkpoint written to {self.update8_dir}")+ return str(self.update8_dir), str(portable)++ def _portable_dtypes(self) -> dict[str, str]:+ from safetensors import safe_open++ dtypes: dict[str, str] = {}+ for path in sorted(self.model_path.glob("*.safetensors")):+ with safe_open(path, framework="pt", device="cpu") as handle:+ for key in handle.keys():+ dtypes[key] = str(handle.get_slice(key).get_dtype())+ if not dtypes:+ raise RuntimeError("initial model safetensors are absent")+ return dtypes++ def _write_runtime_state(self, state: dict[str, Any]) -> None:+ self.update8_dir.mkdir(parents=True, exist_ok=True)+ (self.update8_dir / "runtime-state.json").write_text(+ json.dumps(state, indent=2, sort_keys=True) + "\n", encoding="utf-8"+ )++ def _load_runtime_state(self) -> dict[str, Any]:+ path = self.update8_dir / "runtime-state.json"+ if not path.is_file():+ return {"actor_version": 8}+ return json.loads(path.read_text(encoding="utf-8"))++ # -- probes ---------------------------------------------------------------------++ def _generate_probe(self, version: int, prompt_ids: list[int], seed: int, max_tokens: int):+ async def generate():+ return await self.client.generate(+ f"freshness-{version}",+ prompt_ids=prompt_ids,+ sampling_params={+ "temperature": TEMPERATURE,+ "top_p": TOP_P,+ "top_k": TOP_K,+ "max_tokens": max_tokens,+ "logprobs": True,+ "seed": seed,+ },+ )++ return asyncio.run(generate())++ def _probe_from_tokens(self, version: int, prompt_ids: list[int], output):+ import torch+ from tensordict import TensorDict++ if output.stop_reason != "completed" or not output.token_ids or output.log_probs is None:+ raise RuntimeError("freshness rollout did not complete with logprobs")+ prompt_width = len(prompt_ids)+ response_width = len(output.token_ids)+ replicas = 2+ padded = TensorDict(+ {+ "input_ids": torch.tensor([prompt_ids + list(output.token_ids)], dtype=torch.long).repeat(+ replicas, 1+ ),+ "attention_mask": torch.ones((replicas, prompt_width + response_width), dtype=torch.bool),+ "position_ids": torch.arange(prompt_width + response_width, dtype=torch.long)+ .unsqueeze(0)+ .repeat(replicas, 1),+ "prompts": torch.tensor([prompt_ids], dtype=torch.long).repeat(replicas, 1),+ "responses": torch.tensor([list(output.token_ids)], dtype=torch.long).repeat(replicas, 1),+ "response_mask": torch.ones((replicas, response_width), dtype=torch.bool),+ "old_log_probs": torch.tensor([list(output.log_probs)], dtype=torch.float32).repeat(+ replicas, 1+ ),+ "advantages": torch.zeros((replicas, response_width), dtype=torch.float32),+ },+ batch_size=[replicas],+ )+ actor_values = self._actor_log_probs(padded)[0, :response_width].tolist()+ rollout_values = list(output.log_probs or [])+ positions = sorted({0, len(actor_values) // 2, len(actor_values) - 1})+ selected = [+ {+ "position": position,+ "actor_log_prob": float(actor_values[position]),+ "rollout_log_prob": float(rollout_values[position]),+ }+ for position in positions+ ]+ return {+ "policy_version": version,+ "rollout_reported_version": output.extra_fields.get("global_steps"),+ "selected_log_probs": selected,+ "max_abs_logprob_difference": max(+ abs(item["actor_log_prob"] - item["rollout_log_prob"]) for item in selected+ ),+ }++ def _freshness_probe(self, version: int) -> dict[str, Any]:+ prompt = self.prompt_batches[0][0]+ output = self._generate_probe(+ version, prompt["token_ids"], self.base_seed + 81983 + version, 32+ )+ return self._probe_from_tokens(version, prompt["token_ids"], output)++ def _final_probe(self, request: dict[str, Any]) -> dict[str, Any]:+ """Live freshness probe driven by the host on an unseen prompt."""+ question = str(request["question"])+ seed = int(request["seed"])+ max_tokens = int(request.get("max_tokens", 32))+ token_ids = self.tokenizer.apply_chat_template(+ [+ {"role": "system", "content": self.system_prompt},+ {"role": "user", "content": question},+ ],+ tokenize=True,+ add_generation_prompt=True,+ enable_thinking=False,+ )+ if isinstance(token_ids, Mapping):+ token_ids = token_ids["input_ids"]+ output = self._generate_probe(self.final_policy_version, list(token_ids), seed, max_tokens)+ result = self._probe_from_tokens(self.final_policy_version, list(token_ids), output)+ self.channel_probe = result+ return {+ "type": "probe_result",+ "policy_version": result["policy_version"],+ "rollout_reported_version": result["rollout_reported_version"],+ "actor_log_probs": [item["actor_log_prob"] for item in result["selected_log_probs"]],+ "rollout_log_probs": [item["rollout_log_prob"] for item in result["selected_log_probs"]],+ "max_abs_logprob_difference": result["max_abs_logprob_difference"],+ }++ # -- misc -----------------------------------------------------------------------++ def _tu(self):+ from verl.utils import tensordict_utils++ return tensordict_utils++ def _worker_results(self, value: Any, *, expected: int) -> list[Any]:+ while isinstance(value, (list, tuple)) and len(value) == 1 and isinstance(value[0], (list, tuple)):+ value = value[0]+ if not isinstance(value, (list, tuple)) or len(value) != expected:+ raise RuntimeError(f"expected {expected} worker results")+ return list(value)++ def _aggregate_projection(self, value: Any) -> dict[str, Any]:+ workers = self._worker_results(value, expected=2)+ if not all(isinstance(item, dict) for item in workers):+ raise RuntimeError("worker parameter projections are invalid")+ return {+ "value": math.fsum(float(item["value"]) for item in workers),+ "logical_parameter_count": sum(int(item["logical_parameter_count"]) for item in workers),+ "parameter_tensor_count": sum(int(item["parameter_tensor_count"]) for item in workers),+ "worker_count": len(workers),+ }++ def _aggregate_state_dtypes(self, value: Any) -> dict[str, dict[str, int]]:+ workers = self._worker_results(value, expected=2)+ result: dict[str, dict[str, int]] = {"parameters": {}, "optimizer": {}}+ for worker in workers:+ if not isinstance(worker, dict):+ raise RuntimeError("worker state dtype observation is invalid")+ for state_kind in result:+ observed = worker.get(state_kind)+ if not isinstance(observed, dict):+ raise RuntimeError("worker state dtype observation is incomplete")+ for dtype, count in observed.items():+ result[state_kind][str(dtype)] = result[state_kind].get(str(dtype), 0) + int(count)+ return result++ def _teardown(self) -> None:+ manager = getattr(self, "checkpoint_manager", None)+ if manager is not None:+ try:+ if self.free_cache:+ manager.sleep_replicas()+ except Exception: # pragma: no cover - best effort teardown+ pass+ import ray++ if ray.is_initialized():+ ray.shutdown()+ temp = getattr(self, "_ray_temp", None)+ if temp is not None:+ shutil.rmtree(temp, ignore_errors=True)+++def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:+ parser = argparse.ArgumentParser(description="Framework-owned online GRPO runtime")+ parser.add_argument("--run-spec", required=True)+ parser.add_argument("--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)+ return parser.parse_args(argv)+++def main(argv: list[str] | None = None) -> int:+ args = _parse_args(argv)+ runtime = OnlineGRPORuntime(+ run_spec_path=Path(args.run_spec),+ model_path=Path(args.model_path),+ tokenizer_path=Path(args.tokenizer_path),+ runtime_dir=Path(args.runtime_dir),+ result_dir=Path(args.result_dir),+ control_socket=Path(args.control_socket),+ )+ try:+ return runtime.start()+ except BaseException:+ traceback.print_exc()+ try:+ runtime.result_dir.mkdir(parents=True, exist_ok=True)+ (runtime.result_dir / "run-result.json").write_text(+ json.dumps(+ {+ "schema_version": 1,+ "kind": "online_grpo_worker",+ "action": runtime.action,+ "status": "failed",+ "reason": traceback.format_exc()[-4000:],+ },+ indent=2,+ )+ + "\n",+ encoding="utf-8",+ )+ except Exception: # pragma: no cover+ pass+ return 1+++if __name__ == "__main__":+ raise SystemExit(main())