Kimi K3 · RL

R03 · PPO joint

Correctness rejected

Qwen3-1.7B online PPO 2dev · Joint Optimization

—PERFORMANCE RATIO
138TOOL EVENTS
1TEXT PATCHES
0BINARY NAMES

01 / PROCESS MAP

Tool activity

Each row shows one agent’s tool events in its own recorded order. Colors show broad activities; bar widths do not represent duration.

Main agentKimi K3 · 138 visible calls

InspectEditValidateExecuteBuildProfileRollbackOther
69Inspect
21Edit
24Validate
9Execute
1Profile
14Other

02 / EVENT SEQUENCE

Event timeline

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.

Show event timelineHide event timeline99 groups · 138 calls

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>.

Main agent

  1. Inspect · Source & workspace

    Requested workspace inspection related to source & workspace.

    1 call · #0001–#0001

    echo <val>ls <val> <n> > <path>
  2. Inspect · Task requirements

    Requested file and log inspection, environment setup or inspection and workspace inspection related to task requirements.

    3 calls · #0002–#0004

    Read <path>env <vars>ls -R <path> <path> <path> <path> <path>
  3. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0005–#0005

    Read <path>
  4. Inspect · Reward & policy updates

    Requested file and log inspection related to reward & policy updates.

    1 call · #0006–#0006

    Read <path>
  5. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    2 calls · #0007–#0008

    Read <path>
  6. Inspect · Benchmark & validation setup

    Requested file and log inspection related to benchmark & validation setup.

    3 calls · #0009–#0011

    Read <path>
  7. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    9 calls · #0012–#0020

    Read <path>sed -n <val> <path>
  8. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    1 call · #0021–#0021

    cat <path>echo <flag>head -c <n> <path>
  9. Inspect · Source & workspace

    Requested environment setup or inspection, source searches and file and log inspection related to source & workspace.

    2 calls · #0022–#0023

    envgrep -E <val>sortecho <flag>cat <val> <n> > <path>head -c <n>
    1 more command sketches
    Read <path>
  10. Inspect · Benchmark & validation setup

    Requested file and log inspection related to benchmark & validation setup.

    1 call · #0024–#0024

    Read <path>
  11. Inspect · Device memory

    Requested runtime inspection, file and log inspection and workspace inspection related to device memory.

    1 call · #0025–#0025

    npu-smi info <n> > <path>head -n <n>echo <flag>ls <path> <n> > <path>
  12. Inspect · Source & workspace

    Requested script or workload execution, file and log inspection and workspace inspection related to source & workspace.

    4 calls · #0026–#0029

    python3 -c <script> <n> >& <path>tail -n <n>echo <val>ls <path>grep -i -E <val>head
    4 more command sketches
    echo <flag>cat <path>head -n <n> <path>grep -n <val> <path>
  13. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    1 call · #0030–#0030

    Read <path>
  14. Inspect · Source & workspace

    Requested file and log inspection, task coordination and source searches related to source & workspace.

    5 calls · #0031–#0035

    sed -n <val> <path>Update task list <tasks>grep -n <val> <path>headsed -n <path> <path>cd <path>
    6 more command sketches
    env <vars> python3 - <script>head -n <n> <path>grep -E <val>echo <val>ls <path> <n> > <path>grep -c <val> <path>
  15. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0036–#0037

    Write <path>
  16. Inspect · Source & workspace

    Requested environment setup or inspection related to source & workspace.

    1 call · #0038–#0038

    cd <path>env <vars> timeout <n> <path> <val> <script>
  17. Edit · Source & workspace

    Requested code edits and source searches related to source & workspace.

    1 call · #0039–#0039

    cd <path>sed -i <path> <path>grep -n <val> <path>
  18. Validate · Benchmark & validation setup

    1 tool error

    Requested workspace file updates, script or workload execution and file and log inspection related to benchmark & validation setup.

    2 calls · #0040–#0041

    mkdir -p <val>cd <path>timeout <n> <val> <path> > <path> <n> >& <path>echo <val>tail -n <n> <path>
  19. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0042–#0042

    Edit <path>
  20. Inspect · Source & workspace

    Requested file and log inspection and runtime inspection related to source & workspace.

    1 call · #0043–#0043

    df -h <path>tail -n <n>free -ghead -n <n>
  21. Inspect · Benchmark & validation setup

    Requested file and log inspection and workspace inspection related to benchmark & validation setup.

    1 call · #0044–#0044

    tail -n <n> <path>echo <val>ls <val>
  22. Validate · Benchmark & validation setup

    Requested script or workload execution related to benchmark & validation setup.

    1 call · #0045–#0045

    python3 -c <script>
  23. Inspect · Runtime processes

    Requested source searches, runtime inspection and file and log inspection related to runtime processes.

    1 call · #0046–#0046

    tr <val> <val> < <path> <n> > <path>grep <flag> <args>sort -uecho <flag>ps <flag> <args>grep -E <val>
    3 more command sketches
    grep -v <val>awk <val>head
  24. Inspect · Source & workspace

    Requested runtime inspection and file and log inspection related to source & workspace.

    1 call · #0047–#0047

    echo <val>ps -o <val> -p <val> <n> > <path>head -n <n>ps -o <val> -p <n> <n> > <path>cut <flag>
  25. Validate · Benchmark & validation setup

    Requested script or workload execution related to benchmark & validation setup.

    1 call · #0048–#0048

    python3 -c <script>
  26. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0049–#0049

    Write <path>
  27. Validate · Benchmark & validation setup

    Requested script or workload execution and file and log inspection related to benchmark & validation setup.

    1 call · #0050–#0050

    cd <path>timeout <n> <val> <path> <val> <n> >& <path>tail -n <n>
  28. Other · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0051–#0051

    Read task output <task>
  29. Inspect · Source & workspace

    Requested script or workload execution and workspace inspection related to source & workspace.

    1 call · #0052–#0052

    python3 -m <module> <script>echo <val>ls <path> <n> > <path>ls <val> <n> > <path>
  30. Validate · Benchmark & validation setup

    Requested file and log inspection related to benchmark & validation setup.

    1 call · #0053–#0053

    tail -n <n> <path> <n> > <path>echo <val>
  31. Inspect · Source & workspace

    Requested file and log inspection and task coordination related to source & workspace.

    2 calls · #0054–#0055

    cat <path>Update task list <tasks>
  32. Validate · Benchmark & validation setup

    Requested script or workload execution and file and log inspection related to benchmark & validation setup.

    1 call · #0056–#0056

    cd <path>timeout <n> <val> <path> <val> <val> <n> >& <path>tail -n <n>
  33. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0057–#0057

    cd <path>python3 -X <val> -c <script> <n> > <path>python3 - <script>
  34. Inspect · Source & workspace

    Requested workspace inspection, file and log inspection and environment setup or inspection related to source & workspace.

    2 calls · #0058–#0059

    ls -l -a <val> <n> > <path>headfind <val> -maxdepth <n> -name <val> <flag> <args>ls <path> <n> > <path>envgrep -i <val>
    1 more command sketches
    cat <path>
  35. Validate · Benchmark & validation setup

    Requested file and log inspection related to benchmark & validation setup.

    1 call · #0060–#0060

    tail -n <n> <path> <n> > <path>echo <val> <val> <val>
  36. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0061–#0061

    Read <path>
  37. Edit · Source & workspace

    Requested code edits related to source & workspace.

    5 calls · #0062–#0066

    Edit <path>
  38. Edit · Batching & scheduling

    Requested code edits and source searches related to batching & scheduling.

    1 call · #0067–#0067

    cd <path>sed -i <path> <path>grep -c <val> <path>
  39. Edit · Source & workspace

    Requested code edits related to source & workspace.

    3 calls · #0068–#0070

    Edit <path>
  40. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0071–#0071

    python3 -m <module> <script>echo <val>
  41. Validate · Benchmark & validation setup

    Requested script or workload execution and file and log inspection related to benchmark & validation setup.

    1 call · #0072–#0072

    cd <path>timeout <n> <val> <path> <val> <n> >& <path>tail -n <n>
  42. Other · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0073–#0073

    Read task output <task>
  43. Other · Task requirements

    Requested script or workload execution related to task requirements.

    1 call · #0074–#0074

    python3 - <script>
  44. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0075–#0075

    cat <path>
  45. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0076–#0076

    Edit <path>
  46. Validate · Benchmark & validation setup

    Requested script or workload execution and file and log inspection related to benchmark & validation setup.

    1 call · #0077–#0077

    cd <path>timeout <n> <val> <path> <val> <n> >& <path>tail -n <n>
  47. Other · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0078–#0078

    Read task output <task>
  48. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0079–#0079

    sed -n <val> <path>
  49. Other · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0080–#0080

    Read task output <task>
  50. Validate · Benchmark & validation setup

    Requested execution waits, file and log inspection and source searches related to benchmark & validation setup.

    1 call · #0081–#0081

    sleep <n>tail -n <n> <path> <n> > <path>grep -v <val>
  51. Inspect · Batching & scheduling

    Requested source searches related to batching & scheduling.

    1 call · #0082–#0082

    cd <path>grep -n <val> <path>
  52. Edit · Batching & scheduling

    Requested code edits and script or workload execution related to batching & scheduling.

    1 call · #0083–#0083

    cd <path>sed -i <path> <path>python3 -m <module> <script>echo <val>
  53. Other · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0084–#0084

    Read task output <task>
  54. Validate · Batching & scheduling

    Requested script or workload execution and file and log inspection related to batching & scheduling.

    1 call · #0085–#0085

    cd <path>timeout <n> <val> <path> <val> <n> >& <path>tail -n <n>
  55. Other · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0086–#0086

    Read task output <task>
  56. Inspect · Source & workspace

    Requested source searches, script or workload execution and file and log inspection related to source & workspace.

    1 call · #0087–#0087

    grep -n <val> <path>python3 -c <script> <n> > <path>tail -n <n>
  57. Validate · Benchmark & validation setup

    Requested execution waits and file and log inspection related to benchmark & validation setup.

    1 call · #0088–#0088

    sleep <n>tail -n <n> <path> <n> > <path>
  58. Other · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0089–#0089

    Read task output <task>
  59. Validate · Benchmark & validation setup

    Requested execution waits and file and log inspection related to benchmark & validation setup.

    1 call · #0090–#0090

    sleep <n>tail -n <n> <path> <n> > <path>
  60. Inspect · Benchmark & validation setup

    Requested file and log inspection and source searches related to benchmark & validation setup.

    1 call · #0091–#0091

    cat <path>tail -n <n>echo <val>tail -n <n> <path>grep -v <val>
  61. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0092–#0092

    Edit <path>
  62. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0093–#0093

    sed -n <val> <path>
  63. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0094–#0094

    Edit <path>
  64. Validate · Benchmark & validation setup

    Requested script or workload execution and file and log inspection related to benchmark & validation setup.

    1 call · #0095–#0095

    python3 -m <module> <script>echo <val>cd <path>timeout <n> <val> <path> <val> > <path> <n> >& <path>tail -n <n> <path>
  65. Other · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0096–#0096

    Read task output <task>
  66. Validate · Benchmark & validation setup

    Requested execution waits and file and log inspection related to benchmark & validation setup.

    1 call · #0097–#0097

    sleep <n>tail -n <n> <path> <n> > <path>
  67. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0098–#0098

    cat <path>
  68. Validate · Benchmark & validation setup

    Requested script or workload execution and file and log inspection related to benchmark & validation setup.

    1 call · #0099–#0099

    cd <path>timeout <n> <val> <path> <val> <val> > <path> <n> >& <path>echo <val>tail -n <n> <path>
  69. Inspect · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0100–#0100

    Update task list <tasks>
  70. Validate · Checkpoints & weight state

    Requested execution waits, source searches and file and log inspection related to checkpoints & weight state.

    1 call · #0101–#0101

    sleep <n>grep -E <val> <path> <n> > <path>tail -n <n>
  71. Inspect · Source & workspace

    Requested source searches, file and log inspection and execution waits related to source & workspace.

    4 calls · #0102–#0105

    grep -n <val> -A <n> <path>sed -n <val>sleep <n>tail -n <n> <path> <n> > <path>grep -E <val> <path> <n> > <path>tail -n <n>
    2 more command sketches
    cat <path>Update task list <tasks>
  72. Inspect · Attention kernels

    Requested environment setup or inspection related to attention kernels.

    2 calls · #0106–#0107

    cd <path>env <vars> timeout <n> <path> <val> <script>
  73. Profile · Attention kernels

    Requested environment setup or inspection related to attention kernels.

    1 call · #0108–#0108

    cd <path>env <vars> timeout <n> <path> <val> <script>
  74. Inspect · Runtime processes

    Requested workspace file updates, file and log inspection and runtime inspection related to runtime processes.

    2 calls · #0109–#0110

    mkdir -p <path>cat > <path> <script>chmod <val> <path>ps <flag> <args>awk <val>wc -l
    3 more command sketches
    env <vars> ps <flag> <args>grep <flag> <args>env <vars> python3 -c <script>
  75. Execute · Benchmark & validation setup

    Requested environment setup or inspection and file and log inspection related to benchmark & validation setup.

    1 call · #0111–#0111

    cd <path>env <vars> timeout <n> <val> <path> > <path> <n> >& <path>echo <val> >> <path>tail -n <n> <path>
  76. Inspect · Source & workspace

    Requested script or workload execution and file and log inspection related to source & workspace.

    1 call · #0112–#0112

    python3 -c <script> <n> >& <path>tail -n <n>
  77. Execute · Benchmark & validation setup

    1 tool error

    Requested file and log inspection and script or workload execution related to benchmark & validation setup.

    1 call · #0113–#0113

    cat <path>echo <val>python3 -c <script>
  78. Execute · Task requirements

    Requested environment setup or inspection and file and log inspection related to task requirements.

    1 call · #0114–#0114

    cd <path>env <vars> timeout <n> <val> <path> > <path> <n> >& <path>echo <val> >> <path>tail -n <n> <path>
  79. Other · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0115–#0115

    Read task output <task>
  80. Execute · Benchmark & validation setup

    Requested execution waits and file and log inspection related to benchmark & validation setup.

    1 call · #0116–#0116

    sleep <n>tail -n <n> <path> <n> > <path>
  81. Inspect · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0117–#0117

    Update task list <tasks>
  82. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0118–#0119

    Edit <path>
  83. Validate · Benchmark & validation setup

    Requested script or workload execution and file and log inspection related to benchmark & validation setup.

    1 call · #0120–#0120

    python3 -m <module> <script>echo <val>cd <path>timeout <n> <val> <path> <val> > <path> <n> >& <path>tail -n <n> <path>
  84. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0121–#0121

    Read <path>
  85. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0122–#0122

    Edit <path>
  86. Inspect · Source & workspace

    Requested script or workload execution, source searches and file and log inspection related to source & workspace.

    2 calls · #0123–#0124

    python3 -c <script> <n> >& <path>grep -v <val>tail -n <n>cat <path>
  87. Execute · Task requirements

    Requested environment setup or inspection and file and log inspection related to task requirements.

    1 call · #0125–#0125

    cd <path>env <vars> timeout <n> <val> <path> > <path> <n> >& <path>echo <val> >> <path>tail -n <n> <path>
  88. Other · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0126–#0126

    Stop task <task>
  89. Execute · Benchmark & validation setup

    Requested workspace file updates, runtime inspection and source searches related to benchmark & validation setup.

    1 call · #0127–#0127

    rm -f <path> <path>rm -rf <path>ps <flag> <args>grep -E <val>grep -v <val>head -n <n>
    1 more command sketches
    echo <val>
  90. Execute · Task requirements

    Requested environment setup or inspection and file and log inspection related to task requirements.

    1 call · #0128–#0128

    cd <path>env <vars> timeout <n> <val> <path> > <path> <n> >& <path>echo <val> >> <path>tail -n <n> <path>
  91. Execute · Benchmark & validation setup

    Requested execution waits, source searches and file and log inspection related to benchmark & validation setup.

    2 calls · #0129–#0130

    sleep <n>grep -E <val> <path> <n> > <path>tail -n <n>python3 -c <script>
  92. Inspect · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0131–#0131

    Update task list <tasks>
  93. Validate · Benchmark & validation setup

    Requested workspace file updates related to benchmark & validation setup.

    1 call · #0132–#0132

    rm -f <path> <path> <path> <path> <path>echo <val>
  94. Validate · Task requirements

    Requested environment setup or inspection and script or workload execution related to task requirements.

    1 call · #0133–#0133

    cd <path>export <vars><command> <args>echo <val>timeout <n> <val> <path> > <path> <n> >& <path>
  95. Other · Runtime processes

    Requested script or workload execution related to runtime processes.

    1 call · #0134–#0134

    cd <path>bash <script> <n> > <path>python3 -c <script>
  96. Validate · Checkpoints & weight state

    Requested execution waits, file and log inspection and source searches related to checkpoints & weight state.

    1 call · #0135–#0135

    sleep <n>echo <flag>tail -n <n> <path> <n> > <path>grep -E <val> <path> <n> > <path>tail -n <n>
  97. Inspect · Source & workspace

    Requested execution waits, file and log inspection and source searches related to source & workspace.

    1 call · #0136–#0136

    sleep <n>tail -n <n> <path> <n> > <path>grep -E <val> <path> <n> > <path>tail -n <n>
  98. Validate · Rollout generation

    Requested file and log inspection and script or workload execution related to rollout generation.

    1 call · #0137–#0137

    cat <path>python3 -c <script>
  99. Validate · Benchmark & validation setup

    1 tool error

    Requested script or workload execution, file and log inspection and source searches related to benchmark & validation setup.

    1 call · #0138–#0138

    python3 -c <script>echo <val>tail -n <n> <path> <n> > <path>grep -v <val>tail -n <n>

03 / CANDIDATE ARTIFACT

Text patches & binary names

Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.

verl · 3 changed files

Base commit: 0b2151ec61de5d99e0811b01c09e43a99a23e69d

diff --git a/verl/__init__.py b/verl/__init__.pyindex 26af7e77f19905538f4cdfabc7fbb74e8acd9471..b986cb1b222d699e77d69f1492694f099ac4aa8b 100644--- a/verl/__init__.py+++ b/verl/__init__.py@@ -18,11 +18,20 @@ import os  from packaging.version import parse as parse_version -from .protocol import DataProto from .utils.device import is_npu_available from .utils.import_utils import import_external_libs from .utils.logging_utils import set_basic_config ++def __getattr__(name: str):+    # Defer importing `verl.protocol` (which pulls in ray/tensordict) until the+    # attribute is actually accessed, keeping lightweight entrypoints fast.+    if name == "DataProto":+        from .protocol import DataProto++        return DataProto+    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ version_folder = os.path.dirname(os.path.join(os.path.abspath(__file__)))  with open(os.path.join(version_folder, "version/version")) as f:diff --git a/verl/trainer/runtime/__init__.py b/verl/trainer/runtime/__init__.pynew file mode 100644index 0000000000000000000000000000000000000000..142f71bf354962a6855c10d1bc4898379fe3e0e2--- /dev/null+++ b/verl/trainer/runtime/__init__.py@@ -0,0 +1,15 @@+# Copyright 2024 Bytedance Ltd. and/or its affiliates+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+#     http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""Runtime entrypoints for the verl trainer."""diff --git a/verl/trainer/runtime/online_ppo.py b/verl/trainer/runtime/online_ppo.pynew file mode 100644index 0000000000000000000000000000000000000000..c9320045c91e90f6abbb5f1d47eaa6bd166da9c6--- /dev/null+++ b/verl/trainer/runtime/online_ppo.py@@ -0,0 +1,873 @@+# Copyright 2024 Bytedance Ltd. and/or its affiliates+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+#     http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++"""Framework-owned online PPO runtime for two-device Ascend hosts.++This module implements the `verl.trainer.runtime.online_ppo` entrypoint used by+the online PPO runtime contract.  It is a self-contained, single-process PPO+engine that colocates the four model roles on at most two Ascend devices+without Ray, vLLM, or CPU offloading:++    device 0: trainable actor (bf16 compute, fp32 AdamW master weights),+              also serves half of the rollout generation shards+    device 1: rollout policy copy + frozen reference policy+              + trainable critic (bf16/fp32 master)+              + frozen sequence-classification reward model++The runtime speaks a one-JSON-object-per-line protocol over a Unix stream+socket: it loads all models, reports ``ready``, executes the fixed PPO work on+``start``, answers a policy-freshness ``probe``, and exits cleanly on+``shutdown``.+"""++from __future__ import annotations++import argparse+import json+import math+import os+import socket+import sys+import threading+import time+import traceback+from pathlib import Path++import torch+import torch.nn.functional as F++try:+    import torch_npu  # noqa: F401+except ImportError:  # pragma: no cover - the runtime always targets NPU hosts+    torch_npu = None+++MICRO_BATCH = 16+++def _run_parallel(jobs: dict) -> dict:+    """Run device-bound callables concurrently; re-raise the first failure."""+    results: dict = {}++    def _wrap(tag, fn):+        try:+            results[tag] = fn()+        except BaseException:+            results[tag] = sys.exc_info()[1]++    threads = [+        threading.Thread(target=_wrap, args=(tag, fn)) for tag, fn in jobs.items()+    ]+    for thread in threads:+        thread.start()+    for thread in threads:+        thread.join()+    for tag, value in results.items():+        if isinstance(value, BaseException):+            raise value+    return results+++def _log(message: str) -> None:+    print(f"[online_ppo {time.strftime('%H:%M:%S')}] {message}", flush=True)+++def _send(conn: socket.socket, value: dict) -> None:+    conn.sendall(json.dumps(value, allow_nan=False, separators=(",", ":")).encode("utf-8") + b"\n")+++def _recv(conn: socket.socket) -> dict:+    raw = bytearray()+    while not raw.endswith(b"\n"):+        chunk = conn.recv(65536)+        if not chunk:+            raise RuntimeError("control connection closed by host")+        raw.extend(chunk)+    return json.loads(raw)+++class _Sampler:+    """Seeded temperature / top-k / top-p sampler matching the workload contract."""++    def __init__(self, temperature: float, top_p: float, top_k: int, eos_ids: tuple[int, ...]):+        self.temperature = float(temperature)+        self.top_p = float(top_p)+        self.top_k = int(top_k)+        self.eos_ids = tuple(int(v) for v in eos_ids)++    def sample(self, logits: torch.Tensor, generator: torch.Generator) -> torch.Tensor:+        scores = logits.float() / self.temperature+        k = min(self.top_k, scores.shape[-1])+        vals, idx = torch.topk(scores, k, dim=-1)+        probs = torch.softmax(vals, dim=-1)+        sprobs, sidx = torch.sort(probs, descending=True, dim=-1)+        cum = torch.cumsum(sprobs, dim=-1)+        keep = (cum - sprobs) < self.top_p+        sprobs = torch.where(keep, sprobs, torch.zeros_like(sprobs))+        sprobs = sprobs / sprobs.sum(dim=-1, keepdim=True).clamp_min(1e-12)+        pick = torch.multinomial(sprobs, 1, generator=generator)+        return idx.gather(-1, sidx.gather(-1, pick)).squeeze(1)+++class _AdamWMaster:+    """AdamW over fp32 master weights with bf16 model parameters."""++    def __init__(self, params: list[torch.Tensor], lr: float):+        self.params = list(params)+        self.masters = [+            p.detach().to(torch.float32).clone().requires_grad_(True) for p in self.params+        ]+        self.optimizer = torch.optim.AdamW(+            self.masters, lr=lr, betas=(0.9, 0.999), eps=1e-8, weight_decay=0.01+        )++    def step(self, max_grad_norm: float) -> float:+        total = torch.zeros((), dtype=torch.float32, device=self.params[0].device)+        grads = []+        for p in self.params:+            g = p.grad+            grads.append(g)+            if g is not None:+                total += g.detach().float().pow(2).sum()+        norm = torch.sqrt(total)+        clip = (max_grad_norm / (norm + 1e-6)).clamp(max=1.0)+        with torch.no_grad():+            for p, m, g in zip(self.params, self.masters, grads):+                if g is None:+                    m.grad = None+                    continue+                m.grad = g.detach().float() * clip+        self.optimizer.step()+        with torch.no_grad():+            for p, m in zip(self.params, self.masters):+                p.copy_(m.to(p.dtype))+                p.grad = None+        return float(norm.item())++    def state_dict_cpu(self) -> dict:+        state = self.optimizer.state_dict()+        for group in state["state"].values():+            for key, value in group.items():+                if torch.is_tensor(value):+                    group[key] = value.cpu()+        return {+            "optimizer": state,+            "masters": [m.detach().cpu() for m in self.masters],+        }++    def load_state_dict_cpu(self, payload: dict) -> None:+        for m, saved in zip(self.masters, payload["masters"]):+            m.data.copy_(saved.to(m.device))+        state = payload["optimizer"]+        for group in state["state"].values():+            for key, value in group.items():+                if torch.is_tensor(value):+                    group[key] = value.to(self.masters[0].device)+        self.optimizer.load_state_dict(state)+        with torch.no_grad():+            for p, m in zip(self.params, self.masters):+                p.copy_(m.to(p.dtype))+++class OnlinePPORuntime:+    def __init__(self, args: argparse.Namespace):+        self.args = args+        self.spec = json.loads(Path(args.run_spec).read_text(encoding="utf-8"))+        self.action = self.spec["action"]+        self.algorithm = self.spec["algorithm"]+        self.sampling = self.spec["sampling"]+        self.measurement = self.spec["measurement"]+        self.resolved = self.spec["resolved_work"]+        self.max_prompt_tokens = int(self.measurement["max_prompt_tokens"])+        self.max_response_tokens = int(self.measurement["max_response_tokens"])+        self.updates = int(self.resolved["committed_updates"])+        self.gamma = float(self.algorithm["gamma"])+        self.gae_lambda = float(self.algorithm["lambda"])+        self.kl_coef = float(self.algorithm["reference_kl"]["coefficient"])+        self.actor_clip = float(self.algorithm["actor_clip"])+        self.value_clip = float(self.algorithm["value_clip"])+        self.actor_epochs = int(self.algorithm.get("actor_epochs", 1))+        self.critic_epochs = int(self.algorithm.get("critic_epochs", 1))+        self.actor_lr = float(self.spec["actor_optimizer"]["learning_rate"])+        self.critic_lr = float(self.spec["critic_optimizer"]["learning_rate"])+        self.committed_updates = 0+        self.rollout_version = 0+        self.trajectory_records: list[dict] = []+        self.step_metrics: list[dict] = []+        self.actor_grad_norms: list[float] = []+        self.critic_grad_norms: list[float] = []+        self.ppo_seconds = 0.0+        self.checkpoint_path = None+        self.portable_actor_path = None++    # ------------------------------------------------------------------ setup+    def setup(self) -> None:+        import torch_npu  # noqa: F401  (ensures NPU device registration)+        from transformers import (+            AutoConfig,+            AutoModelForCausalLM,+            AutoModelForSequenceClassification,+            AutoModelForTokenClassification,+            AutoTokenizer,+        )++        device_ids = [int(v) for v in self.spec["resource_ceiling"]["device_ids"]][:2]+        if len(device_ids) == 0:+            device_ids = [0]+        self.dev_actor = torch.device(f"npu:{device_ids[0]}")+        self.dev_rollout = torch.device(f"npu:{device_ids[-1]}")+        torch.npu.set_device(self.dev_actor)+        _log(f"devices: actor={self.dev_actor} rollout/ref/critic/rm={self.dev_rollout}")++        self.tokenizer = AutoTokenizer.from_pretrained(+            self.args.tokenizer_path, local_files_only=True, trust_remote_code=True+        )+        if self.tokenizer.pad_token_id is None:+            self.tokenizer.pad_token = self.tokenizer.eos_token+        self.pad_id = int(self.tokenizer.pad_token_id)+        gen_cfg = json.loads(+            (Path(self.args.policy_model_path) / "generation_config.json").read_text(encoding="utf-8")+        )+        eos = gen_cfg.get("eos_token_id", self.tokenizer.eos_token_id)+        eos_ids = eos if isinstance(eos, list) else [eos]+        if self.tokenizer.eos_token_id not in eos_ids:+            eos_ids.append(self.tokenizer.eos_token_id)+        self.sampler = _Sampler(+            self.sampling["temperature"], self.sampling["top_p"], self.sampling["top_k"],+            tuple(eos_ids),+        )++        load_dtype = torch.bfloat16+        t0 = time.monotonic()+        self.actor = AutoModelForCausalLM.from_pretrained(+            self.args.policy_model_path, dtype=load_dtype, local_files_only=True+        ).to(self.dev_actor)+        self.actor.requires_grad_(True)+        _log("actor loaded")+        self.reference = AutoModelForCausalLM.from_pretrained(+            self.args.policy_model_path, dtype=load_dtype, local_files_only=True+        ).to(self.dev_rollout)+        self.reference.requires_grad_(False)+        self.reference.eval()+        _log("reference loaded")+        self.rollout = AutoModelForCausalLM.from_pretrained(+            self.args.policy_model_path, dtype=load_dtype, local_files_only=True+        ).to(self.dev_rollout)+        self.rollout.requires_grad_(False)+        self.rollout.eval()+        _log("rollout loaded")++        critic_cfg = AutoConfig.from_pretrained(self.args.auxiliary_model_path)+        critic_cfg.num_labels = 1+        self.critic = AutoModelForTokenClassification.from_pretrained(+            self.args.auxiliary_model_path, config=critic_cfg,+            dtype=load_dtype, local_files_only=True,+        ).to(self.dev_rollout)+        self.critic.requires_grad_(True)+        _log("critic loaded")+        self.reward_model = AutoModelForSequenceClassification.from_pretrained(+            self.spec["reward_model_path"], dtype=load_dtype, local_files_only=True+        ).to(self.dev_rollout)+        self.reward_model.requires_grad_(False)+        self.reward_model.eval()+        _log("reward model loaded")++        self.actor_params = [p for _, p in self.actor.named_parameters()]+        self.critic_params = [p for _, p in self.critic.named_parameters()]+        self.actor_optim = _AdamWMaster(self.actor_params, lr=self.actor_lr)+        self.critic_optim = _AdamWMaster(self.critic_params, lr=self.critic_lr)++        restart = self.spec.get("restart_checkpoint")+        if restart:+            self._load_checkpoint(Path(restart))+        self._sync_rollout()+        torch.npu.synchronize(self.dev_actor)+        torch.npu.synchronize(self.dev_rollout)+        _log(f"setup completed in {time.monotonic() - t0:.1f}s")++    # ------------------------------------------------------------- primitives+    def _sync_rollout(self) -> None:+        with torch.no_grad():+            for (_, p), (_, q) in zip(+                self.actor.named_parameters(), self.rollout.named_parameters()+            ):+                q.copy_(p, non_blocking=True)+        torch.npu.synchronize(self.dev_rollout)+        self.rollout_version = self.committed_updates++    @staticmethod+    def _pad_batch(seqs: list[list[int]], pad_id: int, left: bool) -> tuple[torch.Tensor, torch.Tensor]:+        width = max(len(s) for s in seqs)+        ids = torch.full((len(seqs), width), pad_id, dtype=torch.long)+        mask = torch.zeros((len(seqs), width), dtype=torch.long)+        for row, seq in enumerate(seqs):+            if left:+                ids[row, width - len(seq):] = torch.tensor(seq, dtype=torch.long)+                mask[row, width - len(seq):] = 1+            else:+                ids[row, : len(seq)] = torch.tensor(seq, dtype=torch.long)+                mask[row, : len(seq)] = 1+        return ids, mask++    def _generate_shard(+        self,+        model,+        device: torch.device,+        prompts: list[list[int]],+        seed: int,+        out: dict,+        tag: str,+    ) -> None:+        try:+            torch.npu.set_device(device)+            with torch.no_grad():+                self._generate_shard_impl(model, device, prompts, seed, out, tag)+            torch.npu.empty_cache()+        except BaseException:+            out[tag] = sys.exc_info()[1]++    def _generate_shard_impl(+        self, model, device, prompts, seed, out, tag+    ) -> None:+        ids, mask = self._pad_batch(prompts, self.pad_id, left=True)+        ids = ids.to(device)+        mask = mask.to(device)+        positions = (mask.cumsum(-1) - 1).clamp(min=0)+        generator = torch.Generator(device=device)+        generator.manual_seed(seed)+        result = model(+            input_ids=ids, attention_mask=mask, position_ids=positions,+            use_cache=True, logits_to_keep=1,+        )+        cache = result.past_key_values+        logits = result.logits[:, -1, :]+        tokens: list[torch.Tensor] = []+        token_logps: list[torch.Tensor] = []+        finished = torch.zeros(ids.shape[0], dtype=torch.bool, device=device)+        cur_pos = mask.sum(-1, keepdim=True)+        for _ in range(self.max_response_tokens):+            step_logp = torch.log_softmax(logits.float(), dim=-1)+            token = self.sampler.sample(logits, generator)+            token = torch.where(finished, torch.full_like(token, self.pad_id), token)+            tokens.append(token)+            token_logps.append(+                step_logp.gather(-1, token.unsqueeze(-1)).squeeze(-1)+            )+            for eos_id in self.sampler.eos_ids:+                finished |= token == eos_id+            if bool(finished.all()):+                break+            mask = torch.cat([mask, torch.ones_like(cur_pos)], dim=1)+            step_pos = cur_pos+            cur_pos = cur_pos + 1+            result = model(+                input_ids=token.unsqueeze(1), attention_mask=mask,+                position_ids=step_pos, past_key_values=cache,+                use_cache=True, logits_to_keep=1,+            )+            cache = result.past_key_values+            logits = result.logits[:, -1, :]+        response = torch.stack(tokens, dim=1).cpu()+        logps = torch.stack(token_logps, dim=1).cpu()+        out[tag] = (response, logps)+        del cache, result++    def _generate(self, prompts: list[list[int]], seed: int) -> tuple[list[list[int]], torch.Tensor]:+        # Decode steps are dominated by per-op CPU launch overhead, and Python+        # threads serialize on the GIL, so one full batch on the rollout device+        # is faster than two half batches racing on both devices.+        out: dict[str, object] = {}+        self._generate_shard(self.rollout, self.dev_rollout, prompts, seed * 2 + 1, out, "shard0")+        value = out["shard0"]+        if isinstance(value, BaseException):+            raise value+        shard_tokens, shard_logps = value+        logps = torch.zeros(len(prompts), self.max_response_tokens, dtype=torch.float32)+        logps[:, : shard_logps.shape[1]] = shard_logps+        responses: list[list[int]] = []+        for row in shard_tokens.tolist():+            trimmed = row+            for pos, token_id in enumerate(row):+                if token_id in self.sampler.eos_ids:+                    trimmed = row[: pos + 1]+                    break+            responses.append(trimmed[: self.max_response_tokens])+        return responses, logps++    def _select_response_logprobs(+        self,+        model,+        device: torch.device,+        ids: torch.Tensor,+        mask: torch.Tensor,+        pos_idx: torch.Tensor,+        targets: torch.Tensor,+    ) -> torch.Tensor:+        values = []+        batch_index = torch.arange(ids.shape[0]).unsqueeze(1)+        with torch.no_grad():+            for start in range(0, ids.shape[0], MICRO_BATCH):+                stop = min(start + MICRO_BATCH, ids.shape[0])+                sub_ids = ids[start:stop].to(device)+                sub_mask = mask[start:stop].to(device)+                hidden = model.model(+                    input_ids=sub_ids, attention_mask=sub_mask, use_cache=False+                ).last_hidden_state+                picked = hidden[batch_index[: stop - start].to(device), pos_idx[start:stop].to(device)]+                logits = model.lm_head(picked)+                logp = torch.log_softmax(logits.float(), dim=-1)+                selected = logp.gather(-1, targets[start:stop].to(device).unsqueeze(-1)).squeeze(-1)+                values.append(selected.cpu())+        return torch.cat(values, dim=0)++    def _critic_values(self, ids, mask, val_idx) -> torch.Tensor:+        values = []+        batch_index = torch.arange(ids.shape[0]).unsqueeze(1)+        with torch.no_grad():+            for start in range(0, ids.shape[0], MICRO_BATCH):+                stop = min(start + MICRO_BATCH, ids.shape[0])+                hidden = self.critic.model(+                    input_ids=ids[start:stop].to(self.dev_rollout),+                    attention_mask=mask[start:stop].to(self.dev_rollout),+                    use_cache=False,+                ).last_hidden_state+                scores = self.critic.score(hidden).squeeze(-1)+                picked = scores[+                    batch_index[: stop - start].to(self.dev_rollout),+                    val_idx[start:stop].to(self.dev_rollout),+                ]+                values.append(picked.float().cpu())+        return torch.cat(values, dim=0)++    def _reward_scores(self, ids, mask, last_idx) -> torch.Tensor:+        scores = []+        with torch.no_grad():+            for start in range(0, ids.shape[0], MICRO_BATCH):+                stop = min(start + MICRO_BATCH, ids.shape[0])+                hidden = self.reward_model.model(+                    input_ids=ids[start:stop].to(self.dev_rollout),+                    attention_mask=mask[start:stop].to(self.dev_rollout),+                    use_cache=False,+                ).last_hidden_state+                logits = self.reward_model.score(hidden)+                rows = torch.arange(stop - start, device=self.dev_rollout)+                picked = logits[rows, last_idx[start:stop].to(self.dev_rollout)]+                scores.append(picked.float().cpu())+        return torch.cat(scores, dim=0)++    @staticmethod+    def _gae(rewards, values, mask, gamma, lam):+        steps = rewards.shape[1]+        rewards = rewards * mask+        values = values * mask+        next_values = torch.cat([values[:, 1:], torch.zeros_like(values[:, :1])], dim=1)+        delta = rewards + gamma * next_values - values+        advantages = torch.zeros_like(delta)+        running = torch.zeros_like(delta[:, 0])+        for t in range(steps - 1, -1, -1):+            running = delta[:, t] + gamma * lam * running+            advantages[:, t] = running+        advantages = advantages * mask+        returns = advantages + values * mask+        return advantages, returns++    # ---------------------------------------------------------------- updates+    def _actor_update(self, ids, mask, pos_idx, targets, resp_mask, old_logp, advantages):+        actor = self.actor+        actor.train()+        denom = resp_mask.sum().clamp(min=1.0)+        batch_index = torch.arange(ids.shape[0]).unsqueeze(1)+        pg_loss_sum = torch.zeros((), dtype=torch.float32)+        kl_sum = torch.zeros((), dtype=torch.float32)+        clip_sum = torch.zeros((), dtype=torch.float32)+        for _ in range(self.actor_epochs):+            for start in range(0, ids.shape[0], MICRO_BATCH):+                stop = min(start + MICRO_BATCH, ids.shape[0])+                sub_ids = ids[start:stop].to(self.dev_actor)+                sub_mask = mask[start:stop].to(self.dev_actor)+                hidden = actor.model(+                    input_ids=sub_ids, attention_mask=sub_mask, use_cache=False+                ).last_hidden_state+                picked = hidden[+                    batch_index[: stop - start].to(self.dev_actor),+                    pos_idx[start:stop].to(self.dev_actor),+                ]+                logits = actor.lm_head(picked)+                logp = torch.log_softmax(logits.float(), dim=-1)+                logp = logp.gather(-1, targets[start:stop].to(self.dev_actor).unsqueeze(-1)).squeeze(-1)+                old = old_logp[start:stop].to(self.dev_actor)+                adv = advantages[start:stop].to(self.dev_actor)+                rmask = resp_mask[start:stop].to(self.dev_actor)+                logratio = logp - old+                ratio = torch.exp(logratio)+                pg1 = -ratio * adv+                pg2 = -ratio.clamp(1.0 - self.actor_clip, 1.0 + self.actor_clip) * adv+                loss = (torch.max(pg1, pg2) * rmask).sum() / denom+                loss.backward()+                with torch.no_grad():+                    pg_loss_sum += (torch.max(pg1, pg2) * rmask).sum().cpu()+                    kl_sum += ((old - logp) * rmask).sum().cpu()+                    clip_sum += (+                        ((ratio - 1.0).abs() > self.actor_clip).float() * rmask+                    ).sum().cpu()+        norm = self.actor_optim.step(1.0)+        count = float(denom.item())+        return {+            "actor/pg_loss": float(pg_loss_sum) / count,+            "actor/ppo_kl": float(kl_sum) / count,+            "actor/pg_clipfrac": float(clip_sum) / count,+            "actor/grad_norm": norm,+        }++    def _critic_update(self, ids, mask, val_idx, resp_mask, old_values, returns):+        critic = self.critic+        critic.train()+        denom = resp_mask.sum().clamp(min=1.0)+        batch_index = torch.arange(ids.shape[0]).unsqueeze(1)+        vf_loss_sum = torch.zeros((), dtype=torch.float32)+        clip_sum = torch.zeros((), dtype=torch.float32)+        for _ in range(self.critic_epochs):+            for start in range(0, ids.shape[0], MICRO_BATCH):+                stop = min(start + MICRO_BATCH, ids.shape[0])+                hidden = critic.model(+                    input_ids=ids[start:stop].to(self.dev_rollout),+                    attention_mask=mask[start:stop].to(self.dev_rollout),+                    use_cache=False,+                ).last_hidden_state+                scores = critic.score(hidden).squeeze(-1)+                picked = scores[+                    batch_index[: stop - start].to(self.dev_rollout),+                    val_idx[start:stop].to(self.dev_rollout),+                ].float()+                old = old_values[start:stop].to(self.dev_rollout)+                ret = returns[start:stop].to(self.dev_rollout)+                rmask = resp_mask[start:stop].to(self.dev_rollout)+                clipped = old + (picked - old).clamp(-self.value_clip, self.value_clip)+                loss1 = (picked - ret) ** 2+                loss2 = (clipped - ret) ** 2+                loss = 0.5 * (torch.max(loss1, loss2) * rmask).sum() / denom+                loss.backward()+                with torch.no_grad():+                    vf_loss_sum += (torch.max(loss1, loss2) * rmask).sum().cpu()+                    clip_sum += (+                        ((picked - old).abs() > self.value_clip).float() * rmask+                    ).sum().cpu()+        norm = self.critic_optim.step(1.0)+        count = float(denom.item())+        return {+            "critic/vf_loss": 0.5 * float(vf_loss_sum) / count,+            "critic/vf_clipfrac": float(clip_sum) / count,+            "critic/grad_norm": norm,+        }++    # --------------------------------------------------------------- main run+    def run(self, input_path: str, sampling_seed: int) -> None:+        payload = json.loads(Path(input_path).read_text(encoding="utf-8"))+        system_prompt = payload["system_prompt"]+        prompt_records = payload["prompts"]+        prompt_ids_list = []+        for record in prompt_records:+            text = self.tokenizer.apply_chat_template(+                [+                    {"role": "system", "content": system_prompt},+                    {"role": "user", "content": record["question"]},+                ],+                tokenize=False,+                add_generation_prompt=True,+            )+            ids = self.tokenizer(text, add_special_tokens=False)["input_ids"]+            if not 1 <= len(ids) <= self.max_prompt_tokens:+                raise RuntimeError(f"prompt {record['id']} length {len(ids)} out of bounds")+            prompt_ids_list.append(ids)++        for step in range(1, self.updates + 1):+            update_no = self.committed_updates + step+            t_step = time.monotonic()+            self._sync_rollout()+            t_sync = time.monotonic()+            responses, old_logp = self._generate(prompt_ids_list, sampling_seed + update_no)+            torch.npu.synchronize(self.dev_actor)+            torch.npu.synchronize(self.dev_rollout)+            t_gen = time.monotonic()++            seqs = [p + r for p, r in zip(prompt_ids_list, responses)]+            plens = [len(p) for p in prompt_ids_list]+            rlens = [len(r) for r in responses]+            ids, mask = self._pad_batch(seqs, self.pad_id, left=False)+            max_r = self.max_response_tokens+            pos_idx = torch.zeros((len(seqs), max_r), dtype=torch.long)+            val_idx = torch.zeros((len(seqs), max_r), dtype=torch.long)+            targets = torch.zeros((len(seqs), max_r), dtype=torch.long)+            resp_mask = torch.zeros((len(seqs), max_r), dtype=torch.float32)+            last_idx = torch.zeros(len(seqs), dtype=torch.long)+            for row, (plen, rlen, resp) in enumerate(zip(plens, rlens, responses)):+                seq_len = plen + rlen+                for j in range(max_r):+                    jj = min(j, rlen - 1)+                    pos_idx[row, j] = plen - 1 + jj+                    val_idx[row, j] = plen + jj+                    targets[row, j] = resp[jj]+                    if j < rlen:+                        resp_mask[row, j] = 1.0+                last_idx[row] = seq_len - 1++            t_old = time.monotonic()+            ref_logp = self._select_response_logprobs(+                self.reference, self.dev_rollout, ids, mask, pos_idx, targets+            )+            torch.npu.synchronize(self.dev_rollout)+            t_ref = time.monotonic()+            values = self._critic_values(ids, mask, val_idx)+            rm_scores = self._reward_scores(ids, mask, last_idx)+            torch.npu.synchronize(self.dev_rollout)+            t_val = time.monotonic()++            kl = old_logp - ref_logp+            token_rewards = -self.kl_coef * kl+            for row, rlen in enumerate(rlens):+                token_rewards[row, rlen - 1] += rm_scores[row, 1]+            advantages, returns = self._gae(token_rewards, values, resp_mask, self.gamma, self.gae_lambda)+            t_adv = time.monotonic()++            def _actor_job():+                t_inner = time.monotonic()+                result = self._actor_update(+                    ids, mask, pos_idx, targets, resp_mask, old_logp, advantages+                )+                torch.npu.synchronize(self.dev_actor)+                return result, time.monotonic() - t_inner++            def _critic_job():+                t_inner = time.monotonic()+                result = self._critic_update(ids, mask, val_idx, resp_mask, values, returns)+                torch.npu.synchronize(self.dev_rollout)+                return result, time.monotonic() - t_inner++            results = _run_parallel({"actor": _actor_job, "critic": _critic_job})+            actor_metrics, actor_seconds = results["actor"]+            critic_metrics, critic_seconds = results["critic"]+            t_critic = time.monotonic()+            torch.npu.empty_cache()++            step_time = t_critic - t_step+            self.ppo_seconds += step_time+            metrics = {+                "step": update_no,+                "training/global_step": float(update_no),+                **actor_metrics,+                **critic_metrics,+                "critic/score/mean": float(rm_scores[:, 1].mean()),+                "critic/advantages/mean": float(advantages.sum() / resp_mask.sum().clamp(min=1.0)),+                "critic/returns/mean": float(returns.sum() / resp_mask.sum().clamp(min=1.0)),+                "critic/values/mean": float((values * resp_mask).sum() / resp_mask.sum().clamp(min=1.0)),+                "actor/reward_kl_penalty": float((token_rewards * resp_mask).sum() / resp_mask.sum().clamp(min=1.0)),+                "actor/reward_kl_penalty_coeff": self.kl_coef,+                "response_length/mean": float(sum(rlens)) / len(rlens),+                "response/aborted_ratio": float(sum(1 for r in rlens if r >= self.max_response_tokens)) / len(rlens),+                "timing_s/gen": t_gen - t_sync,+                "timing_s/update_weights": t_sync - t_step,+                "timing_s/old_log_prob": t_old - t_gen,+                "timing_s/ref": t_ref - t_old,+                "timing_s/values": t_val - t_ref,+                "timing_s/adv": t_adv - t_val,+                "timing_s/update_actor": actor_seconds,+                "timing_s/update_critic": critic_seconds,+                "timing_s/step": step_time,+            }+            metrics = {k: (float(v) if isinstance(v, (int, float)) else v) for k, v in metrics.items()}+            if not all(math.isfinite(v) for v in metrics.values() if isinstance(v, float)):+                raise RuntimeError("non-finite PPO metric observed")+            self.step_metrics.append(metrics)+            self.actor_grad_norms.append(actor_metrics["actor/grad_norm"])+            self.critic_grad_norms.append(critic_metrics["critic/grad_norm"])+            for record, response in zip(prompt_records, responses):+                self.trajectory_records.append(+                    {"update": update_no, "prompt_id": record["id"], "response_ids": [int(v) for v in response]}+                )+            _log(+                f"update {update_no}: step={step_time:.2f}s gen={metrics['timing_s/gen']:.2f}s "+                f"actor={metrics['timing_s/update_actor']:.2f}s critic={metrics['timing_s/update_critic']:.2f}s "+                f"resp_len={metrics['response_length/mean']:.1f}"+            )++        self.committed_updates += self.updates+        self._sync_rollout()+        if self.action == "correctness":+            self._save_checkpoint()+        self._write_result()++    # ------------------------------------------------------------------ probe+    def probe(self, request: dict) -> dict:+        prompt_ids = self.tokenizer(request["prompt"], add_special_tokens=True)["input_ids"]+        cont_ids = self.tokenizer(request["continuation"], add_special_tokens=False)["input_ids"]+        if not prompt_ids or not cont_ids:+            raise RuntimeError("probe tokenization is empty")+        ids = torch.tensor([prompt_ids + cont_ids], dtype=torch.long)+        positions = torch.tensor(+            [[len(prompt_ids) - 1 + j for j in range(len(cont_ids))]], dtype=torch.long+        )+        targets = torch.tensor([cont_ids], dtype=torch.long)++        def compute(model, device):+            with torch.no_grad():+                hidden = model.model(input_ids=ids.to(device), use_cache=False).last_hidden_state+                picked = hidden[0, positions[0].to(device)]+                logits = model.lm_head(picked)+                logp = torch.log_softmax(logits.float(), dim=-1)+                selected = logp.gather(-1, targets[0].to(device).unsqueeze(-1)).squeeze(-1)+                return [float(v) for v in selected.cpu()]++        actor_lp = compute(self.actor, self.dev_actor)+        rollout_lp = compute(self.rollout, self.dev_rollout)+        return {+            "type": "probe_result",+            "policy_version": self.committed_updates,+            "rollout_reported_version": self.rollout_version,+            "actor_log_probs": actor_lp,+            "rollout_log_probs": rollout_lp,+        }++    # ------------------------------------------------------------- checkpoint+    def _save_checkpoint(self) -> None:+        root = Path(self.args.runtime_dir).parent / "checkpoints" / "update-8"+        root.mkdir(parents=True, exist_ok=True)+        torch.save(self.actor_optim.state_dict_cpu(), root / "actor_trainer.pt")+        torch.save(self.critic_optim.state_dict_cpu(), root / "critic_trainer.pt")+        (root / "meta.json").write_text(+            json.dumps({"committed_updates": self.committed_updates}) + "\n", encoding="utf-8"+        )+        portable = root / "portable-actor"+        self.actor.save_pretrained(portable, safe_serialization=True)+        self.tokenizer.save_pretrained(portable)+        self.checkpoint_path = str(root)+        self.portable_actor_path = str(portable)+        _log(f"checkpoint written to {root}")++    def _load_checkpoint(self, root: Path) -> None:+        meta = json.loads((root / "meta.json").read_text(encoding="utf-8"))+        actor_state = torch.load(root / "actor_trainer.pt", map_location="cpu", weights_only=False)+        critic_state = torch.load(root / "critic_trainer.pt", map_location="cpu", weights_only=False)+        self.actor_optim.load_state_dict_cpu(actor_state)+        self.critic_optim.load_state_dict_cpu(critic_state)+        self.committed_updates = int(meta["committed_updates"])+        _log(f"resumed from {root} at update {self.committed_updates}")++    # ----------------------------------------------------------------- result+    def _write_result(self) -> None:+        result = {+            "status": "passed",+            "action": self.action,+            "committed_actor_updates": self.updates,+            "committed_critic_updates": self.updates,+            "accepted_trajectories": len(self.trajectory_records),+            "step_metrics": self.step_metrics,+            "actor_grad_norms": self.actor_grad_norms,+            "critic_grad_norms": self.critic_grad_norms,+            "runtime_layout": {+                "framework": "verl.trainer.runtime.online_ppo",+                "process_graph": "single_process_two_device",+                "actor_backend": "hf_bf16_adamw_fp32_master",+                "actor_device": str(self.dev_actor),+                "reference_device": str(self.dev_rollout),+                "rollout_backend": "hf_bf16_kv_cache_sampling",+                "rollout_devices": [str(self.dev_rollout)],+                "critic_backend": "hf_bf16_adamw_fp32_master",+                "critic_device": str(self.dev_rollout),+                "reward_backend": "hf_sequence_classification",+                "placement": "colocated_single_process",+                "micro_batch_size": MICRO_BATCH,+                "offload": False,+            },+            "trajectory_records": self.trajectory_records,+            "reward_model_frozen": True,+            "reference_policy_frozen": True,+            "reported_ppo_seconds": self.ppo_seconds,+            "policy_version": self.committed_updates,+        }+        if self.checkpoint_path is not None:+            result["checkpoint_path"] = self.checkpoint_path+            result["portable_actor_path"] = self.portable_actor_path+        out = Path(self.args.result_dir) / "run-result.json"+        out.write_text(json.dumps(result, allow_nan=False) + "\n", encoding="utf-8")+        _log(f"run result written to {out}")++    def close(self) -> None:+        try:+            torch.npu.empty_cache()+        except Exception:+            pass+++def main(argv=None) -> int:+    parser = argparse.ArgumentParser()+    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)+    args = parser.parse_args(argv)++    runtime = OnlinePPORuntime(args)+    try:+        runtime.setup()+    except BaseException:+        traceback.print_exc()+        return 2++    conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+    deadline = time.monotonic() + 120.0+    while True:+        try:+            conn.connect(args.control_socket)+            break+        except OSError:+            if time.monotonic() > deadline:+                traceback.print_exc()+                return 2+            time.sleep(0.2)+    _log("control channel connected")++    try:+        _send(conn, {"type": "ready"})+        while True:+            message = _recv(conn)+            kind = message.get("type")+            if kind == "start":+                runtime.run(message["input_path"], int(message["sampling_seed"]))+                _send(conn, {"type": "completed"})+            elif kind == "probe":+                _send(conn, runtime.probe(message["request"]))+            elif kind == "shutdown":+                break+            else:+                raise RuntimeError(f"unknown control message type: {kind}")+    except BaseException:+        traceback.print_exc()+        try:+            conn.close()+        finally:+            return 2+    try:+        conn.close()+    except OSError:+        pass+    runtime.close()+    _log("shutdown complete")+    return 0+++if __name__ == "__main__":+    sys.exit(main())