GPT-5.6 Sol · RL

R03 · PPO joint

Valid

Qwen3-1.7B online PPO 2dev · Joint Optimization

7.58×PERFORMANCE RATIO
111TOOL 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 agentGPT-5.6 Sol · 111 visible calls

InspectEditValidateExecuteBuildProfileRollbackOther
53Inspect
11Edit
30Validate
3Execute
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 timeline79 groups · 111 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 · Task requirements

    Requested workspace inspection, environment setup or inspection and source searches related to task requirements.

    2 calls · #0001–#0002

    pwdprintenv <vars>rg --files -g <val> -g <path> -g <path> <path> <path> <path> <path> <args>head -n <n>sed -n <val> <path>
  2. Inspect · Reward & policy updates

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

    1 call · #0003–#0003

    sed -n <val> <path>find <val> -maxdepth <n> -type <val> <flag> <args>sort
  3. Inspect · Benchmark & validation setup

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

    1 call · #0004–#0004

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

    Requested file and log inspection related to task requirements.

    2 calls · #0005–#0006

    sed -n <val> <path>
  5. Inspect · Source & workspace

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

    2 calls · #0007–#0008

    tail -n <n> <path>git -C <path> <val> --shortrg --files <path> <path> <n> > <path>head -n <n>test -f <path>sed -n <val> <path>
    7 more command sketches
    trueenvrg <val>sortls -l -a <val>git -C <path> <val> <flag> <args>python - <script>
  6. Inspect · Device memory

    Requested file and log inspection, runtime inspection and script or workload execution related to device memory.

    1 call · #0009–#0009

    sed -n <val> <val>npu-smi infodu <flag> <args>sed -n <val> <path>python - <script>
  7. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0010–#0010

    python - <script>
  8. Inspect · Reward & policy updates

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

    1 call · #0011–#0011

    rg -n <val> <path> <path> <path>head -n <n>rg -n <val> <path> <path>
  9. Inspect · Source & workspace

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

    8 calls · #0012–#0019

    rg -n <val> <path> <path> <path>head -n <n>rg -n <val> <path> <n> > <path>sed -n <val> <path>python - <script>rg -n <val> <path>
    1 more command sketches
    rg -n <val> <path> <path> -g <path>
  10. Inspect · Runtime processes

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

    1 call · #0020–#0020

    rg -n <val> <path>sed -n <val> <path>
  11. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0021–#0021

    sed -n <val> <path>
  12. Inspect · Reward & policy updates

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

    3 calls · #0022–#0024

    rg -n <val> <path> <path> -g <path>head -n <n>sed -n <val> <path> <n> > <path>truerg -n <val> <path>sed -n <val> <path>
    1 more command sketches
    rg -n <val> <path> <path>
  13. Inspect · Source & workspace

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

    1 call · #0025–#0025

    sed -n <val> <path>rg -n <val> <path> -g <path>head -n <n>
  14. Inspect · Reward & policy updates

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

    5 calls · #0026–#0030

    rg -n <val> <path> <path>head -n <n>sed -n <val> <path>rg -n <val> <path>tail -n <n>
  15. Inspect · Source & workspace

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

    1 call · #0031–#0031

    df -h <path> <path> <path>free -hulimit -ased -n <val>python - <script>
  16. Other · Device memory

    Requested script or workload execution related to device memory.

    1 call · #0032–#0032

    python -u - <script>
  17. Other · Attention kernels

    2 tool errors

    Requested script or workload execution related to attention kernels.

    3 calls · #0033–#0035

    python -u - <script>
  18. Other · Source & workspace

    Requested workspace file updates related to source & workspace.

    1 call · #0036–#0036

    mkdir -p <path>
  19. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0037–#0038

    Apply patch <patch>
  20. Other · Source & workspace

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

    1 call · #0039–#0039

    python -B - <script><command> <args>truegit status --shortgit diff --statgit diff --check
  21. Validate · Device memory

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

    1 call · #0040–#0040

    ps <flag> <args>rg <path>rg -v <val>npu-smi infotail -n <n><command> <args>
    1 more command sketches
    tail -n <n> <val>
  22. Validate · Benchmark & validation setup

    1 tool error

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

    2 calls · #0041–#0042

    bash <script>ps <flag> <args>tail -n <n>find <val> -maxdepth <n> -type <val> <flag> <args>sortwc -c <path> <n> > <path>
    3 more command sketches
    tail -n <n> <path><command> <args>true
  23. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0043–#0043

    bash <script>
  24. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0044–#0044

    Apply patch <patch>
  25. Inspect · Source & workspace

    Requested workspace inspection related to source & workspace.

    1 call · #0045–#0045

    find <val> -maxdepth <n> -type <val> <flag> <args>sort
  26. Validate · Benchmark & validation setup

    Requested workspace file updates related to benchmark & validation setup.

    1 call · #0046–#0046

    rm <path> <path> <path> <path>
  27. Validate · Device memory

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

    2 calls · #0047–#0048

    ps <flag> <args>rg <val>rg -v <val>tail -n <n> <path>npu-smi infotail -n <n>
  28. Validate · Benchmark & validation setup

    1 tool error

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

    1 call · #0049–#0049

    bash <script>
  29. Inspect · Source & workspace

    Requested workspace inspection related to source & workspace.

    1 call · #0050–#0050

    find <val> -maxdepth <n> -type <val> <flag> <args>sort
  30. Validate · Device memory

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

    1 call · #0051–#0051

    ps <flag> <args>rg <val>rg -v <val>tail -n <n> <path>npu-smi infotail -n <n>
  31. Other · Task requirements

    Requested script or workload execution related to task requirements.

    1 call · #0052–#0052

    python -u - <script>
  32. Validate · Task requirements

    1 tool error

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

    1 call · #0053–#0053

    rm <path> <path> <path> <path> <path>env <vars> bash <script>
  33. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0054–#0054

    Apply patch <patch>
  34. Validate · Device memory

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

    1 call · #0055–#0055

    ps <flag> <args>rg <val>rg -v <val>tail -n <n> <path>npu-smi infotail -n <n>
  35. Inspect · Benchmark & validation setup

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

    1 call · #0056–#0056

    tail -n <n> <path>
  36. Validate · Task requirements

    1 tool error

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

    1 call · #0057–#0057

    rm <path> <path> <path> <path> <path>env <vars> bash <script>
  37. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0058–#0058

    Apply patch <patch>
  38. Inspect · Benchmark & validation setup

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

    1 call · #0059–#0059

    ps <flag> <args>rg <val>rg -v <val>tail -n <n> <path>
  39. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0060–#0060

    Apply patch <patch>
  40. Validate · Task requirements

    1 tool error

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

    1 call · #0061–#0061

    rm <path> <path> <path> <path> <path>env <vars> bash <script>
  41. Validate · Device memory

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

    1 call · #0062–#0062

    ps <flag> <args>rg <val>rg -v <val>tail -n <n> <path>npu-smi infotail -n <n>
  42. Validate · Task requirements

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

    1 call · #0063–#0063

    rm <path> <path> <path> <path> <path>env <vars> bash <script>
  43. Inspect · Source & workspace

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

    2 calls · #0064–#0065

    rg -n <val> <path>rg <val>head -n <n>sed -n <val> <path>
  44. Execute · Device memory

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

    2 calls · #0066–#0067

    ps <flag> <args>rg <val>rg -v <val>tail -n <n> <path> <n> > <path>npu-smi infotail -n <n>
    1 more command sketches
    tail -n <n> <path>
  45. Inspect · Benchmark & validation setup

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

    1 call · #0068–#0068

    tail -n <n> <path>
  46. Other · Task requirements

    Requested environment setup or inspection related to task requirements.

    1 call · #0069–#0069

    env <vars> bash <script>
  47. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0070–#0070

    Apply patch <patch>
  48. Validate · Device memory

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

    1 call · #0071–#0071

    ps <flag> <args>rg <val>rg -v <val>tail -n <n> <path> <n> > <path>npu-smi infotail -n <n>
  49. Validate · Checkpoints & weight state

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

    3 calls · #0072–#0074

    tail -n <n> <path>ps <flag> <args>rg <val>rg -v <val>du <flag> <args>true
    4 more command sketches
    find <path> -maxdepth <n> -type <val> <flag> <args>tail -n <n>sortnpu-smi info
  50. Inspect · Checkpoints & weight state

    Requested runtime inspection, source searches and workspace inspection related to checkpoints & weight state.

    1 call · #0075–#0075

    ps <flag> <args>rg <val>rg -v <val>find <path> -maxdepth <n> -type <val> <flag> <args>sorttail -n <n> <path>
  51. Validate · Benchmark & validation setup

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

    1 call · #0076–#0076

    ps <flag> <args>rg <val>rg -v <val>tail -n <n>tail -n <n> <path> <n> > <path>
  52. Inspect · Benchmark & validation setup

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

    1 call · #0077–#0077

    ps <flag> <args>rg <val>rg -v <val>tail -n <n>free -h
  53. Validate · Task requirements

    1 tool error

    Requested environment setup or inspection related to task requirements.

    1 call · #0078–#0078

    env <vars> bash <script>
  54. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0079–#0079

    Apply patch <patch>
  55. Inspect · Benchmark & validation setup

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

    2 calls · #0080–#0081

    find <val> -maxdepth <n> -type <val> -name <val> <flag> <args>sorttail -n <n> <path>ps <flag> <args>rg <val>rg -v <val>
  56. Validate · Checkpoints & weight state

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

    2 calls · #0082–#0083

    tail -n <n> <path>ps <flag> <args>rg <val>rg -v <val>tail -n <n>du <flag> <args>
    1 more command sketches
    true
  57. Inspect · Benchmark & validation setup

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

    2 calls · #0084–#0085

    ps <flag> <args>rg <val>rg -v <val>tail -n <n>
  58. Validate · Task requirements

    1 tool error

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

    1 call · #0086–#0086

    rm <path> <path> <path> <path> <path>env <vars> bash <script>
  59. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0087–#0087

    Apply patch <patch>
  60. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0088–#0088

    date -u <val>python - <script>
  61. Validate · Checkpoints & weight state

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

    2 calls · #0089–#0090

    tail -n <n> <path>ps <flag> <args>rg <val>rg -v <val>tail -n <n>du <flag> <args>
    1 more command sketches
    true
  62. Inspect · Checkpoints & weight state

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

    1 call · #0091–#0091

    ps <flag> <args>rg <val>rg -v <val>tail -n <n>find <path> -maxdepth <n> -type <val> <flag> <args>sort
  63. Validate · Benchmark & validation setup

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

    1 call · #0092–#0092

    ps <flag> <args>rg <val>rg -v <val>tail -n <n>ls <path> <n> > <path>true
    1 more command sketches
    tail -n <n> <path> <n> > <path>
  64. Inspect · Device memory

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

    1 call · #0093–#0093

    tail -n <n> <path>npu-smi infotail -n <n>
  65. Validate · Device memory

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

    1 call · #0094–#0094

    tail -n <n> <path>tail -n <n>ps <flag> <args>rg <val>rg -v <val>npu-smi info
  66. Validate · Task requirements

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

    1 call · #0095–#0095

    rm <path> <path> <path> <path> <path>env <vars> bash <script>
  67. Inspect · Source & workspace

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

    1 call · #0096–#0096

    git status --shortgit diff --checkpython -B - <script>awk <val> <path>head -n <n>command -v <val>
    1 more command sketches
    true
  68. Inspect · Dependencies & build setup

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

    1 call · #0097–#0097

    python -m <module> <val> <val> <val> <val> <n> > <path>truerg -n <val> <path>sed -n <val> <val>rg -n <val> -C <n>
  69. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0098–#0098

    Apply patch <patch>
  70. Inspect · Benchmark & validation setup

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

    2 calls · #0099–#0100

    find <val> -maxdepth <n> -type <val> -name <val> <flag> <args>sorttail -n <n> <path>ps <flag> <args>rg <val>rg -v <val>
  71. Execute · Task requirements

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

    1 call · #0101–#0101

    rm <path> <path> <path> <path> <path>env <vars> bash <script>
  72. Inspect · Source & workspace

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

    1 call · #0102–#0102

    envrg <val>sorttruegit diff --checkgit status --short
    1 more command sketches
    wc -l <path>
  73. Other · Source & workspace

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

    3 calls · #0103–#0105

    env <vars> bash <script>bash <script>
  74. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0106–#0106

    sed -n <val> <path>
  75. Validate · Reward & policy updates

    Requested source searches, script or workload execution and repository inspection related to reward & policy updates.

    1 call · #0107–#0107

    rg -n <val> <path>truepython -B -m <module> <script> <script><command> <args>test <val> <flag> <args>git status --short <flag> <args>
    5 more command sketches
    jq <val> <path>jq <val> <path> <n> > <path>ps <flag> <args>rg <val>rg -v <val>
  76. Inspect · Benchmark & validation setup

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

    1 call · #0108–#0108

    sed -n <val> <path>jq <path> <path>head -n <n>
  77. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0109–#0109

    Apply patch <patch>
  78. Validate · Reward & policy updates

    Requested script or workload execution, file and log inspection and runtime inspection related to reward & policy updates.

    1 call · #0110–#0110

    python -B -m <module> <script> <script><command> <args>test <val> <flag> <args>jq <val> <path>head -n <n>npu-smi info <n> > <path>
    2 more command sketches
    sed -n <val>git status --short <flag> <args>
  79. Inspect · Benchmark & validation setup

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

    1 call · #0111–#0111

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

Base commit: 0b2151ec61de5d99e0811b01c09e43a99a23e69d

diff --git a/verl/trainer/runtime/__init__.py b/verl/trainer/runtime/__init__.pynew file mode 100644index 0000000000000000000000000000000000000000..0971bf7b1d70bedcab2094ef19b5cf6225d70c9b--- /dev/null+++ b/verl/trainer/runtime/__init__.py@@ -0,0 +1,2 @@+"""Small, framework-owned runtimes for fixed training workflows."""+diff --git a/verl/trainer/runtime/online_ppo.py b/verl/trainer/runtime/online_ppo.pynew file mode 100644index 0000000000000000000000000000000000000000..c637f73e329a06ea4066402710676ec38c34066f--- /dev/null+++ b/verl/trainer/runtime/online_ppo.py@@ -0,0 +1,1186 @@+"""Two-device, framework-owned online PPO runtime.++This entry point is intentionally self contained.  The regular PPO trainer is+designed for large, distributed jobs and pays a sizeable process, sharding,+offload, and rollout-weight-transfer cost on a two-device job.  Here all four+roles stay resident, the trainable actor is also the rollout policy, and the+actor and critic optimizer steps run concurrently on separate NPUs.++The implementation is specialized for the small fixed online workload exposed+by the runtime contract, but the PPO calculations themselves are conventional:+raw rollout log probabilities, a frozen-reference token KL reward, terminal+sequence-classifier reward, masked GAE, and clipped actor/value objectives.+"""++from __future__ import annotations++import argparse+import json+import math+import os+import shutil+import socket+import sys+import time+import traceback+from concurrent.futures import ThreadPoolExecutor+from dataclasses import dataclass+from pathlib import Path+from typing import Any++import torch+import torch_npu+from transformers import (+    AutoModelForCausalLM,+    AutoModelForSequenceClassification,+    AutoModelForTokenClassification,+    AutoTokenizer,+    LogitsProcessor,+    LogitsProcessorList,+    StoppingCriteria,+    StoppingCriteriaList,+)+++_POLICY_ID = "Qwen/Qwen3-1.7B"+_AUXILIARY_ID = "Qwen/Qwen3-0.6B"+_PAD_TOKEN_ID = 151643+_ACTOR_MICRO_BATCH = 4+_AUXILIARY_MICRO_BATCH = 8+_OPTIMIZER_WEIGHT_DECAY = 0.01+_GRAD_CLIP = 1.0+++def _log(message: str) -> None:+    print(f"[online-ppo] {message}", flush=True)+++def _read_json(path: Path) -> dict[str, Any]:+    value = json.loads(path.read_text(encoding="utf-8"))+    if not isinstance(value, dict):+        raise ValueError(f"{path} must contain a JSON object")+    return value+++def _write_json(path: Path, value: dict[str, Any]) -> None:+    temporary = path.with_suffix(path.suffix + ".tmp")+    temporary.write_text(+        json.dumps(value, allow_nan=False, indent=2, sort_keys=True) + "\n",+        encoding="utf-8",+    )+    os.replace(temporary, path)+++def _expect_equal(name: str, actual: object, expected: object) -> None:+    if actual != expected:+        raise ValueError(f"unsupported {name}: expected {expected!r}, got {actual!r}")+++@dataclass(frozen=True)+class RuntimeArguments:+    run_spec: Path+    policy_model_path: Path+    auxiliary_model_path: Path+    tokenizer_path: Path+    runtime_dir: Path+    result_dir: Path+    control_socket: Path+++@dataclass+class PackedBatch:+    """Right-padded prompt/response tensors kept on the host."""++    input_ids: torch.Tensor+    attention_mask: torch.Tensor+    token_response_mask: torch.Tensor+    response_mask: torch.Tensor+    prompt_lengths: list[int]+    response_lengths: list[int]++    @property+    def batch_size(self) -> int:+        return self.input_ids.shape[0]+++class _RawLogitsRecorder(LogitsProcessor):+    """Expose pre-sampling logits to a paired stopping criterion.++    Transformers invokes custom processors before temperature/top-k/top-p and+    invokes stopping criteria after selecting the next token.  Pairing the two+    callbacks records the raw policy log probability without retaining a full+    vocabulary tensor for every decode step or doing another actor forward.+    """++    def __init__(self) -> None:+        self.current_logits: torch.Tensor | None = None+        self.current_logsumexp: torch.Tensor | None = None++    def __call__(self, input_ids: torch.Tensor, scores: torch.Tensor) -> torch.Tensor:+        del input_ids+        self.current_logits = scores+        self.current_logsumexp = torch.logsumexp(scores, dim=-1)+        return scores+++class _SelectedLogprobRecorder(StoppingCriteria):+    def __init__(self, raw: _RawLogitsRecorder) -> None:+        self.raw = raw+        self.values: list[torch.Tensor] = []++    def __call__(self, input_ids: torch.Tensor, scores: torch.Tensor, **kwargs: Any) -> torch.Tensor:+        del scores, kwargs+        if self.raw.current_logits is None or self.raw.current_logsumexp is None:+            raise RuntimeError("generation did not expose raw logits")+        token_ids = input_ids[:, -1, None]+        selected = self.raw.current_logits.gather(1, token_ids).squeeze(1)+        self.values.append(selected - self.raw.current_logsumexp)+        self.raw.current_logits = None+        self.raw.current_logsumexp = None+        return torch.zeros(input_ids.shape[0], dtype=torch.bool, device=input_ids.device)+++def _parse_args(argv: list[str] | None = None) -> RuntimeArguments:+    parser = argparse.ArgumentParser()+    parser.add_argument("--run-spec", type=Path, required=True)+    parser.add_argument("--policy-model-path", type=Path, required=True)+    parser.add_argument("--auxiliary-model-path", type=Path, required=True)+    parser.add_argument("--tokenizer-path", type=Path, required=True)+    parser.add_argument("--runtime-dir", type=Path, required=True)+    parser.add_argument("--result-dir", type=Path, required=True)+    parser.add_argument("--control-socket", type=Path, required=True)+    parsed = parser.parse_args(argv)+    return RuntimeArguments(+        run_spec=parsed.run_spec.resolve(strict=True),+        policy_model_path=parsed.policy_model_path.resolve(strict=True),+        auxiliary_model_path=parsed.auxiliary_model_path.resolve(strict=True),+        tokenizer_path=parsed.tokenizer_path.resolve(strict=True),+        runtime_dir=parsed.runtime_dir.resolve(strict=True),+        result_dir=parsed.result_dir.resolve(strict=True),+        control_socket=parsed.control_socket,+    )+++def _validate_run_spec(spec: dict[str, Any]) -> None:+    action = spec.get("action")+    if action not in {"smoke", "correctness", "measurement", "restart"}:+        raise ValueError("run action is invalid")+    _expect_equal("run schema", spec.get("schema_version"), 1)+    _expect_equal(+        "algorithm",+        spec.get("algorithm"),+        {+            "name": "ppo",+            "advantage_estimator": "gae",+            "gamma": 1.0,+            "lambda": 0.95,+            "reference_kl": {"placement": "token_reward", "coefficient": 0.001},+            "actor_clip": 0.2,+            "value_clip": 0.5,+            "actor_epochs": 1,+            "critic_epochs": 1,+            "shuffle": False,+        },+    )+    _expect_equal(+        "sampling",+        spec.get("sampling"),+        {+            "temperature": 0.7,+            "top_p": 0.8,+            "top_k": 20,+            "responses_per_prompt": 1,+            "ignore_eos": False,+        },+    )+    _expect_equal(+        "actor optimizer",+        spec.get("actor_optimizer"),+        {"name": "adamw", "learning_rate": 1e-6},+    )+    _expect_equal(+        "critic optimizer",+        spec.get("critic_optimizer"),+        {"name": "adamw", "learning_rate": 1e-5},+    )+    _expect_equal(+        "models",+        spec.get("models"),+        {+            "actor_rollout_reference": _POLICY_ID,+            "critic_reward": _AUXILIARY_ID,+            "reward_model": "frozen_two_class_sequence_classifier",+        },+    )+    _expect_equal(+        "measurement",+        spec.get("measurement"),+        {+            "committed_updates": 8,+            "trajectories_per_update": 32,+            "accepted_trajectories": 256,+            "responses_per_prompt": 1,+            "max_prompt_tokens": 128,+            "max_response_tokens": 64,+        },+    )+    _expect_equal(+        "precision",+        spec.get("precision"),+        {"model_compute": "bfloat16", "master_parameters": "float32"},+    )+    resources = spec.get("resource_ceiling")+    if not isinstance(resources, dict):+        raise ValueError("resource ceiling is missing")+    device_ids = resources.get("device_ids")+    if (+        not isinstance(device_ids, list)+        or len(device_ids) != 2+        or any(type(item) is not int for item in device_ids)+        or len(set(device_ids)) != 2+    ):+        raise ValueError("this runtime requires exactly two projected logical devices")+    expected_work = {+        "smoke": {"committed_updates": 1, "trajectories_per_update": 8, "accepted_trajectories": 8},+        "correctness": {+            "committed_updates": 8,+            "trajectories_per_update": 32,+            "accepted_trajectories": 256,+        },+        "measurement": {+            "committed_updates": 8,+            "trajectories_per_update": 32,+            "accepted_trajectories": 256,+        },+        "restart": {"committed_updates": 1, "trajectories_per_update": 32, "accepted_trajectories": 32},+    }+    _expect_equal("resolved work", spec.get("resolved_work"), expected_work[action])+    if action == "restart":+        checkpoint = spec.get("restart_checkpoint")+        if not isinstance(checkpoint, str) or not Path(checkpoint).is_dir():+            raise ValueError("restart checkpoint is unavailable")+++def _fingerprint(model: torch.nn.Module) -> tuple[float, ...]:+    """Cheap immutable-role observation, synchronized from model parameters."""++    parameters = list(model.parameters())+    if not parameters:+        raise RuntimeError("model has no parameters")+    selected = (parameters[0], parameters[len(parameters) // 2], parameters[-1])+    result = []+    with torch.no_grad():+        for parameter in selected:+            flat = parameter.detach().reshape(-1)+            sample = flat[: min(32, flat.numel())].float()+            result.append(float(sample.sum().cpu()))+    return tuple(result)+++def _to_cpu(value: Any) -> Any:+    if isinstance(value, torch.Tensor):+        return value.detach().cpu()+    if isinstance(value, dict):+        return {key: _to_cpu(item) for key, item in value.items()}+    if isinstance(value, list):+        return [_to_cpu(item) for item in value]+    if isinstance(value, tuple):+        return tuple(_to_cpu(item) for item in value)+    return value+++class OnlinePPORuntime:+    def __init__(self, arguments: RuntimeArguments, spec: dict[str, Any]) -> None:+        self.arguments = arguments+        self.spec = spec+        self.action = str(spec["action"])+        self.actor_device = torch.device("npu:0")+        self.auxiliary_device = torch.device("npu:1")+        self.tokenizer = AutoTokenizer.from_pretrained(+            arguments.tokenizer_path,+            local_files_only=True,+            trust_remote_code=False,+        )+        if self.tokenizer.pad_token_id is None:+            self.tokenizer.pad_token_id = _PAD_TOKEN_ID+        self.tokenizer.padding_side = "left"++        torch.manual_seed(1234)+        torch.npu.manual_seed_all(1234)+        self.actor, self.critic, initial_version = self._load_trainable_models()+        self.policy_version = initial_version+        _log("trainable actor and critic loaded")++        self.reference = AutoModelForCausalLM.from_pretrained(+            arguments.policy_model_path,+            local_files_only=True,+            trust_remote_code=False,+            dtype=torch.bfloat16,+            low_cpu_mem_usage=True,+        ).to(self.auxiliary_device)+        self.reference.requires_grad_(False).eval()+        _log("frozen reference loaded")++        reward_path = Path(spec["reward_model_path"]).resolve(strict=True)+        self.reward_model = AutoModelForSequenceClassification.from_pretrained(+            reward_path,+            local_files_only=True,+            trust_remote_code=False,+            dtype=torch.bfloat16,+            low_cpu_mem_usage=True,+        ).to(self.auxiliary_device)+        self.reward_model.config.pad_token_id = self.tokenizer.pad_token_id+        self.reward_model.requires_grad_(False).eval()+        _log("frozen reward model loaded")++        self.actor_optimizer = torch_npu.optim.NpuFusedAdamW(+            self.actor.parameters(),+            lr=float(spec["actor_optimizer"]["learning_rate"]),+            weight_decay=_OPTIMIZER_WEIGHT_DECAY,+            betas=(0.9, 0.999),+            eps=1e-8,+        )+        _log("actor optimizer initialized")+        self.critic_optimizer = torch_npu.optim.NpuFusedAdamW(+            self.critic.parameters(),+            lr=float(spec["critic_optimizer"]["learning_rate"]),+            weight_decay=_OPTIMIZER_WEIGHT_DECAY,+            betas=(0.9, 0.999),+            eps=1e-8,+        )+        _log("critic optimizer initialized")+        if self.action == "restart":+            self._load_optimizer_checkpoint(Path(spec["restart_checkpoint"]))++        self.reference_fingerprint = _fingerprint(self.reference)+        self.reward_fingerprint = _fingerprint(self.reward_model)+        _log("immutable-role fingerprints captured")+        self.actor.eval()+        self.critic.eval()++    def _load_trainable_models(self) -> tuple[torch.nn.Module, torch.nn.Module, int]:+        if self.action == "restart":+            checkpoint = Path(self.spec["restart_checkpoint"])+            metadata = _read_json(checkpoint / "metadata.json")+            _expect_equal("checkpoint schema", metadata.get("schema_version"), 1)+            _expect_equal("checkpoint update", metadata.get("policy_version"), 8)+            actor_path = checkpoint / "portable-actor"+            critic_path = checkpoint / "critic"+            initial_version = 8+        else:+            actor_path = self.arguments.policy_model_path+            critic_path = self.arguments.auxiliary_model_path+            initial_version = 0++        actor = AutoModelForCausalLM.from_pretrained(+            actor_path,+            local_files_only=True,+            trust_remote_code=False,+            dtype=torch.float32,+            low_cpu_mem_usage=True,+        ).to(self.actor_device)+        critic = AutoModelForTokenClassification.from_pretrained(+            critic_path,+            local_files_only=True,+            trust_remote_code=False,+            dtype=torch.float32,+            low_cpu_mem_usage=True,+            num_labels=1,+            ignore_mismatched_sizes=True,+        ).to(self.auxiliary_device)+        critic.config.pad_token_id = self.tokenizer.pad_token_id+        return actor, critic, initial_version++    def _load_optimizer_checkpoint(self, checkpoint: Path) -> None:+        actor_state = torch.load(+            checkpoint / "actor-optimizer.pt", map_location="cpu", weights_only=False+        )+        critic_state = torch.load(+            checkpoint / "critic-optimizer.pt", map_location="cpu", weights_only=False+        )+        self.actor_optimizer.load_state_dict(actor_state)+        self.critic_optimizer.load_state_dict(critic_state)++    def run(self, prompt_input: Path, sampling_seed: int) -> dict[str, Any]:+        prompts = _read_json(prompt_input)+        prompt_records = prompts.get("prompts")+        system_prompt = prompts.get("system_prompt")+        expected_trajectories = int(self.spec["resolved_work"]["trajectories_per_update"])+        if (+            not isinstance(system_prompt, str)+            or not system_prompt+            or not isinstance(prompt_records, list)+            or len(prompt_records) != expected_trajectories+        ):+            raise ValueError("formal prompt input has the wrong shape")+        prompt_ids: list[list[int]] = []+        prompt_names: list[str] = []+        for item in prompt_records:+            if (+                not isinstance(item, dict)+                or not isinstance(item.get("id"), str)+                or not item["id"]+                or not isinstance(item.get("question"), str)+                or not item["question"]+            ):+                raise ValueError("formal prompt record is invalid")+            messages = [+                {"role": "system", "content": system_prompt},+                {"role": "user", "content": item["question"]},+            ]+            encoded = self.tokenizer.apply_chat_template(+                messages,+                tokenize=True,+                add_generation_prompt=True,+            )+            # Transformers 5 returns a BatchEncoding here, while the 4.x API+            # returned the input-id list directly.+            if not isinstance(encoded, list) and hasattr(encoded, "get"):+                encoded = encoded.get("input_ids")+            if not isinstance(encoded, list) or not 0 < len(encoded) <= 128:+                raise ValueError("formal prompt exceeds the token contract")+            prompt_ids.append([int(token_id) for token_id in encoded])+            prompt_names.append(item["id"])+        if len(set(prompt_names)) != len(prompt_names):+            raise ValueError("formal prompt ids are not unique")++        torch.manual_seed(sampling_seed)+        torch.npu.manual_seed_all(sampling_seed)+        update_count = int(self.spec["resolved_work"]["committed_updates"])+        step_metrics: list[dict[str, Any]] = []+        trajectory_records: list[dict[str, Any]] = []+        actor_grad_norms: list[float] = []+        critic_grad_norms: list[float] = []+        ppo_started = time.monotonic()++        with ThreadPoolExecutor(max_workers=2, thread_name_prefix="ppo-update") as executor:+            for _ in range(update_count):+                update_number = self.policy_version + 1+                step_started = time.monotonic()++                generation_started = time.monotonic()+                _log(f"update {update_number}: generating rollouts")+                response_ids, old_log_probs = self._generate(prompt_ids)+                generation_seconds = time.monotonic() - generation_started+                packed = self._pack(prompt_ids, response_ids)++                auxiliary_started = time.monotonic()+                _log(f"update {update_number}: evaluating frozen and value roles")+                reference_log_probs, old_values, reward_scores = self._evaluate_auxiliary(packed)+                auxiliary_seconds = time.monotonic() - auxiliary_started++                advantage_started = time.monotonic()+                advantages, returns, token_rewards = self._gae(+                    packed,+                    old_log_probs,+                    reference_log_probs,+                    old_values,+                    reward_scores,+                )+                advantage_seconds = time.monotonic() - advantage_started++                _log(f"update {update_number}: applying actor and critic updates")+                actor_future = executor.submit(+                    self._update_actor, packed, old_log_probs, advantages+                )+                critic_future = executor.submit(+                    self._update_critic, packed, old_values, returns+                )+                actor_metrics = actor_future.result()+                critic_metrics = critic_future.result()++                self.policy_version = update_number+                actor_grad_norms.append(actor_metrics["grad_norm"])+                critic_grad_norms.append(critic_metrics["grad_norm"])++                mask = packed.response_mask+                valid_count = int(mask.sum())+                old_cpu = old_log_probs[mask]+                ref_cpu = reference_log_probs.cpu()[mask]+                values_cpu = old_values.cpu()[mask]+                rewards_cpu = token_rewards.cpu()[mask]+                advantages_cpu = advantages.cpu()[mask]+                returns_cpu = returns.cpu()[mask]+                kl_mean = float((old_cpu - ref_cpu).mean())+                step_seconds = time.monotonic() - step_started+                step_metrics.append(+                    {+                        "step": update_number,+                        "training/global_step": update_number,+                        "actor/pg_loss": actor_metrics["loss"],+                        "actor/ppo_kl": actor_metrics["ppo_kl"],+                        "actor/pg_clipfrac": actor_metrics["clipfrac"],+                        "actor/grad_norm": actor_metrics["grad_norm"],+                        "actor/reward_kl_penalty": -0.001 * kl_mean,+                        "actor/reward_kl_penalty_coeff": 0.001,+                        "critic/vf_loss": critic_metrics["loss"],+                        "critic/vf_clipfrac": critic_metrics["clipfrac"],+                        "critic/grad_norm": critic_metrics["grad_norm"],+                        "critic/score/mean": float(reward_scores.float().mean().cpu()),+                        "critic/rewards/mean": float(rewards_cpu.mean()),+                        "critic/advantages/mean": float(advantages_cpu.mean()),+                        "critic/returns/mean": float(returns_cpu.mean()),+                        "critic/values/mean": float(values_cpu.mean()),+                        "response_length/mean": valid_count / packed.batch_size,+                        "response_length/total": valid_count,+                        "timing_s/gen": generation_seconds,+                        "timing_s/reward": auxiliary_seconds,+                        "timing_s/old_log_prob": 0.0,+                        "timing_s/ref": auxiliary_seconds,+                        "timing_s/values": auxiliary_seconds,+                        "timing_s/adv": advantage_seconds,+                        "timing_s/update_critic": critic_metrics["seconds"],+                        "timing_s/update_actor": actor_metrics["seconds"],+                        "timing_s/update_weights": 0.0,+                        "timing_s/step": step_seconds,+                    }+                )++                row_offset = 0+                for row, (prompt_name, tokens) in enumerate(zip(prompt_names, response_ids, strict=True)):+                    length = len(tokens)+                    trajectory_records.append(+                        {+                            "update": update_number,+                            "prompt_id": prompt_name,+                            "response_ids": tokens,+                            "old_log_prob_mean": float(old_cpu[row_offset : row_offset + length].mean()),+                            "reference_log_prob_mean": float(ref_cpu[row_offset : row_offset + length].mean()),+                            "reward_score": float(reward_scores[row].float().cpu()),+                            "advantage_mean": float(+                                advantages_cpu[row_offset : row_offset + length].mean()+                            ),+                            "value_mean": float(values_cpu[row_offset : row_offset + length].mean()),+                        }+                    )+                    row_offset += length++        torch.npu.synchronize(self.actor_device)+        torch.npu.synchronize(self.auxiliary_device)+        reported_ppo_seconds = time.monotonic() - ppo_started+        if _fingerprint(self.reference) != self.reference_fingerprint:+            raise RuntimeError("frozen reference policy changed")+        if _fingerprint(self.reward_model) != self.reward_fingerprint:+            raise RuntimeError("frozen reward model changed")++        checkpoint_path: str | None = None+        portable_actor_path: str | None = None+        if self.action == "correctness":+            checkpoint = self.arguments.runtime_dir.parent / "checkpoints" / "update-8"+            self._save_checkpoint(checkpoint)+            checkpoint_path = str(checkpoint)+            portable_actor_path = str(checkpoint / "portable-actor")++        result = {+            "schema_version": 1,+            "status": "passed",+            "action": self.action,+            "committed_actor_updates": update_count,+            "committed_critic_updates": update_count,+            "accepted_trajectories": update_count * expected_trajectories,+            "policy_version": self.policy_version,+            "trajectory_records": trajectory_records,+            "step_metrics": step_metrics,+            "actor_grad_norms": actor_grad_norms,+            "critic_grad_norms": critic_grad_norms,+            "reference_policy_frozen": True,+            "reward_model_frozen": True,+            "reported_ppo_seconds": reported_ppo_seconds,+            "checkpoint_path": checkpoint_path,+            "portable_actor_path": portable_actor_path,+            "runtime_layout": {+                "placement": "split_role_resident",+                "logical_devices": [0, 1],+                "actor_device": 0,+                "actor_strategy": "fp32_master_bf16_compute",+                "actor_world_size": 1,+                "actor_micro_batch_size_per_gpu": _ACTOR_MICRO_BATCH,+                "actor_parameter_offload": False,+                "actor_optimizer_offload": False,+                "rollout_device": 0,+                "rollout_engine": "transformers_shared_live_actor",+                "rollout_tensor_parallel_size": 1,+                "rollout_max_num_batched_tokens": 32 * 192,+                "reference_device": 1,+                "critic_device": 1,+                "critic_strategy": "fp32_master_bf16_compute",+                "critic_world_size": 1,+                "critic_micro_batch_size_per_gpu": _AUXILIARY_MICRO_BATCH,+                "critic_parameter_offload": False,+                "critic_optimizer_offload": False,+                "reward_model_device": 1,+                "reward_model_tensor_parallel_size": 1,+                "actor_critic_updates_concurrent": True,+                "weight_transport": "none_shared_actor_rollout",+            },+        }+        _write_json(self.arguments.result_dir / "run-result.json", result)+        return result++    def _generate(+        self, prompt_ids: list[list[int]]+    ) -> tuple[list[list[int]], torch.Tensor]:+        batch_size = len(prompt_ids)+        width = max(len(item) for item in prompt_ids)+        input_ids = torch.full(+            (batch_size, width), self.tokenizer.pad_token_id, dtype=torch.long+        )+        attention_mask = torch.zeros((batch_size, width), dtype=torch.long)+        for row, tokens in enumerate(prompt_ids):+            input_ids[row, width - len(tokens) :] = torch.tensor(tokens, dtype=torch.long)+            attention_mask[row, width - len(tokens) :] = 1+        input_ids = input_ids.to(self.actor_device)+        attention_mask = attention_mask.to(self.actor_device)++        raw_recorder = _RawLogitsRecorder()+        logprob_recorder = _SelectedLogprobRecorder(raw_recorder)+        self.actor.eval()+        with torch.no_grad(), torch.autocast("npu", dtype=torch.bfloat16):+            sequences = self.actor.generate(+                input_ids=input_ids,+                attention_mask=attention_mask,+                do_sample=True,+                temperature=float(self.spec["sampling"]["temperature"]),+                top_p=float(self.spec["sampling"]["top_p"]),+                top_k=int(self.spec["sampling"]["top_k"]),+                num_return_sequences=1,+                max_new_tokens=int(self.spec["measurement"]["max_response_tokens"]),+                eos_token_id=self.tokenizer.eos_token_id,+                pad_token_id=self.tokenizer.pad_token_id,+                use_cache=True,+                logits_processor=LogitsProcessorList([raw_recorder]),+                stopping_criteria=StoppingCriteriaList([logprob_recorder]),+            )+        torch.npu.synchronize(self.actor_device)+        generated = sequences[:, width:].cpu()+        if not logprob_recorder.values or len(logprob_recorder.values) != generated.shape[1]:+            raise RuntimeError("rollout log-probability coverage is incomplete")+        recorded = torch.stack(logprob_recorder.values, dim=1).float().cpu()+        responses: list[list[int]] = []+        old_log_probs = torch.zeros(+            (batch_size, generated.shape[1]), dtype=torch.float32+        )+        eos_id = self.tokenizer.eos_token_id+        for row in range(batch_size):+            tokens = [int(value) for value in generated[row].tolist()]+            if eos_id in tokens:+                tokens = tokens[: tokens.index(eos_id) + 1]+            if not tokens:+                raise RuntimeError("rollout produced an empty response")+            responses.append(tokens)+            old_log_probs[row, : len(tokens)] = recorded[row, : len(tokens)]+        return responses, old_log_probs++    def _pack(+        self, prompt_ids: list[list[int]], response_ids: list[list[int]]+    ) -> PackedBatch:+        prompt_lengths = [len(item) for item in prompt_ids]+        response_lengths = [len(item) for item in response_ids]+        sequence_lengths = [+            prompt_length + response_length+            for prompt_length, response_length in zip(+                prompt_lengths, response_lengths, strict=True+            )+        ]+        max_sequence = max(sequence_lengths)+        max_response = max(response_lengths)+        batch_size = len(prompt_ids)+        input_ids = torch.full(+            (batch_size, max_sequence), self.tokenizer.pad_token_id, dtype=torch.long+        )+        attention_mask = torch.zeros((batch_size, max_sequence), dtype=torch.long)+        token_response_mask = torch.zeros(+            (batch_size, max_sequence), dtype=torch.bool+        )+        response_mask = torch.zeros((batch_size, max_response), dtype=torch.bool)+        for row, (prompt, response) in enumerate(+            zip(prompt_ids, response_ids, strict=True)+        ):+            sequence = prompt + response+            input_ids[row, : len(sequence)] = torch.tensor(sequence, dtype=torch.long)+            attention_mask[row, : len(sequence)] = 1+            token_response_mask[row, len(prompt) : len(sequence)] = True+            response_mask[row, : len(response)] = True+        return PackedBatch(+            input_ids=input_ids,+            attention_mask=attention_mask,+            token_response_mask=token_response_mask,+            response_mask=response_mask,+            prompt_lengths=prompt_lengths,+            response_lengths=response_lengths,+        )++    @staticmethod+    def _flat_to_padded(+        values: torch.Tensor, response_lengths: list[int], width: int+    ) -> torch.Tensor:+        output = torch.zeros(+            (len(response_lengths), width), dtype=values.dtype, device=values.device+        )+        offset = 0+        for row, length in enumerate(response_lengths):+            output[row, :length] = values[offset : offset + length]+            offset += length+        if offset != values.numel():+            raise RuntimeError("response tensor packing is inconsistent")+        return output++    def _evaluate_auxiliary(+        self, packed: PackedBatch+    ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+        device = self.auxiliary_device+        ids = packed.input_ids.to(device)+        attention = packed.attention_mask.to(device)+        token_mask = packed.token_response_mask.to(device)+        reference_parts: list[torch.Tensor] = []+        value_parts: list[torch.Tensor] = []+        reward_parts: list[torch.Tensor] = []+        self.reference.eval()+        self.critic.eval()+        self.reward_model.eval()+        with torch.npu.device(device), torch.no_grad(), torch.autocast(+            "npu", dtype=torch.bfloat16+        ):+            for start in range(0, packed.batch_size, _AUXILIARY_MICRO_BATCH):+                end = min(start + _AUXILIARY_MICRO_BATCH, packed.batch_size)+                micro_ids = ids[start:end]+                micro_attention = attention[start:end]+                micro_mask = token_mask[start:end]+                predictor_mask = micro_mask[:, 1:]++                reference_hidden = self.reference.model(+                    input_ids=micro_ids,+                    attention_mask=micro_attention,+                    use_cache=False,+                ).last_hidden_state[:, :-1]+                reference_logits = self.reference.lm_head(+                    reference_hidden[predictor_mask]+                )+                labels = micro_ids[:, 1:][predictor_mask]+                reference_loss, _, _, _ = torch_npu.npu_cross_entropy_loss(+                    reference_logits, labels, reduction="none"+                )+                reference_parts.append(-reference_loss.float())+                del reference_hidden, reference_logits, reference_loss++                critic_hidden = self.critic.model(+                    input_ids=micro_ids,+                    attention_mask=micro_attention,+                    use_cache=False,+                ).last_hidden_state[:, :-1]+                value_parts.append(+                    self.critic.score(critic_hidden[predictor_mask]).squeeze(-1).float()+                )+                del critic_hidden++                reward_hidden = self.reward_model.model(+                    input_ids=micro_ids,+                    attention_mask=micro_attention,+                    use_cache=False,+                ).last_hidden_state+                local_lengths = torch.tensor(+                    [+                        packed.prompt_lengths[row] + packed.response_lengths[row]+                        for row in range(start, end)+                    ],+                    dtype=torch.long,+                    device=device,+                )+                last_hidden = reward_hidden[+                    torch.arange(end - start, device=device), local_lengths - 1+                ]+                reward_logits = self.reward_model.score(last_hidden).float()+                reward_parts.append(torch.softmax(reward_logits, dim=-1)[:, 1])+                del reward_hidden, last_hidden, reward_logits+        torch.npu.synchronize(device)+        width = packed.response_mask.shape[1]+        reference = self._flat_to_padded(+            torch.cat(reference_parts), packed.response_lengths, width+        )+        values = self._flat_to_padded(+            torch.cat(value_parts), packed.response_lengths, width+        )+        rewards = torch.cat(reward_parts)+        return reference, values, rewards++    def _gae(+        self,+        packed: PackedBatch,+        old_log_probs: torch.Tensor,+        reference_log_probs: torch.Tensor,+        old_values: torch.Tensor,+        reward_scores: torch.Tensor,+    ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+        device = self.auxiliary_device+        width = packed.response_mask.shape[1]+        old = old_log_probs[:, :width].to(device)+        mask = packed.response_mask.to(device=device, dtype=torch.float32)+        token_rewards = -float(+            self.spec["algorithm"]["reference_kl"]["coefficient"]+        ) * (old - reference_log_probs)+        token_rewards = token_rewards * mask+        rows = torch.arange(packed.batch_size, device=device)+        final_columns = torch.tensor(+            packed.response_lengths, dtype=torch.long, device=device+        ) - 1+        token_rewards[rows, final_columns] += reward_scores++        gamma = float(self.spec["algorithm"]["gamma"])+        gae_lambda = float(self.spec["algorithm"]["lambda"])+        next_values: torch.Tensor | float = 0.0+        last_gae: torch.Tensor | float = 0.0+        reversed_advantages = []+        with torch.no_grad():+            for position in reversed(range(width)):+                delta = (+                    token_rewards[:, position]+                    + gamma * next_values+                    - old_values[:, position]+                )+                candidate = delta + gamma * gae_lambda * last_gae+                position_mask = mask[:, position]+                next_values = (+                    old_values[:, position] * position_mask+                    + (1.0 - position_mask) * next_values+                )+                last_gae = (+                    candidate * position_mask + (1.0 - position_mask) * last_gae+                )+                reversed_advantages.append(last_gae)+            advantages = torch.stack(reversed_advantages[::-1], dim=1)+            returns = advantages + old_values+            valid = advantages[mask.bool()]+            mean = valid.mean()+            variance = valid.var(unbiased=True)+            advantages = (advantages - mean) * torch.rsqrt(variance + 1e-8)+        if not torch.isfinite(advantages[mask.bool()]).all():+            raise RuntimeError("GAE produced non-finite advantages")+        return advantages, returns, token_rewards++    def _update_actor(+        self, packed: PackedBatch, old_log_probs: torch.Tensor, advantages: torch.Tensor+    ) -> dict[str, float]:+        started = time.monotonic()+        device = self.actor_device+        with torch.npu.device(device):+            ids = packed.input_ids.to(device)+            attention = packed.attention_mask.to(device)+            token_mask = packed.token_response_mask.to(device)+            response_mask = packed.response_mask.to(device)+            width = response_mask.shape[1]+            old = old_log_probs[:, :width].to(device)+            actor_advantages = advantages.to(device)+            token_count = response_mask.sum()+            self.actor.train()+            self.actor_optimizer.zero_grad()+            loss_sum = torch.zeros((), dtype=torch.float32, device=device)+            kl_sum = torch.zeros((), dtype=torch.float32, device=device)+            clip_sum = torch.zeros((), dtype=torch.float32, device=device)+            for start in range(0, packed.batch_size, _ACTOR_MICRO_BATCH):+                end = min(start + _ACTOR_MICRO_BATCH, packed.batch_size)+                micro_ids = ids[start:end]+                micro_attention = attention[start:end]+                predictor_mask = token_mask[start:end, 1:]+                local_response_mask = response_mask[start:end]+                with torch.autocast("npu", dtype=torch.bfloat16):+                    hidden = self.actor.model(+                        input_ids=micro_ids,+                        attention_mask=micro_attention,+                        use_cache=False,+                    ).last_hidden_state[:, :-1]+                    logits = self.actor.lm_head(hidden[predictor_mask])+                    labels = micro_ids[:, 1:][predictor_mask]+                    negative_log_probs, _, _, _ = torch_npu.npu_cross_entropy_loss(+                        logits, labels, reduction="none"+                    )+                    new_log_probs = -negative_log_probs.float()+                    local_old = old[start:end][local_response_mask]+                    local_advantages = actor_advantages[start:end][local_response_mask]+                    log_ratio = torch.clamp(+                        new_log_probs - local_old, min=-20.0, max=20.0+                    )+                    ratio = torch.exp(log_ratio)+                    losses_unclipped = -local_advantages * ratio+                    losses_clipped = -local_advantages * torch.clamp(+                        ratio,+                        1.0 - float(self.spec["algorithm"]["actor_clip"]),+                        1.0 + float(self.spec["algorithm"]["actor_clip"]),+                    )+                    clipped = torch.maximum(losses_unclipped, losses_clipped)+                    # Verl's vanilla PPO objective uses the conventional+                    # lower dual clip for negative advantages.+                    policy_losses = torch.where(+                        local_advantages < 0,+                        torch.minimum(-3.0 * local_advantages, clipped),+                        clipped,+                    )+                    micro_loss_sum = policy_losses.sum()+                    loss = micro_loss_sum / token_count+                loss.backward()+                loss_sum += micro_loss_sum.detach()+                kl_sum += (-log_ratio).sum().detach()+                clip_sum += (losses_clipped > losses_unclipped).float().sum().detach()+                del hidden, logits, negative_log_probs, new_log_probs, loss+            grad_norm = torch.nn.utils.clip_grad_norm_(+                self.actor.parameters(), _GRAD_CLIP+            )+            self.actor_optimizer.step()+            torch.npu.synchronize(device)+            self.actor.eval()+            count = float(token_count.cpu())+            return {+                "loss": float(loss_sum.cpu()) / count,+                "ppo_kl": float(kl_sum.cpu()) / count,+                "clipfrac": float(clip_sum.cpu()) / count,+                "grad_norm": float(grad_norm.float().cpu()),+                "seconds": time.monotonic() - started,+            }++    def _update_critic(+        self, packed: PackedBatch, old_values: torch.Tensor, returns: torch.Tensor+    ) -> dict[str, float]:+        started = time.monotonic()+        device = self.auxiliary_device+        with torch.npu.device(device):+            ids = packed.input_ids.to(device)+            attention = packed.attention_mask.to(device)+            token_mask = packed.token_response_mask.to(device)+            response_mask = packed.response_mask.to(device)+            critic_returns = returns.to(device)+            token_count = response_mask.sum()+            self.critic.train()+            self.critic_optimizer.zero_grad()+            loss_sum = torch.zeros((), dtype=torch.float32, device=device)+            clip_sum = torch.zeros((), dtype=torch.float32, device=device)+            for start in range(0, packed.batch_size, _AUXILIARY_MICRO_BATCH):+                end = min(start + _AUXILIARY_MICRO_BATCH, packed.batch_size)+                micro_ids = ids[start:end]+                micro_attention = attention[start:end]+                predictor_mask = token_mask[start:end, 1:]+                local_response_mask = response_mask[start:end]+                with torch.autocast("npu", dtype=torch.bfloat16):+                    hidden = self.critic.model(+                        input_ids=micro_ids,+                        attention_mask=micro_attention,+                        use_cache=False,+                    ).last_hidden_state[:, :-1]+                    hidden = self.critic.dropout(hidden[predictor_mask])+                    predictions = self.critic.score(hidden).squeeze(-1).float()+                    local_old = old_values[start:end][local_response_mask]+                    local_returns = critic_returns[start:end][local_response_mask]+                    clipped_predictions = torch.clamp(+                        predictions,+                        local_old - float(self.spec["algorithm"]["value_clip"]),+                        local_old + float(self.spec["algorithm"]["value_clip"]),+                    )+                    losses_unclipped = (predictions - local_returns).square()+                    losses_clipped = (clipped_predictions - local_returns).square()+                    selected_losses = torch.maximum(losses_unclipped, losses_clipped)+                    micro_loss_sum = 0.5 * selected_losses.sum()+                    loss = micro_loss_sum / token_count+                loss.backward()+                loss_sum += micro_loss_sum.detach()+                clip_sum += (losses_clipped > losses_unclipped).float().sum().detach()+                del hidden, predictions, loss+            grad_norm = torch.nn.utils.clip_grad_norm_(+                self.critic.parameters(), _GRAD_CLIP+            )+            self.critic_optimizer.step()+            torch.npu.synchronize(device)+            self.critic.eval()+            count = float(token_count.cpu())+            return {+                "loss": float(loss_sum.cpu()) / count,+                "clipfrac": float(clip_sum.cpu()) / count,+                "grad_norm": float(grad_norm.float().cpu()),+                "seconds": time.monotonic() - started,+            }++    def _save_checkpoint(self, checkpoint: Path) -> None:+        if self.policy_version != 8:+            raise RuntimeError("only update eight is checkpointable")+        checkpoint.parent.mkdir(parents=True, exist_ok=True)+        temporary = checkpoint.with_name(checkpoint.name + ".tmp")+        if temporary.exists():+            shutil.rmtree(temporary)+        temporary.mkdir()+        portable = temporary / "portable-actor"+        critic_path = temporary / "critic"++        # Preserve the actual FP32 master parameters in the portable artifact.+        # Besides making update-nine restart exact, this gives CPU and NPU+        # freshness probes the same source precision.+        actor_state = {+            name: tensor.detach().cpu() for name, tensor in self.actor.state_dict().items()+        }+        self.actor.save_pretrained(+            portable,+            state_dict=actor_state,+            safe_serialization=True,+            max_shard_size="4GB",+        )+        self.tokenizer.save_pretrained(portable)+        del actor_state++        critic_state = {+            name: tensor.detach().cpu() for name, tensor in self.critic.state_dict().items()+        }+        self.critic.save_pretrained(+            critic_path,+            state_dict=critic_state,+            safe_serialization=True,+            max_shard_size="4GB",+        )+        del critic_state++        torch.save(+            _to_cpu(self.actor_optimizer.state_dict()),+            temporary / "actor-optimizer.pt",+        )+        torch.save(+            _to_cpu(self.critic_optimizer.state_dict()),+            temporary / "critic-optimizer.pt",+        )+        _write_json(+            temporary / "metadata.json",+            {+                "schema_version": 1,+                "policy_version": self.policy_version,+                "actor_optimizer": self.spec["actor_optimizer"],+                "critic_optimizer": self.spec["critic_optimizer"],+                "precision": self.spec["precision"],+            },+        )+        if checkpoint.exists():+            raise RuntimeError("update-eight checkpoint already exists")+        os.replace(temporary, checkpoint)++    def probe(self, request: dict[str, Any]) -> dict[str, Any]:+        prompt = request.get("prompt")+        continuation = request.get("continuation")+        if not isinstance(prompt, str) or not prompt or not isinstance(continuation, str) or not continuation:+            raise ValueError("freshness probe is invalid")+        prompt_ids = self.tokenizer.encode(prompt, add_special_tokens=True)+        continuation_ids = self.tokenizer.encode(+            continuation, add_special_tokens=False+        )+        if not prompt_ids or not continuation_ids:+            raise ValueError("freshness probe tokenization is empty")+        input_ids = torch.tensor(+            [prompt_ids + continuation_ids], dtype=torch.long, device=self.actor_device+        )+        predictor_positions = torch.arange(+            len(prompt_ids) - 1,+            len(prompt_ids) + len(continuation_ids) - 1,+            device=self.actor_device,+        )+        labels = torch.tensor(+            continuation_ids, dtype=torch.long, device=self.actor_device+        )+        self.actor.eval()+        # Probe from the FP32 masters exported to the portable actor.  PPO and+        # rollout forwards use BF16; this tiny correctness-only evaluation+        # avoids backend-specific BF16 accumulation drift in the CPU/NPU+        # portability comparison.+        with torch.no_grad():+            hidden = self.actor.model(input_ids=input_ids, use_cache=False).last_hidden_state[0]+            logits = self.actor.lm_head(hidden[predictor_positions])+            log_probs = torch.log_softmax(logits.float(), dim=-1)+            selected = log_probs.gather(1, labels[:, None]).squeeze(1)+        torch.npu.synchronize(self.actor_device)+        values = selected.cpu().tolist()+        if not values or not all(math.isfinite(float(value)) for value in values):+            raise RuntimeError("freshness probe produced invalid log probabilities")+        # Rollout shares the actor object, so this is both exact and a direct+        # statement of the live rollout policy rather than a stale replica.+        return {+            "type": "probe_result",+            "policy_version": self.policy_version,+            "rollout_reported_version": self.policy_version,+            "actor_log_probs": values,+            "rollout_log_probs": list(values),+        }+++def _connect(path: Path) -> socket.socket:+    deadline = time.monotonic() + 60.0+    while True:+        connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+        try:+            connection.connect(str(path))+            return connection+        except OSError:+            connection.close()+            if time.monotonic() >= deadline:+                raise+            time.sleep(0.05)+++def _send(handle: Any, value: dict[str, Any]) -> None:+    handle.write(+        json.dumps(value, allow_nan=False, separators=(",", ":")).encode("utf-8")+        + b"\n"+    )+    handle.flush()+++def _receive(handle: Any) -> dict[str, Any]:+    raw = handle.readline(1024 * 1024 + 1)+    if not raw or len(raw) > 1024 * 1024:+        raise RuntimeError("control connection closed or sent an oversized message")+    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 main(argv: list[str] | None = None) -> int:+    arguments = _parse_args(argv)+    spec = _read_json(arguments.run_spec)+    _validate_run_spec(spec)+    if torch.npu.device_count() != 2:+        raise RuntimeError("exactly two projected NPUs are required")+    torch.set_num_threads(min(16, os.cpu_count() or 1))+    runtime = OnlinePPORuntime(arguments, spec)++    connection = _connect(arguments.control_socket)+    with connection, connection.makefile("rwb", buffering=0) as control:+        _send(control, {"type": "ready"})+        started = False+        while True:+            message = _receive(control)+            message_type = message["type"]+            if message_type == "start" and not started:+                input_path = message.get("input_path")+                sampling_seed = message.get("sampling_seed")+                if (+                    not isinstance(input_path, str)+                    or type(sampling_seed) is not int+                    or sampling_seed < 0+                ):+                    raise ValueError("start request is invalid")+                prompt_path = Path(input_path).resolve(strict=True)+                if not prompt_path.is_relative_to(arguments.runtime_dir):+                    raise ValueError("formal prompt path is outside the runtime directory")+                try:+                    runtime.run(prompt_path, sampling_seed)+                except BaseException:+                    traceback.print_exc(file=sys.stderr)+                    sys.stderr.flush()+                    _send(control, {"type": "error"})+                    raise+                started = True+                _send(control, {"type": "completed"})+            elif message_type == "probe" and started:+                request = message.get("request")+                if message.get("kind") != "freshness" or not isinstance(request, dict):+                    raise ValueError("probe request is invalid")+                _send(control, runtime.probe(request))+            elif message_type == "shutdown" and started:+                return 0+            else:+                raise ValueError(f"unexpected control message: {message_type}")+++if __name__ == "__main__":+    raise SystemExit(main())