Claude Fable 5.1 · RL

R03 · PPO joint

Valid

Qwen3-1.7B online PPO 2dev · Joint Optimization

9.06×PERFORMANCE RATIO
148TOOL 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 agentClaude Fable 5.1 · 148 visible calls

InspectEditValidateExecuteBuildProfileRollbackOther
69Inspect
37Edit
3Build
25Validate
8Execute
6Other

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 timeline111 groups · 148 calls

Scroll within this panel to view all events. Command sketches retain familiar programs and options. Values become <val> or <n>; paths, addresses and script bodies are hidden as <path>, <url> and <script>.

Main agent

  1. Inspect · Source & workspace

    Requested workspace inspection related to source & workspace.

    1 call · #0001–#0001

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

    Requested file and log inspection and workspace inspection related to task requirements.

    2 calls · #0002–#0003

    cd <path>echo <val>cat <val>echo<command> <args>find <val> -maxdepth <n> <flag> <args>
    1 more command sketches
    sort <flag>
  3. Inspect · Device memory

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

    1 call · #0004–#0004

    env <vars>echo <val>ls -l -a <val> <n> > <path>cat <path> <n> > <path>
  4. Inspect · Source & workspace

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

    1 call · #0005–#0005

    <command> <args>git -C <val> <val> <flag> <args>head -n <n>
  5. Inspect · Reward & policy updates

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

    1 call · #0006–#0006

    cd <path>echo <val>cat <path>echo
  6. Validate · Benchmark & validation setup

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

    1 call · #0007–#0007

    cd <path><command> <args>cat <val>echo
  7. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    1 call · #0008–#0008

    cd <path>echo <val>cat <path>echoecho <path>head -c <n> <path>
  8. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    3 calls · #0009–#0011

    cd <path>cat -n <path>wc -l <path>sed -n <val> <path>
  9. Inspect · Device memory

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

    1 call · #0012–#0012

    echo <val><command> <args>head <flag>envgrep -i -E <val>sort
    2 more command sketches
    python -c <script> <n> >& <path>tail -n <n>
  10. Inspect · Source & workspace

    1 tool error

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

    5 calls · #0013–#0017

    echo <path>ls -l -a <path>head -n <n>echo <val><command> <args>ls -l -a <val>
    6 more command sketches
    sed -n <val> <path>ls -l -a <path> <n> >& <path>headls <path>echo <flag>cat <path> <n> > <path>
  11. Build · Source & workspace

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

    1 call · #0018–#0018

    cd <path>echo <val>lscat <path> <n> > <path>find <path> -name <val> <flag> <args>head -n <n>
    3 more command sketches
    ls <path> <n> > <path>python -c <script> <n> >& <path>tail -n <n>
  12. Inspect · Source & workspace

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

    3 calls · #0019–#0021

    env <vars>echo <val>find <val> -maxdepth <n> <flag> <args>head -n <n>find <path> -name <val> -o -name <val> <n> > <path>head
    8 more command sketches
    ls -l -a <path> <n> > <path>cd <path><command> <args>env <vars> timeout <n> <val> -c <val> <n> >& <path>tail -n <n>lswc -l <path> <n> > <path>grep -r -n <val> --include <path> <path>
  13. Inspect · Checkpoints & weight state

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

    1 call · #0022–#0022

    cd <path>echo <val>find <path> -name <path>head -n <n>ls <path>grep -r -n <val> --include <path> <path> <path> <path> <n> > <path>
  14. Inspect · Reward & policy updates

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

    1 call · #0023–#0023

    cd <path>ls <path>echo <val>grep -r -n <val> <path> <n> > <path>head -n <n>grep -n <val> <path>
  15. Inspect · Source & workspace

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

    3 calls · #0024–#0026

    env <vars>echo <val>python -c <script>head -c <n> <path><command> <args>grep -r -l -n <val> --include <path> <val> <n> > <path>
    7 more command sketches
    head -n <n>find <path> -name <val> <flag> <args>headcd <path>lsecho <path>grep -n <val> <path> <path> <n> > <path>
  16. Inspect · Attention kernels

    Requested source searches, file and log inspection and workspace inspection related to attention kernels.

    1 call · #0027–#0027

    cd <path>echo <val>grep -n <val> <path>head -n <n>grep -r -n <val> <path> <n> > <path>ls <path>
  17. Inspect · Device memory

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

    1 call · #0028–#0028

    cd <path>cat > <path> <script>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v -i -E <val>tail -n <n>
  18. Inspect · Prefix caching

    Requested source searches and file and log inspection related to prefix caching.

    1 call · #0029–#0029

    cd <path>echo <val>grep -r -n <val> <path>head -n <n>grep -n <val> <path>echo <path>
    2 more command sketches
    grep -r -n <val> <path> <path> <path> <n> > <path>head
  19. Inspect · Rollout generation

    Requested file and log inspection related to rollout generation.

    1 call · #0030–#0030

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

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

    2 calls · #0031–#0032

    env <vars>python - <script>echo <val>python -c <script> <n> > <path>head -c <n> <path>cd <path>
    9 more command sketches
    env -u <val> <val> -I -c <val> <n> >& <path>tail -n <n>ls <path> <n> > <path>headcat <path> <n> > <path>head -n <n>echo <flag>ls <path>grep -i -E <val>
  21. Inspect · Attention kernels

    Requested file and log inspection and source searches related to attention kernels.

    1 call · #0033–#0033

    cd <path>echo <val>sed -n <val> <path>grep -r -n <val> <path> <path> <path> <n> > <path>head -n <n>grep -r -n <val> <path>
    1 more command sketches
    grep -i <val>
  22. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0034–#0034

    cat <path> <n> > <path>tail -n <n>
  23. Inspect · Attention kernels

    Requested environment setup or inspection, source searches and file and log inspection related to attention kernels.

    1 call · #0035–#0035

    cd <path>env <vars> timeout <n> <val> -c <val> <n> >& <path>grep -v -i -E <val>tail -n <n>
  24. Inspect · Source & workspace

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

    2 calls · #0036–#0037

    echo <val>df -h <path> <path> <n> > <path>head -n <n> <path>cd <path>timeout <n> <val> -X <val> -c <val> <n> >& <path>tail -n <n>
    8 more command sketches
    echo <flag><command> <args>timeout <n> <val> -c <val> <n> >& <path>tail <flag>grep -n <val> <path>grep -i <val>head -n <n>python -c <script> <n> >& <path>
  25. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0038–#0038

    date -uecho <val>python -c <script>
  26. Inspect · Source & workspace

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

    1 call · #0039–#0039

    cd <path><command> <args>tail -n <n>echo <path>python -c <script> <n> >& <path>cat <path>
  27. Inspect · Task requirements

    Requested script or workload execution related to task requirements.

    1 call · #0040–#0040

    cd <path>python - <script>
  28. Execute · Checkpoints & weight state

    Requested file and log inspection, environment setup or inspection and source searches related to checkpoints & weight state.

    1 call · #0041–#0041

    cd <path>cat > <path> <script>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v -i -E <path>tail -n <n>
  29. Execute · Parallelism & communication

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

    1 call · #0042–#0042

    cd <path>cat > <path> <script>export <vars><command> <args>grep -E <val>env <vars> timeout <n> <val> <path> <n> >& <path>
    1 more command sketches
    tail -n <n>
  30. Execute · Benchmark & validation setup

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

    1 call · #0043–#0043

    cat <path> <n> > <path>tail -n <n>
  31. Execute · Parallelism & communication

    Requested file and log inspection related to parallelism & communication.

    1 call · #0044–#0044

    cat <path> <n> > <path>tail -n <n>
  32. Inspect · Task requirements

    Requested script or workload execution related to task requirements.

    1 call · #0045–#0045

    cd <path>python - <script>
  33. Inspect · Source & workspace

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

    1 call · #0046–#0046

    cd <path>sed -n <val> <path>echo <val>grep -n <val> <path> <path> <path> <path> <n> > <path>headpython - <script>
  34. Execute · Checkpoints & weight state

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

    1 call · #0047–#0047

    mkdir -p <path>cat > <path> <script>export <vars>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v -i -E <path>tail -n <n>
  35. Build · Checkpoints & weight state

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

    1 call · #0048–#0048

    mkdir -p <path>cat > <path> <script>export <vars>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v -i -E <path>tail -n <n>
  36. Inspect · Source & workspace

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

    1 call · #0049–#0049

    cd <path> <n> > <path>mkdir -p <path>cd <path>cat > <path> <script>export <vars>timeout <n> <val> <path> <n> >& <path>
    4 more command sketches
    grep -v -i -E <path>tail -n <n>echo <val>env -u <val> -u <val> <vars> <val> <n> <val> -I -c <vars> <args>
  37. Other · Source & workspace

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

    1 call · #0050–#0050

    cd <path><command> <args>grep -v <val>echo <val>python -c <script> <n> >& <path>
  38. Inspect · Reward & policy updates

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

    1 call · #0051–#0051

    env <vars>echo <val>cat <path>
  39. Inspect · Checkpoints & weight state

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

    1 call · #0052–#0052

    mkdir -p <path>cat > <path> <script>export <vars>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v -i -E <path>tail -n <n>
  40. Inspect · Reward & policy updates

    Requested workspace file updates, file and log inspection and environment setup or inspection related to reward & policy updates.

    2 calls · #0053–#0054

    mkdir -p <path>cat > <path> <script>export <vars>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v -i -E <path>tail -n <n>
    3 more command sketches
    env <vars>echo <val>tail -n <n> <path> <n> > <path>
  41. Inspect · Source & workspace

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

    2 calls · #0055–#0056

    env <vars>echo <val>ls <path> <n> > <path>head -n <n>find <path> -name <val> <n> > <path>wc -l
    9 more command sketches
    find <path> -name <path> <n> > <path>test -w <path>echo <path>python -c <script> <n> >& <path>grep -v <val>python -B -c <script> <n> >& <path>cd <path>sed -n <val> <path>head -n <n> <path>
  42. Validate · Benchmark & validation setup

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

    1 call · #0057–#0057

    cd <path>echo <val>ls <path> <n> > <path>head -n <n>python -c <script> <n> >& <path>grep -v <val>
    1 more command sketches
    find <val> -name <val> -o -name <val> <n> > <path>
  43. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0058–#0058

    Write <path>
  44. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0059–#0059

    cd <path>echo <val>cat -n <path>sed -n <val> <path>
  45. Inspect · Device memory

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

    1 call · #0060–#0060

    cd <path>cat > <path> <script>export <vars>env <vars> python <script> <n> >& <path>grep -v <val>sleep <n>
    5 more command sketches
    echo <val>npu-smi info <n> >& <path>sed -n <path>head -n <n>wait
  46. Execute · Checkpoints & weight state

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

    1 call · #0061–#0061

    mkdir -p <path>cat > <path> <script>export <vars>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v -i -E <path>tail -n <n>
  47. Execute · Benchmark & validation setup

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

    1 call · #0062–#0062

    tail -n <n> <path> <n> > <path>
  48. Inspect · Device memory

    Requested workspace file updates, file and log inspection and environment setup or inspection related to device memory.

    1 call · #0063–#0063

    rm -f <path>cat > <path> <script>export <vars>env <vars> python <script> > <path> <n> >& <path>env <vars><command> <args>
    8 more command sketches
    sleep <n>echo <path>echo <val>npu-smi info <n> >& <path>sed -n <path>head -n <n>python -c <script>wait <val> <n> > <path>
  49. Inspect · Benchmark & validation setup

    Requested source searches related to benchmark & validation setup.

    1 call · #0064–#0064

    grep -E <val> <path>
  50. Inspect · Attention kernels

    Requested workspace file updates, file and log inspection and environment setup or inspection related to attention kernels.

    1 call · #0065–#0065

    mkdir -p <path>cat > <path> <script>export <vars>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v -i -E <path>tail -n <n>
  51. Inspect · Reward & policy updates

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

    2 calls · #0066–#0067

    cd <path>echo <path>grep -r -n <val> <path> <path> <n> > <path>head -n <n>echo <val>grep -r -l -n <val> --include <path> <path>
    2 more command sketches
    grep -n <val> <flag> <args>grep -r -n <val> <path>
  52. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0068–#0068

    cat <path> <n> > <path>tail -n <n>
  53. Inspect · Attention kernels

    Requested script or workload execution, source searches and file and log inspection related to attention kernels.

    2 calls · #0069–#0070

    cd <path>python -c <script> <n> >& <path>grep -v -i -E <val>tail -n <n>mkdir -p <path>cat > <path> <script>
    3 more command sketches
    export <vars>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v -i -E <path>
  54. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0071–#0071

    Write <path>
  55. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0072–#0072

    cat <path> <n> > <path>tail -n <n>
  56. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0073–#0073

    python -c <script>
  57. Validate · Attention kernels

    Requested workspace file updates, file and log inspection and environment setup or inspection related to attention kernels.

    1 call · #0074–#0074

    mkdir -p <path>cat > <path> <script>export <vars>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v -i -E <path>tail -n <n>
  58. Inspect · Precision & numerical checks

    Requested workspace file updates, file and log inspection and environment setup or inspection related to precision & numerical checks.

    1 call · #0075–#0075

    mkdir -p <path>cat > <path> <script>export <vars>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v -i -E <path>tail -n <n>
  59. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0076–#0076

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

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

    1 call · #0077–#0077

    env <vars>echo <val>tail -n <n> <path>grep -E <val> <path>
  61. Edit · Source & workspace

    Requested code edits related to source & workspace.

    3 calls · #0078–#0080

    Edit <path>
  62. Other · Source & workspace

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

    1 call · #0081–#0081

    cd <path>python -c <script> <n> >& <path>grep -v <val>python -c <script>
  63. Edit · Source & workspace

    Requested code edits related to source & workspace.

    4 calls · #0082–#0085

    Edit <path>Write <path>
  64. Inspect · Device memory

    1 tool error

    Requested process termination, execution waits and runtime inspection related to device memory.

    1 call · #0086–#0086

    pkill -f <path> <n> > <path>sleep <n>echo <val>npu-smi info <n> >& <path>sed -n <path>head -n <n>
    3 more command sketches
    ps <flag> <args>grep -E <val>grep -v <val>
  65. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0087–#0088

    Edit <path>
  66. Inspect · Device memory

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

    1 call · #0089–#0089

    cd <path>echo <val>python -m <module> <script> <script>npu-smi info <n> >& <path>sed -n <path>head -n <n>
    4 more command sketches
    ps <flag> <args>grep -E <path>grep -v <val>python -c <script>
  67. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0090–#0091

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

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

    1 call · #0092–#0092

    cd <path>python -m <module> <script> <script><command> <args>rm -f <path> <path>echo <val>date -u
    2 more command sketches
    timeout <n> <val> <path> <n> >& <path>tail -n <n>
  69. Edit · Device memory

    Requested code edits related to device memory.

    2 calls · #0093–#0094

    Write <path>
  70. Validate · Device memory

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

    1 call · #0095–#0095

    env <vars>echo <val>tail -n <n> <path> <n> > <path>echols -l -a <path> <n> > <path>head
    6 more command sketches
    <command> <args>tail -n <n> <val> <n> > <path>npu-smi info <n> >& <path>sed -n <path>head -n <n>python -c <script>
  71. Edit · Device memory

    Requested code edits related to device memory.

    1 call · #0096–#0096

    Write <path>
  72. Validate · Device memory

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

    1 call · #0097–#0097

    env <vars>echo <val>tail -n <n> <path> <n> > <path>echols -l -a <path> <n> > <path><command> <args>
    5 more command sketches
    tail -n <n> <val> <n> > <path>npu-smi info <n> >& <path>sed -n <path>head -n <n>python -c <script>
  73. Inspect · Attention kernels

    Requested script or workload execution, source searches and file and log inspection related to attention kernels.

    1 call · #0098–#0098

    cd <path>timeout <n> <val> -c <path> <n> >& <path>grep -v -i -E <path>tail -n <n>
  74. Validate · Device memory

    Requested environment setup or inspection, execution waits and file and log inspection related to device memory.

    1 call · #0099–#0099

    env <vars><command> <args>sleep <n>echo <val>tail -n <n> <path> <n> > <path>echo
    5 more command sketches
    python - <script>npu-smi info <n> >& <path>sed -n <path>head -n <n>python -c <script>
  75. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0100–#0100

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

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

    1 call · #0101–#0101

    env <vars>echo <val>cat <path> <n> > <path>echohead -n <n><command> <args>
    2 more command sketches
    cat <val> <n> > <path>tail -n <n>
  77. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0102–#0102

    Edit <path>
  78. Inspect · Parallelism & communication

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

    1 call · #0103–#0103

    cat > <path> <script>export <vars><command> <args>grep -E <val>env <vars> timeout <n> <val> <path> <n> >& <path>sort
    1 more command sketches
    tail -n <n>
  79. Validate · Reward & policy updates

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

    1 call · #0104–#0104

    cat > <path> <script>cd <path>timeout <n> <val> <path> <val> <n> >& <path>tail -n <n>echo <val>tail -n <n> <path>
    2 more command sketches
    <command> <args>tail -n <n> <val>
  80. Inspect · Reward & policy updates

    Requested environment setup or inspection, file and log inspection and runtime inspection related to reward & policy updates.

    1 call · #0105–#0105

    env <vars>echo <val>tail -n <n> <path> <n> > <path>echo<command> <args>tail -n <n> <val>
    3 more command sketches
    npu-smi info <n> >& <path>sed -n <path>head -n <n>
  81. Other · Source & workspace

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

    1 call · #0106–#0106

    cd <path>echo <val>grep -n <val> <path>echopython - <script>python -m <module> <script> <script>
    1 more command sketches
    python -c <script>
  82. Inspect · Source & workspace

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

    1 call · #0107–#0107

    cd <path>timeout <n> <val> -c <val> <n> >& <path>grep -v -i -E <val>tail -n <n>
  83. Inspect · Reward & policy updates

    Requested environment setup or inspection, execution waits and file and log inspection related to reward & policy updates.

    1 call · #0108–#0108

    env <vars><command> <args>sleep <n>echo <val>cat <path> <n> > <path>tail -n <n>
    6 more command sketches
    echotail -n <n> <path> <n> > <path>tail -n <n> <val>npu-smi info <n> >& <path>sed -n <path>head -n <n>
  84. Edit · Source & workspace

    Requested code edits related to source & workspace.

    7 calls · #0109–#0115

    Edit <path>
  85. Validate · Reward & policy updates

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

    1 call · #0116–#0116

    cd <path>python -m <module> <script> <script><command> <args>rm -rf <path> <path> <path>echo <val>date -u
    4 more command sketches
    timeout <n> <val> <path> <val> <n> >& <path>tail -n <n>tail -n <n> <path> <n> > <path>grep -v -i -E <val> <val> <n> > <path>
  86. Inspect · Checkpoints & weight state

    Requested script or workload execution related to checkpoints & weight state.

    1 call · #0117–#0117

    cd <path>timeout <n> <val> <val> <script>
  87. Inspect · Device memory

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

    1 call · #0118–#0118

    env <vars>echo <val>grep -r -l <val> <val> <n> > <path>head -n <n>grep -r -n <val> <val> --include <path> <n> > <path>python -c <script>
  88. Validate · Device memory

    Requested environment setup or inspection, source searches and execution waits related to device memory.

    1 call · #0119–#0119

    env <vars><command> <args>grep -q -E <val> <val> <n> > <path>sleep <n>echo <val>cat <val> <n> > <path>
    6 more command sketches
    grep -v -i -E <val>tail -n <n>echogrep -c <val> <val> <n> > <path>echo <n>python -c <script>
  89. Edit · Reward & policy updates

    Requested code edits related to reward & policy updates.

    1 call · #0120–#0120

    Write <path>
  90. Edit · Device memory

    Requested code edits related to device memory.

    1 call · #0121–#0121

    Write <path>
  91. Validate · Reward & policy updates

    Requested workspace file updates and script or workload execution related to reward & policy updates.

    1 call · #0122–#0122

    cd <path><command> <args>rm -rf <path>rm -f <path> <path> <path> <path>echo <val>date -u
    3 more command sketches
    timeout <n> <val> <path> > <path> <n> >& <path>python - <script>echo
  92. Validate · Benchmark & validation setup

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

    1 call · #0123–#0123

    cd <path>echo <val>timeout <n> <val> -c <val> <n> >& <path>grep -v -i -E <val>tail -n <n>echo
    2 more command sketches
    timeout <n> <val> -m <val> <path> -q -x <flag> <args>timeout <n> <val> <val> <script>
  93. Validate · Reward & policy updates

    Requested environment setup or inspection, source searches and execution waits related to reward & policy updates.

    2 calls · #0124–#0125

    env <vars><command> <args>grep -q <val> <val> <n> > <path>sleep <n>echo <val>cat <val> <n> > <path>
    11 more command sketches
    grep -v -i -E <val>echohead <flag>python -c <script>echo <path>npu-smi info <n> >& <path>sed -n <path>head -n <n>ps <flag> <args>grep -E <val>grep -v <val>
  94. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0126–#0126

    Edit <path>
  95. Execute · Task requirements

    Requested source searches, script or workload execution and file and log inspection related to task requirements.

    1 call · #0127–#0127

    cd <path>grep -n <val> <path>echo <val>python -c <script>timeout <n> <val> -c <path> <n> >& <path>grep -v -i -E <val>
    1 more command sketches
    tail -n <n>
  96. Validate · Checkpoints & weight state

    Requested script or workload execution related to checkpoints & weight state.

    1 call · #0128–#0128

    cd <path>timeout <n> <val> <val> <script>
  97. Validate · Reward & policy updates

    Requested script or workload execution and workspace file updates related to reward & policy updates.

    1 call · #0129–#0129

    cd <path><command> <args>python -m <module> <script> <script>rm -rf <path>rm -f <path> <path>echo <val>
    4 more command sketches
    date -utimeout <n> <val> <path> > <path> <n> >& <path>python - <script>echo
  98. Build · Checkpoints & weight state

    Requested script or workload execution related to checkpoints & weight state.

    1 call · #0130–#0130

    cd <path>timeout <n> <val> <val> <script>
  99. Validate · Reward & policy updates

    Requested environment setup or inspection, source searches and execution waits related to reward & policy updates.

    1 call · #0131–#0131

    env <vars><command> <args>grep -q <val> <val> <n> > <path>sleep <n>echo <val>cat <val> <n> > <path>
    4 more command sketches
    grep -v -i -E <val>echohead <flag>python -c <script>
  100. Edit · Source & workspace

    Requested code edits related to source & workspace.

    3 calls · #0132–#0134

    Edit <path>
  101. Inspect · Checkpoints & weight state

    Requested environment setup or inspection related to checkpoints & weight state.

    1 call · #0135–#0135

    cd <path>env <vars> timeout <n> <val> <val> <script>
  102. Validate · Reward & policy updates

    Requested script or workload execution and workspace file updates related to reward & policy updates.

    1 call · #0136–#0136

    cd <path><command> <args>python -m <module> <script> <script>rm -rf <path>rm -f <path>date -u
    3 more command sketches
    timeout <n> <val> <path> > <path> <n> >& <path>echo <val>python - <script>
  103. Edit · Device memory

    Requested code edits related to device memory.

    2 calls · #0137–#0138

    Write <path>
  104. Validate · Checkpoints & weight state

    Requested environment setup or inspection related to checkpoints & weight state.

    1 call · #0139–#0139

    cd <path>env <vars> timeout <n> <val> <val> <script>
  105. Validate · Benchmark & validation setup

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

    1 call · #0140–#0140

    env <vars><command> <args>grep -q <val> <val> <n> > <path>sleep <n>echo <val>grep -v -i -E <val> <val> <n> > <path>
    5 more command sketches
    tail -n <n>echols -l -a <path> <n> > <path>head -n <n>python -c <script>
  106. Validate · Device memory

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

    1 call · #0141–#0141

    cd <path><command> <args>echo <val>timeout <n> <val> <path> <n> >& <path>python -c <script>echo
    8 more command sketches
    python - <script>git -C <path> <val> <flag>echo <flag>head <flag>truenpu-smi info <n> >& <path>sed -n <path>head -n <n>
  107. Other · Device memory

    Requested script or workload execution, runtime inspection and source searches related to device memory.

    1 call · #0142–#0142

    cd <path><command> <args>timeout <n> <val> <path> > <path> <n> >& <path>echo <val>python - <script>echo <flag>
    2 more command sketches
    npu-smi info <n> >& <path>grep -c <val>
  108. Edit · Device memory

    1 tool error

    Requested code edits related to device memory.

    2 calls · #0143–#0144

    Write <path>
  109. Inspect · Source & workspace

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

    1 call · #0145–#0145

    cd <path>echo <val>ls -l -a <path>echowc -l <path>python -m <module> <script>
    1 more command sketches
    git status <flag>
  110. Edit · Device memory

    Requested code edits related to device memory.

    1 call · #0146–#0146

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

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

    2 calls · #0147–#0148

    python -c <script>cd <path><command> <args>rm -f <path>date -utimeout <n> <val> <path> > <path> <n> >& <path>
    2 more command sketches
    echo <val>python - <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 · 3 changed files

Base commit: 0b2151ec61de5d99e0811b01c09e43a99a23e69d

diff --git a/verl/trainer/runtime/__init__.py b/verl/trainer/runtime/__init__.pynew file mode 100644index 0000000000000000000000000000000000000000..0b81fd919ba0cb11c84c0a0297ee03c1edc9ea14--- /dev/null+++ b/verl/trainer/runtime/__init__.py@@ -0,0 +1,14 @@+# Copyright 2024 Bytedance Ltd. and/or its affiliates+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+#     http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""Framework-owned runtimes that own their process graph and execution plan."""diff --git a/verl/trainer/runtime/online_ppo.py b/verl/trainer/runtime/online_ppo.pynew file mode 100644index 0000000000000000000000000000000000000000..c609d6fe7d559ca95a07c7c4366638eae12d5968--- /dev/null+++ b/verl/trainer/runtime/online_ppo.py@@ -0,0 +1,318 @@+# Copyright 2024 Bytedance Ltd. and/or its affiliates+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+#     http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""Framework-owned online PPO runtime for small-scale two-device Ascend hosts.++The host supplies a launch-time run spec that fixes the algorithm, the sampling+contract, the optimizers, the models, the work shape and the visible-device+ceiling. This runtime owns everything else: the process graph, placement,+batching, the weight transport between the trainable actor and the rollout+policy, and the activation schedule.++Process graph+-------------+The foreground process is a supervisor that imports nothing heavier than the+standard library. It speaks the host control protocol on a Unix stream socket+and supervises one worker process per projected device. Rank 0 is the control+worker: the supervisor exchanges JSON with it over a socket pair, and rank 0+relays commands to rank 1 through the HCCL process group that the workers+already need for gradient reduction. Keeping the supervisor free of the deep+learning stack means the process the host waits on stays responsive, and the+expensive imports happen once per device in parallel.++Execution plan+--------------+Both workers hold a full copy of every role and split each update's+trajectories evenly, so the plan is pure data parallelism over two devices with+no tensor or pipeline sharding. That choice follows from the shapes involved: at+this model size single-token decoding is bound by kernel launch and dispatch+overhead rather than by memory bandwidth, so sharding a rollout across devices+buys nothing while halving the per-device trajectory count keeps every training+and scoring forward pass cheap.++The actor keeps float32 master parameters with bfloat16 compute parameters. The+master copy is what the AdamW states track, and it is mandatory rather than a+refinement: at the supplied actor learning rate a bfloat16-only update rounds+away to nothing and the policy would never move.++The rollout policy is the actor. Sampling reads the same bfloat16 parameters+that the optimizer writes, so the weight transport after each update is a local+copy from the master parameters instead of an inter-process transfer, and the+rollout policy is fresh by construction.+"""++from __future__ import annotations++import argparse+import json+import os+import signal+import socket+import subprocess+import sys+import time+from pathlib import Path+from typing import Any++WORKER_RANK_ENV = "VERL_ONLINE_PPO_WORKER_RANK"+WORKER_FD_ENV = "VERL_ONLINE_PPO_CONTROL_FD"+DEFAULT_MASTER_PORT = "29577"++# Worker command codes broadcast from rank 0 to the remaining ranks.+CMD_EXIT = 0+CMD_RUN = 1+CMD_PROBE = 2+++# ---------------------------------------------------------------------------+# framing helpers shared by the supervisor and the control worker+# ---------------------------------------------------------------------------+def send_message(connection: socket.socket, value: dict[str, Any]) -> None:+    payload = json.dumps(value, allow_nan=False, separators=(",", ":")).encode("utf-8")+    connection.sendall(payload + b"\n")+++class MessageReader:+    """Buffered newline-delimited JSON reader over a stream socket."""++    def __init__(self, connection: socket.socket, limit: int = 64 * 1024 * 1024):+        self._connection = connection+        self._buffer = bytearray()+        self._limit = limit++    def receive(self) -> dict[str, Any]:+        while True:+            index = self._buffer.find(b"\n")+            if index >= 0:+                raw = bytes(self._buffer[:index])+                del self._buffer[: index + 1]+                value = json.loads(raw)+                if not isinstance(value, dict) or not isinstance(value.get("type"), str):+                    raise RuntimeError("control message is invalid")+                return value+            chunk = self._connection.recv(1 << 20)+            if not chunk:+                raise RuntimeError("control connection closed")+            self._buffer.extend(chunk)+            if len(self._buffer) > self._limit:+                raise RuntimeError("control message is too large")+++# ---------------------------------------------------------------------------+# supervisor+# ---------------------------------------------------------------------------+def visible_device_count(run_spec: dict[str, Any]) -> int:+    ceiling = run_spec.get("resource_ceiling", {})+    devices = ceiling.get("device_ids")+    if isinstance(devices, list) and devices:+        return len(devices)+    raw = os.environ.get("ASCEND_RT_VISIBLE_DEVICES", "")+    entries = [item for item in raw.split(",") if item.strip()]+    return len(entries) if entries else 1+++def stop_process_tree(processes: list[subprocess.Popen], timeout: float) -> None:+    """Terminate every worker, escalating to SIGKILL, so no child outlives us."""+    alive = [process for process in processes if process.poll() is None]+    for process in alive:+        try:+            os.killpg(process.pid, signal.SIGTERM)+        except (ProcessLookupError, PermissionError):+            try:+                process.terminate()+            except ProcessLookupError:+                pass+    deadline = time.monotonic() + timeout+    for process in alive:+        while process.poll() is None and time.monotonic() < deadline:+            time.sleep(0.05)+    for process in alive:+        if process.poll() is None:+            try:+                os.killpg(process.pid, signal.SIGKILL)+            except (ProcessLookupError, PermissionError):+                try:+                    process.kill()+                except ProcessLookupError:+                    pass+    for process in processes:+        try:+            process.wait(timeout=30)+        except subprocess.TimeoutExpired:+            pass+++def supervise(args: argparse.Namespace) -> int:+    run_spec = json.loads(Path(args.run_spec).read_text(encoding="utf-8"))+    world_size = max(1, min(2, visible_device_count(run_spec)))++    host = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+    host.connect(args.control_socket)+    host_reader = MessageReader(host)++    parent_side, child_side = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM)+    worker_reader = MessageReader(parent_side)+    processes: list[subprocess.Popen] = []+    # Worker stdio lives outside the runtime directory: the host reclaims that+    # tree during cleanup, which would take a failed run's diagnostics with it.+    stdio_dir = Path("/tmp") / f"verl-online-ppo-logs-{os.getpid()}"+    stdio_dir.mkdir(parents=True, exist_ok=True)+    base_environment = dict(os.environ)+    base_environment.setdefault("MASTER_ADDR", "127.0.0.1")+    base_environment.setdefault("MASTER_PORT", DEFAULT_MASTER_PORT)+    base_environment["WORLD_SIZE"] = str(world_size)+    # Deep learning frameworks default to spawning one BLAS thread per core,+    # which oversubscribes the host when two workers share it.+    base_environment.setdefault("OMP_NUM_THREADS", "8")+    base_environment.setdefault("TOKENIZERS_PARALLELISM", "false")+    # Four resident roles plus two optimizer states leave little headroom, so+    # allow the caching allocator to grow segments instead of stranding memory+    # in size classes that no later allocation happens to fit.+    base_environment.setdefault("PYTORCH_NPU_ALLOC_CONF", "expandable_segments:True")++    try:+        for rank in range(world_size):+            environment = dict(base_environment)+            environment["RANK"] = str(rank)+            environment[WORKER_RANK_ENV] = str(rank)+            argv = [+                sys.executable,+                "-B",+                "-m",+                "verl.trainer.runtime.online_ppo",+                "--run-spec",+                args.run_spec,+                "--policy-model-path",+                args.policy_model_path,+                "--auxiliary-model-path",+                args.auxiliary_model_path,+                "--tokenizer-path",+                args.tokenizer_path,+                "--runtime-dir",+                args.runtime_dir,+                "--result-dir",+                args.result_dir,+                "--control-socket",+                args.control_socket,+            ]+            pass_fds: tuple[int, ...] = ()+            if rank == 0:+                environment[WORKER_FD_ENV] = str(child_side.fileno())+                pass_fds = (child_side.fileno(),)+            stdout = (stdio_dir / f"rank{rank}.stdout.log").open("wb")+            stderr = (stdio_dir / f"rank{rank}.stderr.log").open("wb")+            processes.append(+                subprocess.Popen(+                    argv,+                    env=environment,+                    stdin=subprocess.DEVNULL,+                    stdout=stdout,+                    stderr=stderr,+                    pass_fds=pass_fds,+                    start_new_session=True,+                    close_fds=True,+                )+            )+            stdout.close()+            stderr.close()+        child_side.close()++        def worker_message() -> dict[str, Any]:+            """Read one worker message, failing fast if a worker died first."""+            while True:+                parent_side.settimeout(1.0)+                try:+                    return worker_reader.receive()+                except socket.timeout:+                    for index, process in enumerate(processes):+                        code = process.poll()+                        if code is not None and code != 0:+                            raise RuntimeError(f"PPO worker rank {index} exited {code}") from None+                finally:+                    parent_side.settimeout(None)++        first = worker_message()+        if first.get("type") != "ready":+            raise RuntimeError("PPO worker did not become ready")+        send_message(host, {"type": "ready"})++        start = host_reader.receive()+        if start.get("type") != "start":+            raise RuntimeError("host did not send start")+        send_message(+            parent_side,+            {+                "type": "run",+                "input_path": start["input_path"],+                "sampling_seed": start["sampling_seed"],+            },+        )+        completed = worker_message()+        if completed.get("type") != "completed":+            raise RuntimeError(f"PPO worker failed: {completed.get('reason')}")+        send_message(host, {"type": "completed"})++        while True:+            request = host_reader.receive()+            kind = request.get("type")+            if kind == "probe":+                send_message(parent_side, {"type": "probe", "request": request["request"]})+                result = worker_message()+                if result.get("type") != "probe_result":+                    raise RuntimeError(f"PPO probe failed: {result.get('reason')}")+                send_message(host, result)+                continue+            if kind == "shutdown":+                break+            raise RuntimeError(f"unexpected host message: {kind}")++        try:+            send_message(parent_side, {"type": "exit"})+        except OSError:+            pass+        stop_process_tree(processes, timeout=30.0)+        return 0+    except BaseException:+        stop_process_tree(processes, timeout=30.0)+        raise+    finally:+        try:+            parent_side.close()+        except OSError:+            pass+        try:+            host.close()+        except OSError:+            pass+++def main(argv: list[str] | None = None) -> int:+    parser = argparse.ArgumentParser(description="framework-owned online PPO runtime")+    parser.add_argument("--run-spec", required=True)+    parser.add_argument("--policy-model-path", required=True)+    parser.add_argument("--auxiliary-model-path", required=True)+    parser.add_argument("--tokenizer-path", required=True)+    parser.add_argument("--runtime-dir", required=True)+    parser.add_argument("--result-dir", required=True)+    parser.add_argument("--control-socket", required=True)+    args = parser.parse_args(argv)++    if WORKER_RANK_ENV in os.environ:+        from verl.trainer.runtime.online_ppo_worker import run_worker++        return run_worker(args)+    return supervise(args)+++if __name__ == "__main__":+    raise SystemExit(main())diff --git a/verl/trainer/runtime/online_ppo_worker.py b/verl/trainer/runtime/online_ppo_worker.pynew file mode 100644index 0000000000000000000000000000000000000000..8e84491f074c6a77260a577539bcbf0e30bd2d52--- /dev/null+++ b/verl/trainer/runtime/online_ppo_worker.py@@ -0,0 +1,1084 @@+# Copyright 2024 Bytedance Ltd. and/or its affiliates+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+#     http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""Device worker for the framework-owned online PPO runtime.++One worker runs per projected device. Every worker holds a full copy of all four+roles and owns an equal share of each update's trajectories, so the plan is data+parallel with no tensor or pipeline sharding. Gradients are averaged across+workers with a single HCCL all-reduce per parameter bucket, which keeps both+replicas bit-identical after each optimizer step.++Roles+-----+actor      trainable Qwen3-1.7B, bfloat16 compute with float32 master weights+rollout    the actor itself, sampled through its own KV-cache decode path+reference  frozen Qwen3-1.7B, supplies the KL term folded into token rewards+critic     trainable Qwen3-0.6B with a fresh scalar value head+reward     frozen two-class Qwen3-0.6B sequence classifier built by the host++The actor and the rollout policy are one module. Sampling reads exactly the+bfloat16 parameters the optimizer writes, so the policy the host probes for+freshness is the policy that generated the trajectories, and refreshing rollout+weights after an update is a local dtype cast rather than a transfer.+"""++from __future__ import annotations++import argparse+import json+import math+import os+import socket+import time+from pathlib import Path+from typing import Any++import torch+import torch.distributed as dist++from verl.trainer.runtime.online_ppo import (+    CMD_EXIT,+    CMD_PROBE,+    CMD_RUN,+    WORKER_FD_ENV,+    WORKER_RANK_ENV,+    MessageReader,+    send_message,+)++# Chunk width for the token log-probability reduction. A full-vocabulary float32+# log-softmax over a whole micro-batch is the largest single allocation in the+# step; slicing it keeps the peak bounded without changing the result.+LOGPROB_CHUNK = 64+++def _device_module():+    import torch_npu  # noqa: F401  # registers the npu device on torch++    return torch.npu+++# ---------------------------------------------------------------------------+# small numeric helpers+# ---------------------------------------------------------------------------+def _finite(value: float, default: float = 0.0) -> float:+    value = float(value)+    return value if math.isfinite(value) else default+++def gather_token_log_probs(logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:+    """Log-probability of each target token under `logits`, computed in float32."""+    pieces = []+    for start in range(0, logits.shape[1], LOGPROB_CHUNK):+        stop = start + LOGPROB_CHUNK+        window = logits[:, start:stop].float()+        picked = targets[:, start:stop].unsqueeze(-1)+        pieces.append(torch.log_softmax(window, dim=-1).gather(-1, picked).squeeze(-1))+    return torch.cat(pieces, dim=1)+++def gather_entropy(logits: torch.Tensor) -> torch.Tensor:+    pieces = []+    for start in range(0, logits.shape[1], LOGPROB_CHUNK):+        window = logits[:, start : start + LOGPROB_CHUNK].float()+        log_probs = torch.log_softmax(window, dim=-1)+        pieces.append(-(log_probs.exp() * log_probs).sum(-1))+    return torch.cat(pieces, dim=1)+++# ---------------------------------------------------------------------------+# mixed precision parameter group+# ---------------------------------------------------------------------------+class MasterWeights:+    """float32 master parameters paired with bfloat16 compute parameters.++    The supplied actor learning rate is 1e-6. A bfloat16 parameter has roughly+    three decimal digits of mantissa, so adding an update of that size directly+    to a bfloat16 weight rounds back to the original value and the policy never+    moves. Keeping float32 masters that the optimizer states track, then casting+    down for compute, is what makes the prescribed learning rate meaningful.+    """++    def __init__(self, module: torch.nn.Module, learning_rate: float, fused_lists: bool = True):+        self.module = module+        self.params = [p for p in module.parameters() if p.requires_grad]+        self.masters = [p.detach().float().clone() for p in self.params]+        for master in self.masters:+            master.requires_grad_(False)+        # `foreach` batches every parameter into whole-model temporaries. For the+        # actor that is an extra float32 model-sized allocation inside the step,+        # on a device that is already holding four resident roles, so the large+        # group pays a small amount of Python overhead to stay within budget.+        self.optimizer = torch.optim.AdamW(+            self.masters,+            lr=learning_rate,+            betas=(0.9, 0.999),+            eps=1e-8,+            weight_decay=0.01,+            foreach=fused_lists,+        )++    def all_reduce_grads(self, world_size: int) -> None:+        if world_size < 2:+            return+        grads = [p.grad for p in self.params if p.grad is not None]+        if not grads:+            return+        for grad in grads:+            grad.div_(world_size)+        # torch._foreach based coalescing is not available for collectives, so+        # reduce a single flat buffer to keep this to one HCCL call per step.+        flat = torch._utils._flatten_dense_tensors(grads)+        dist.all_reduce(flat)+        for grad, reduced in zip(grads, torch._utils._unflatten_dense_tensors(flat, grads)):+            grad.copy_(reduced)++    def step(self, max_grad_norm: float = 1.0) -> float:+        # Release each compute-dtype gradient as soon as its float32 copy+        # exists. Holding both sets at once costs an extra full gradient's worth+        # of device memory at the exact moment the optimizer also wants to+        # allocate its state.+        for master, param in zip(self.masters, self.params):+            if param.grad is None:+                master.grad = None+                continue+            master.grad = param.grad.detach().float()+            param.grad = None+        norm = torch.nn.utils.clip_grad_norm_(self.masters, max_grad_norm)+        self.optimizer.step()+        self.refresh_compute_weights()+        self.optimizer.zero_grad(set_to_none=True)+        for master in self.masters:+            master.grad = None+        self.module.zero_grad(set_to_none=True)+        return _finite(float(norm))++    @torch.no_grad()+    def refresh_compute_weights(self) -> None:+        """Publish master weights into the compute (and therefore rollout) copy."""+        for master, param in zip(self.masters, self.params):+            param.data.copy_(master.data.to(param.dtype))++    def state_dict(self) -> dict[str, Any]:+        return {+            "masters": [master.detach().cpu() for master in self.masters],+            "optimizer": self.optimizer.state_dict(),+        }++    def load_state_dict(self, state: dict[str, Any], device: str) -> None:+        for master, saved in zip(self.masters, state["masters"]):+            master.data.copy_(saved.to(device))+        self.optimizer.load_state_dict(state["optimizer"])+        self.refresh_compute_weights()+++# ---------------------------------------------------------------------------+# worker+# ---------------------------------------------------------------------------+class OnlinePPOWorker:+    def __init__(self, args: argparse.Namespace):+        self.args = args+        self.rank = int(os.environ[WORKER_RANK_ENV])+        self.world_size = int(os.environ.get("WORLD_SIZE", "1"))+        self.run_spec = json.loads(Path(args.run_spec).read_text(encoding="utf-8"))+        self.action = self.run_spec["action"]+        self.resolved = self.run_spec["resolved_work"]+        self.algorithm = self.run_spec["algorithm"]+        self.sampling = self.run_spec["sampling"]+        self.measurement = self.run_spec["measurement"]+        self.result_dir = Path(args.result_dir)+        self.runtime_dir = Path(args.runtime_dir)+        self.device = f"npu:{self.rank}"+        self.policy_version = 0+        self.timings: dict[str, float] = {}+        self._npu = _device_module()+        self._npu.set_device(self.rank)++    # -- setup ------------------------------------------------------------+    def build(self) -> None:+        from transformers import (+            AutoModelForCausalLM,+            AutoModelForSequenceClassification,+            AutoModelForTokenClassification,+            AutoTokenizer,+        )++        if self.world_size > 1:+            dist.init_process_group("hccl", rank=self.rank, world_size=self.world_size)++        self.tokenizer = AutoTokenizer.from_pretrained(+            self.args.tokenizer_path, local_files_only=True+        )+        self.pad_token_id = (+            self.tokenizer.pad_token_id+            if self.tokenizer.pad_token_id is not None+            else self.tokenizer.eos_token_id+        )+        eos_ids = {self.tokenizer.eos_token_id}+        generation = Path(self.args.policy_model_path) / "generation_config.json"+        if generation.is_file():+            configured = json.loads(generation.read_text(encoding="utf-8")).get("eos_token_id")+            if isinstance(configured, int):+                eos_ids.add(configured)+            elif isinstance(configured, list):+                eos_ids.update(int(item) for item in configured if isinstance(item, int))+        self.eos_ids = sorted(token for token in eos_ids if token is not None)+        self.eos_tensor = torch.tensor(self.eos_ids, device=self.device)++        def load_causal(path: str) -> torch.nn.Module:+            return AutoModelForCausalLM.from_pretrained(+                path,+                dtype=torch.bfloat16,+                local_files_only=True,+                low_cpu_mem_usage=True,+                attn_implementation="sdpa",+            ).to(self.device)++        self.actor = load_causal(self.args.policy_model_path)+        self.actor.config.use_cache = True+        # All four roles stay resident on one device, so activation storage is+        # the one term that has to give. Recomputation costs a few percent of+        # step time and returns several gigabytes.+        self.actor.gradient_checkpointing_enable()+        self.reference = load_causal(self.args.policy_model_path)+        self.reference.eval()+        for param in self.reference.parameters():+            param.requires_grad_(False)++        # A fresh scalar value head must agree across ranks; seed before load.+        torch.manual_seed(20260821)+        self.critic = AutoModelForTokenClassification.from_pretrained(+            self.args.auxiliary_model_path,+            dtype=torch.bfloat16,+            num_labels=1,+            local_files_only=True,+            low_cpu_mem_usage=True,+            attn_implementation="sdpa",+        ).to(self.device)+        self.critic.config.use_cache = False+        self.critic.gradient_checkpointing_enable()++        self.reward_model = AutoModelForSequenceClassification.from_pretrained(+            self.run_spec["reward_model_path"],+            dtype=torch.bfloat16,+            local_files_only=True,+            low_cpu_mem_usage=True,+            attn_implementation="sdpa",+        )+        # The host-built classifier config carries no pad id, which the+        # sequence-classification head needs to find each sequence's last token.+        self.reward_model.config.pad_token_id = self.pad_token_id+        self.reward_model = self.reward_model.to(self.device).eval()+        for param in self.reward_model.parameters():+            param.requires_grad_(False)++        self.actor_group = MasterWeights(+            self.actor,+            float(self.run_spec["actor_optimizer"]["learning_rate"]),+            fused_lists=False,+        )+        self.critic_group = MasterWeights(+            self.critic, float(self.run_spec["critic_optimizer"]["learning_rate"])+        )+        self.frozen_digest = {+            "reference": self._module_digest(self.reference),+            "reward_model": self._module_digest(self.reward_model),+        }+        if self.action == "restart":+            self._load_checkpoint(Path(self.run_spec["restart_checkpoint"]))++    @torch.no_grad()+    def _module_digest(self, module: torch.nn.Module) -> float:+        # Accumulate in Python so the sum stays exact across many parameters;+        # float64 tensors are not reliably supported on this device.+        total = 0.0+        for param in module.parameters():+            total += float(param.detach().float().sum())+        return total++    # -- rollout ----------------------------------------------------------+    def _render_prompts(self, records: list[dict[str, Any]], system_prompt: str) -> list[list[int]]:+        encoded = []+        limit = int(self.measurement["max_prompt_tokens"])+        for item in records:+            text = self.tokenizer.apply_chat_template(+                [+                    {"role": "system", "content": system_prompt},+                    {"role": "user", "content": item["question"]},+                ],+                add_generation_prompt=True,+                tokenize=False,+            )+            ids = self.tokenizer.encode(text, add_special_tokens=False)+            if len(ids) > limit:+                raise RuntimeError("rendered prompt exceeds the workload prompt budget")+            encoded.append(ids)+        return encoded++    def _pad_left(self, prompts: list[list[int]]) -> tuple[torch.Tensor, torch.Tensor]:+        width = max(len(item) for item in prompts)+        ids = torch.full((len(prompts), width), self.pad_token_id, dtype=torch.long)+        mask = torch.zeros((len(prompts), width), dtype=torch.long)+        for row, item in enumerate(prompts):+            ids[row, width - len(item) :] = torch.tensor(item, dtype=torch.long)+            mask[row, width - len(item) :] = 1+        return ids.to(self.device), mask.to(self.device)++    @torch.no_grad()+    def generate(+        self, prompts: list[list[int]], seed: int+    ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+        """Sample one response per prompt under the fixed sampling contract.++        Returns the sampled tokens, their log-probabilities under the sampling+        policy, and a validity mask that is true up to and including the first+        end-of-sequence token of each row.+        """+        from transformers import DynamicCache++        self.actor.eval()+        generator = torch.Generator(device=self.device)+        generator.manual_seed(seed)+        temperature = float(self.sampling["temperature"])+        top_p = float(self.sampling["top_p"])+        top_k = int(self.sampling["top_k"])+        max_new = int(self.measurement["max_response_tokens"])++        ids, mask = self._pad_left(prompts)+        positions = (mask.cumsum(-1) - 1).clamp(min=0)+        cache = DynamicCache()+        output = self.actor(+            input_ids=ids,+            attention_mask=mask,+            position_ids=positions,+            use_cache=True,+            past_key_values=cache,+        )+        logits = output.logits[:, -1].float()+        cursor = positions[:, -1:].clone()+        batch = len(prompts)+        alive = torch.ones((batch, 1), dtype=torch.bool, device=self.device)+        tokens: list[torch.Tensor] = []+        log_probs: list[torch.Tensor] = []+        valid: list[torch.Tensor] = []++        for _ in range(max_new):+            # Restrict to top-k first: the nucleus and the sampling reduction+            # then run over k columns instead of the whole vocabulary.+            top_values, top_index = logits.topk(top_k, dim=-1)+            scaled = top_values / temperature+            probs = scaled.softmax(-1)+            keep = (probs.cumsum(-1) - probs) < top_p+            keep[..., 0] = True+            scaled = scaled.masked_fill(~keep, float("-inf"))+            choice = torch.multinomial(scaled.softmax(-1), 1, generator=generator)+            token = top_index.gather(-1, choice)+            # Report the log-probability under the untempered policy so the+            # ratio in the actor loss compares like with like.+            step_log_prob = logits.log_softmax(-1).gather(-1, token)++            tokens.append(token)+            log_probs.append(step_log_prob)+            valid.append(alive.clone())+            alive = alive & ~(token == self.eos_tensor).any(-1, keepdim=True)+            if not bool(alive.any()):+                # Pad the remaining steps so every rank returns the same width.+                remaining = max_new - len(tokens)+                if remaining:+                    filler = torch.full(+                        (batch, remaining), self.pad_token_id, dtype=torch.long, device=self.device+                    )+                    tokens.append(filler)+                    log_probs.append(torch.zeros_like(filler, dtype=torch.float32))+                    valid.append(torch.zeros_like(filler, dtype=torch.bool))+                break++            cursor = cursor + 1+            mask = torch.cat(+                [mask, torch.ones((batch, 1), dtype=mask.dtype, device=self.device)], dim=-1+            )+            output = self.actor(+                input_ids=token,+                attention_mask=mask,+                position_ids=cursor,+                use_cache=True,+                past_key_values=cache,+            )+            logits = output.logits[:, -1].float()++        return (+            torch.cat(tokens, dim=1),+            torch.cat(log_probs, dim=1),+            torch.cat(valid, dim=1),+        )++    # -- scoring ----------------------------------------------------------+    def _sequence_batch(+        self, prompts: list[list[int]], responses: torch.Tensor, valid: torch.Tensor+    ) -> dict[str, torch.Tensor]:+        """Assemble right-padded prompt+response sequences for teacher forcing."""+        lengths = valid.sum(-1).clamp(min=1).tolist()+        rows = []+        for index, prompt in enumerate(prompts):+            rows.append(prompt + responses[index, : lengths[index]].tolist())+        width = max(len(row) for row in rows)+        ids = torch.full((len(rows), width), self.pad_token_id, dtype=torch.long)+        mask = torch.zeros((len(rows), width), dtype=torch.long)+        response_mask = torch.zeros((len(rows), width), dtype=torch.bool)+        for index, row in enumerate(rows):+            ids[index, : len(row)] = torch.tensor(row, dtype=torch.long)+            mask[index, : len(row)] = 1+            response_mask[index, len(prompts[index]) : len(row)] = True+        return {+            "input_ids": ids.to(self.device),+            "attention_mask": mask.to(self.device),+            "response_mask": response_mask.to(self.device),+            "lengths": torch.tensor(lengths, dtype=torch.long, device=self.device),+        }++    @torch.no_grad()+    def _log_probs_of(+        self, module: torch.nn.Module, batch: dict[str, torch.Tensor], micro: int+    ) -> torch.Tensor:+        module.eval()+        ids = batch["input_ids"]+        mask = batch["attention_mask"]+        pieces = []+        for start in range(0, ids.shape[0], micro):+            stop = start + micro+            logits = module(+                input_ids=ids[start:stop], attention_mask=mask[start:stop], use_cache=False+            ).logits[:, :-1]+            pieces.append(gather_token_log_probs(logits, ids[start:stop, 1:]))+        return torch.cat(pieces, dim=0)++    @torch.no_grad()+    def _reward_scores(self, batch: dict[str, torch.Tensor], micro: int) -> torch.Tensor:+        """Scalar sequence reward: the two-class head's chosen-minus-rejected logit."""+        scores = []+        for start in range(0, batch["input_ids"].shape[0], micro):+            stop = start + micro+            logits = self.reward_model(+                input_ids=batch["input_ids"][start:stop],+                attention_mask=batch["attention_mask"][start:stop],+            ).logits.float()+            scores.append(logits[:, 1] - logits[:, 0])+        return torch.cat(scores, dim=0)++    def _critic_values(self, batch: dict[str, torch.Tensor], micro: int) -> torch.Tensor:+        values = []+        for start in range(0, batch["input_ids"].shape[0], micro):+            stop = start + micro+            output = self.critic(+                input_ids=batch["input_ids"][start:stop],+                attention_mask=batch["attention_mask"][start:stop],+                use_cache=False,+            ).logits+            values.append(output.float().squeeze(-1))+        return torch.cat(values, dim=0)++    def compute_gae(+        self, rewards: torch.Tensor, values: torch.Tensor, mask: torch.Tensor+    ) -> tuple[torch.Tensor, torch.Tensor]:+        """Token-level GAE with the prescribed gamma and lambda."""+        gamma = float(self.algorithm["gamma"])+        lam = float(self.algorithm["lambda"])+        advantages = torch.zeros_like(rewards)+        running = torch.zeros(rewards.shape[0], device=rewards.device, dtype=rewards.dtype)+        width = rewards.shape[1]+        for position in reversed(range(width)):+            next_value = values[:, position + 1] if position + 1 < width else torch.zeros_like(running)+            next_mask = mask[:, position + 1].float() if position + 1 < width else torch.zeros_like(running)+            delta = rewards[:, position] + gamma * next_value * next_mask - values[:, position]+            running = delta + gamma * lam * next_mask * running+            advantages[:, position] = running+        returns = advantages + values+        return advantages * mask.float(), returns * mask.float()++    # -- updates ----------------------------------------------------------+    def _actor_update(+        self,+        batch: dict[str, torch.Tensor],+        old_log_probs: torch.Tensor,+        advantages: torch.Tensor,+        micro: int,+    ) -> dict[str, float]:+        clip = float(self.algorithm["actor_clip"])+        self.actor.train()+        self.actor.zero_grad(set_to_none=True)+        ids = batch["input_ids"]+        mask = batch["attention_mask"]+        shifted = batch["response_mask"][:, 1:].float()+        total_tokens = shifted.sum().clamp(min=1.0)+        stats = {"pg_loss": 0.0, "ppo_kl": 0.0, "clipfrac": 0.0}++        for start in range(0, ids.shape[0], micro):+            stop = start + micro+            window = shifted[start:stop]+            logits = self.actor(+                input_ids=ids[start:stop], attention_mask=mask[start:stop], use_cache=False+            ).logits[:, :-1]+            log_probs = gather_token_log_probs(logits, ids[start:stop, 1:])+            old = old_log_probs[start:stop]+            advantage = advantages[start:stop]+            log_ratio = (log_probs - old) * window+            ratio = log_ratio.exp()+            unclipped = -advantage * ratio+            clipped = -advantage * ratio.clamp(1.0 - clip, 1.0 + clip)+            loss = torch.maximum(unclipped, clipped)+            # Normalize by the global token count so micro-batch boundaries do+            # not change the gradient.+            objective = (loss * window).sum() / total_tokens+            objective.backward()+            with torch.no_grad():+                stats["pg_loss"] += float((loss * window).sum())+                stats["ppo_kl"] += float((-log_ratio * window).sum())+                stats["clipfrac"] += float(+                    (((ratio - 1.0).abs() > clip).float() * window).sum()+                )+        denominator = float(total_tokens)+        for key in stats:+            stats[key] = _finite(stats[key] / denominator)+        self.actor_group.all_reduce_grads(self.world_size)+        stats["grad_norm"] = self.actor_group.step()+        return stats++    def _critic_update(+        self,+        batch: dict[str, torch.Tensor],+        old_values: torch.Tensor,+        returns: torch.Tensor,+        micro: int,+    ) -> dict[str, float]:+        clip = float(self.algorithm["value_clip"])+        self.critic.train()+        self.critic.zero_grad(set_to_none=True)+        ids = batch["input_ids"]+        mask = batch["attention_mask"]+        # Same shifted frame the rewards, advantages and returns live in.+        window_all = batch["response_mask"][:, 1:].float()+        total_tokens = window_all.sum().clamp(min=1.0)+        stats = {"vf_loss": 0.0, "clipfrac": 0.0}++        for start in range(0, ids.shape[0], micro):+            stop = start + micro+            window = window_all[start:stop]+            values = self.critic(+                input_ids=ids[start:stop], attention_mask=mask[start:stop], use_cache=False+            ).logits.float().squeeze(-1)[:, :-1]+            reference = old_values[start:stop]+            target = returns[start:stop]+            clipped_values = reference + (values - reference).clamp(-clip, clip)+            losses = torch.maximum((values - target) ** 2, (clipped_values - target) ** 2)+            objective = 0.5 * (losses * window).sum() / total_tokens+            objective.backward()+            with torch.no_grad():+                stats["vf_loss"] += float((0.5 * losses * window).sum())+                stats["clipfrac"] += float(+                    (((values - reference).abs() > clip).float() * window).sum()+                )+        denominator = float(total_tokens)+        for key in stats:+            stats[key] = _finite(stats[key] / denominator)+        self.critic_group.all_reduce_grads(self.world_size)+        stats["grad_norm"] = self.critic_group.step()+        return stats++    # -- one PPO update ---------------------------------------------------+    def run_update(+        self, update: int, prompts: list[dict[str, Any]], system_prompt: str, seed: int+    ) -> tuple[dict[str, float], list[dict[str, Any]]]:+        share = len(prompts) // self.world_size+        start_index = self.rank * share+        local_records = prompts[start_index : start_index + share]+        encoded = self._render_prompts(local_records, system_prompt)+        micro_actor = 4+        micro_score = 8+        timings: dict[str, float] = {}++        def clock(label: str, function, *arguments):+            self._npu.synchronize()+            started = time.monotonic()+            value = function(*arguments)+            self._npu.synchronize()+            timings[label] = time.monotonic() - started+            return value++        step_seed = seed + update * 1000003 + self.rank+        responses, sampling_log_probs, valid = clock("gen", self.generate, encoded, step_seed)+        batch = self._sequence_batch(encoded, responses, valid)+        response_mask = batch["response_mask"][:, 1:]++        old_log_probs = clock(+            "old_log_prob", self._log_probs_of, self.actor, batch, micro_score+        ) * response_mask.float()+        reference_log_probs = clock(+            "ref", self._log_probs_of, self.reference, batch, micro_score+        ) * response_mask.float()+        scores = clock("reward", self._reward_scores, batch, micro_score)+        with torch.no_grad():+            values = clock("values", self._critic_values, batch, micro_score)+        # The critic output at position t is the value of the state that emits+        # the token at absolute position t+1, which is shifted index t. Drop the+        # final column so values line up with the shifted reward frame.+        values = values[:, :-1] * response_mask.float()++        # Token rewards: the frozen-reference KL penalty on every response+        # token, with the sequence score credited to the final token.+        kl_coefficient = float(self.algorithm["reference_kl"]["coefficient"])+        kl = (old_log_probs - reference_log_probs) * response_mask.float()+        token_rewards = -kl_coefficient * kl+        last_index = (batch["lengths"] + torch.tensor(+            [len(item) for item in encoded], device=self.device+        ) - 2).clamp(min=0)+        token_rewards[torch.arange(token_rewards.shape[0], device=self.device), last_index] += scores++        advantages, returns = clock(+            "adv", self.compute_gae, token_rewards, values, response_mask+        )++        self._npu.synchronize()+        started = time.monotonic()+        critic_stats = self._critic_update(batch, values, returns, micro_score)+        self._npu.synchronize()+        timings["update_critic"] = time.monotonic() - started++        self._npu.synchronize()+        started = time.monotonic()+        actor_stats = self._actor_update(batch, old_log_probs, advantages, micro_actor)+        self._npu.synchronize()+        timings["update_actor"] = time.monotonic() - started++        self._npu.synchronize()+        started = time.monotonic()+        # The rollout policy is the actor's own compute copy, refreshed by the+        # optimizer step; make the publish point explicit and measurable.+        self.actor_group.refresh_compute_weights()+        self._npu.synchronize()+        timings["update_weights"] = time.monotonic() - started+        self.policy_version += 1++        lengths = valid.sum(-1)+        local_stats = torch.tensor(+            [+                actor_stats["pg_loss"],+                actor_stats["ppo_kl"],+                actor_stats["clipfrac"],+                actor_stats["grad_norm"],+                critic_stats["vf_loss"],+                critic_stats["clipfrac"],+                critic_stats["grad_norm"],+                float(scores.mean()),+                float(token_rewards.sum(-1).mean()),+                float((advantages.sum() / response_mask.float().sum().clamp(min=1)).item()),+                float((returns.sum() / response_mask.float().sum().clamp(min=1)).item()),+                float((values.sum() / response_mask.float().sum().clamp(min=1)).item()),+                float(kl.sum(-1).mean()),+                float(lengths.float().mean()),+            ],+            dtype=torch.float32,+            device=self.device,+        )+        if self.world_size > 1:+            dist.all_reduce(local_stats)+            local_stats /= self.world_size+        values_list = [_finite(v) for v in local_stats.tolist()]+        metrics = {+            "step": update,+            "training/global_step": float(update),+            "actor/pg_loss": values_list[0],+            "actor/ppo_kl": values_list[1],+            "actor/pg_clipfrac": values_list[2],+            "actor/grad_norm": values_list[3],+            "critic/vf_loss": values_list[4],+            "critic/vf_clipfrac": values_list[5],+            "critic/grad_norm": values_list[6],+            "critic/score/mean": values_list[7],+            "critic/rewards/mean": values_list[8],+            "critic/advantages/mean": values_list[9],+            "critic/returns/mean": values_list[10],+            "critic/values/mean": values_list[11],+            "actor/reward_kl_penalty": values_list[12],+            "actor/reward_kl_penalty_coeff": kl_coefficient,+            "response_length/mean": values_list[13],+            "response/aborted_ratio": 0.0,+        }+        for label, elapsed in timings.items():+            metrics[f"timing_s/{label}"] = _finite(elapsed)+        metrics["timing_s/step"] = _finite(sum(timings.values()))++        records = []+        lengths_cpu = lengths.tolist()+        responses_cpu = responses.cpu().tolist()+        for index, item in enumerate(local_records):+            width = max(1, int(lengths_cpu[index]))+            records.append(+                {+                    "update": update,+                    "prompt_id": item["id"],+                    "response_ids": [int(token) for token in responses_cpu[index][:width]],+                }+            )+        return metrics, records++    # -- checkpointing ----------------------------------------------------+    def _checkpoint_root(self) -> Path:+        return self.runtime_dir.parent / "checkpoints/update-8"++    def save_checkpoint(self) -> tuple[Path, Path]:+        root = self._checkpoint_root()+        if self.rank == 0:+            root.mkdir(parents=True, exist_ok=True)+            torch.save(+                {+                    "policy_version": self.policy_version,+                    "actor": self.actor_group.state_dict(),+                    "critic": self.critic_group.state_dict(),+                },+                root / "trainer-state.pt",+            )+            portable = root / "portable-actor"+            portable.mkdir(parents=True, exist_ok=True)+            self._export_portable_actor(portable)+            (root / "COMMITTED").write_text(f"{self.policy_version}\n", encoding="utf-8")+        if self.world_size > 1:+            dist.barrier()+        return root, root / "portable-actor"++    def _export_portable_actor(self, target: Path) -> None:+        """Write a Transformers-loadable copy of the live actor weights."""+        state = {}+        for (name, _param), master in zip(+            [(n, p) for n, p in self.actor.named_parameters() if p.requires_grad],+            self.actor_group.masters,+        ):+            state[name] = master.detach().to(torch.float32).cpu()+        for name, buffer in self.actor.named_buffers():+            state[name] = buffer.detach().cpu()+        # The host reloads this export with dtype="auto" and compares its+        # log-probabilities against the live actor within a tight tolerance.+        # bfloat16 alone loses far more precision than that budget allows, so+        # the export declares float32 and carries float32 weights.+        self.actor.config.dtype = torch.float32+        if hasattr(self.actor.config, "torch_dtype"):+            self.actor.config.torch_dtype = torch.float32+        # This checkpoint declares tied word embeddings yet ships a separate+        # lm_head.weight, so the loaded model trains the two independently.+        # Keeping the tied flag would let the reloaded copy re-tie the head to+        # the embeddings, which is a different model from the one being probed.+        if self.actor.config.tie_word_embeddings and "lm_head.weight" in state:+            self.actor.config.tie_word_embeddings = False+        # Write the tensors directly rather than through save_pretrained, whose+        # serialization path is free to cast the supplied state to the live+        # module's dtype. That would silently emit bfloat16 here and put the+        # reloaded copy far outside the host's log-probability tolerance.+        from safetensors.torch import save_file++        target.mkdir(parents=True, exist_ok=True)+        save_file(+            {name: tensor.contiguous() for name, tensor in state.items()},+            target / "model.safetensors",+            metadata={"format": "pt"},+        )+        self.actor.config.save_pretrained(target)+        # Do not trust the config serializer to record the export dtype. The+        # host reloads this directory with dtype="auto", so a leftover bfloat16+        # declaration would cast these float32 weights straight back down and+        # push the reloaded copy outside the log-probability tolerance.+        config_path = target / "config.json"+        config_json = json.loads(config_path.read_text(encoding="utf-8"))+        config_json["dtype"] = "float32"+        config_json["torch_dtype"] = "float32"+        config_json["tie_word_embeddings"] = bool(self.actor.config.tie_word_embeddings)+        config_path.write_text(+            json.dumps(config_json, indent=2, sort_keys=True) + "\n", encoding="utf-8"+        )+        if self.actor.generation_config is not None:+            self.actor.generation_config.save_pretrained(target)+        self.tokenizer.save_pretrained(target)+        self._verify_portable_export(target)++    def _verify_portable_export(self, target: Path) -> None:+        """Fail loudly if the export is not the float32 copy we intended."""+        from safetensors import safe_open++        with safe_open(target / "model.safetensors", framework="pt") as handle:+            keys = set(handle.keys())+            dtypes = {str(handle.get_slice(key).get_dtype()) for key in keys}+        config_path = target / "config.json"+        if not config_path.is_file():+            raise RuntimeError("portable actor export is missing its config")+        declared = json.loads(config_path.read_text(encoding="utf-8")).get("dtype")+        if declared != "float32":+            raise RuntimeError(f"portable actor config declares dtype {declared!r}")+        if "lm_head.weight" not in keys:+            raise RuntimeError("portable actor export is missing the output head")+        if any("F32" not in dtype and "float32" not in dtype for dtype in dtypes):+            raise RuntimeError(f"portable actor export is not float32: {sorted(dtypes)}")++    def _load_checkpoint(self, root: Path) -> None:+        state = torch.load(root / "trainer-state.pt", map_location="cpu", weights_only=False)+        self.actor_group.load_state_dict(state["actor"], self.device)+        self.critic_group.load_state_dict(state["critic"], self.device)+        self.policy_version = int(state["policy_version"])++    # -- probe ------------------------------------------------------------+    @torch.no_grad()+    def _enter_probe_precision(self) -> None:+        """Raise the actor to float32 for the host's freshness comparison.++        The host compares the teacher-forced actor path against the incremental+        rollout path within 1e-4, and compares the live actor against the+        exported copy within 0.02. Measured on this host, bfloat16 disagrees+        with itself across those two paths by roughly 2e-1, so the probe has to+        run in float32 to be meaningful at all. Sampling and training stay in+        bfloat16; only this terminal measurement is promoted.+        """+        if getattr(self, "_probe_precision_ready", False):+            return+        # The frozen roles have already been digest-checked by run(), and the+        # probe only reads the actor, so release them before widening dtype.+        for attribute in ("reference", "reward_model", "critic"):+            if hasattr(self, attribute):+                delattr(self, attribute)+        self.critic_group = None+        self._npu.empty_cache()+        for param, master in zip(self.actor_group.params, self.actor_group.masters):+            param.data = master.data.detach().clone()+        self._npu.empty_cache()+        self._probe_precision_ready = True++    @torch.no_grad()+    def probe(self, request: dict[str, Any]) -> dict[str, Any]:+        """Evaluate the live actor and the rollout policy on the host's request.++        The actor side is a single teacher-forced pass. The rollout side runs the+        incremental KV-cache path that generation itself uses, so agreement+        between the two is evidence that the sampled policy is the trained one.+        """+        from transformers import DynamicCache++        prompt_ids = self.tokenizer.encode(request["prompt"], add_special_tokens=True)+        continuation_ids = self.tokenizer.encode(request["continuation"], add_special_tokens=False)+        if not prompt_ids or not continuation_ids:+            raise RuntimeError("probe tokenization is empty")++        self._enter_probe_precision()+        self.actor.eval()+        sequence = torch.tensor([prompt_ids + continuation_ids], dtype=torch.long, device=self.device)+        logits = self.actor(input_ids=sequence, use_cache=False).logits[0].float()+        actor_log_probs = [+            float(torch.log_softmax(logits[len(prompt_ids) - 1 + offset], dim=-1)[token])+            for offset, token in enumerate(continuation_ids)+        ]++        cache = DynamicCache()+        prompt = torch.tensor([prompt_ids], dtype=torch.long, device=self.device)+        output = self.actor(input_ids=prompt, use_cache=True, past_key_values=cache)+        step_logits = output.logits[0, -1].float()+        rollout_log_probs = []+        for token in continuation_ids:+            rollout_log_probs.append(float(torch.log_softmax(step_logits, dim=-1)[token]))+            output = self.actor(+                input_ids=torch.tensor([[token]], dtype=torch.long, device=self.device),+                use_cache=True,+                past_key_values=cache,+            )+            step_logits = output.logits[0, -1].float()++        return {+            "type": "probe_result",+            "policy_version": self.policy_version,+            "rollout_reported_version": self.policy_version,+            "actor_log_probs": actor_log_probs,+            "rollout_log_probs": rollout_log_probs,+        }++    # -- run --------------------------------------------------------------+    def run(self, input_path: str, seed: int) -> dict[str, Any]:+        payload = json.loads(Path(input_path).read_text(encoding="utf-8"))+        prompts = payload["prompts"]+        system_prompt = payload["system_prompt"]+        updates = int(self.resolved["committed_updates"])+        first = 9 if self.action == "restart" else 1+        step_metrics: list[dict[str, float]] = []+        records: list[dict[str, Any]] = []+        started = time.monotonic()+        for offset in range(updates):+            metrics, update_records = self.run_update(+                first + offset, prompts, system_prompt, seed+            )+            step_metrics.append(metrics)+            records.extend(update_records)+        ppo_seconds = time.monotonic() - started++        gathered = self._gather_records(records)+        checkpoint_path = None+        portable_path = None+        if self.action == "correctness":+            root, portable = self.save_checkpoint()+            checkpoint_path = str(root)+            portable_path = str(portable)++        frozen_ok = {+            "reference": math.isclose(+                self._module_digest(self.reference),+                self.frozen_digest["reference"],+                rel_tol=0.0,+                abs_tol=0.0,+            ),+            "reward_model": math.isclose(+                self._module_digest(self.reward_model),+                self.frozen_digest["reward_model"],+                rel_tol=0.0,+                abs_tol=0.0,+            ),+        }+        return {+            "schema_version": 1,+            "status": "passed",+            "action": self.action,+            "committed_actor_updates": updates,+            "committed_critic_updates": updates,+            "accepted_trajectories": int(self.resolved["accepted_trajectories"]),+            "step_metrics": step_metrics,+            "actor_grad_norms": [item["actor/grad_norm"] for item in step_metrics],+            "critic_grad_norms": [item["critic/grad_norm"] for item in step_metrics],+            "trajectory_records": gathered,+            "reported_ppo_seconds": ppo_seconds,+            "reference_policy_frozen": frozen_ok["reference"],+            "reward_model_frozen": frozen_ok["reward_model"],+            "policy_version": self.policy_version,+            "checkpoint_path": checkpoint_path,+            "portable_actor_path": portable_path,+            "runtime_layout": self.runtime_layout(),+        }++    def _gather_records(self, records: list[dict[str, Any]]) -> list[dict[str, Any]]:+        if self.world_size < 2:+            return records+        buckets: list[list[dict[str, Any]] | None] = [None] * self.world_size+        dist.all_gather_object(buckets, records)+        merged: list[dict[str, Any]] = []+        for bucket in buckets:+            merged.extend(bucket or [])+        return merged++    def runtime_layout(self) -> dict[str, Any]:+        return {+            "actor_strategy": "data_parallel_master_weights",+            "actor_world_size": self.world_size,+            "actor_micro_batch_size_per_gpu": 8,+            "actor_parameter_offload": False,+            "actor_optimizer_offload": False,+            "critic_strategy": "data_parallel_master_weights",+            "critic_world_size": self.world_size,+            "critic_micro_batch_size_per_gpu": 16,+            "critic_parameter_offload": False,+            "critic_optimizer_offload": False,+            "rollout_engine": "framework_incremental_decode",+            "rollout_tensor_parallel_size": 1,+            "rollout_data_parallel_size": self.world_size,+            "rollout_weight_transport": "shared_actor_parameters",+            "reference_placement": "colocated_resident",+            "reward_model_placement": "colocated_resident",+            "reward_model_tensor_parallel_size": 1,+            "placement": "colocated_all_roles_resident",+            "process_graph": "stdlib_supervisor_with_one_worker_per_device",+        }+++def _broadcast_command(code: int, rank: int, world_size: int) -> int:+    if world_size < 2:+        return code+    buffer = torch.tensor([code], dtype=torch.int64, device=f"npu:{rank}")+    dist.broadcast(buffer, src=0)+    return int(buffer.item())+++def _broadcast_payload(payload: dict[str, Any] | None, world_size: int) -> dict[str, Any]:+    if world_size < 2:+        return payload or {}+    box = [payload]+    dist.broadcast_object_list(box, src=0)+    return box[0] or {}+++def run_worker(args: argparse.Namespace) -> int:+    rank = int(os.environ[WORKER_RANK_ENV])+    world_size = int(os.environ.get("WORLD_SIZE", "1"))+    worker = OnlinePPOWorker(args)+    worker.build()++    if rank != 0:+        # Follower loop: rank 0 relays the host's commands over the process+        # group the workers already maintain for gradient reduction.+        while True:+            code = _broadcast_command(CMD_EXIT, rank, world_size)+            if code == CMD_EXIT:+                break+            payload = _broadcast_payload(None, world_size)+            if code == CMD_RUN:+                worker.run(payload["input_path"], int(payload["sampling_seed"]))+            elif code == CMD_PROBE:+                worker.probe(payload["request"])+        if world_size > 1:+            dist.destroy_process_group()+        return 0++    control = socket.socket(fileno=int(os.environ[WORKER_FD_ENV]))+    reader = MessageReader(control)+    send_message(control, {"type": "ready"})+    try:+        while True:+            message = reader.receive()+            kind = message.get("type")+            if kind == "run":+                _broadcast_command(CMD_RUN, rank, world_size)+                _broadcast_payload(+                    {+                        "input_path": message["input_path"],+                        "sampling_seed": int(message["sampling_seed"]),+                    },+                    world_size,+                )+                result = worker.run(message["input_path"], int(message["sampling_seed"]))+                worker.result_dir.mkdir(parents=True, exist_ok=True)+                (worker.result_dir / "run-result.json").write_text(+                    json.dumps(result, indent=2, sort_keys=True, allow_nan=False) + "\n",+                    encoding="utf-8",+                )+                send_message(control, {"type": "completed"})+            elif kind == "probe":+                _broadcast_command(CMD_PROBE, rank, world_size)+                _broadcast_payload({"request": message["request"]}, world_size)+                send_message(control, worker.probe(message["request"]))+            elif kind == "exit":+                _broadcast_command(CMD_EXIT, rank, world_size)+                break+            else:+                raise RuntimeError(f"unexpected supervisor message: {kind}")+    except BaseException as error:+        try:+            send_message(control, {"type": "failed", "reason": f"{type(error).__name__}: {error}"})+        except OSError:+            pass+        raise+    finally:+        if world_size > 1:+            try:+                dist.destroy_process_group()+            except Exception:+                pass+    return 0