Kimi K3 · RL

R02 · GRPO joint

Valid

Qwen3-1.7B online GRPO 2dev · Joint Optimization

2.06×PERFORMANCE RATIO
174TOOL EVENTS
1TEXT PATCHES
0BINARY NAMES

01 / PROCESS MAP

Agents over time

Compare agents on one time axis; overlapping spans line up vertically. Select an agent or bar to inspect its events.

Elapsed time · mm:ss

Agent / model
+12:06+12:14+12:21+12:29+12:36
Main agentKimi K3Main timeline · 174 calls
Subagent 1Model not recordedFrom Main agent · 0 calls
Delegation only · child timing not recorded

Time starts at the first recorded activity. Select a bar or agent to open its events. Bars span the first and last recorded observation, including gaps; colored ticks mark tool calls. A hollow diamond marks a delegation whose child timing is unavailable.

InspectEditValidateExecuteBuildProfileRollbackOther
117Inspect
14Edit
29Validate
10Execute
4Other

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 timeline89 groups · 174 calls · 1 subagents

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>. Each branch belongs to its named agent. Expand a delegation to inspect its child; branches can run concurrently. Call numbers preserve source order, not a serial schedule. Times are relative to the first recorded activity.

Main agent

  1. Inspect · Source & workspace

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

    1 call · #0001–#0001

    ls <path>ls <path> <n> > <path>head -n <n>
  2. Inspect · Checkpoints & weight state

    Requested workspace inspection and file and log inspection related to checkpoints & weight state.

    1 call · #0002–#0002

    ls <path> <path> <path> <n> > <path>ls <path>head -n <n>
  3. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    1 call · #0003–#0003

    Read <path>
  4. Inspect · Checkpoints & weight state

    Requested file and log inspection related to checkpoints & weight state.

    4 calls · #0004–#0007

    Read <path>
  5. Inspect · Rollout generation

    Requested file and log inspection and workspace inspection related to rollout generation.

    10 calls · #0008–#0017

    Read <path>ls <path>sed -n <val> <path>
  6. Inspect · Source & workspace

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

    2 calls · #0018–#0019

    Read <path>ls <path> <path> <path> <n> > <path>ls <path>head -n <n>
  7. Inspect · Rollout generation

    Requested file and log inspection related to rollout generation.

    1 call · #0020–#0020

    Read <path>
  8. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    2 calls · #0021–#0022

    Read <path>
  9. Inspect · Rollout generation

    Requested file and log inspection and workspace inspection related to rollout generation.

    2 calls · #0023–#0024

    Read <path>ls <path>wc -l <path> <path> <path> <path> <path> <path>
  10. Inspect · Runtime processes

    Requested source searches related to runtime processes.

    1 call · #0025–#0025

    Search <pattern> <path>
  11. Inspect · Rollout generation

    Requested source searches and file and log inspection related to rollout generation.

    4 calls · #0026–#0029

    Search <pattern> <path>Read <path>
  12. Inspect · Source & workspace

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

    4 calls · #0030–#0033

    Read <path>Search <pattern> <path>sed -n <val> <path>
  13. Inspect · Rollout generation

    Requested file and log inspection related to rollout generation.

    1 call · #0034–#0034

    Read <path>
  14. Inspect · Source & workspace

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

    2 calls · #0035–#0036

    Read <path>Search <pattern> <path>
  15. Inspect · Reward & policy updates

    Requested source searches related to reward & policy updates.

    1 call · #0037–#0037

    Search <pattern> <path>
  16. Inspect · Batching & scheduling

    Requested source searches related to batching & scheduling.

    2 calls · #0038–#0039

    Search <pattern> <path>
  17. Inspect · Source & workspace

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

    5 calls · #0040–#0044

    sed -n <val> <path>Search <pattern> <path>Read <path>
  18. Inspect · Rollout generation

    Requested workspace inspection and file and log inspection related to rollout generation.

    1 call · #0045–#0045

    ls <path> <path>sed -n <val> <path> <n> > <path>
  19. Inspect · Checkpoints & weight state

    Requested source searches related to checkpoints & weight state.

    1 call · #0046–#0046

    Search <pattern> <path>
  20. Inspect · Source & workspace

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

    3 calls · #0047–#0049

    sed -n <val> <path>Search <pattern> <path>
  21. Inspect · Batching & scheduling

    Requested source searches related to batching & scheduling.

    2 calls · #0050–#0051

    Search <pattern> <path>
  22. Inspect · Reward & policy updates

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

    1 call · #0052–#0052

    sed -n <val> <path>
  23. Inspect · Checkpoints & weight state

    Requested source searches related to checkpoints & weight state.

    1 call · #0053–#0053

    Search <pattern> <path>
  24. Inspect · Source & workspace

    Requested workspace inspection related to source & workspace.

    1 call · #0054–#0054

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

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

    3 calls · #0055–#0057

    Read <path>env <vars>ls -l -a <path> <path> <path> <path> <path> <path>
  26. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0058–#0058

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

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

    1 call · #0059–#0059

    Read <path>
  28. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0060–#0060

    Read <path>
  29. Validate · Benchmark & validation setup

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

    1 call · #0061–#0061

    env <vars><command> <args>cat <path>
  30. Inspect · Source & workspace

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

    14 calls · #0062–#0075

    env <vars>wc -l <path> <path>head -n <n> <path>Read <path>Update task list <tasks>sed -n <val> <path>
  31. Inspect · Parallelism & communication

    Requested environment setup or inspection, source searches and runtime inspection related to parallelism & communication.

    1 call · #0076–#0076

    envgrep -E <val>sortecho <flag>npu-smi info <n> >& <path>head -n <n>
  32. Inspect · Task requirements

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

    2 calls · #0077–#0078

    env <vars>cat <path> <path> <path> <path>echo <val>head -c <n> <path>echocat <path>
    4 more command sketches
    ls <path> <n> >& <path>ls <path>headRead <path>
  33. Other · Source & workspace

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

    1 call · #0079–#0079

    python3 -c <script> <n> >& <path>grep -v <val>
  34. Execute · Benchmark & validation setup

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

    1 call · #0080–#0080

    env <vars>cat <path>echo <val>
  35. Inspect · Source & workspace

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

    2 calls · #0081–#0082

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

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

    1 call · #0083–#0083

    cd <path>bash <script> > <path> <n> >& <path>echo <val>
  37. Execute · Checkpoints & weight state

    Requested task coordination related to checkpoints & weight state.

    1 call · #0084–#0084

    Delegate <task>
    Subagent 1· Model not recorded · explore · 0 visible callsCompleted

    Delegated by Main agent at call #0084.

    Only the returned summary is retained; child tool events are not available.

  38. Other · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0085–#0085

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

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

    3 calls · #0086–#0088

    env <vars>ls -l -a <val>python3 -c <script>tail -n <n> <path>grep -i -E <val> <path>grep -v <val>
    1 more command sketches
    head -n <n>
  40. Inspect · Source & workspace

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

    1 call · #0089–#0089

    python3 -c <script>ls <path>
  41. Execute · Benchmark & validation setup

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

    1 call · #0090–#0090

    cd <path>bash <script> > <path> <n> >& <path>echo <val>
  42. Inspect · Rollout generation

    Requested source searches and file and log inspection related to rollout generation.

    1 call · #0091–#0091

    grep -n <val> <path>head -n <n>echo <val>
  43. Inspect · Checkpoints & weight state

    Requested source searches related to checkpoints & weight state.

    1 call · #0092–#0092

    grep -n <val> <path>
  44. Inspect · Rollout generation

    Requested workspace inspection, source searches and file and log inspection related to rollout generation.

    4 calls · #0093–#0096

    ls <path>echo <val>find <path> -name <path>xargs <val> <flag> <args>grep -n <val> <path>head -n <n>
    2 more command sketches
    sed -n <val> <path>echo <path>
  45. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0097–#0097

    sed -n <val> <path>
  46. Inspect · Rollout generation

    Requested file and log inspection related to rollout generation.

    1 call · #0098–#0098

    sed -n <val> <path>
  47. Inspect · Checkpoints & weight state

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

    1 call · #0099–#0099

    grep -n <val> <path> <path>headecho <val>sed -n <val> <path>
  48. Inspect · Rollout generation

    Requested file and log inspection and source searches related to rollout generation.

    2 calls · #0100–#0101

    sed -n <val> <path>grep -n <val> <path>headecho <val>grep -r -n <val> <path>grep -r -n <val> <path> <path> <n> > <path>
  49. Inspect · Source & workspace

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

    1 call · #0102–#0102

    grep -n <val> -A <n> <path>head -n <n>
  50. Inspect · Rollout generation

    Requested source searches and file and log inspection related to rollout generation.

    1 call · #0103–#0103

    grep -n <val> -A <n> <path>head -n <n>
  51. Other · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0104–#0104

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

    Requested script or workload execution related to task requirements.

    1 call · #0105–#0105

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

    Requested task coordination, script or workload execution and source searches related to source & workspace.

    4 calls · #0106–#0109

    Update task list <tasks>python3 -c <script> <n> >& <path>grep -n <val> <path>head -n <n>grep -n <val> -A <n> <path>sed -n <val>
    4 more command sketches
    grep -r -n <val> -A <n> <path>grep -r -n <val> <path>headsed -n <val> <path>
  54. Execute · Checkpoints & weight state

    Requested environment setup or inspection and script or workload execution related to checkpoints & weight state.

    1 call · #0110–#0110

    env <vars>python3 - <script>
  55. Inspect · Rollout generation

    Requested file and log inspection, source searches and workspace inspection related to rollout generation.

    5 calls · #0111–#0115

    sed -n <val> <path>grep -r -n <val> -A <n> <path> <path> <n> > <path>head -n <n>find <path> -name <path>headecho <val>
    2 more command sketches
    grep -n <val> <path>grep -n <val> <path> <path>
  56. Inspect · Source & workspace

    Requested workspace file updates, workspace inspection and file and log inspection related to source & workspace.

    1 call · #0116–#0116

    mkdir -p <path>touch <path>ls <path>head
  57. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0117–#0118

    Write <path>
  58. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0119–#0119

    Read <path>
  59. Edit · Source & workspace

    Requested code edits related to source & workspace.

    6 calls · #0120–#0125

    Edit <path>
  60. Inspect · Source & workspace

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

    3 calls · #0126–#0128

    cd <path>python3 -m <module> <script>echo <val>sed -n <val> <path>grep -n <val> <path>head -n <n>
    1 more command sketches
    grep -r -n <val> -A <n> <path>
  61. Inspect · Runtime processes

    Requested script or workload execution and file and log inspection related to runtime processes.

    1 call · #0129–#0129

    cd <path>timeout <n> <path> -B -c <val> <n> >& <path>tail -n <n>
  62. Validate · Benchmark & validation setup

    Requested script or workload execution, execution waits and environment setup or inspection related to benchmark & validation setup.

    4 calls · #0130–#0133

    cd <path>bash <script> > <path> <n> >& <path>echo <val>sleep <n>env <vars>ls -l -a <path> <n> > <path>
    9 more command sketches
    tail -n <n> <path> <n> > <path>python3 -c <script>echo <val> <val> <val>tail -n <n> <path>head -n <n> <path>grep -n <val> <path>grep -v -i <val>head -n <n>grep -n <val> -A <n> <path>
  63. Edit · Source & workspace

    Requested code edits related to source & workspace.

    3 calls · #0134–#0136

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

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

    1 call · #0137–#0137

    cd <path>python3 -m <module> <script>echo <val>bash <script> > <path> <n> >& <path>
  65. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0138–#0138

    Read <path>
  66. Validate · Checkpoints & weight state

    Requested environment setup or inspection and script or workload execution related to checkpoints & weight state.

    1 call · #0139–#0139

    env <vars>python3 -c <script>
  67. Validate · Benchmark & validation setup

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

    1 call · #0140–#0140

    env <vars>rm -f <path> <path>cd <path>bash <script> > <path> <n> >& <path>echo <val>
  68. Execute · Device memory

    Requested environment setup or inspection, source searches and file and log inspection related to device memory.

    2 calls · #0141–#0142

    env <vars>grep -i <val> <path>head -n <n>headgrep -i -E <val> <path>tail -n <n>
    5 more command sketches
    grep -i -v <val>echo <val>grep -i -E <path> <path>echo <val> <val> <val> <val>grep <flag> <args>
  69. Inspect · Source & workspace

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

    2 calls · #0143–#0144

    grep -n <val> -A <n> <path>sed -n <val>cd <path>env <vars> python3 -c <script> <n> >& <path>tail -n <n>
  70. Validate · Benchmark & validation setup

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

    1 call · #0145–#0145

    env <vars>ls <path> <n> > <path>tail -n <n> <path> <n> > <path>grep -c <val> <path> <n> > <path>
  71. Inspect · Checkpoints & weight state

    Requested file and log inspection related to checkpoints & weight state.

    1 call · #0146–#0146

    sed -n <val> <path>
  72. Validate · Benchmark & validation setup

    1 tool error

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

    2 calls · #0147–#0148

    sleep <n>env <vars>tail -n <n> <path>ls <path> <n> > <path>echo <val>grep -c <val> <path> <n> > <path>
  73. Validate · Checkpoints & weight state

    Requested environment setup or inspection and script or workload execution related to checkpoints & weight state.

    1 call · #0149–#0149

    env <vars>python3 - <script>
  74. Validate · Benchmark & validation setup

    Requested workspace inspection, environment setup or inspection and source searches related to benchmark & validation setup.

    4 calls · #0150–#0153

    ls <path> <n> > <path>env <vars>grep -n <val> -A <n> <path>tail -n <n>grep -n <val> <path>grep -v <val>
    4 more command sketches
    tailawk <path> <path>echo <val>tail -n <n> <path>
  75. Validate · Checkpoints & weight state

    1 tool error

    Requested environment setup or inspection, workspace inspection and script or workload execution related to checkpoints & weight state.

    1 call · #0154–#0154

    env <vars>ls -l -a <path>python3 - <script>
  76. Validate · Benchmark & validation setup

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

    1 call · #0155–#0155

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

    Requested code edits related to source & workspace.

    1 call · #0156–#0156

    Edit <path>
  78. Inspect · Source & workspace

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

    1 call · #0157–#0157

    grep -n <val> -A <n> <path>sed -n <val>
  79. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0158–#0159

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

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

    3 calls · #0160–#0162

    cd <path>python3 -m <module> <script>echo <val>env <vars>rm -f <path> <path>bash <script> > <path> <n> >& <path>
    5 more command sketches
    sleep <n>grep -a <val> <path>tail -n <n>tailtail -n <n> <path>
  81. Execute · Benchmark & validation setup

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

    1 call · #0163–#0163

    env <vars>rm -f <path> <path>cd <path>bash <script> > <path> <n> >& <path>echo <val>
  82. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0164–#0164

    sed -n <val> <path>
  83. Execute · Benchmark & validation setup

    Requested execution waits, environment setup or inspection and source searches related to benchmark & validation setup.

    3 calls · #0165–#0167

    sleep <n>env <vars>grep -a <val> <path> <n> > <path>tailtail -n <n> <path> <n> > <path>head -c <n>
    2 more command sketches
    tail -n <n>python3 -c <script>
  84. Validate · Checkpoints & weight state

    Requested environment setup or inspection, workspace file updates and script or workload execution related to checkpoints & weight state.

    1 call · #0168–#0168

    env <vars>rm -f <path> <path>cd <path>bash <script> > <path> <n> >& <path>echo <val>
  85. Inspect · Source & workspace

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

    1 call · #0169–#0169

    cd <path>env <vars> bash <script> <n> >& <path>tail -n <n>
  86. Validate · Benchmark & validation setup

    Requested execution waits, environment setup or inspection and source searches related to benchmark & validation setup.

    2 calls · #0170–#0171

    sleep <n>env <vars>grep -a <val> <path> <n> > <path>tail -n <n>tail -n <n> <path> <n> > <path>head -c <n>
  87. Inspect · Checkpoints & weight state

    Requested execution waits, environment setup or inspection and workspace inspection related to checkpoints & weight state.

    1 call · #0172–#0172

    sleep <n>env <vars>ls -l -a <path> <n> > <path>ls <path> <n> > <path>cat <path>
  88. Inspect · Source & workspace

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

    1 call · #0173–#0173

    cd <path>git status --short <n> > <path>headecho <val><command> <args>git -C <val> <val> --short <n> > <path>
    1 more command sketches
    head -n <n>
  89. Validate · Benchmark & validation setup

    1 missing return

    Requested execution waits, environment setup or inspection and source searches related to benchmark & validation setup.

    1 call · #0174–#0174

    sleep <n>env <vars>grep -a <val> <path> <n> > <path>tail -n <n>ls <path> <n> > <path>python3 -c <script>

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 · 2 changed files

Base commit: 0b2151ec61de5d99e0811b01c09e43a99a23e69d

diff --git a/verl/trainer/runtime/__init__.py b/verl/trainer/runtime/__init__.pynew file mode 100644index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391diff --git a/verl/trainer/runtime/online_grpo.py b/verl/trainer/runtime/online_grpo.pynew file mode 100644index 0000000000000000000000000000000000000000..3716771c3b438af8d250f8021aa247f55b863eec--- /dev/null+++ b/verl/trainer/runtime/online_grpo.py@@ -0,0 +1,1257 @@+"""Framework-owned online GRPO runtime for the two-device Ascend benchmark.++This module implements the runtime half of the public online-GRPO contract+(see ``config/framework-runtime-contract.md`` in the task bundle):++* It boots a colocated verl FSDP2 actor (world size 2) and a vLLM v1 TP2+  rollout replica on the two visible Ascend devices.+* It speaks the line-delimited JSON control protocol over the supplied Unix+  stream socket: ``ready`` -> ``start`` -> run -> ``completed`` -> ``probe``+  -> ``probe_result`` -> ``shutdown``.+* It writes ``run-result.json`` with the same worker record layout as the+  public reference runtime.++Performance-relevant execution plan (numerics and workload semantics are+identical to the reference implementation):++* vLLM loads the real policy weights at server startup (``load_format=auto``)+  so the initial weight stream is replaced by a cheap ``set_global_steps``.+* Rollout sleep/wake churn is eliminated (``free_cache_engine=False``): the+  engine stays resident; the small KV footprint fits alongside the actor.+* A warmup generation batch and a forward-only log-prob pass are executed+  before ``ready`` so one-time kernel autotuning happens outside the measured+  interval.+* Gradient checkpointing is disabled (bit-identical recompute vs. stored+  activations; only speed/memory change).+* Weight sync uses one large IPC bucket instead of four 1 GiB round trips.+"""++from __future__ import annotations++import argparse+import asyncio+import hashlib+import json+import math+import os+import shutil+import socket+import time+import traceback+from collections.abc import Mapping+from pathlib import Path+from typing import Any+from urllib.parse import urlsplit+from urllib.request import Request, urlopen++SAMPLING_TEMPERATURE = 0.7+SAMPLING_TOP_P = 0.8+SAMPLING_TOP_K = 20+MAX_PROMPT_TOKENS = 256+MAX_RESPONSE_TOKENS = 256+ADVANTAGE_EPSILON = 1e-6+POLICY_LAG_MAX = 1+++def _send_message(connection: socket.socket, value: dict[str, Any]) -> None:+    connection.sendall(+        json.dumps(value, allow_nan=False, separators=(",", ":")).encode("utf-8") + b"\n"+    )+++def _receive_message(connection: socket.socket) -> dict[str, Any]:+    raw = bytearray()+    while not raw.endswith(b"\n"):+        chunk = connection.recv(65536)+        if not chunk:+            raise RuntimeError("control connection closed")+        raw.extend(chunk)+        if len(raw) > 16 * 1024 * 1024:+            raise RuntimeError("control message 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+++def _score_responses(endpoint: tuple[str, str], items: list[tuple[str, str]]) -> list[float]:+    request = Request(+        endpoint[0].rstrip("/") + "/score_batch",+        data=json.dumps(+            {"items": [{"prompt_id": pid, "response_text": text} for pid, text in items]},+            allow_nan=False,+            separators=(",", ":"),+        ).encode("utf-8"),+        headers={+            "Authorization": f"Bearer {endpoint[1]}",+            "Content-Type": "application/json",+        },+        method="POST",+    )+    with urlopen(request, timeout=300) as response:+        payload = json.loads(response.read())+    rewards = payload.get("rewards") if isinstance(payload, dict) else None+    if (+        not isinstance(rewards, list)+        or len(rewards) != len(items)+        or any(+            isinstance(value, bool)+            or not isinstance(value, (int, float))+            or float(value) not in {0.0, 1.0}+            for value in rewards+        )+    ):+        raise RuntimeError("online reward endpoint returned invalid rewards")+    return [float(value) for value in rewards]+++def _numeric_metrics(raw: Any) -> dict[str, float]:+    if not hasattr(raw, "items"):+        raise RuntimeError("actor metrics are not a mapping")+    result: dict[str, float] = {}+    for name, value in raw.items():+        values = value if isinstance(value, list) else [value]+        numeric = []+        for item in values:+            if hasattr(item, "value"):+                item = item.value+            if hasattr(item, "item"):+                item = item.item()+            if isinstance(item, (int, float)) and not isinstance(item, bool):+                numeric.append(float(item))+        if numeric:+            result[str(name)] = math.fsum(numeric) / len(numeric)+    required_fragments = ("pg_loss", "ppo_kl", "clipfrac", "grad_norm")+    if not all(any(fragment in name for name in result) for fragment in required_fragments):+        raise RuntimeError(f"actor metrics are missing required values: {sorted(result)}")+    return result+++def _worker_results(value: Any, *, expected: int) -> list[Any]:+    while isinstance(value, (list, tuple)) and len(value) == 1 and isinstance(value[0], (list, tuple)):+        value = value[0]+    if not isinstance(value, (list, tuple)) or len(value) != expected:+        raise RuntimeError(f"expected {expected} worker results")+    return list(value)+++def _aggregate_projection(value: Any) -> dict[str, Any]:+    workers = _worker_results(value, expected=2)+    if not all(isinstance(item, dict) for item in workers):+        raise RuntimeError("worker parameter projections are invalid")+    return {+        "value": math.fsum(float(item["value"]) for item in workers),+        "logical_parameter_count": sum(int(item["logical_parameter_count"]) for item in workers),+        "parameter_tensor_count": sum(int(item["parameter_tensor_count"]) for item in workers),+        "worker_count": len(workers),+    }+++def _aggregate_state_dtypes(value: Any) -> dict[str, dict[str, int]]:+    workers = _worker_results(value, expected=2)+    result: dict[str, dict[str, int]] = {"parameters": {}, "optimizer": {}}+    for worker in workers:+        if not isinstance(worker, dict):+            raise RuntimeError("worker state dtype observation is invalid")+        for state_kind in result:+            observed = worker.get(state_kind)+            if not isinstance(observed, dict):+                raise RuntimeError("worker state dtype observation is incomplete")+            for dtype, count in observed.items():+                result[state_kind][str(dtype)] = result[state_kind].get(str(dtype), 0) + int(count)+    return result+++# ---------------------------------------------------------------------------+# Actor worker with observation helpers (same contract as the reference).+# ---------------------------------------------------------------------------++from verl.single_controller.base.decorator import Dispatch, register  # noqa: E402+from verl.utils import tensordict_utils as tu  # noqa: E402+from verl.workers.engine_workers import ActorRolloutRefWorker  # noqa: E402+++class ObservedActorWorker(ActorRolloutRefWorker):+    @register(dispatch_mode=Dispatch.ONE_TO_ALL)+    def synchronize(self):+        import torch++        torch.npu.synchronize()+        return True++    @register(dispatch_mode=Dispatch.ONE_TO_ALL)+    def policy_projection(self):+        import torch++        terms = []+        parameter_count = 0+        tensor_count = 0+        sampled = []+        weights = []+        for ordinal, parameter in enumerate(self.actor.engine.module.parameters()):+            local = parameter.detach()+            if hasattr(local, "to_local"):+                local = local.to_local()+            flat = local.reshape(-1)+            parameter_count += flat.numel()+            tensor_count += 1+            if flat.numel():+                positions = sorted({0, flat.numel() // 2, flat.numel() - 1})+                index = torch.tensor(positions, device=flat.device, dtype=torch.long)+                sampled.append(flat[index].float())+                weights.extend(float((ordinal + position) % 31 + 1) / 31 for position in positions)+        if sampled:+            values = torch.cat(sampled).cpu()+            terms = (values * torch.tensor(weights, dtype=torch.float32)).tolist()+        return {+            "value": math.fsum(terms),+            "logical_parameter_count": parameter_count,+            "parameter_tensor_count": tensor_count,+        }++    @register(dispatch_mode=Dispatch.ONE_TO_ALL)+    def state_dtypes(self):+        import torch++        parameter_dtypes: dict[str, int] = {}+        optimizer_dtypes: dict[str, int] = {}+        for parameter in self.actor.engine.module.parameters():+            name = str(parameter.dtype).removeprefix("torch.")+            parameter_dtypes[name] = parameter_dtypes.get(name, 0) + parameter.numel()+        for state in self.actor.engine.optimizer.state.values():+            for value in state.values():+                if isinstance(value, torch.Tensor):+                    name = str(value.dtype).removeprefix("torch.")+                    optimizer_dtypes[name] = optimizer_dtypes.get(name, 0) + value.numel()+        return {"parameters": parameter_dtypes, "optimizer": optimizer_dtypes}++    @register(dispatch_mode=Dispatch.ONE_TO_ALL)+    def device_observation(self):+        import os+        import torch++        return {+            "role": "actor",+            "current_device": int(torch.npu.current_device()),+            "visible_devices": os.environ.get("ASCEND_RT_VISIBLE_DEVICES", "not set"),+        }++    @register(dispatch_mode=Dispatch.ONE_TO_ALL, blocking=False)+    async def update_weights(self, global_steps: int = None, mode: str = "auto"):+        """Lean colocated weight sync: no sleep/wake, no cache flushing.++        The rollout engine is never put to sleep by this runtime, so the+        resume calls and allocator churn in the stock implementation are+        unnecessary.  The transfer itself (full-tensor gather + IPC bucket+        stream + ``load_weights``) is unchanged.+        """+        per_tensor_param, peft_config = self.actor.engine.get_per_tensor_param(+            layered_summon=self.layered_summon, base_sync_done=True+        )+        await self.rollout.update_weights(+            per_tensor_param, peft_config=peft_config, base_sync_done=True, global_steps=global_steps+        )+        self.base_sync_done = True++    @register(dispatch_mode=Dispatch.ONE_TO_ALL)+    def export_portable_actor(self, export_dir: str, config_source: str):+        """Export the full bf16 policy as a Transformers-compatible directory."""+        import torch++        params, _ = self.actor.engine.get_per_tensor_param(+            layered_summon=self.layered_summon, base_sync_done=True+        )+        rank = int(os.environ.get("RANK", "0"))+        tensors = {}+        for name, tensor in params:+            if name == "lm_head.weight":+                # Tied checkpoint convention: lm_head is reconstructed from+                # the embedding matrix on load.+                continue+            if rank == 0:+                tensors[name] = tensor.detach().to("cpu", copy=True).contiguous()+        if rank == 0:+            from safetensors.torch import save_file++            out = Path(export_dir)+            out.mkdir(parents=True, exist_ok=False)+            save_file(tensors, str(out / "model.safetensors"), metadata={"format": "pt"})+            shutil.copyfile(config_source, out / "config.json")+        return True+++# ---------------------------------------------------------------------------+# GRPO driver+# ---------------------------------------------------------------------------+++def _encode_prompt(tokenizer, system_prompt: str, question: str) -> list[int]:+    token_ids = tokenizer.apply_chat_template(+        [+            {"role": "system", "content": system_prompt},+            {"role": "user", "content": question},+        ],+        tokenize=True,+        add_generation_prompt=True,+        enable_thinking=False,+    )+    if isinstance(token_ids, Mapping):+        token_ids = token_ids["input_ids"]+    return list(token_ids)+++class OnlineGRPO:+    def __init__(self, args: argparse.Namespace):+        self.args = args+        self.runtime_dir = Path(args.runtime_dir)+        self.result_dir = Path(args.result_dir)+        self.home = self.runtime_dir.parent+        self.run_spec = json.loads(Path(args.run_spec).read_text(encoding="utf-8"))+        self.action = str(self.run_spec["action"])+        self.restart_checkpoint = self.run_spec.get("restart_checkpoint")+        self.model_path = str(args.model_path)+        self.tokenizer_path = str(args.tokenizer_path)+        self.source_root = Path(__file__).resolve().parents[3]+        self.actor_group = None+        self.llm_server_manager = None+        self.rollout_replicas = None+        self.client = None+        self.current_actor_version = 0+        self.prompt_asset = None+        self.device_observations = None++    # -- lifecycle ------------------------------------------------------++    def initialize(self) -> None:+        import torch+        from hydra import compose, initialize_config_dir+        from omegaconf import open_dict+        from transformers import AutoTokenizer++        import ray+        from verl.single_controller.ray import RayClassWithInitArgs, RayWorkerGroup+        from verl.single_controller.ray.base import create_colocated_worker_cls+        from verl.trainer.ppo.ray_trainer import ResourcePoolManager, Role+        from verl.utils.device import get_device_name+        from verl.workers.rollout.llm_server import LLMServerManager++        self._torch = torch+        self._ray = ray++        tokenizer = AutoTokenizer.from_pretrained(+            self.tokenizer_path, local_files_only=True, trust_remote_code=True+        )+        if tokenizer.pad_token_id is None:+            tokenizer.pad_token_id = tokenizer.eos_token_id+        self.tokenizer = tokenizer++        if self.action == "smoke":+            committed_updates = 1+        elif self.action == "restart":+            committed_updates = 1+        else:+            committed_updates = 8+        self.committed_updates = committed_updates++        config_dir = self.source_root / "verl/trainer/config"+        with initialize_config_dir(version_base=None, config_dir=str(config_dir)):+            config = compose(+                config_name="ppo_trainer", overrides=["actor_rollout_ref.rollout.name=vllm"]+            )+        groups_per_batch = 8 if self.action in {"correctness", "measurement"} else (1 if self.action == "smoke" else 8)+        with open_dict(config):+            config.trainer.n_gpus_per_node = 2+            config.trainer.nnodes = 1+            config.trainer.logger = ["console"]+            config.actor_rollout_ref.model.path = self.model_path+            config.actor_rollout_ref.model.tokenizer_path = self.tokenizer_path+            config.actor_rollout_ref.model.enable_gradient_checkpointing = False+            config.actor_rollout_ref.model.use_remove_padding = True+            config.actor_rollout_ref.actor.strategy = "fsdp2"+            config.actor_rollout_ref.actor.ppo_mini_batch_size = groups_per_batch * 4+            config.actor_rollout_ref.actor.ppo_micro_batch_size = None+            config.actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu = None+            config.actor_rollout_ref.actor.ppo_max_token_len_per_gpu = 2048+            config.actor_rollout_ref.actor.use_dynamic_bsz = True+            config.actor_rollout_ref.actor.use_torch_compile = False+            config.actor_rollout_ref.actor.ppo_epochs = 1+            config.actor_rollout_ref.actor.shuffle = False+            config.actor_rollout_ref.actor.loss_agg_mode = "token-mean"+            config.actor_rollout_ref.actor.entropy_coeff = 0.0+            config.actor_rollout_ref.actor.calculate_entropy = False+            config.actor_rollout_ref.actor.use_kl_loss = False+            config.actor_rollout_ref.actor.clip_ratio = 0.2+            config.actor_rollout_ref.actor.clip_ratio_low = 0.2+            config.actor_rollout_ref.actor.clip_ratio_high = 0.2+            config.actor_rollout_ref.actor.optim.lr = 0.000001+            config.actor_rollout_ref.actor.optim.weight_decay = 0.01+            config.actor_rollout_ref.actor.optim.betas = [0.9, 0.999]+            config.actor_rollout_ref.actor.optim.clip_grad = 1.0+            config.actor_rollout_ref.actor.optim.total_training_steps = committed_updates+            config.actor_rollout_ref.actor.fsdp_config.strategy = "fsdp2"+            config.actor_rollout_ref.actor.fsdp_config.fsdp_size = 2+            config.actor_rollout_ref.actor.fsdp_config.forward_only = False+            config.actor_rollout_ref.actor.fsdp_config.model_dtype = "fp32"+            config.actor_rollout_ref.actor.fsdp_config.dtype = "bfloat16"+            config.actor_rollout_ref.actor.fsdp_config.param_offload = False+            config.actor_rollout_ref.actor.fsdp_config.optimizer_offload = False+            config.actor_rollout_ref.actor.fsdp_config.offload_policy = False+            config.actor_rollout_ref.actor.fsdp_config.use_torch_compile = False+            rollout = config.actor_rollout_ref.rollout+            rollout.name = "vllm"+            rollout.mode = "async"+            rollout.nnodes = 1+            rollout.n_gpus_per_node = 2+            rollout.tensor_model_parallel_size = 2+            rollout.data_parallel_size = 1+            rollout.pipeline_model_parallel_size = 1+            rollout.prompt_length = MAX_PROMPT_TOKENS+            rollout.response_length = MAX_RESPONSE_TOKENS+            rollout.max_model_len = MAX_PROMPT_TOKENS + MAX_RESPONSE_TOKENS+            rollout.gpu_memory_utilization = 0.25+            rollout.max_num_seqs = 32+            rollout.max_num_batched_tokens = 4096+            rollout.enable_chunked_prefill = True+            rollout.skip_tokenizer_init = False+            rollout.log_prob_use_dynamic_bsz = True+            rollout.log_prob_max_token_len_per_gpu = 2048+            rollout.log_prob_micro_batch_size = None+            rollout.log_prob_micro_batch_size_per_gpu = None+            rollout.checkpoint_engine.backend = "naive"+            rollout.checkpoint_engine.update_weights_bucket_megabytes = 4096+            rollout.checkpoint_engine.engine_kwargs = {}+            rollout.load_format = "auto"+            rollout.free_cache_engine = False+        self.config = config++        namespace = hashlib.sha256(f"{self.home}:{self.action}".encode()).hexdigest()[:10]+        ray_temp = Path("/tmp") / f"vr-g2-{self.action[:2]}-{namespace}"+        ray_temp.mkdir(parents=True, exist_ok=True)+        ray.init(+            include_dashboard=False,+            _temp_dir=str(ray_temp),+            runtime_env={+                "env_vars": {+                    "TOKENIZERS_PARALLELISM": "false",+                    "RAY_EXPERIMENTAL_NOSET_CUDA_VISIBLE_DEVICES": "1",+                    "RAY_EXPERIMENTAL_NOSET_ASCEND_RT_VISIBLE_DEVICES": "1",+                    "VLLM_USE_V1": "1",+                    "HCCL_CONNECT_TIMEOUT": "1500",+                    "HCCL_NPU_SOCKET_PORT_RANGE": os.environ.get(+                        "HCCL_NPU_SOCKET_PORT_RANGE", "61000-61050"+                    ),+                }+            },+        )+        pool_id = "colocated_pool"+        actor_role = Role.ActorRollout+        role_name = str(actor_role)+        pool_manager = ResourcePoolManager(+            resource_pool_spec={pool_id: [2]}, mapping={actor_role: pool_id}+        )+        pool_manager.create_resource_pool()+        actor_cls = RayClassWithInitArgs(+            cls=ray.remote(ObservedActorWorker),+            config=config.actor_rollout_ref,+            role=role_name,+        )+        colocated_cls = create_colocated_worker_cls(class_dict={role_name: actor_cls})+        self.actor_group = RayWorkerGroup(+            resource_pool=pool_manager.get_resource_pool(actor_role),+            ray_cls_with_init=colocated_cls,+            device_name=get_device_name(),+        ).spawn(prefix_set={role_name})[role_name]+        self.actor_group.init_model()++        self.checkpoint_reloaded = self.restart_checkpoint is not None+        if self.checkpoint_reloaded:+            checkpoint_path = Path(str(self.restart_checkpoint))+            if not checkpoint_path.is_dir():+                raise RuntimeError("update-eight actor checkpoint is unavailable")+            self.actor_group.load_checkpoint(str(checkpoint_path))+            self.current_actor_version = 8++        self.llm_server_manager = LLMServerManager.create(+            config=config,+            worker_group=self.actor_group,+            rollout_resource_pool=pool_manager.get_resource_pool(actor_role),+        )+        self.rollout_replicas = self.llm_server_manager.get_replicas()+        if len(self.rollout_replicas) != 1 or len(self.rollout_replicas[0].workers) != 2:+            raise RuntimeError("rollout did not create exactly one TP2 replica")+        self.client = self.llm_server_manager.get_client()++        actor_devices = _worker_results(self.actor_group.device_observation(), expected=2)+        rollout_workers = self.rollout_replicas[0].workers+        rollout_visible = ray.get(+            [worker.get_cuda_visible_devices.remote() for worker in rollout_workers]+        )++        def observe_rollout_device(worker):+            import os+            import torch++            return {+                "role": "rollout",+                "current_device": int(torch.npu.current_device()),+                "visible_devices": os.environ.get("ASCEND_RT_VISIBLE_DEVICES", "not set"),+            }++        rollout_devices = ray.get(+            [+                worker.execute_with_func_generator.remote(observe_rollout_device)+                for worker in rollout_workers+            ]+        )+        for observation, visible in zip(rollout_devices, rollout_visible, strict=True):+            observation["reported_visible_devices"] = visible+        self.device_observations = {"actor": actor_devices, "rollout": rollout_devices}+        actor_device_set = {item["current_device"] for item in actor_devices}+        rollout_device_set = {item["current_device"] for item in rollout_devices}+        if actor_device_set != rollout_device_set or len(actor_device_set) != 2:+            raise RuntimeError("actor FSDP2 and rollout TP2 did not share the same two devices")++        if self.checkpoint_reloaded:+            # vLLM started from the base policy: stream the reloaded update-8+            # weights into the engine before generating.+            self._sync_weights(self.current_actor_version)+        else:+            # vLLM already holds the base policy (load_format=auto); only the+            # version tag needs to be set.+            self._set_rollout_version(0)++        self.initial_projection = _aggregate_projection(self.actor_group.policy_projection())++    def _set_rollout_version(self, version: int) -> None:+        servers = self.rollout_replicas[0].servers+        self._ray.get([server.set_global_steps.remote(version) for server in servers])++    def _sync_weights(self, version: int) -> float:+        started = time.monotonic()+        self._ray.get(self.actor_group.update_weights(global_steps=version, mode="naive"))+        return time.monotonic() - started++    # -- warmup (before the measured window) -----------------------------++    def warmup(self) -> None:+        import torch+        from tensordict import TensorDict++        from verl.utils import tensordict_utils as tu+        from verl.workers.utils.padding import left_right_2_no_padding++        prompt_ids = _encode_prompt(+            self.tokenizer,+            "You are a helpful assistant.",+            "What is 17 plus 25?",+        )+        async def warm_generate():+            requests = []+            for index in range(32):+                requests.append(+                    self.client.generate(+                        f"warmup-{index}",+                        prompt_ids=prompt_ids,+                        sampling_params={+                            "temperature": SAMPLING_TEMPERATURE,+                            "top_p": SAMPLING_TOP_P,+                            "top_k": SAMPLING_TOP_K,+                            "max_tokens": MAX_RESPONSE_TOKENS,+                            "logprobs": True,+                            "seed": 17 + index,+                        },+                    )+                )+            return await asyncio.gather(*requests)++        outputs = asyncio.run(warm_generate())+        for output in outputs:+            if output.stop_reason != "completed" or not output.token_ids:+                raise RuntimeError("warmup generation did not complete")+        # Warm the actor forward/log-prob path (no parameter update).+        rows = max(2, min(4, len(outputs)))+        response_width = max(min(len(list(o.token_ids)), 64) for o in outputs[:rows])+        prompt_width = len(prompt_ids)+        total = prompt_width + response_width+        input_ids = torch.full((2, total), int(self.tokenizer.pad_token_id), dtype=torch.long)+        attention_mask = torch.zeros((2, total), dtype=torch.bool)+        position_ids = torch.arange(total, dtype=torch.long).unsqueeze(0).repeat(2, 1)+        responses = torch.full((2, response_width), int(self.tokenizer.pad_token_id), dtype=torch.long)+        response_mask = torch.ones((2, response_width), dtype=torch.bool)+        old_log_probs = torch.zeros((2, response_width), dtype=torch.float32)+        for row in range(2):+            ids = list(outputs[row].token_ids)[:response_width]+            input_ids[row, :prompt_width] = torch.tensor(prompt_ids, dtype=torch.long)+            input_ids[row, prompt_width : prompt_width + len(ids)] = torch.tensor(ids, dtype=torch.long)+            attention_mask[row, :] = True+            responses[row, : len(ids)] = torch.tensor(ids, dtype=torch.long)+            response_mask[row, len(ids) :] = False+        padded = TensorDict(+            {+                "input_ids": input_ids,+                "attention_mask": attention_mask,+                "position_ids": position_ids,+                "prompts": input_ids[:, :prompt_width].clone(),+                "responses": responses,+                "response_mask": response_mask,+                "old_log_probs": old_log_probs,+                "advantages": torch.zeros((2, response_width), dtype=torch.float32),+            },+            batch_size=[2],+        )+        batch = left_right_2_no_padding(padded.clone())+        tu.assign_non_tensor(batch, calculate_entropy=False, compute_loss=False, temperature=SAMPLING_TEMPERATURE)+        self.actor_group.compute_log_prob(batch)++    # -- rollout helpers --------------------------------------------------++    async def _generate_batch(self, batch_ordinal: int, policy_version: int, prompt_batch):+        requests = []+        metadata = []+        base_seed = int(self.prompt_asset.get("seed", 20260817))+        for prompt_ordinal, prompt in enumerate(prompt_batch):+            for response_ordinal in range(4):+                seed = (+                    base_seed+                    + batch_ordinal * 100000+                    + policy_version * 10000+                    + prompt_ordinal * 4+                    + response_ordinal+                )+                request_id = f"b{batch_ordinal}-v{policy_version}-{prompt['id']}-{response_ordinal}"+                requests.append(+                    self.client.generate(+                        request_id,+                        prompt_ids=prompt["token_ids"],+                        sampling_params={+                            "temperature": SAMPLING_TEMPERATURE,+                            "top_p": SAMPLING_TOP_P,+                            "top_k": SAMPLING_TOP_K,+                            "max_tokens": MAX_RESPONSE_TOKENS,+                            "logprobs": True,+                            "seed": seed,+                        },+                    )+                )+                metadata.append((prompt_ordinal, prompt, response_ordinal, seed))+        outputs = await asyncio.gather(*requests)+        return metadata, outputs, prompt_batch++    def generate_batch_sync(self, batch_ordinal: int, policy_version: int, prompt_batch):+        return asyncio.run(self._generate_batch(batch_ordinal, policy_version, prompt_batch))++    def build_batch(self, generated, reward_endpoint):+        import numpy as np+        import torch+        from tensordict import TensorDict++        from verl.utils import tensordict_utils as tu+        from verl.workers.utils.padding import left_right_2_no_padding++        metadata, outputs, prompt_batch = generated+        rows = []+        group_rewards: dict[int, list[float]] = {index: [] for index in range(len(prompt_batch))}+        group_texts: dict[int, list[str]] = {index: [] for index in range(len(prompt_batch))}+        policy_versions = set()+        decoded = []+        for (prompt_ordinal, prompt, response_ordinal, seed), output in zip(+            metadata, outputs, strict=True+        ):+            if output.stop_reason != "completed" or not output.token_ids:+                raise RuntimeError(f"rollout {prompt['id']}/{response_ordinal} did not complete")+            if output.log_probs is None or len(output.log_probs) != len(output.token_ids):+                raise RuntimeError("rollout logprobs are incomplete")+            policy_versions.add(output.extra_fields.get("global_steps"))+            text = self.tokenizer.decode(output.token_ids, skip_special_tokens=True)+            decoded.append((prompt_ordinal, prompt, response_ordinal, seed, output, text))+        rewards = _score_responses(+            reward_endpoint,+            [(str(prompt["id"]), text) for _, prompt, _, _, _, text in decoded],+        )+        for (+            prompt_ordinal,+            prompt,+            response_ordinal,+            seed,+            output,+            text,+        ), reward in zip(decoded, rewards, strict=True):+            group_rewards[prompt_ordinal].append(reward)+            group_texts[prompt_ordinal].append(text)+            rows.append(+                {+                    "prompt_ordinal": prompt_ordinal,+                    "prompt_id": prompt["id"],+                    "response_ordinal": response_ordinal,+                    "seed": seed,+                    "prompt_ids": prompt["token_ids"],+                    "response_ids": list(output.token_ids),+                    "old_log_probs": list(output.log_probs),+                    "reward": reward,+                }+            )+        if len(policy_versions) != 1 or next(iter(policy_versions)) is None:+            raise RuntimeError(f"rollout policy version is ambiguous: {policy_versions}")+        advantages: dict[int, list[float]] = {}+        for group, group_reward in group_rewards.items():+            mean = float(np.mean(group_reward))+            std = float(np.std(group_reward, ddof=1))+            advantages[group] = (+                [0.0] * len(group_reward)+                if std == 0+                else [(reward - mean) / (std + ADVANTAGE_EPSILON) for reward in group_reward]+            )+        for row in rows:+            row["advantage"] = advantages[row["prompt_ordinal"]][row["response_ordinal"]]++        prompt_width = max(len(row["prompt_ids"]) for row in rows)+        response_width = max(len(row["response_ids"]) for row in rows)+        pad = self.tokenizer.pad_token_id+        input_ids = []+        attention_mask = []+        position_ids = []+        responses = []+        response_mask = []+        old_log_probs = []+        advantage_values = []+        prompts = []+        for row in rows:+            prompt_padding = prompt_width - len(row["prompt_ids"])+            response_padding = response_width - len(row["response_ids"])+            prompt_row = [pad] * prompt_padding + row["prompt_ids"]+            response_row = row["response_ids"] + [pad] * response_padding+            mask = (+                [0] * prompt_padding+                + [1] * len(row["prompt_ids"])+                + [1] * len(row["response_ids"])+                + [0] * response_padding+            )+            positions = []+            position = 0+            for active in mask:+                positions.append(position if active else 0)+                if active:+                    position += 1+            prompts.append(prompt_row)+            responses.append(response_row)+            input_ids.append(prompt_row + response_row)+            attention_mask.append(mask)+            position_ids.append(positions)+            response_mask.append([1] * len(row["response_ids"]) + [0] * response_padding)+            old_log_probs.append(row["old_log_probs"] + [0.0] * response_padding)+            advantage_values.append(+                [row["advantage"]] * len(row["response_ids"]) + [0.0] * response_padding+            )+        padded = TensorDict(+            {+                "input_ids": torch.tensor(input_ids, dtype=torch.long),+                "attention_mask": torch.tensor(attention_mask, dtype=torch.bool),+                "position_ids": torch.tensor(position_ids, dtype=torch.long),+                "prompts": torch.tensor(prompts, dtype=torch.long),+                "responses": torch.tensor(responses, dtype=torch.long),+                "response_mask": torch.tensor(response_mask, dtype=torch.bool),+                "old_log_probs": torch.tensor(old_log_probs, dtype=torch.float32),+                "advantages": torch.tensor(advantage_values, dtype=torch.float32),+            },+            batch_size=[len(rows)],+        )+        batch = left_right_2_no_padding(padded.clone())+        tu.assign_non_tensor(+            batch,+            calculate_entropy=False,+            compute_loss=True,+            temperature=SAMPLING_TEMPERATURE,+            global_batch_size=len(rows),+            mini_batch_size=len(rows),+            epochs=1,+            seed=int(self.prompt_asset.get("seed", 20260817)),+            dataloader_kwargs={"shuffle": False},+        )+        observation = {+            "policy_version": int(next(iter(policy_versions))),+            "prompt_ids": [prompt["id"] for prompt in prompt_batch],+            "rewards": [group_rewards[index] for index in range(len(prompt_batch))],+            "advantages": [advantages[index] for index in range(len(prompt_batch))],+            "response_lengths": [len(row["response_ids"]) for row in rows],+            "response_texts": [group_texts[index] for index in range(len(prompt_batch))],+            "consumed_response_tokens": sum(len(row["response_ids"]) for row in rows),+            "nonzero_advantage_groups": sum(+                any(abs(value) > 0 for value in values) for values in advantages.values()+            ),+            "trajectories": [+                {+                    "prompt_id": row["prompt_id"],+                    "response_ordinal": row["response_ordinal"],+                    "seed": row["seed"],+                    "response_ids": row["response_ids"],+                    "old_log_probs": row["old_log_probs"],+                    "response_text": group_texts[row["prompt_ordinal"]][row["response_ordinal"]],+                    "reward": row["reward"],+                    "advantage": row["advantage"],+                }+                for row in rows+            ],+        }+        return batch, padded, observation++    def actor_log_probs(self, padded):+        from verl.utils import tensordict_utils as tu+        from verl.workers.utils.padding import left_right_2_no_padding, no_padding_2_padding++        batch = left_right_2_no_padding(padded.clone())+        tu.assign_non_tensor(batch, calculate_entropy=False, compute_loss=False, temperature=SAMPLING_TEMPERATURE)+        output = self.actor_group.compute_log_prob(batch)+        return no_padding_2_padding(tu.get(output, "log_probs"), batch).float().cpu()++    def evaluate_log_probs(self, prompt_token_ids: list[int], response_token_ids: list[int]):+        """Actor log-probs of the given response tokens (probe alignment)."""+        import torch+        from tensordict import TensorDict++        response_width = len(response_token_ids)+        total = len(prompt_token_ids) + response_width+        replicas = 2+        padded = TensorDict(+            {+                "input_ids": torch.tensor([prompt_token_ids + list(response_token_ids)], dtype=torch.long).repeat(replicas, 1),+                "attention_mask": torch.ones((replicas, total), dtype=torch.bool),+                "position_ids": torch.arange(total, dtype=torch.long).unsqueeze(0).repeat(replicas, 1),+                "prompts": torch.tensor([prompt_token_ids], dtype=torch.long).repeat(replicas, 1),+                "responses": torch.tensor([list(response_token_ids)], dtype=torch.long).repeat(replicas, 1),+                "response_mask": torch.ones((replicas, response_width), dtype=torch.bool),+                "old_log_probs": torch.zeros((replicas, response_width), dtype=torch.float32),+                "advantages": torch.zeros((replicas, response_width), dtype=torch.float32),+            },+            batch_size=[replicas],+        )+        return self.actor_log_probs(padded)[0, :response_width].tolist()++    def freshness_probe(self, version: int, first_prompt) -> dict[str, Any]:+        base_seed = int(self.prompt_asset.get("seed", 20260817))+        return self._run_probe(+            prompt_token_ids=first_prompt["token_ids"],+            seed=base_seed + 81983 + version,+            max_tokens=32,+            version=version,+        )++    def _run_probe(self, prompt_token_ids, seed: int, max_tokens: int, version: int) -> dict[str, Any]:+        async def generate():+            return await self.client.generate(+                f"freshness-{version}-{seed}",+                prompt_ids=prompt_token_ids,+                sampling_params={+                    "temperature": SAMPLING_TEMPERATURE,+                    "top_p": SAMPLING_TOP_P,+                    "top_k": SAMPLING_TOP_K,+                    "max_tokens": max_tokens,+                    "logprobs": True,+                    "seed": seed,+                },+            )++        output = asyncio.run(generate())+        if output.stop_reason != "completed" or not output.token_ids or output.log_probs is None:+            raise RuntimeError("freshness rollout did not complete with logprobs")+        actor_values = self.evaluate_log_probs(prompt_token_ids, list(output.token_ids))+        rollout_values = [float(value) for value in output.log_probs]+        positions = sorted({0, len(actor_values) // 2, len(actor_values) - 1})+        selected = [+            {+                "position": position,+                "actor_log_prob": float(actor_values[position]),+                "rollout_log_prob": float(rollout_values[position]),+            }+            for position in positions+        ]+        return {+            "policy_version": version,+            "rollout_reported_version": output.extra_fields.get("global_steps"),+            "selected_log_probs": selected,+            "max_abs_logprob_difference": max(+                abs(item["actor_log_prob"] - item["rollout_log_prob"]) for item in selected+            ),+            "actor_log_probs": actor_values,+            "rollout_log_probs": rollout_values,+        }++    # -- main run ---------------------------------------------------------++    def prepare_prompts(self, prompt_path: str) -> None:+        prompt_asset = json.loads(Path(prompt_path).read_text(encoding="utf-8"))+        prompt_records = prompt_asset["prompts"]+        if self.action == "smoke":+            prompt_records = prompt_records[:1]+        elif self.action == "restart":+            prompt_records = prompt_records[-8:]+        encoded_prompts = []+        for item in prompt_records:+            token_ids = _encode_prompt(+                self.tokenizer, prompt_asset["system_prompt"], item["question"]+            )+            if len(token_ids) > MAX_PROMPT_TOKENS:+                raise RuntimeError(f"prompt {item['id']} exceeds {MAX_PROMPT_TOKENS} tokens")+            encoded_prompts.append({**item, "token_ids": list(token_ids)})+        if self.action in {"smoke", "restart"}:+            prompt_batches = [encoded_prompts]+        else:+            if len(encoded_prompts) != 64:+                raise RuntimeError("a full run requires 64 distinct prompt groups")+            prompt_batches = [encoded_prompts[index : index + 8] for index in range(0, 64, 8)]+        self.prompt_asset = prompt_asset+        self.prompt_batches = prompt_batches++    def run(self, prompt_path: str, reward_endpoint: tuple[str, str]) -> dict[str, Any]:+        self.prepare_prompts(prompt_path)+        prompt_batches = self.prompt_batches+        committed_updates = self.committed_updates++        observations: dict[str, Any] = {"initial": {"parameter_projection": self.initial_projection}}+        freshness_probes = []+        step_metrics = []+        policy_versions = []+        total_tokens = 0+        accepted_trajectories = 0+        trajectory_records = []+        sync_count = 0+        state_dtypes = None+        timed_start = time.monotonic()+        rollout_generation_started = time.monotonic()+        current_generated = self.generate_batch_sync(+            1, self.current_actor_version, prompt_batches[0]+        )+        current_rollout_generation_seconds = time.monotonic() - rollout_generation_started+        current_rollout_sleep_seconds = 0.0+        for update in range(1, committed_updates + 1):+            scoring_started = time.monotonic()+            batch, padded, trajectory_observation = self.build_batch(+                current_generated, reward_endpoint+            )+            scoring_seconds = time.monotonic() - scoring_started+            if self.action in {"correctness", "restart"}:+                pre_update_log_probs = self.actor_log_probs(padded)+                for row_index, row in enumerate(trajectory_observation["trajectories"]):+                    response_length = len(row["response_ids"])+                    row["new_log_probs"] = [+                        float(value)+                        for value in pre_update_log_probs[row_index, :response_length].tolist()+                    ]+            trajectory_version = trajectory_observation["policy_version"]+            lag = self.current_actor_version - trajectory_version+            if lag < 0 or lag > POLICY_LAG_MAX:+                raise RuntimeError(f"trajectory policy lag {lag} is outside [0, {POLICY_LAG_MAX}]")+            total_tokens += trajectory_observation["consumed_response_tokens"]+            trajectory_records.extend(+                {"update": update, **row} for row in trajectory_observation["trajectories"]+            )+            update_trajectories = len(prompt_batches[(update - 1) % len(prompt_batches)]) * 4+            accepted_trajectories += update_trajectories++            self.actor_group.synchronize()+            actor_started = time.monotonic()+            actor_output = self.actor_group.update_actor(batch)+            self.actor_group.synchronize()+            actor_seconds = time.monotonic() - actor_started+            metrics = _numeric_metrics(tu.get(actor_output, "metrics"))+            if update == 1:+                state_dtypes = _aggregate_state_dtypes(self.actor_group.state_dtypes())+            self.current_actor_version += 1++            sync_seconds = self._sync_weights(self.current_actor_version)+            sync_count += 1++            if update in {1, committed_updates}:+                probe_started = time.monotonic()+                probe = self.freshness_probe(self.current_actor_version, prompt_batches[0][0])+                probe["seconds"] = time.monotonic() - probe_started+                probe.pop("actor_log_probs", None)+                probe.pop("rollout_log_probs", None)+                freshness_probes.append(probe)++            selected_updates = {1} if self.action in {"smoke", "restart"} else {1, 4, 8}+            if update in selected_updates:+                current_log_probs = self.actor_log_probs(padded)+                probe_positions = []+                for row in range(min(4, current_log_probs.shape[0])):+                    length = int(padded["response_mask"][row].sum())+                    positions = sorted({0, length // 2, length - 1})+                    probe_positions.append(+                        [float(current_log_probs[row, position]) for position in positions]+                    )+                observations[str(update)] = {+                    "trajectory": trajectory_observation,+                    "actor_metrics": metrics,+                    "parameter_projection": _aggregate_projection(+                        self.actor_group.policy_projection()+                    ),+                    "selected_log_probs": probe_positions,+                }++            step_metrics.append(+                {+                    "update": update,+                    "trajectory_policy_version": trajectory_version,+                    "actor_version_before_update": self.current_actor_version - 1,+                    "actor_version_after_update": self.current_actor_version,+                    "policy_lag": lag,+                    "consumed_response_tokens": trajectory_observation["consumed_response_tokens"],+                    "accepted_trajectories": update_trajectories,+                    "scoring_seconds": scoring_seconds,+                    "rollout_generation_seconds": current_rollout_generation_seconds,+                    "rollout_sleep_seconds": current_rollout_sleep_seconds,+                    "actor_update_seconds": actor_seconds,+                    "weight_sync_seconds": sync_seconds,+                    "actor_metrics": metrics,+                    "nonzero_advantage_groups": trajectory_observation["nonzero_advantage_groups"],+                }+            )+            print(+                f"[online_grpo] update {update}/{committed_updates}: "+                f"gen={current_rollout_generation_seconds:.2f}s "+                f"score={scoring_seconds:.2f}s actor={actor_seconds:.2f}s "+                f"sync={sync_seconds:.2f}s "+                f"tokens={trajectory_observation['consumed_response_tokens']}",+                flush=True,+            )+            policy_versions.append(+                {+                    "update": update,+                    "trajectory": trajectory_version,+                    "actor_before": self.current_actor_version - 1,+                    "actor_after": self.current_actor_version,+                    "rollout_after_sync": self.current_actor_version,+                    "lag": lag,+                }+            )+            if update < committed_updates:+                rollout_generation_started = time.monotonic()+                current_generated = self.generate_batch_sync(+                    update + 1, self.current_actor_version, prompt_batches[update]+                )+                current_rollout_generation_seconds = time.monotonic() - rollout_generation_started+                current_rollout_sleep_seconds = 0.0++        end_to_end_seconds = time.monotonic() - timed_start+        assert state_dtypes is not None+        final_projection = observations[str(committed_updates)]["parameter_projection"]+        parameters_changed = final_projection["value"] != self.initial_projection["value"]+        freshness_valid = all(+            probe["rollout_reported_version"] == probe["policy_version"]+            and probe["max_abs_logprob_difference"] <= 0.5+            for probe in freshness_probes+        )+        metrics_finite = (+            end_to_end_seconds > 0+            and all(+                item["actor_metrics"]+                and all(math.isfinite(value) for value in item["actor_metrics"].values())+                and item["actor_update_seconds"] > 0+                and item["weight_sync_seconds"] > 0+                for item in step_metrics+            )+            and set(state_dtypes["parameters"]) == {"float32"}+            and set(state_dtypes["optimizer"]).issubset({"float32"})+            and bool(state_dtypes["optimizer"])+        )+        expected_trajectories = sum(len(batch) * 4 for batch in prompt_batches)+        observation_updates = {"1"} if self.action in {"smoke", "restart"} else {"1", "4", "8"}+        gates = {+            "actor_initialized": True,+            "rollout_initialized": True,+            "rollouts_complete": accepted_trajectories == expected_trajectories,+            "reward_advantage_valid": all(+                math.isfinite(value)+                for key in observation_updates+                for group in observations[key]["trajectory"]["advantages"]+                for value in group+            ),+            "updates_complete": len(step_metrics) == committed_updates,+            "weights_synced": sync_count == committed_updates,+            "policy_lag_valid": all(0 <= item["lag"] <= 1 for item in policy_versions),+            "freshness_valid": freshness_valid,+            "parameters_changed": parameters_changed,+            "metrics_finite": metrics_finite,+            "observations_complete": observation_updates.issubset(observations)+            and len(freshness_probes) == (1 if self.action in {"smoke", "restart"} else 2),+        }++        saved_checkpoint = None+        portable_actor_path = None+        if self.action == "correctness":+            checkpoint_path = self.home / "checkpoints" / "update-8"+            checkpoint_path.parent.mkdir(parents=True, exist_ok=True)+            self.actor_group.save_checkpoint(+                str(checkpoint_path),+                global_step=8,+                max_ckpt_to_keep=1,+            )+            if not checkpoint_path.is_dir():+                raise RuntimeError("update-eight actor checkpoint was not created")+            portable_dir = checkpoint_path / "portable-actor"+            self.actor_group.export_portable_actor(+                str(portable_dir), str(Path(self.model_path) / "config.json")+            )+            if not portable_dir.is_dir():+                raise RuntimeError("portable actor export was not created")+            saved_checkpoint = str(checkpoint_path)+            portable_actor_path = str(portable_dir)++        record = {+            "schema_version": 1,+            "kind": "online_grpo_worker",+            "action": self.action,+            "status": "passed" if all(gates.values()) else "failed",+            "gates": gates,+            "committed_updates": committed_updates,+            "accepted_trajectories": accepted_trajectories,+            "consumed_response_tokens": total_tokens,+            "trajectory_records": trajectory_records,+            "end_to_end_seconds": end_to_end_seconds,+            "policy_versions": policy_versions,+            "step_metrics": step_metrics,+            "observations": observations,+            "freshness_probes": freshness_probes,+            "device_observations": self.device_observations,+            "logical_parameter_count": self.initial_projection["logical_parameter_count"],+            "parameter_tensor_count": self.initial_projection["parameter_tensor_count"],+            "state_dtypes": state_dtypes,+            "checkpoint_path": saved_checkpoint,+            "portable_actor_path": portable_actor_path,+            "checkpoint_reloaded": self.checkpoint_reloaded,+            "runtime_layout": {+                "activation_checkpointing": False,+                "actor_world_size": 2,+                "dynamic_batching": True,+                "enable_chunked_prefill": True,+                "gpu_memory_utilization": 0.25,+                "log_prob_max_tokens_per_microbatch": 2048,+                "max_num_batched_tokens": 4096,+                "max_num_seqs": 32,+                "max_tokens_per_microbatch": 2048,+                "optimizer_offload": False,+                "parameter_offload": False,+                "remove_padding": True,+                "rollout_tensor_parallel_size": 2,+                "rollout_sleep_enabled": False,+                "weight_sync_bucket_megabytes": 4096,+            },+        }+        print(+            "[online_grpo] run finished: "+            f"status={record['status']} gates={json.dumps(gates, sort_keys=True)} "+            f"tokens={record['consumed_response_tokens']} "+            f"e2e={record['end_to_end_seconds']:.2f}s",+            flush=True,+        )+        return record++    def host_probe(self, request: dict[str, Any]) -> dict[str, Any]:+        prompt_ids = _encode_prompt(+            self.tokenizer, self.prompt_asset["system_prompt"], str(request["question"])+        )+        probe = self._run_probe(+            prompt_token_ids=prompt_ids,+            seed=int(request["seed"]),+            max_tokens=int(request.get("max_tokens", 32)),+            version=self.current_actor_version,+        )+        return {+            "type": "probe_result",+            "policy_version": probe["policy_version"],+            "rollout_reported_version": probe["rollout_reported_version"],+            "actor_log_probs": probe["actor_log_probs"],+            "rollout_log_probs": probe["rollout_log_probs"],+        }++    def shutdown(self) -> None:+        try:+            if self._ray.is_initialized():+                self._ray.shutdown()+        except Exception:+            pass+        try:+            import psutil++            current = psutil.Process()+            children = current.children(recursive=True)+            for child in children:+                try:+                    child.terminate()+                except Exception:+                    pass+            _, alive = psutil.wait_procs(children, timeout=30)+            for child in alive:+                try:+                    child.kill()+                except Exception:+                    pass+            psutil.wait_procs(alive, timeout=10)+        except Exception:+            pass+        try:+            namespace = hashlib.sha256(f"{self.home}:{self.action}".encode()).hexdigest()[:10]+            shutil.rmtree(Path("/tmp") / f"vr-g2-{self.action[:2]}-{namespace}", ignore_errors=True)+        except Exception:+            pass+++def main(argv: list[str] | None = None) -> int:+    parser = argparse.ArgumentParser()+    parser.add_argument("--run-spec", required=True)+    parser.add_argument("--model-path", required=True)+    parser.add_argument("--tokenizer-path", required=True)+    parser.add_argument("--runtime-dir", required=True)+    parser.add_argument("--result-dir", required=True)+    parser.add_argument("--control-socket", required=True)+    args = parser.parse_args(argv)++    runtime = OnlineGRPO(args)+    connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+    try:+        connection.connect(args.control_socket)+        connection.settimeout(float(os.environ.get("GRPO_CONTROL_TIMEOUT_S", "5400")))+        runtime.initialize()+        runtime.warmup()+        _send_message(connection, {"type": "ready"})+        while True:+            message = _receive_message(connection)+            kind = message.get("type")+            if kind == "start":+                endpoint = message["reward_endpoint"]+                url = str(endpoint["url"])+                token = str(endpoint["token"])+                parsed = urlsplit(url)+                if parsed.scheme != "http" or parsed.hostname != "127.0.0.1":+                    raise RuntimeError("reward endpoint is invalid")+                result = runtime.run(+                    str(message["prompt_path"]), (url.rstrip("/"), token)+                )+                result_path = Path(args.result_dir) / "run-result.json"+                result_path.write_text(+                    json.dumps(result, allow_nan=False, indent=2, sort_keys=True) + "\n",+                    encoding="utf-8",+                )+                _send_message(connection, {"type": "completed"})+            elif kind == "probe":+                if message.get("kind") != "freshness":+                    raise RuntimeError("unknown probe kind")+                probe = runtime.host_probe(message["request"])+                _send_message(connection, probe)+            elif kind == "shutdown":+                break+            else:+                raise RuntimeError(f"unknown control message: {kind}")+    except BaseException:+        traceback.print_exc()+        try:+            runtime.shutdown()+        finally:+            connection.close()+        return 1+    runtime.shutdown()+    connection.close()+    return 0+++if __name__ == "__main__":+    raise SystemExit(main())