Inspect · Task requirements
Requested workspace inspection and file and log inspection related to task requirements.
1 call · #0001–#0001
echo <val>ls -l -a <val>cat <path>echo <flag>DeepSeek-V4-Pro · 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 agentDeepSeek-V4-Pro · 157 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 task requirements.
1 call · #0001–#0001
echo <val>ls -l -a <val>cat <path>echo <flag>Requested workspace inspection and file and log inspection related to reward & policy updates.
1 call · #0002–#0002
cd <val>find <path> -maxdepth <n> -type <val>sortsed -n <val>echo <flag>cat <path>Requested file and log inspection and workspace inspection related to source & workspace.
7 calls · #0003–#0009
cd <val><command> <args>cat <val>cat <path>wc -l <path>sed -n <val> <path>ls -l -a <path> <n> > <path>echo <val>ls -l -a <path>sed -n <val>Requested environment setup or inspection, source searches and file and log inspection related to task requirements.
1 call · #0010–#0010
envsortgrep -E <val>sed -n <val>echo <flag>cat <path>echohead -n <n> <path>Requested repository inspection, script or workload execution and file and log inspection related to source & workspace.
2 calls · #0011–#0012
cd <path>git status --shortgit log <flag> <args>python - <script>cd <val>bash <script>echo <val>cat <path> <n> > <path>head -n <n>Requested file and log inspection and workspace inspection related to benchmark & validation setup.
1 call · #0013–#0013
cd <val><command> <args>echo <val>tail -n <n> <path>ls -l -h <val>Requested file and log inspection, workspace inspection and runtime inspection related to device memory.
2 calls · #0014–#0015
cat <val>echols -l -a <path>find <path> -maxdepth <n> -type <val>headdu <flag> <args>npu-smi infohead -n <n>echo <val>ls -l <path>python - <script>Requested workspace file updates, script or workload execution and source searches related to source & workspace.
1 call · #0016–#0016
cd <val>cp <path> <path>python - <script>grep -n <val> <path>Requested workspace file updates, script or workload execution and execution waits related to benchmark & validation setup.
4 calls · #0017–#0020
cd <val>rm -f <path> <path>nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>echo <val>sleep <n>ps <flag>grep -E <val>grep -v <val>head -n <n>tail -n <n> <path>ls -l -a <val>rm -f <path> <path> <path>ps <flag> <args>headRequested workspace file updates, environment setup or inspection and execution waits related to task requirements.
1 call · #0021–#0021
cd <val>rm -f <path> <path> <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>sleep <n>echo <flag>tail -n <n> <path>ps <flag> <args>grep -E <val>grep -v <val>head -n <n>Requested file and log inspection, runtime inspection and source searches related to benchmark & validation setup.
5 calls · #0022–#0026
tail -n <n> <path> <n> > <path>echo <flag>ps <flag> <args>sed -n <path>grep -E <val>headsleep <n>grep -v <val>tail -n <n> <path>head -n <n>wc -lRequested process termination, execution waits and runtime inspection related to checkpoints & weight state.
1 call · #0027–#0027
kill <flag> <args>truesleep <n>pkill <flag> <args><command> <args>ps <flag> <args>grep -E <val>grep -v <val>rm -rf <path> <path> <path> <path> <path> <path>Requested file and log inspection and script or workload execution related to source & workspace.
1 call · #0028–#0028
cd <path>cat > <path> <script>timeout <n> <val> <path>Requested script or workload execution related to runtime processes.
1 call · #0029–#0029
python - <script>cd <path>Requested source searches, file and log inspection and workspace inspection related to reward & policy updates.
15 calls · #0030–#0044
cd <path>grep -R <val> -n <path> <path> <path>head -n <n>grep -R <val> -n <path>headgrep -R <val> -n <val>grep -R <val> -n <path> <path>find <val> -path <val> -type <val>sed -n <val> <path>echo <flag>find <path> -path <val> -type <val>sortls <path>find <path> -type <val> -maxdepth <n>grep -n <val> -n <path>grep -n <val> <flag> <args>Requested file and log inspection and source searches related to rollout generation.
1 call · #0045–#0045
cd <path>sed -n <val> <path>grep -R <val> -n <val>head -n <n>grep -R <val> -n <path>Requested source searches and file and log inspection related to reward & policy updates.
2 calls · #0046–#0047
cd <path>grep -R <val> -n <path> <path>head -n <n>grep -n <val> -R <path>sed -n <val> <path>grep -n <val> <flag> <args>Requested file and log inspection and source searches related to source & workspace.
2 calls · #0048–#0049
cat <path>head -n <n>cd <path>grep -R <val> -n <val>sed -n <val> <path>Requested file and log inspection and script or workload execution related to reward & policy updates.
1 call · #0050–#0050
cd <path>cat > <path> <script>timeout <n> <val> <path>Requested script or workload execution and file and log inspection related to source & workspace.
3 calls · #0051–#0053
cd <path>python - <script>sed -n <val> <path>timeout <n> <val> <path>Requested file and log inspection related to task requirements.
1 call · #0054–#0054
cat <path>sed -n <val>echo <flag>Requested workspace inspection, file and log inspection and source searches related to source & workspace.
2 calls · #0055–#0056
cd <path>find <path> -maxdepth <n> -type <val>sorthead -n <n>grep <val>headls <path> <n> > <path>echo <val>sed -n <val> <path>cd <val>Requested script or workload execution related to attention kernels.
1 call · #0057–#0057
cd <path>python - <script>Requested file and log inspection and source searches related to source & workspace.
2 calls · #0058–#0059
cat <path>head -n <n>grep -n <val> <path>trueRequested file and log inspection, script or workload execution and source searches related to reward & policy updates.
2 calls · #0060–#0061
cd <path>cat > <path> <script>timeout <n> <val> <path>sed -n <val> <path>grep -n <val> <flag> <args>Requested source searches and file and log inspection related to source & workspace.
3 calls · #0062–#0064
grep -n <val> <flag> <args>head -n <n>grep -n <val> -R <path>headsed -n <val> <path>Requested file and log inspection, source searches and workspace inspection related to reward & policy updates.
3 calls · #0065–#0067
cd <path>sed -n <val> <path>grep -R <val> -n <path>grep -n <val> -n <path> <path> <path> <n> > <path>find <path> -name <val> -o -name <val>headgrep -R <val> -n <path> <path>head -n <n>grep -n <val> <path> <path>Requested source searches and file and log inspection related to source & workspace.
1 call · #0068–#0068
cd <path>grep -R <val> -n <path> <path>head -n <n>grep -R <val> -n <val>Requested script or workload execution related to source & workspace.
2 calls · #0069–#0070
python - <script>Requested source searches and file and log inspection related to source & workspace.
1 call · #0071–#0071
grep -n <val> <path>head -n <n>headRequested script or workload execution related to source & workspace.
1 call · #0072–#0072
python - <script>Requested script or workload execution related to attention kernels.
2 calls · #0073–#0074
python - <script>Requested source searches and file and log inspection related to source & workspace.
2 calls · #0075–#0076
grep -n <val> -n <path>head -n <n>sed -n <val> <path>grep -n <val> <flag> <args>grep -n <val> <path>Requested script or workload execution related to source & workspace.
1 call · #0077–#0077
python - <script>Requested workspace file updates and workspace inspection related to source & workspace.
1 call · #0078–#0078
mkdir -p <path>touch <path>ls -l -a <path>Requested file and log inspection and script or workload execution related to checkpoints & weight state.
1 call · #0079–#0079
cat > <path> <script>python -m <module> <script>echo <val>Requested script or workload execution related to source & workspace.
1 call · #0080–#0080
python - <script>Requested script or workload execution and source searches related to checkpoints & weight state.
1 call · #0081–#0081
cd <path>python - <script>python -m <module> <script>grep -n <val> <path>echo <val>Requested file and log inspection and script or workload execution related to source & workspace.
3 calls · #0082–#0084
cd <path>sed -n <val> <path>python -m <module> <script>echo <val>Requested script or workload execution related to source & workspace.
1 call · #0085–#0085
python - <script>Requested script or workload execution related to attention kernels.
1 call · #0086–#0086
cd <path>python - <script>python -m <module> <script>echo <val>Requested workspace file updates, environment setup or inspection and execution waits related to task requirements.
1 call · #0087–#0087
cd <val>rm -f <path> <path> <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>sleep <n>echo <flag>tail -n <n> <path>tail -n <n> <path> <n> > <path>ps <flag> <args>grep -E <val>grep -v <val>Requested script or workload execution, source searches and file and log inspection related to source & workspace.
1 call · #0088–#0088
cd <path>python - <script>python -m <module> <script>echo <val>grep -n <val> <path>grep -v <val>head -n <n>Requested runtime inspection, source searches and workspace file updates related to task requirements.
1 call · #0089–#0089
ps <flag> <args>grep -E <val>grep -v <val>truecd <val>rm -f <path> <path> <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val>sleep <n>echo <flag>tail -n <n> <path>tail -n <n> <path> <n> > <path>Requested execution waits, file and log inspection and runtime inspection related to benchmark & validation setup.
2 calls · #0090–#0091
sleep <n>echo <flag>tail -n <n> <path> <n> > <path>ps <flag> <args>grep -E <val>grep -v <val>cat <path>cat <path> <n> > <path>python -m <module>head -n <n>Requested script or workload execution related to source & workspace.
1 call · #0092–#0092
cd <path>python - <script>python -m <module> <script>echo <val>Requested workspace file updates, environment setup or inspection and execution waits related to task requirements.
1 call · #0093–#0093
cd <val>rm -f <path> <path> <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>sleep <n>tail -n <n> <path>echo <flag>tail -n <n> <path> <n> > <path>ps <flag> <args>grep -E <val>grep -v <val>Requested execution waits, file and log inspection and runtime inspection related to benchmark & validation setup.
3 calls · #0094–#0096
sleep <n>echo <flag>tail -n <n> <path>tail -n <n> <path> <n> > <path>ps <flag> <args>grep -E <val>grep -v <val>trueRequested script or workload execution and source searches related to checkpoints & weight state.
1 call · #0097–#0097
cd <path>python - <script>python -m <module> <script>grep -n <val> <path>echo <val>Requested workspace file updates, environment setup or inspection and execution waits related to task requirements.
1 call · #0098–#0098
cd <val>rm -f <path> <path> <path> <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>sleep <n>echo <flag>tail -n <n> <path>tail -n <n> <path> <n> > <path>ps <flag> <args>grep -E <val>grep -v <val>Requested execution waits, file and log inspection and runtime inspection related to checkpoints & weight state.
1 call · #0099–#0099
sleep <n>echo <flag>tail -n <n> <path>tail -n <n> <path> <n> > <path>ps <flag> <args>grep -E <val>grep -v <val>ls -l -a <path> <n> > <path>Requested file and log inspection and script or workload execution related to checkpoints & weight state.
3 calls · #0100–#0102
cd <path>cat > <path> <script>timeout <n> <val> <path>Requested script or workload execution and source searches related to checkpoints & weight state.
1 call · #0103–#0103
cd <path>python - <script>python -m <module> <script>echo <val>grep -n <val> <path>Requested workspace file updates, environment setup or inspection and execution waits related to task requirements.
1 call · #0104–#0104
cd <val>rm -f <path> <path> <path> <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>sleep <n>echo <flag>tail -n <n> <path>tail -n <n> <path> <n> > <path>ps <flag> <args>grep -E <val>grep -v <val>Requested execution waits, file and log inspection and runtime inspection related to checkpoints & weight state.
1 call · #0105–#0105
sleep <n>echo <flag>tail -n <n> <path>tail -n <n> <path> <n> > <path>ps <flag> <args>grep -E <val>grep -v <val>ls -l -a <path> <n> > <path>Requested execution waits, file and log inspection and runtime inspection related to source & workspace.
2 calls · #0106–#0107
sleep <n>echo <flag>tail -n <n> <path>tail -n <n> <path> <n> > <path>ps <flag> <args>grep -E <val>grep -v <val><command> <args>ls -l <path>Requested script or workload execution related to reward & policy updates.
1 call · #0108–#0108
cd <path>python - <script>python -m <module> <script>echo <val>Requested source searches and file and log inspection related to reward & policy updates.
1 call · #0109–#0109
cd <path>grep -n <val> -n <path>head -n <n>grep -n <val> <flag> <args>Requested workspace file updates, environment setup or inspection and execution waits related to task requirements.
1 call · #0110–#0110
cd <val>rm -f <path> <path> <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>sleep <n>echo <flag>tail -n <n> <path>tail -n <n> <path> <n> > <path>ps <flag> <args>grep -E <val>grep -v <val>Requested execution waits, file and log inspection and runtime inspection related to benchmark & validation setup.
1 call · #0111–#0111
sleep <n>echo <flag>tail -n <n> <path>tail -n <n> <path> <n> > <path>ps <flag> <args>grep -E <val>grep -v <val>Requested file and log inspection and script or workload execution related to reward & policy updates.
1 call · #0112–#0112
cd <path>cat > <path> <script>timeout <n> <val> <path>Requested script or workload execution related to source & workspace.
2 calls · #0113–#0114
cd <path>python - <script><command> <args>Requested workspace file updates, environment setup or inspection and file and log inspection related to task requirements.
2 calls · #0115–#0116
cd <val>rm -f <path> <path> <path>env <vars> bash <script> > <path> <n> >& <path>echo <val>tail -n <n> <path>python - <script>rm -f <path> <path> <path> <path>Requested runtime inspection, source searches and workspace inspection related to benchmark & validation setup.
1 call · #0117–#0117
ps <flag> <args>grep -E <val>grep -v <val>truels -l -a <val>tail -n <n> <path> <n> > <path>Requested script or workload execution, file and log inspection and workspace file updates related to task requirements.
1 call · #0118–#0118
cd <val>bash <script> > <path> <n> >& <path>truecat <path>tail -n <n>rm -f <path> <path> <path> <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path>echo <val> <val> <path>Requested execution waits, file and log inspection and runtime inspection related to benchmark & validation setup.
2 calls · #0119–#0120
sleep <n>tail -n <n> <path>echo <flag>ps <flag> <args>grep -E <val>grep -v <val>truetail -n <n> <path> <n> > <path>ls -l -a <path> <n> > <path>Requested script or workload execution, workspace file updates and environment setup or inspection related to task requirements.
1 call · #0121–#0121
cd <val>bash <script> > <path> <n> >& <path>truerm -f <path> <path> <path> <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path><command> <args>echo <val> <val> <path>date -u <val>Requested execution waits, file and log inspection and runtime inspection related to benchmark & validation setup.
3 calls · #0122–#0124
sleep <n>date -u <val>tail -n <n> <path> <n> > <path>echo <flag>ps <flag> <args>grep -E <val>grep -v <val>truetest -f <path>python - <script>Requested repository inspection, file and log inspection and environment setup or inspection related to source & workspace.
4 calls · #0125–#0128
cd <path>git status --shortgit diff --statgit diff <flag> <args>headecho <flag>envgrep <val>truefind <path> -maxdepth <n> -type <val> -name <val> -o -name <val>head -n <n>find <path> -type <val> -maxdepth <n> <flag> <args><command> <args>grep -R <val> -n <path> <path> <n> > <path>grep -R <val> -n <path> <n> > <path>cd <val>env <vars> bash <script>echo <val>ls -l -a <val>tailRequested script or workload execution, file and log inspection and runtime inspection related to runtime processes.
1 call · #0129–#0129
cd <val>bash <script>echo <val>cat <path>python -m <module>head -n <n>ps <flag> <args>grep -E <val>grep -v <val>trueRequested script or workload execution related to source & workspace.
1 call · #0130–#0130
cd <path>python -m <module> <script> <script>echo <val>command -v <val> > <path><command> <args>python - <script>Requested source searches related to source & workspace.
1 call · #0131–#0131
cd <path>grep -n <val> <path>Requested script or workload execution and source searches related to checkpoints & weight state.
1 call · #0132–#0132
cd <path>python - <script>python -m <module> <script>echo <val>grep -n <val> <path>Requested script or workload execution and file and log inspection related to source & workspace.
2 calls · #0133–#0134
cd <path>python -B -m <module> --helphead -n <n>echo <val>python -B -m <module> --help > <path> <n> > <path>cat <path>Requested script or workload execution, workspace file updates and environment setup or inspection related to task requirements.
1 call · #0135–#0135
cd <val>bash <script> > <path> <n> >& <path>truerm -f <path> <path> <path> <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path><command> <args>echo <val> <val> <path> <val> -u <val>Requested execution waits, file and log inspection and runtime inspection related to benchmark & validation setup.
3 calls · #0136–#0138
sleep <n>date -u <val>tail -n <n> <path>tail -n <n> <path> <n> > <path>ps <flag> <args>grep -E <val>grep -v <val>trueecho <flag>test -f <path>python - <script>Requested script or workload execution, workspace file updates and environment setup or inspection related to task requirements.
1 call · #0139–#0139
cd <val>bash <script> > <path> <n> >& <path>truerm -f <path> <path> <path>env <vars> nohup <val> <path> > <path> <n> >& <path>echo <val> > <path><command> <args>echo <val> <val> -u <val>Requested execution waits, file and log inspection and runtime inspection related to benchmark & validation setup.
1 call · #0140–#0140
sleep <n>date -u <val>tail -n <n> <path>tail -n <n> <path> <n> > <path>ps <flag> <args>grep -E <val>grep -v <val>truetest -f <path>python - <script>Requested execution waits, file and log inspection and script or workload execution related to reward & policy updates.
1 call · #0141–#0141
sleep <n>tail -n <n> <path>tail -n <n> <path> <n> > <path>test -f <path>python - <script>Requested repository inspection, script or workload execution and file and log inspection related to source & workspace.
2 calls · #0142–#0143
cd <path>git diff --checkgit status --shortpython -m <module> <script>wc -l <path>cd <val>bash <script> > <path> <n> >& <path>echo <val>tail -n <n> <path>sed -n <val> <path>Requested script or workload execution, file and log inspection and workspace file updates related to source & workspace.
2 calls · #0144–#0145
cd <path>python - <script>python -m <module> <script>echo <val>wc -l <path>cd <val>cp <path> <path>grep -n <val> <path>git -C <path> <val> --shortgit -C <path> <val> --checkpython -m <module> <script> <script>Requested workspace file updates, workspace inspection and repository inspection related to source & workspace.
5 calls · #0146–#0150
chmod <n> <path> <path>ls -l <path>cd <path>git status --shortfind <path> -maxdepth <n> -type <val>sed -n <val>ls -l -a <path>cat <path>headpython -m <module> <path>head -n <n>echocd <val>bash <script> > <path> <n> >& <path>echo <val>tail -n <n> <path>sha256sum <path> <path>Requested script or workload execution related to benchmark & validation setup.
1 call · #0151–#0151
cd <val>python - <script>Requested script or workload execution, file and log inspection and source searches related to source & workspace.
2 calls · #0152–#0153
cd <path>python -X <val> -c <script> <n> > <path> > <path>tail -n <n> <path>awk <val> <path>head -n <n>head -n <n> <path>grep -n <val> <path>headRequested repository inspection related to source & workspace.
1 call · #0154–#0154
<command> <args>git -C <val> <val> --shortecho <val>sha256sum <path>cut <flag> <args>Requested file and log inspection related to source & workspace.
1 call · #0155–#0155
cd <path>sed -n <val> <path>Requested script or workload execution related to source & workspace.
1 call · #0156–#0156
cd <path>python -m <module> -q <path>echo <val>python - <script>Requested workspace inspection and script or workload execution related to reward & policy updates.
1 call · #0157–#0157
cd <path>find <path> -maxdepth <n> -type <val> <flag> <args>echo <flag>python - <script>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,957 @@+# Copyright 2026 The online PPO runtime authors.+#+# 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.+"""Two-device, single-process online PPO runtime.++This is the framework-owned runtime described in+``config/framework-runtime-contract.md``. It deliberately avoids the+Ray/Megatron/vLLM server process graph used by the generic trainer and runs a+compact two-NPU pipeline instead:++* one Qwen3-1.7B model serves as both the trainable actor and the rollout+ policy on the first projected Ascend device, so rollout weights are fresh by+ construction after every actor step;+* the frozen Qwen3-1.7B reference, the Qwen3-0.6B critic, and the frozen+ Qwen3-0.6B sequence-classification reward model share the second device;+* PPO evidence (old/reference log-probs, critic values, reward scores, GAE,+ clipped critic update, clipped actor update) is computed with regular+ Transformers/PyTorch NPU ops;+* checkpoints are portable Transformers safetensors exports plus a small+ optimizer/runtime state file that a fresh ``restart`` process reloads.+"""++from __future__ import annotations++import argparse+import json+import math+import os+import socket+import sys+import time+import traceback+from pathlib import Path+from typing import Any+++SCHEMA_VERSION = 1+++def _load_json(path: Path) -> dict[str, Any]:+ value = json.loads(path.read_text(encoding="utf-8"))+ if not isinstance(value, dict):+ raise ValueError(f"{path} must contain one JSON object")+ return value+++def _send_message(sock: socket.socket, value: dict[str, Any]) -> None:+ payload = json.dumps(value, allow_nan=False, separators=(",", ":")).encode("utf-8") + b"\n"+ sock.sendall(payload)+++def _receive_message(sock: socket.socket) -> dict[str, Any]:+ raw = bytearray()+ while not raw.endswith(b"\n"):+ chunk = sock.recv(65536)+ if not chunk:+ raise RuntimeError("control socket closed by host")+ raw.extend(chunk)+ if len(raw) > 1024 * 1024:+ raise RuntimeError("control message is too large")+ value = json.loads(raw)+ if not isinstance(value, dict) or not isinstance(value.get("type"), str):+ raise RuntimeError("control message is invalid")+ return value+++class OnlinePPORuntime:+ """Compact online PPO worker that owns the complete two-device process graph."""++ def __init__(self, args: argparse.Namespace) -> None:+ self.args = args+ self.run_spec_path = Path(args.run_spec).resolve(strict=True)+ self.policy_model_path = Path(args.policy_model_path).resolve(strict=True)+ self.auxiliary_model_path = Path(args.auxiliary_model_path).resolve(strict=True)+ self.tokenizer_path = Path(args.tokenizer_path).resolve(strict=True)+ self.runtime_dir = Path(args.runtime_dir).resolve()+ self.result_dir = Path(args.result_dir).resolve()+ self.control_path = Path(args.control_socket).resolve()++ self.spec = _load_json(self.run_spec_path)+ self._validate_run_spec()++ self.action: str = self.spec["action"]+ resolved = self.spec["resolved_work"]+ self.committed_updates = int(resolved["committed_updates"])+ self.trajectories_per_update = int(resolved["trajectories_per_update"])+ self.max_prompt_tokens = int(self.spec["measurement"]["max_prompt_tokens"])+ self.max_response_tokens = int(self.spec["measurement"]["max_response_tokens"])+ self.policy_version = 0+ self.trajectory_records: list[dict[str, Any]] = []+ self.step_metrics: list[dict[str, float]] = []+ self.actor_grad_norms: list[float] = []+ self.critic_grad_norms: list[float] = []+ self.checkpoint_path: str | None = None+ self.portable_actor_path: str | None = None++ self.sampling = self.spec["sampling"]+ self.algorithm = self.spec["algorithm"]+ self.actor_lr = float(self.spec["actor_optimizer"]["learning_rate"])+ self.critic_lr = float(self.spec["critic_optimizer"]["learning_rate"])+ self.kl_coef = float(self.algorithm["reference_kl"]["coefficient"])+ self.gamma = float(self.algorithm["gamma"])+ self.lam = float(self.algorithm["lambda"])+ self.actor_clip = float(self.algorithm["actor_clip"])+ self.value_clip = float(self.algorithm["value_clip"])+ self.reward_model_path = Path(self.spec["reward_model_path"]).resolve(strict=True)+ self.restart_checkpoint = (+ Path(self.spec["restart_checkpoint"]).resolve(strict=True)+ if self.spec.get("restart_checkpoint")+ else None+ )++ self._connect_control()+ self._load_runtime()++ def _validate_run_spec(self) -> None:+ spec = self.spec+ if spec.get("schema_version") != SCHEMA_VERSION:+ raise ValueError("unsupported run-spec schema")+ if spec.get("action") not in {"smoke", "correctness", "measurement", "restart"}:+ raise ValueError("unsupported run-spec action")+ if not isinstance(spec.get("resolved_work"), dict):+ raise ValueError("run-spec resolved_work is unavailable")+ if not isinstance(spec.get("sampling"), dict) or not isinstance(spec.get("algorithm"), dict):+ raise ValueError("run-spec sampling/algorithm is unavailable")+ algorithm = spec["algorithm"]+ if (+ algorithm.get("advantage_estimator") != "gae"+ or algorithm.get("gamma") != 1.0+ or algorithm.get("lambda") != 0.95+ or algorithm.get("reference_kl", {}).get("placement") != "token_reward"+ or algorithm.get("actor_clip") != 0.2+ or algorithm.get("value_clip") != 0.5+ or algorithm.get("actor_epochs") != 1+ or algorithm.get("critic_epochs") != 1+ ):+ raise ValueError("run-spec algorithm differs from the fixed online PPO contract")+ if spec.get("actor_optimizer", {}).get("name") != "adamw":+ raise ValueError("actor optimizer differs from the fixed online PPO contract")+ if spec.get("critic_optimizer", {}).get("name") != "adamw":+ raise ValueError("critic optimizer differs from the fixed online PPO contract")+ ceiling = spec.get("resource_ceiling", {}).get("device_ids")+ if not isinstance(ceiling, list) or len(ceiling) < 1 or len(ceiling) > 2:+ raise ValueError("resource ceiling requires one or two logical devices")+ measurement = spec.get("measurement")+ if (+ not isinstance(measurement, dict)+ or measurement.get("max_prompt_tokens") != 128+ or measurement.get("max_response_tokens") != 64+ ):+ raise ValueError("run-spec measurement contract differs")+ resolved = spec["resolved_work"]+ if resolved.get("accepted_trajectories") != int(resolved.get("committed_updates", 0)) * int(+ resolved.get("trajectories_per_update", 0)+ ):+ raise ValueError("run-spec work shape is inconsistent")++ def _connect_control(self) -> None:+ last_error: Exception | None = None+ for _ in range(150):+ try:+ self.control = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ self.control.settimeout(600.0)+ self.control.connect(str(self.control_path))+ return+ except (FileNotFoundError, ConnectionRefusedError, OSError) as exc:+ last_error = exc+ try:+ self.control.close()+ except OSError:+ pass+ time.sleep(0.2)+ raise RuntimeError(f"unable to connect to control socket: {last_error}")++ def _load_runtime(self) -> None:+ import torch+ import torch_npu # noqa: F401 (registers the Ascend NPU backend)++ from safetensors.torch import load_file+ from transformers import (+ AutoConfig,+ AutoModelForCausalLM,+ AutoModelForSequenceClassification,+ AutoModelForTokenClassification,+ AutoTokenizer,+ )++ self.torch = torch+ self.load_file = load_file+ self.device_count = torch_npu.npu.device_count()+ if self.device_count < 2:+ raise RuntimeError(f"online PPO runtime requires two NPUs, found {self.device_count}")+ self.actor_device = torch.device("npu:0")+ self.aux_device = torch.device("npu:1")++ self.tokenizer = AutoTokenizer.from_pretrained(+ str(self.tokenizer_path), local_files_only=True, trust_remote_code=True+ )+ self.pad_token_id = int(self.tokenizer.pad_token_id)+ self.eos_token_id = int(self.tokenizer.eos_token_id)+ if self.pad_token_id is None or self.eos_token_id is None:+ raise RuntimeError("policy tokenizer is missing pad/eos token ids")++ self.actor_model = AutoModelForCausalLM.from_pretrained(+ str(self.policy_model_path),+ local_files_only=True,+ trust_remote_code=True,+ dtype=torch.bfloat16,+ low_cpu_mem_usage=True,+ ).to(self.actor_device)++ self.reference_model = AutoModelForCausalLM.from_pretrained(+ str(self.policy_model_path),+ local_files_only=True,+ trust_remote_code=True,+ dtype=torch.bfloat16,+ low_cpu_mem_usage=True,+ ).to(self.aux_device)++ critic_config = AutoConfig.from_pretrained(+ str(self.auxiliary_model_path), local_files_only=True, trust_remote_code=True+ )+ critic_config.architectures = ["Qwen3ForTokenClassification"]+ critic_config.num_labels = 1+ critic_config.id2label = {0: "value"}+ critic_config.label2id = {"value": 0}+ self.critic_model = AutoModelForTokenClassification.from_pretrained(+ str(self.auxiliary_model_path),+ local_files_only=True,+ trust_remote_code=True,+ config=critic_config,+ dtype=torch.bfloat16,+ low_cpu_mem_usage=True,+ ).to(self.aux_device)++ # The supplied Qwen3-0.6B and Qwen3-1.7B projections share byte-for-byte+ # tokenizer artifacts, so reuse the already-loaded tokenizer instead of+ # paying a second parser initialization on the measured path.+ self.reward_tokenizer = self.tokenizer+ self.reward_model = AutoModelForSequenceClassification.from_pretrained(+ str(self.reward_model_path),+ local_files_only=True,+ trust_remote_code=True,+ dtype=torch.bfloat16,+ low_cpu_mem_usage=True,+ ).to(self.aux_device)+ if self.reward_model.config.pad_token_id is None:+ self.reward_model.config.pad_token_id = self.reward_tokenizer.pad_token_id++ for model in (self.actor_model, self.reference_model, self.critic_model, self.reward_model):+ model.eval()++ restart_training_state = None+ if self.restart_checkpoint is not None:+ self._load_checkpoint(self.restart_checkpoint)+ restart_training_state = torch.load(+ self.restart_checkpoint / "training_state.pt", map_location="cpu", weights_only=False+ )+ self.policy_version = int(restart_training_state["policy_version"])+ else:+ self.policy_version = 0++ self.actor_optimizer = torch.optim.AdamW(+ self.actor_model.parameters(),+ lr=self.actor_lr,+ betas=(0.9, 0.999),+ eps=1e-8,+ weight_decay=0.01,+ )+ self.critic_optimizer = torch.optim.AdamW(+ self.critic_model.parameters(),+ lr=self.critic_lr,+ betas=(0.9, 0.999),+ eps=1e-8,+ weight_decay=0.01,+ )++ if restart_training_state is not None:+ self.actor_optimizer.load_state_dict(restart_training_state["actor_optimizer"])+ self.critic_optimizer.load_state_dict(restart_training_state["critic_optimizer"])+ self._move_optimizer_state_to_parameters(self.actor_optimizer)+ self._move_optimizer_state_to_parameters(self.critic_optimizer)++ def _save_safetensors(+ self, model: Any, path: Path, *, save_config: bool = True, cast_to_float32: bool = False+ ) -> None:+ from safetensors.torch import save_file++ state_dict: dict[str, Any] = {}+ for name, tensor in model.state_dict().items():+ detached = tensor.detach()+ if cast_to_float32:+ detached = detached.float()+ state_dict[name] = detached.to("cpu").contiguous()+ save_file(state_dict, str(path))+ if save_config:+ config = model.config+ if hasattr(config, "tie_word_embeddings"):+ config.tie_word_embeddings = False+ config.save_pretrained(str(path.parent))+ (path.parent / "model.safetensors.index.json").unlink(missing_ok=True)++ def _save_checkpoint(self, version: int) -> tuple[str, str]:+ import torch++ checkpoint_dir = self.runtime_dir.parent / "checkpoints" / f"update-{version}"+ checkpoint_dir.mkdir(parents=True, exist_ok=False)+ portable_dir = checkpoint_dir / "portable-actor"+ portable_dir.mkdir(parents=True, exist_ok=False)++ self._save_safetensors(self.actor_model, checkpoint_dir / "actor.safetensors", save_config=False)+ self._save_safetensors(self.critic_model, checkpoint_dir / "critic.safetensors", save_config=False)++ actor_config = self.actor_model.config+ actor_config.tie_word_embeddings = False+ actor_config.save_pretrained(str(checkpoint_dir))++ training_state = {+ "policy_version": version,+ "actor_optimizer": self._optimizer_state_to_cpu(self.actor_optimizer),+ "critic_optimizer": self._optimizer_state_to_cpu(self.critic_optimizer),+ "rng": {+ "torch": torch.random.get_rng_state().cpu(),+ "npu": torch.npu.get_rng_state().cpu(),+ },+ }+ torch.save(training_state, str(checkpoint_dir / "training_state.pt"))++ self._save_safetensors(+ self.actor_model, portable_dir / "model.safetensors", save_config=False, cast_to_float32=True+ )+ # The host loads the portable actor on CPU with ``torch_dtype="auto"``.+ # A float32 export reproduces the live NPU float32 probe (used after+ # training for freshness checks) to well under the host tolerance.+ actor_config.torch_dtype = "float32"+ actor_config.save_pretrained(str(portable_dir))+ for name in ("tokenizer.json", "tokenizer_config.json", "generation_config.json", "merges.txt", "vocab.json"):+ source = self.tokenizer_path / name+ if source.is_file() and not (portable_dir / name).exists():+ (portable_dir / name).symlink_to(source)++ self.checkpoint_path = str(checkpoint_dir)+ self.portable_actor_path = str(portable_dir)+ return self.checkpoint_path, self.portable_actor_path++ @staticmethod+ def _optimizer_state_to_cpu(optimizer: Any) -> dict[str, Any]:+ state = optimizer.state_dict()+ for param_group in state["param_groups"]:+ for key, value in list(param_group.items()):+ if hasattr(value, "cpu"):+ param_group[key] = value.cpu()+ for param_state in state["state"].values():+ for key, value in list(param_state.items()):+ if hasattr(value, "cpu"):+ param_state[key] = value.cpu()+ return state++ @staticmethod+ def _move_optimizer_state_to_parameters(optimizer: Any) -> None:+ for param_group in optimizer.param_groups:+ for parameter in param_group["params"]:+ state = optimizer.state[parameter]+ for key, value in list(state.items()):+ if hasattr(value, "to"):+ state[key] = value.to(parameter.device)++ def _load_checkpoint(self, checkpoint_dir: Path) -> None:+ if not (checkpoint_dir / "actor.safetensors").is_file():+ raise RuntimeError("restart checkpoint actor weights are unavailable")+ if not (checkpoint_dir / "critic.safetensors").is_file():+ raise RuntimeError("restart checkpoint critic weights are unavailable")+ if not (checkpoint_dir / "training_state.pt").is_file():+ raise RuntimeError("restart checkpoint training state is unavailable")++ actor_state = self.load_file(str(checkpoint_dir / "actor.safetensors"), device="cpu")+ critic_state = self.load_file(str(checkpoint_dir / "critic.safetensors"), device="cpu")+ actor_result = self.actor_model.load_state_dict(actor_state, strict=True)+ critic_result = self.critic_model.load_state_dict(critic_state, strict=True)+ if actor_result.missing_keys or actor_result.unexpected_keys:+ raise RuntimeError(f"actor checkpoint is not portable: {actor_result}")+ if critic_result.missing_keys or critic_result.unexpected_keys:+ raise RuntimeError(f"critic checkpoint is not portable: {critic_result}")++ def _load_prompts(self, input_path: str) -> list[dict[str, Any]]:+ data = _load_json(Path(input_path))+ if data.get("schema_version") != 1 or not isinstance(data.get("prompts"), list):+ raise RuntimeError("formal prompt projection is invalid")+ prompts = data["prompts"]+ if len(prompts) != self.trajectories_per_update:+ raise RuntimeError(+ f"formal prompt projection has {len(prompts)} prompts, expected {self.trajectories_per_update}"+ )+ system_prompt = data.get("system_prompt", "")+ for prompt in prompts:+ if not isinstance(prompt, dict) or not isinstance(prompt.get("id"), str) or not isinstance(+ prompt.get("question"), str+ ):+ raise RuntimeError("formal prompt record is invalid")+ return [+ {+ "id": prompt["id"],+ "chat": [+ {"role": "system", "content": system_prompt},+ {"role": "user", "content": prompt["question"]},+ ],+ }+ for prompt in prompts+ ]++ def _tokenize_prompts(self, prompt_records: list[dict[str, Any]]) -> dict[str, Any]:+ texts = [+ self.tokenizer.apply_chat_template(+ record["chat"], tokenize=False, add_generation_prompt=True+ )+ for record in prompt_records+ ]+ encoded = self.tokenizer(+ texts,+ return_tensors="pt",+ padding=True,+ padding_side="left",+ truncation=False,+ )+ input_ids = encoded["input_ids"].to(self.actor_device)+ attention_mask = encoded["attention_mask"].to(self.actor_device)+ prompt_lens = attention_mask.sum(dim=1).to(self.torch.long)+ max_length = int(prompt_lens.max().cpu())+ if max_length > self.max_prompt_tokens:+ raise RuntimeError(+ f"formal prompt length {max_length} exceeds the configured maximum {self.max_prompt_tokens}"+ )+ return {+ "input_ids": input_ids,+ "attention_mask": attention_mask,+ "prompt_lens": prompt_lens,+ "max_prompt_len": int(input_ids.shape[1]),+ "prompt_records": prompt_records,+ }++ def _generate_responses(self, batch: dict[str, Any]) -> dict[str, Any]:+ torch = self.torch+ max_response = self.max_response_tokens+ prompt_len = batch["max_prompt_len"]+ generation_kwargs = {+ "max_new_tokens": max_response,+ "do_sample": True,+ "temperature": float(self.sampling["temperature"]),+ "top_p": float(self.sampling["top_p"]),+ "top_k": int(self.sampling["top_k"]),+ "eos_token_id": self.eos_token_id,+ "pad_token_id": self.pad_token_id,+ "use_cache": True,+ }+ with torch.no_grad():+ generated = self.actor_model.generate(+ input_ids=batch["input_ids"],+ attention_mask=batch["attention_mask"],+ **generation_kwargs,+ )+ raw_responses = generated[:, prompt_len:]+ if raw_responses.shape[1] < max_response:+ padding = torch.full(+ (raw_responses.shape[0], max_response - raw_responses.shape[1]),+ self.pad_token_id,+ dtype=raw_responses.dtype,+ device=raw_responses.device,+ )+ raw_responses = torch.cat([raw_responses, padding], dim=1)+ responses = raw_responses[:, :max_response].contiguous()++ eos_mask = responses.eq(self.eos_token_id)+ first_eos = eos_mask.int().argmax(dim=1)+ has_eos = eos_mask.any(dim=1)+ pad_mask = responses.eq(self.pad_token_id)+ first_pad = pad_mask.int().argmax(dim=1)+ has_pad = pad_mask.any(dim=1)+ valid_lengths = torch.full_like(first_eos, max_response)+ valid_lengths = torch.where(has_eos, first_eos + 1, valid_lengths)+ valid_lengths = torch.where(has_pad, torch.minimum(valid_lengths, first_pad), valid_lengths)+ valid_lengths = valid_lengths.clamp(min=1)++ positions = torch.arange(max_response, device=responses.device).unsqueeze(0)+ response_mask = (positions < valid_lengths.unsqueeze(1)).to(torch.float32)+ responses = responses * response_mask.to(torch.long) + self.pad_token_id * (1 - response_mask.to(torch.long))+ batch["responses"] = responses+ batch["response_mask"] = response_mask+ batch["valid_lengths"] = valid_lengths+ return batch++ @staticmethod+ def _position_ids(attention_mask: Any) -> Any:+ positions = attention_mask.long().cumsum(dim=-1) - 1+ return positions.masked_fill(attention_mask.eq(0), 0)++ def _full_inputs(self, batch: dict[str, Any], *, device: Any) -> tuple[Any, Any, Any]:+ torch = self.torch+ input_ids = batch["input_ids"].to(device)+ prompt_attention = batch["attention_mask"].to(device)+ responses = batch["responses"].to(device)+ response_mask = batch["response_mask"].to(device)+ full_ids = torch.cat([input_ids, responses], dim=1)+ full_attention = torch.cat(+ [prompt_attention.to(torch.long), response_mask.to(torch.long)], dim=1+ )+ full_positions = self._position_ids(full_attention)+ return full_ids, full_attention, full_positions++ def _forward_full(self, model: Any, batch: dict[str, Any], *, device: Any, use_cache: bool = False) -> Any:+ full_ids, full_attention, full_positions = self._full_inputs(batch, device=device)+ return model(input_ids=full_ids, attention_mask=full_attention, position_ids=full_positions, use_cache=use_cache)++ def _response_logits(self, logits: Any, batch: dict[str, Any]) -> Any:+ batch_size = logits.shape[0]+ response_len = self.max_response_tokens+ rows = self.torch.arange(batch_size, device=logits.device).unsqueeze(1)+ cols = (+ batch["prompt_lens"].to(logits.device) - 1+ ).unsqueeze(1) + self.torch.arange(response_len, device=logits.device).unsqueeze(0)+ return logits[rows, cols]++ def _response_values(self, logits: Any, batch: dict[str, Any]) -> Any:+ batch_size = logits.shape[0]+ response_len = self.max_response_tokens+ rows = self.torch.arange(batch_size, device=logits.device).unsqueeze(1)+ cols = batch["prompt_lens"].to(logits.device).unsqueeze(1) + self.torch.arange(+ response_len, device=logits.device+ ).unsqueeze(0)+ return logits[rows, cols].squeeze(-1)++ def _token_log_probs(self, logits: Any, batch: dict[str, Any], *, mask: bool = True) -> Any:+ selected = self._response_logits(logits, batch)+ log_probs = self.torch.log_softmax(selected.float(), dim=-1)+ labels = batch["responses"].to(logits.device).unsqueeze(-1)+ token_log_probs = log_probs.gather(dim=-1, index=labels).squeeze(-1)+ if mask:+ token_log_probs = token_log_probs * batch["response_mask"].to(logits.device)+ return token_log_probs++ def _reward_scores(self, batch: dict[str, Any]) -> Any:+ torch = self.torch+ prompt_records = batch["prompt_records"]+ reward_texts: list[str] = []+ for index, record in enumerate(prompt_records):+ valid_length = int(batch["valid_lengths"][index].cpu())+ response_ids = batch["responses"][index, :valid_length].tolist()+ response_text = self.tokenizer.decode(response_ids, skip_special_tokens=False)+ if self.tokenizer.eos_token is not None:+ response_text = response_text.replace(self.tokenizer.eos_token, "")+ chat = list(record["chat"])+ chat.append({"role": "assistant", "content": response_text})+ reward_texts.append(+ self.reward_tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=False)+ )+ encoded = self.reward_tokenizer(+ reward_texts,+ return_tensors="pt",+ padding=True,+ padding_side="left",+ truncation=False,+ )+ input_ids = encoded["input_ids"].to(self.aux_device)+ attention_mask = encoded["attention_mask"].to(self.aux_device)+ with torch.no_grad():+ outputs = self.reward_model(input_ids=input_ids, attention_mask=attention_mask)+ probabilities = torch.softmax(outputs.logits.float(), dim=-1)+ scores = probabilities[:, 1]+ token_scores = torch.zeros(+ (len(prompt_records), self.max_response_tokens), dtype=torch.float32, device=self.aux_device+ )+ rows = torch.arange(len(prompt_records), device=self.aux_device)+ token_scores[rows, batch["valid_lengths"].to(self.aux_device) - 1] = scores.to(torch.float32)+ return token_scores * batch["response_mask"].to(self.aux_device)++ def _masked_mean(self, values: Any, mask: Any) -> Any:+ return (values * mask).sum() / mask.sum().clamp(min=1)++ def _masked_whiten(self, values: Any, mask: Any) -> Any:+ torch = self.torch+ mean = self._masked_mean(values, mask)+ diff = values - mean+ var = self._masked_mean(diff * diff, mask)+ return diff * torch.rsqrt(var + 1e-8)++ def _gae(self, rewards: Any, values: Any, response_mask: Any) -> tuple[Any, Any]:+ torch = self.torch+ advantages_reversed: list[Any] = []+ next_values = torch.zeros_like(rewards[:, 0])+ last_gae_lambda = torch.zeros_like(rewards[:, 0])+ for position in reversed(range(rewards.shape[1])):+ delta = rewards[:, position] + self.gamma * next_values - values[:, position]+ last_gae_lambda_next = delta + self.gamma * self.lam * last_gae_lambda+ mask = response_mask[:, position]+ next_values = values[:, position] * mask + (1.0 - mask) * next_values+ last_gae_lambda = last_gae_lambda_next * mask + (1.0 - mask) * last_gae_lambda+ advantages_reversed.append(last_gae_lambda)+ advantages = torch.stack(advantages_reversed[::-1], dim=1)+ returns = advantages + values+ advantages = self._masked_whiten(advantages, response_mask) * response_mask+ return advantages, returns++ def _grad_norm(self, model: Any) -> float:+ total = 0.0+ for parameter in model.parameters():+ if parameter.grad is not None:+ total += float(parameter.grad.detach().float().pow(2).sum().cpu())+ return math.sqrt(total)++ def _clip_grad_norm(self, model: Any) -> float:+ return float(+ self.torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0, error_if_nonfinite=True)+ )++ def _run_update(self, update: int, prompt_records: list[dict[str, Any]]) -> dict[str, float]:+ torch = self.torch+ timers: dict[str, float] = {}+ started = time.perf_counter()++ self.actor_model.eval()+ self.critic_model.eval()+ self.reference_model.eval()+ self.reward_model.eval()++ def mark(name: str) -> None:+ timers[name] = time.perf_counter()++ batch = self._tokenize_prompts(prompt_records)+ mark("tokenize")++ batch = self._generate_responses(batch)+ mark("gen")+ response_lengths = batch["valid_lengths"].float()+ mean_response_length = float(response_lengths.mean().cpu())++ with torch.no_grad():+ actor_outputs = self._forward_full(self.actor_model, batch, device=self.actor_device)+ old_log_probs = self._token_log_probs(actor_outputs.logits, batch, mask=True)+ mark("old_log_prob")++ with torch.no_grad():+ reference_outputs = self._forward_full(self.reference_model, batch, device=self.aux_device)+ ref_log_probs = self._token_log_probs(reference_outputs.logits, batch, mask=True)+ mark("ref")++ with torch.no_grad():+ critic_outputs = self._forward_full(self.critic_model, batch, device=self.aux_device)+ values = self._response_values(critic_outputs.logits, batch)+ values = values * batch["response_mask"].to(self.aux_device)+ old_values = values.detach().clone()+ mark("values")++ token_scores = self._reward_scores(batch)+ mark("reward")++ kl = old_log_probs.to(self.aux_device) - ref_log_probs+ token_rewards = token_scores - self.kl_coef * kl+ token_rewards = token_rewards * batch["response_mask"].to(self.aux_device)+ advantages, returns = self._gae(token_rewards, values, batch["response_mask"].to(self.aux_device))+ mark("adv")++ # ---- critic update (one epoch, full mini-batch) -----------------+ self.critic_model.train()+ self.critic_optimizer.zero_grad(set_to_none=True)+ critic_outputs = self._forward_full(self.critic_model, batch, device=self.aux_device)+ value_predictions = self._response_values(critic_outputs.logits, batch)+ response_mask_aux = batch["response_mask"].to(self.aux_device)+ value_predictions_clipped = torch.clamp(+ value_predictions, old_values - self.value_clip, old_values + self.value_clip+ )+ value_losses_1 = (value_predictions - returns) ** 2+ value_losses_2 = (value_predictions_clipped - returns) ** 2+ value_losses = torch.maximum(value_losses_1, value_losses_2)+ critic_vf_loss = 0.5 * self._masked_mean(value_losses, response_mask_aux)+ critic_vf_loss.backward()+ critic_grad_norm = self._grad_norm(self.critic_model)+ self._clip_grad_norm(self.critic_model)+ self.critic_optimizer.step()+ critic_vf_clipfrac = self._masked_mean(+ (value_losses_2 > value_losses_1).to(torch.float32), response_mask_aux+ )+ mark("update_critic")++ # ---- actor update (one epoch, full mini-batch) ------------------+ self.actor_model.train()+ self.actor_optimizer.zero_grad(set_to_none=True)+ actor_outputs = self._forward_full(self.actor_model, batch, device=self.actor_device)+ new_log_probs = self._token_log_probs(actor_outputs.logits, batch, mask=True)+ old_log_probs_actor = old_log_probs.to(self.actor_device)+ advantages_actor = advantages.to(self.actor_device)+ response_mask_actor = batch["response_mask"].to(self.actor_device)++ negative_approx_kl = torch.clamp(new_log_probs - old_log_probs_actor, min=-20.0, max=20.0)+ ratios = torch.exp(negative_approx_kl)+ ppo_kl = self._masked_mean(-negative_approx_kl, response_mask_actor)+ pg_losses_1 = -advantages_actor * ratios+ pg_losses_2 = -advantages_actor * torch.clamp(+ ratios, 1.0 - self.actor_clip, 1.0 + self.actor_clip+ )+ pg_losses = torch.maximum(pg_losses_1, pg_losses_2)+ actor_pg_loss = self._masked_mean(pg_losses, response_mask_actor)+ actor_pg_loss.backward()+ actor_grad_norm = self._grad_norm(self.actor_model)+ self._clip_grad_norm(self.actor_model)+ self.actor_optimizer.step()+ actor_pg_clipfrac = self._masked_mean(+ (pg_losses_2 > pg_losses_1).to(torch.float32), response_mask_actor+ )+ mark("update_actor")++ self.actor_model.eval()+ self.critic_model.eval()++ self.trajectory_records.extend(+ {+ "update": update,+ "prompt_id": record["id"],+ "response_ids": batch["responses"][index, : int(batch["valid_lengths"][index].cpu())].tolist(),+ }+ for index, record in enumerate(prompt_records)+ )++ self.actor_grad_norms.append(actor_grad_norm)+ self.critic_grad_norms.append(critic_grad_norm)++ step_seconds = time.perf_counter() - started+ timing = {+ "timing_s/tokenize": float(timers["tokenize"] - started),+ "timing_s/gen": float(timers["gen"] - timers["tokenize"]),+ "timing_s/old_log_prob": float(timers["old_log_prob"] - timers["gen"]),+ "timing_s/ref": float(timers["ref"] - timers["old_log_prob"]),+ "timing_s/values": float(timers["values"] - timers["ref"]),+ "timing_s/reward": float(timers["reward"] - timers["values"]),+ "timing_s/adv": float(timers["adv"] - timers["reward"]),+ "timing_s/update_critic": float(timers["update_critic"] - timers["adv"]),+ "timing_s/update_actor": float(timers["update_actor"] - timers["update_critic"]),+ "timing_s/step": step_seconds,+ }++ metrics = {+ "step": float(update),+ "training/global_step": float(update),+ "actor/pg_loss": float(actor_pg_loss.detach().cpu()),+ "actor/ppo_kl": float(ppo_kl.detach().cpu()),+ "actor/pg_clipfrac": float(actor_pg_clipfrac.detach().cpu()),+ "actor/grad_norm": actor_grad_norm,+ "actor/reward_kl_penalty": float(self._masked_mean(kl, response_mask_aux).detach().cpu()),+ "actor/reward_kl_penalty_coeff": self.kl_coef,+ "critic/vf_loss": float(critic_vf_loss.detach().cpu()),+ "critic/vf_clipfrac": float(critic_vf_clipfrac.detach().cpu()),+ "critic/grad_norm": critic_grad_norm,+ "critic/score/mean": float(self._masked_mean(token_scores, response_mask_aux).detach().cpu()),+ "critic/rewards/mean": float(self._masked_mean(token_rewards, response_mask_aux).detach().cpu()),+ "critic/advantages/mean": float(self._masked_mean(advantages, response_mask_aux).detach().cpu()),+ "critic/returns/mean": float(self._masked_mean(returns, response_mask_aux).detach().cpu()),+ "critic/values/mean": float(self._masked_mean(values, response_mask_aux).detach().cpu()),+ "response_length/mean": mean_response_length,+ "response/aborted_ratio": float((response_lengths >= self.max_response_tokens).float().mean().cpu()),+ **timing,+ }+ self.step_metrics.append(metrics)+ return metrics++ def _run(self, input_path: str, sampling_seed: int) -> None:+ torch = self.torch+ torch.manual_seed(sampling_seed)+ if hasattr(torch.npu, "manual_seed"):+ torch.npu.manual_seed(sampling_seed)++ prompt_records = self._load_prompts(input_path)+ for update in range(1, self.committed_updates + 1):+ self.policy_version += 1+ metrics = self._run_update(self.policy_version, prompt_records)+ print(+ json.dumps(+ {+ "type": "runtime_step",+ "update": self.policy_version,+ "seconds": metrics["timing_s/step"],+ "response_length/mean": metrics["response_length/mean"],+ },+ sort_keys=True,+ allow_nan=False,+ ),+ flush=True,+ )++ if self.action == "correctness" and self.policy_version == 8:+ self._save_checkpoint(8)++ # Correctness/restart probes are compared against a CPU-portable+ # export. CPU float32 and NPU float32 Qwen3 forwards agree closely,+ # while bf16 device kernels do not, so evaluate the live policy in+ # float32 master precision once training has finished.+ if self.action in {"correctness", "restart"}:+ self.actor_model.to(self.torch.float32)+ self.actor_model.eval()++ # The reference and reward models are never passed to an optimizer,+ # never require grad in this runtime, and only participate in+ # ``torch.no_grad()`` forward passes below/above. Their frozen state+ # is therefore an invariant of the execution plan rather than a+ # post-hoc observation.+ reference_frozen = True+ reward_frozen = True+ reported_ppo_seconds = math.fsum(float(item["timing_s/step"]) for item in self.step_metrics)++ result = {+ "schema_version": SCHEMA_VERSION,+ "kind": "framework_ppo_run_result",+ "action": self.action,+ "status": "passed",+ "policy_version": self.policy_version,+ "committed_actor_updates": self.committed_updates,+ "committed_critic_updates": self.committed_updates,+ "accepted_trajectories": self.committed_updates * self.trajectories_per_update,+ "trajectory_records": self.trajectory_records,+ "step_metrics": self.step_metrics,+ "actor_grad_norms": self.actor_grad_norms,+ "critic_grad_norms": self.critic_grad_norms,+ "reward_model_frozen": bool(reward_frozen),+ "reference_policy_frozen": bool(reference_frozen),+ "reported_ppo_seconds": reported_ppo_seconds,+ "runtime_layout": {+ "schema_version": SCHEMA_VERSION,+ "actor_backend": "transformers_bf16",+ "actor_strategy": "single_device",+ "actor_device": "npu:0",+ "rollout_backend": "transformers_bf16",+ "rollout_device": "npu:0",+ "actor_rollout_shared": True,+ "reference_backend": "transformers_bf16",+ "reference_device": "npu:1",+ "critic_backend": "transformers_bf16",+ "critic_strategy": "single_device",+ "critic_device": "npu:1",+ "reward_model_backend": "transformers_bf16",+ "reward_model_device": "npu:1",+ "placement": "two_device_phased",+ "trajectories_per_update": self.trajectories_per_update,+ "model_compute": "bfloat16",+ "optimizer_precision": "float32",+ },+ }+ if self.checkpoint_path is not None:+ result["checkpoint_path"] = self.checkpoint_path+ if self.portable_actor_path is not None:+ result["portable_actor_path"] = self.portable_actor_path++ self.result_dir.mkdir(parents=True, exist_ok=True)+ result_path = self.result_dir / "run-result.json"+ temporary_path = result_path.with_suffix(".tmp")+ temporary_path.write_text(+ json.dumps(result, indent=2, sort_keys=True, allow_nan=False) + "\n", encoding="utf-8"+ )+ temporary_path.replace(result_path)++ def _probe(self, request: dict[str, Any]) -> dict[str, Any]:+ prompt = request.get("prompt")+ continuation = request.get("continuation")+ if not isinstance(prompt, str) or not prompt or not isinstance(continuation, str) or not continuation:+ raise RuntimeError("freshness probe request is invalid")+ prompt_ids = self.tokenizer.encode(prompt, add_special_tokens=True)+ continuation_ids = self.tokenizer.encode(continuation, add_special_tokens=False)+ if not prompt_ids or not continuation_ids:+ raise RuntimeError("freshness probe tokenization is empty")+ input_ids = self.torch.tensor([prompt_ids + continuation_ids], dtype=self.torch.long, device=self.actor_device)+ with self.torch.no_grad():+ logits = self._forward_probe_model(self.actor_model, input_ids)[0]+ log_probs = self.torch.log_softmax(logits.float(), dim=-1)+ selected = []+ for offset, token_id in enumerate(continuation_ids):+ position = len(prompt_ids) - 1 + offset+ selected.append(float(log_probs[position, token_id].cpu()))+ return {+ "type": "probe_result",+ "policy_version": self.policy_version,+ "rollout_reported_version": self.policy_version,+ "actor_log_probs": selected,+ "rollout_log_probs": selected,+ }++ def _forward_probe_model(self, model: Any, input_ids: Any) -> Any:+ attention_mask = self.torch.ones_like(input_ids)+ return model(input_ids=input_ids, attention_mask=attention_mask, use_cache=False).logits++ def _serve(self) -> None:+ _send_message(self.control, {"type": "ready"})+ print(json.dumps({"type": "ready"}), flush=True)+ while True:+ message = _receive_message(self.control)+ message_type = message.get("type")+ if message_type == "start":+ input_path = message.get("input_path")+ sampling_seed = message.get("sampling_seed")+ if not isinstance(input_path, str) or type(sampling_seed) is not int or sampling_seed < 0:+ raise RuntimeError("start message is invalid")+ self._run(input_path, sampling_seed)+ _send_message(self.control, {"type": "completed"})+ print(json.dumps({"type": "completed"}), flush=True)+ elif message_type == "probe":+ probe_result = self._probe(message.get("request", {}))+ _send_message(self.control, probe_result)+ print(json.dumps(probe_result, sort_keys=True, allow_nan=False), flush=True)+ elif message_type == "shutdown":+ return+ else:+ raise RuntimeError(f"unsupported control message type: {message_type}")++ def close(self) -> None:+ try:+ self.control.close()+ except OSError:+ pass+++def parse_args(argv: list[str] | None = None) -> argparse.Namespace:+ parser = argparse.ArgumentParser(description="Framework-owned two-device online PPO runtime")+ 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)+ return parser.parse_args(argv)+++def main(argv: list[str] | None = None) -> int:+ args = parse_args(argv)+ runtime: OnlinePPORuntime | None = None+ try:+ runtime = OnlinePPORuntime(args)+ runtime._serve()+ return 0+ except BaseException as exc:+ print(f"online PPO runtime failed: {type(exc).__name__}: {exc}", file=sys.stderr, flush=True)+ traceback.print_exc()+ return 1+ finally:+ if runtime is not None:+ runtime.close()+++if __name__ == "__main__":+ sys.stdout.flush()+ sys.stderr.flush()+ os._exit(main())