GPT-6 Astra · RL

R03 · PPO joint

Valid

Qwen3-1.7B online PPO 2dev · Joint Optimization

16.43×PERFORMANCE RATIO
257TOOL EVENTS
2TEXT PATCHES
0BINARY NAMES

01 / PROCESS MAP

Tool activity

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

Main agentGPT-6 Astra · 257 visible calls

InspectEditValidateExecuteBuildProfileRollbackOther
141Inspect
27Edit
48Validate
15Execute
26Other

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 timeline198 groups · 257 calls

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

Main agent

  1. Inspect · Task requirements

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

    3 calls · #0001–#0003

    pwdprintenv <vars>rg --files -g <val> -g <path> <path> <path> <path> <path> <path> <path> <args>cat <path> <path><command> <args>cat <val>
  2. Inspect · Source & workspace

    Requested repository inspection related to source & workspace.

    1 call · #0004–#0004

    git status --short
  3. Inspect · Reward & policy updates

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

    1 call · #0005–#0005

    cat <path> <path> <path> <path> <path>
  4. Inspect · Benchmark & validation setup

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

    1 call · #0006–#0006

    cat <path> <path> <path> <path> <path> <path> <path>
  5. Inspect · Checkpoints & weight state

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

    1 call · #0007–#0007

    rg -n <val> <path>rg --files <path>rg <val>git status --short
  6. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    2 calls · #0008–#0009

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

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

    1 call · #0010–#0010

    printenvsortrg <val>rg -n <val> <path> <path> <path>rg -n <val> <path>
  8. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    3 calls · #0011–#0013

    sed -n <val> <path>cat <val>cat <path>cat <path> <path>
  9. Other · Device memory

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

    1 call · #0014–#0014

    bash <script>npu-smi infopython -c <script>
  10. Inspect · Reward & policy updates

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

    4 calls · #0015–#0018

    sed -n <val> <path>cat <path>ps <flag> <args>rg <val>head -n <n>rg -n <val> <path> <path> <path> <path>
    2 more command sketches
    rg --files <path>rg -n <val> <path> <path> <path>
  11. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0019–#0019

    python -u -c <script>
  12. Inspect · Reward & policy updates

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

    3 calls · #0020–#0022

    cat <path>sed -n <val> <path>rg -n <val> <path> <path>rg -n <val> <path>rg -n <val> <path> <path> <path> <path>rg -n <val> <path> <path> <path>
    1 more command sketches
    head -n <n>
  13. Inspect · Benchmark & validation setup

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

    1 call · #0023–#0023

    tail -n <n> <path>rg --files <val>head -n <n>
  14. Validate · Benchmark & validation setup

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

    1 call · #0024–#0024

    sed -n <val> <path>rg -n <val> <path>tail -n <n>tail -n <n> <path>command -v <val>
  15. Edit · Optimizer & gradients

    Requested code edits related to optimizer & gradients.

    1 call · #0025–#0025

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

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

    1 call · #0026–#0026

    tail -n <n> <path>ps <flag> <args>rg <val>head -n <n>df -h <val>
  17. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0027–#0027

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

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

    1 call · #0028–#0028

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

    Requested repository inspection and runtime inspection related to device memory.

    1 call · #0029–#0029

    git diff --checkgit status --shortnpu-smi info
  20. Validate · Benchmark & validation setup

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

    2 calls · #0030–#0031

    rg -n <val> <path> <path> <n> > <path>tail -n <n>du <flag> <args>tail -n <n> <path>python -c <script>
  21. Validate · Reward & policy updates

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

    1 call · #0032–#0032

    python -m <module> -q <path>python -m <module> <script> -q -k <val>
  22. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0033–#0033

    Apply patch <patch>
  23. Inspect · Reward & policy updates

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

    3 calls · #0034–#0036

    tail -n <n> <path>rg -n <val> <path>head -n <n>sed -n <val> <path>rg -n <val> <path> <path> <path>
  24. Validate · Reward & policy updates

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

    1 call · #0037–#0037

    python -m <module> <script> -q -k <val> > <path> <n> >& <path>
  25. Inspect · Reward & policy updates

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

    2 calls · #0038–#0039

    ps <flag> <args>sort <flag>head -n <n>tail -n <n> <path>rg -n <val> <path> <path>
  26. Other · Source & workspace

    Requested process termination related to source & workspace.

    1 call · #0040–#0040

    kill <flag> <args>
  27. Inspect · Reward & policy updates

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

    1 call · #0041–#0041

    tail -n <n> <path>
  28. Validate · Reward & policy updates

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

    1 call · #0042–#0042

    python -m <module> <script> -q -k <val> > <path> <n> >& <path>
  29. Validate · Device memory

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

    1 call · #0043–#0043

    sed -n <val> <path>tail -n <n> <path>npu-smi info
  30. Validate · Task requirements

    1 tool error

    Requested environment setup or inspection related to task requirements.

    1 call · #0044–#0044

    env <vars> bash <script> > <path> <n> >& <path>
  31. Inspect · Source & workspace

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

    1 call · #0045–#0045

    git diff --checkpython - <script>
  32. Validate · Device memory

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

    1 call · #0046–#0046

    tail -n <n> <path> <n> > <path>tail -n <n> <path>npu-smi info
  33. Inspect · Source & workspace

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

    1 call · #0047–#0047

    sed -n <val> <path>rg --files <val>rg <val>ps <flag> <args>sort <flag>head -n <n>
  34. Inspect · Reward & policy updates

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

    1 call · #0048–#0048

    sed -n <val> <path>
  35. Inspect · Benchmark & validation setup

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

    1 call · #0049–#0049

    tail -n <n> <path>
  36. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0050–#0050

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

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

    3 calls · #0051–#0053

    tail -n <n> <path>ps <flag> <args>rg <val>head -n <n>sed -n <val> <path>
  38. Validate · Task requirements

    1 tool error

    Requested workspace file updates, script or workload execution and environment setup or inspection related to task requirements.

    1 call · #0054–#0054

    mkdir -p <path>python - <script>env <vars> bash <script> > <path> <n> >& <path>
  39. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0055–#0055

    python - <script>
  40. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0056–#0056

    Apply patch <patch>
  41. Validate · Benchmark & validation setup

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

    1 call · #0057–#0057

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

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

    1 call · #0058–#0058

    sed -n <val> <path>rg -n <val> <path>head -n <n>
  43. Validate · Benchmark & validation setup

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

    1 call · #0059–#0059

    tail -n <n> <path> <n> > <path>ps <flag> <args>sort <flag>head -n <n>
  44. Inspect · Source & workspace

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

    1 call · #0060–#0060

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

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

    1 call · #0061–#0061

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

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

    1 call · #0062–#0062

    ls -l -h <path> <path>cat <path>tail -n <n> <path>
  47. Inspect · Reward & policy updates

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

    1 call · #0063–#0063

    rg -n <val> <path> <path> <path> <path>sed -n <val> <path>git diff --statgit status --short
  48. Validate · Device memory

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

    1 call · #0064–#0064

    tail -n <n> <path>npu-smi info
  49. Inspect · Source & workspace

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

    1 call · #0065–#0065

    rg -n <val> <path>tail -n <n>sed -n <val> <path>head -n <n> <path>
  50. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0066–#0066

    Apply patch <patch>
  51. Validate · Benchmark & validation setup

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

    1 call · #0067–#0067

    tail -n <n> <path>python - <script>
  52. Validate · Task requirements

    1 tool error

    Requested workspace file updates, script or workload execution and environment setup or inspection related to task requirements.

    1 call · #0068–#0068

    mkdir -p <path>python - <script>env <vars> bash <script> > <path> <n> >& <path>
  53. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0069–#0069

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

    Requested environment setup or inspection related to source & workspace.

    1 call · #0070–#0070

    env <vars> bash <script>
  55. Validate · Reward & policy updates

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

    2 calls · #0071–#0072

    tail -n <n> <path>tail -n <n> <path> <n> > <path>python -m <module> <script> -q -k <val> > <path> <n> >& <path>
  56. Validate · Benchmark & validation setup

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

    1 call · #0073–#0073

    tail -n <n> <path> <n> > <path>ps <flag> <args>sort <flag>head -n <n>
  57. Validate · Task requirements

    Requested workspace file updates, script or workload execution and environment setup or inspection related to task requirements.

    1 call · #0074–#0074

    mkdir -p <path>python - <script>env <vars> bash <script> > <path> <n> >& <path>
  58. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0075–#0076

    Apply patch <patch>
  59. Validate · Benchmark & validation setup

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

    1 call · #0077–#0077

    tail -n <n> <path> <n> > <path>tail -n <n> <path>
  60. Validate · Reward & policy updates

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

    2 calls · #0078–#0079

    python -m <module> <script> -q -k <val> > <path> <n> >& <path>tail -n <n> <path>tail -n <n> <path> <n> > <path>python - <script>
  61. Other · Reward & policy updates

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

    1 call · #0080–#0080

    python -X <val> -c <script> > <path> <n> > <path>
  62. Validate · Reward & policy updates

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

    1 call · #0081–#0081

    tail -n <n> <path> <n> > <path>tail -n <n> <path>
  63. Other · Reward & policy updates

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

    1 call · #0082–#0082

    python - <script>
  64. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0083–#0083

    Apply patch <patch>
  65. Inspect · Reward & policy updates

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

    1 call · #0084–#0084

    rg -n <val> <path>sed -n <val> <path>head -n <n>tail -n <n>
  66. Inspect · Benchmark & validation setup

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

    1 call · #0085–#0085

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

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

    1 call · #0086–#0086

    sed -n <val> <path>head -n <n> <path>rg -n <val> <path>head -n <n>
  68. Inspect · Checkpoints & weight state

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

    1 call · #0087–#0087

    tail -n <n> <path>du <flag> <args>
  69. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0088–#0088

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

    Requested script or workload execution related to source & workspace.

    1 call · #0089–#0089

    python - <script>
  71. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0090–#0090

    Apply patch <patch>
  72. Inspect · Checkpoints & weight state

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

    1 call · #0091–#0091

    tail -n <n> <path>du <flag> <args>ps <flag> <args>sort <flag>head -n <n>
  73. Validate · Benchmark & validation setup

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

    1 call · #0092–#0092

    python -m <module> <script> -q -k <val> > <path> <n> >& <path>
  74. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0093–#0093

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

    Requested file and log inspection related to source & workspace.

    1 call · #0094–#0094

    tail -n <n> <path>
  76. Validate · Checkpoints & weight state

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

    1 call · #0095–#0095

    tail -n <n> <path>du <flag> <args>ls -l -h <path> <n> > <path>ps <flag> <args>sort <flag>head -n <n>
  77. Inspect · Reward & policy updates

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

    2 calls · #0096–#0097

    sed -n <val> <path>rg -n <val> <path>head -n <n>git diff --checktail -n <n> <path>
  78. Validate · Reward & policy updates

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

    2 calls · #0098–#0099

    python -m <module> <script> -q -k <val> > <path> <n> >& <path>tail -n <n> <path>tail -n <n> <path> <n> > <path>ps <flag> <args>sort <flag>head -n <n>
  79. Validate · Task requirements

    1 tool error

    Requested environment setup or inspection related to task requirements.

    1 call · #0100–#0100

    env <vars> bash <script> > <path> <n> >& <path>
  80. Validate · Benchmark & validation setup

    1 tool error

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

    1 call · #0101–#0101

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

    Requested script or workload execution related to source & workspace.

    1 call · #0102–#0102

    python - <script>
  82. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0103–#0103

    Apply patch <patch>
  83. Inspect · Reward & policy updates

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

    1 call · #0104–#0104

    tail -n <n> <path>git diff --numstatgit diff --check
  84. Other · Reward & policy updates

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

    1 call · #0105–#0105

    python -u - <script>
  85. Validate · Reward & policy updates

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

    1 call · #0106–#0106

    python -m <module> <script> -q -k <val> > <path> <n> >& <path>
  86. Inspect · Reward & policy updates

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

    2 calls · #0107–#0108

    tail -n <n> <path>ps <flag> <args>sort <flag>head -n <n>rg -n <val> <path>
  87. Other · Reward & policy updates

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

    1 call · #0109–#0109

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

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

    1 call · #0110–#0110

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

    1 tool error

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

    7 calls · #0111–#0117

    rg -n <val> <path>head -n <n>rg -n <val> <path> <path>cat <path>rg -n <val> <path> -g <path> -g <val> -g <val>sed -n <val> <path>
    3 more command sketches
    rg --files <path>rg -n <val> <path> -g <val> -g <val>rg -n <val> <path> <path> <path> -g <path>
  90. Edit · Optimizer & gradients

    Requested code edits related to optimizer & gradients.

    1 call · #0118–#0118

    Apply patch <patch>
  91. Inspect · Reward & policy updates

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

    1 call · #0119–#0119

    cat > <path> <script>python -u <script>
  92. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0120–#0120

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

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

    2 calls · #0121–#0122

    python -m <module> <script> -q -k <val> > <path> <n> >& <path>tail -n <n> <path>tail -n <n> <path> <n> > <path>npu-smi info
  94. Inspect · Benchmark & validation setup

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

    1 call · #0123–#0123

    ls -l -h <path>tail -n <n> <path>ps <flag> <args>sort <flag>head -n <n>
  95. Inspect · Rollout generation

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

    1 call · #0124–#0124

    rg -n <val> <path> <path> <path>tail -n <n> <path>
  96. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0125–#0125

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

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

    1 call · #0126–#0126

    python -m <module> <script> -q -k <val> > <path> <n> >& <path>
  98. Validate · Checkpoints & weight state

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

    1 call · #0127–#0127

    tail -n <n> <path>tail -n <n> <path> <n> > <path>du <flag> <args>
  99. Validate · Benchmark & validation setup

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

    1 call · #0128–#0128

    tail -n <n> <path>tail -n <n> <path> <n> > <path>ps <flag> <args>sort <flag>head -n <n>
  100. Validate · Task requirements

    Requested workspace file updates, script or workload execution and environment setup or inspection related to task requirements.

    1 call · #0129–#0129

    mkdir -p <path>python - <script>env <vars> bash <script> > <path> <n> >& <path>
  101. Validate · Device memory

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

    1 call · #0130–#0130

    tail -n <n> <path>npu-smi info
  102. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0131–#0131

    tail -n <n> <path>
  103. Validate · Benchmark & validation setup

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

    1 call · #0132–#0132

    python - <script>
  104. Inspect · Source & workspace

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

    3 calls · #0133–#0135

    git diff --statgit status --shortsed -n <val> <path>cat <path>
  105. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    1 call · #0136–#0136

    cat <path>
  106. Inspect · Optimizer & gradients

    Requested file and log inspection related to optimizer & gradients.

    1 call · #0137–#0137

    cat <path>
  107. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    4 calls · #0138–#0141

    sed -n <val> <path>cat <path>
  108. Inspect · Benchmark & validation setup

    1 tool error

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

    1 call · #0142–#0142

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

    Requested script or workload execution related to source & workspace.

    1 call · #0143–#0143

    python - <script>
  110. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    1 call · #0144–#0144

    cat <path>
  111. Inspect · Benchmark & validation setup

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

    1 call · #0145–#0145

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

    Requested source searches and repository inspection related to source & workspace.

    2 calls · #0146–#0147

    rg --files <val> -g <val> -g <val> -g <val>git diff <flag> <args>
  113. Inspect · Benchmark & validation setup

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

    2 calls · #0148–#0149

    tail -n <n> <path>
  114. Inspect · Task requirements

    1 tool error

    Requested source searches related to task requirements.

    1 call · #0150–#0150

    rg -n <val> <val> <val> <val>
  115. Inspect · Source & workspace

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

    2 calls · #0151–#0152

    rg --files <path>sed -n <val> <val>
  116. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    1 call · #0153–#0153

    cat <val>
  117. Inspect · Benchmark & validation setup

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

    1 call · #0154–#0154

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

    Requested script or workload execution related to source & workspace.

    1 call · #0155–#0155

    python - <script>
  119. Inspect · Benchmark & validation setup

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

    2 calls · #0156–#0157

    tail -n <n> <path>
  120. Execute · Task requirements

    Requested environment setup or inspection related to task requirements.

    1 call · #0158–#0158

    env <vars> bash <script> > <path> <n> >& <path>
  121. Execute · Benchmark & validation setup

    1 tool error

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

    1 call · #0159–#0159

    python - <script>
  122. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0160–#0160

    Apply patch <patch>
  123. Execute · Benchmark & validation setup

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

    1 call · #0161–#0161

    python - <script>
  124. Inspect · Attention kernels

    Requested source searches related to attention kernels.

    1 call · #0162–#0162

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

    Requested source searches related to source & workspace.

    1 call · #0163–#0163

    rg -n <val> <val> -g <path> -g <val>
  126. Inspect · Attention kernels

    1 tool error

    Requested source searches related to attention kernels.

    1 call · #0164–#0164

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

    Requested repository inspection related to source & workspace.

    1 call · #0165–#0165

    git status --short
  128. Edit · Optimizer & gradients

    Requested code edits related to optimizer & gradients.

    1 call · #0166–#0166

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

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

    1 call · #0167–#0167

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

    Requested file and log inspection related to source & workspace.

    1 call · #0168–#0168

    cat <path>
  131. Other · Source & workspace

    1 tool error

    Requested tool activity related to source & workspace.

    1 call · #0169–#0169

    command -v <val>
  132. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0170–#0170

    sed -n <val> <path>
  133. Inspect · Benchmark & validation setup

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

    1 call · #0171–#0171

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

    Requested script or workload execution related to source & workspace.

    1 call · #0172–#0172

    python - <script>
  135. Inspect · Benchmark & validation setup

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

    1 call · #0173–#0173

    tail -n <n> <path>
  136. Execute · Task requirements

    Requested environment setup or inspection related to task requirements.

    1 call · #0174–#0174

    env <vars> bash <script> > <path> <n> >& <path>
  137. Execute · Benchmark & validation setup

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

    1 call · #0175–#0175

    python - <script>
  138. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0176–#0176

    Apply patch <patch>
  139. Execute · Benchmark & validation setup

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

    1 call · #0177–#0177

    python - <script>
  140. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0178–#0178

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

    Requested script or workload execution related to source & workspace.

    1 call · #0179–#0179

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

    1 tool error

    Requested source searches related to reward & policy updates.

    1 call · #0180–#0180

    rg -n <val> <path> <path>
  143. Inspect · Benchmark & validation setup

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

    1 call · #0181–#0181

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

    Requested file and log inspection related to source & workspace.

    1 call · #0182–#0182

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

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

    2 calls · #0183–#0184

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

    Requested file and log inspection related to source & workspace.

    1 call · #0185–#0185

    sed -n <val> <path>
  147. Inspect · Benchmark & validation setup

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

    1 call · #0186–#0186

    tail -n <n> <path>
  148. Other · Reward & policy updates

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

    1 call · #0187–#0187

    python - <script>
  149. Inspect · Benchmark & validation setup

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

    2 calls · #0188–#0189

    tail -n <n> <path>
  150. Execute · Benchmark & validation setup

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

    1 call · #0190–#0190

    python - <script>
  151. Execute · Task requirements

    Requested environment setup or inspection related to task requirements.

    1 call · #0191–#0191

    env <vars> bash <script> > <path> <n> >& <path>
  152. Execute · Benchmark & validation setup

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

    1 call · #0192–#0192

    python - <script>
  153. Other · Source & workspace

    Requested workspace file updates related to source & workspace.

    1 call · #0193–#0193

    cp <path> <path>
  154. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0194–#0194

    Apply patch <patch>
  155. Inspect · Reward & policy updates

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

    1 call · #0195–#0195

    tail -n <n> <path>
  156. Validate · Reward & policy updates

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

    1 call · #0196–#0196

    python -m <module> <script> -q > <path> <n> >& <path>
  157. Inspect · Source & workspace

    Requested repository inspection related to source & workspace.

    1 call · #0197–#0197

    git diff --check
  158. Inspect · Reward & policy updates

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

    1 call · #0198–#0198

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

    Requested script or workload execution related to source & workspace.

    1 call · #0199–#0199

    python - <script>
  160. Execute · Benchmark & validation setup

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

    1 call · #0200–#0200

    python - <script>
  161. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0201–#0201

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

    Requested file and log inspection related to source & workspace.

    1 call · #0202–#0202

    sed -n <val> <path>
  163. Inspect · Benchmark & validation setup

    1 tool error

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

    1 call · #0203–#0203

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

    Requested file and log inspection related to source & workspace.

    1 call · #0204–#0204

    tail -n <n> <path>
  165. Inspect · Reward & policy updates

    1 tool error

    Requested source searches related to reward & policy updates.

    1 call · #0205–#0205

    rg -n <val> <path> <path>
  166. Inspect · Benchmark & validation setup

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

    2 calls · #0206–#0207

    tail -n <n> <path>
  167. Execute · Task requirements

    Requested environment setup or inspection related to task requirements.

    1 call · #0208–#0208

    env <vars> bash <script> > <path> <n> >& <path>
  168. Execute · Benchmark & validation setup

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

    1 call · #0209–#0209

    python - <script>
  169. Other · Source & workspace

    Requested workspace file updates related to source & workspace.

    1 call · #0210–#0210

    cp <path> <path>
  170. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0211–#0211

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

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

    1 call · #0212–#0212

    python -m <module> <script> -q -k <val> > <path> <n> >& <path>
  172. Inspect · Reward & policy updates

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

    1 call · #0213–#0213

    tail -n <n> <path>
  173. Execute · Benchmark & validation setup

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

    1 call · #0214–#0214

    python - <script>
  174. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0215–#0215

    python - <script>
  175. Inspect · Source & workspace

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

    3 calls · #0216–#0218

    cat <path>sed -n <val> <path>git diff --check
  176. Inspect · Task requirements

    1 tool error

    Requested source searches related to task requirements.

    1 call · #0219–#0219

    rg --files -g <val> <path> <path>
  177. Inspect · Benchmark & validation setup

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

    2 calls · #0220–#0221

    tail -n <n> <path>
  178. Execute · Task requirements

    Requested environment setup or inspection related to task requirements.

    1 call · #0222–#0222

    env <vars> bash <script> > <path> <n> >& <path>
  179. Inspect · Benchmark & validation setup

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

    2 calls · #0223–#0224

    tail -n <n> <path>
  180. Execute · Precision & numerical checks

    Requested script or workload execution related to precision & numerical checks.

    1 call · #0225–#0225

    python - <script>
  181. Validate · Benchmark & validation setup

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

    1 call · #0226–#0226

    python - <script>
  182. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0227–#0227

    python - <script>
  183. Inspect · Benchmark & validation setup

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

    3 calls · #0228–#0230

    tail -n <n> <path>
  184. Other · Checkpoints & weight state

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

    1 call · #0231–#0231

    python - <script>
  185. Inspect · Source & workspace

    Requested repository inspection related to source & workspace.

    7 calls · #0232–#0238

    git status --short <flag> <args>
  186. Validate · Checkpoints & weight state

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

    1 call · #0239–#0239

    python - <script>
  187. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0240–#0240

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

    Requested script or workload execution related to source & workspace.

    1 call · #0241–#0241

    python - <script>
  189. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    2 calls · #0242–#0243

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

    Requested environment setup or inspection related to task requirements.

    1 call · #0244–#0244

    env <vars> bash <script> > <path> <n> >& <path>
  191. Validate · Benchmark & validation setup

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

    2 calls · #0245–#0246

    python - <script>
  192. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0247–#0247

    Apply patch <patch>
  193. Validate · Task requirements

    Requested environment setup or inspection related to task requirements.

    1 call · #0248–#0248

    env <vars> bash <script> > <path> <n> >& <path>
  194. Inspect · Benchmark & validation setup

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

    2 calls · #0249–#0250

    tail -n <n> <path>
  195. Validate · Benchmark & validation setup

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

    1 call · #0251–#0251

    python - <script>
  196. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0252–#0252

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

    Requested script or workload execution related to source & workspace.

    2 calls · #0253–#0254

    python - <script>bash <script> > <path> <n> >& <path>
  198. Inspect · Source & workspace

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

    3 calls · #0255–#0257

    tail -n <n> <path>git diff --check

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.

transformers · 1 changed files

Base commit: 76b3bd40ca74d26f0c2bffaf42ed01f422fc70f6

diff --git a/src/transformers/generation/candidate_generator.py b/src/transformers/generation/candidate_generator.pyindex 51612dddb2cc526c8a523296cdf7fc96c113cef9..cd3543be42a78a7838c7db7aa2b638a906529bbc 100644--- a/src/transformers/generation/candidate_generator.py+++ b/src/transformers/generation/candidate_generator.py@@ -22,11 +22,6 @@ import torch.nn as nn  from ..pytorch_utils import prune_linear_layer from ..utils import is_sklearn_available---if is_sklearn_available():-    from sklearn.metrics import roc_curve- from .logits_process import LogitsProcessorList, MinLengthLogitsProcessor, SuppressTokensLogitsProcessor  @@ -268,6 +263,10 @@ class AssistedCandidateGenerator(CandidateGenerator):             if (                 len(self.probs) > 5 and {0, 1}.issubset(self.matches)             ):  # require at least 5 samples to calculate the ROC curve and at least one positive and one negative sample+                # Import only when adaptive assisted decoding needs the ROC+                # curve; ordinary model loading and generation do not need sklearn.+                from sklearn.metrics import roc_curve+                 fpr, tpr, thresholds = roc_curve(self.matches, self.probs)                 fnr = 1 - tpr 
verl · 6 changed files

Base commit: 0b2151ec61de5d99e0811b01c09e43a99a23e69d

diff --git a/verl/trainer/runtime/README.md b/verl/trainer/runtime/README.mdnew file mode 100644index 0000000000000000000000000000000000000000..52d00b68776bcc436614f059e2a3e26f9b556032--- /dev/null+++ b/verl/trainer/runtime/README.md@@ -0,0 +1,109 @@+# Resident online PPO on Ascend++`online_ppo` runs a dense Qwen3 actor, reference, token-value critic and frozen+sequence reward classifier on two projected Ascend devices. It provides an+optional runtime entry point for a single foreground process.++The first device owns the actor and its FP32 AdamW master parameters and+moments. The rollout policy uses that same master module under BF16 autocast+with a bounded KV cache. Generation finishes before training, so each rollout+uses exactly the last committed actor version. The second device owns the+frozen reference, critic and frozen reward model. Scoring and actor/critic+backward passes can overlap across devices. Parameters and optimizer state+stay on their device.++Decode steps replay an NPU graph with fixed input, KV and BF16 linear-weight+storage. Linear weights are copied from the live masters after each optimizer+step, avoiding full-model casts on every generated token. Parameter mutation+counters check that these buffers are current before accepting a probe.+Sampling happens outside the captured graph.++The decoder uses Ascend's fused grouped-query attention, RMS normalization,+rotary embedding and SiLU kernels. Vocabulary projection only covers the+response positions during PPO scoring and training.++The runtime preserves temperature-scaled policy log probabilities, top-k then+top-p sampling, EOS termination, reference KL in token rewards, masked GAE,+and the clipped actor and value objectives from `verl.trainer.ppo.core_algos`.+Microbatches contain at most 32 trajectories. Each contributes its fraction of+the complete batch's response tokens to the loss. Gradients accumulate in FP32+before a single clipped AdamW step. Reward inputs use the reward tokenizer's+chat template, and the chosen-class score is returned without a classification activation, matching+the reward loop's `use_activation=False` contract.++## Control interface++```sh+python -m verl.trainer.runtime.online_ppo \+  --run-spec RUN_SPEC.json \+  --policy-model-path POLICY_DIRECTORY \+  --auxiliary-model-path AUXILIARY_DIRECTORY \+  --tokenizer-path TOKENIZER_DIRECTORY \+  --runtime-dir RUNTIME_DIRECTORY \+  --result-dir RESULT_DIRECTORY \+  --control-socket CONTROL_SOCKET+```++The foreground process connects to the Unix socket. After loading all roles+it sends `ready`, accepts a `start` message with the input path and sampling+seed, writes `run-result.json`, and sends `completed`. Subsequent `probe`+messages evaluate continuation log probabilities on the live FP32 master+module on the NPU, in the same precision as the portable export. PPO training+and rollout use BF16 autocast, including BF16 attention and KV storage.+`shutdown` joins the execution thread and synchronizes both devices before+exiting. The runtime creates no child processes or distributed services.++Correctness runs save FP32 master weights, both AdamW optimizers, version,+algorithm settings and random states, together with a Transformers-compatible+actor. A completion marker is written only after both artifacts are saved.+Restart restores the masters and moments before accepting new input. Frozen+roles are loaded from their original artifacts and checked for parameter+mutations and changes to bounded weight samples.++## Focused checks++```sh+python -m pytest verl/trainer/runtime/test_online_ppo.py -q+python -m pytest tests/trainer/ppo/test_core_algos_on_cpu.py -q -k 'gae or kl_penalty'+```++The decoder and device-optimizer checks require an Ascend device. They compare+padded forward outputs and backward gradients to Transformers, and verify+cached decoding against a full forward. Other checks cover FP32 accumulation+and optimizer restart, EOS/padding masks, nucleus sampling and frozen weights.+The graph check reuses a captured graph after a weight update and checks+multiple decode positions against a full forward pass.++## Supplied workload validation++Validated on two Ascend 910B1 devices using the supplied formal workload:++| Measurement | Observed result |+| --- | ---: |+| Actor / critic updates | 8 / 8 |+| Accepted trajectories | 256 |+| Consumed response tokens | 16,384 |+| Host-timed end-to-end duration | 74.263 s |+| End-to-end throughput | 220.622 response tokens/s |+| PPO duration | 19.090 s |+| Peak allocated memory, actor / auxiliary NPU | 47.8 / 27.1 GB |++Smoke and full correctness passed every gate. The update-eight portable actor+matched the live NPU probe within 0.000177 log-probability units. A fresh process+restored both optimizers and completed update nine. Frozen-role and cleanup+checks passed. These are measurements of this runtime, with startup and shutdown+included in the end-to-end interval.++Focused validation covered 10 runtime tests, seven upstream PPO GAE/KL tests,+and eight upstream Transformers candidate-generator tests. The affected decoder+and graph cases were rerun after adding the persistent BF16 weight buffers.++The public checks can be run from the supplied task environment:++```sh+export TASK_EXTERNAL_INPUT_ROOT="$TASK_DIR/workloads/formal"+bash "$TASK_DIR/run/smoke.sh"+bash "$TASK_DIR/run/correctness.sh"+bash "$TASK_DIR/run/benchmark_once.sh"+bash "$TASK_DIR/run/cleanup.sh"+```diff --git a/verl/trainer/runtime/__init__.py b/verl/trainer/runtime/__init__.pynew file mode 100644index 0000000000000000000000000000000000000000..67edb5ddb7b51edfc6dd19ee500a6b3a6ceb8bed--- /dev/null+++ b/verl/trainer/runtime/__init__.py@@ -0,0 +1,14 @@+# Copyright 2026 The verl contributors+#+# 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.+"""Small, persistent runtimes for colocated online training."""diff --git a/verl/trainer/runtime/ascend_decoder.py b/verl/trainer/runtime/ascend_decoder.pynew file mode 100644index 0000000000000000000000000000000000000000..dc6becf7a34958c90a8286e5c5b0f74acf7bbe4e--- /dev/null+++ b/verl/trainer/runtime/ascend_decoder.py@@ -0,0 +1,281 @@+# Copyright 2026 The verl contributors+#+# 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.+"""Ascend execution adapter for dense Qwen3 decoders.++The Hugging Face module remains the owner of every parameter. Training,+generation and portable export therefore use the same weights, including tied+embeddings. Only execution is specialized: masks and rotary embeddings are+prepared once per batch, attention keeps grouped KV heads, and generation uses+a bounded cache without reallocating it at every token.+"""++from dataclasses import dataclass++import torch+import torch.nn.functional as F+import torch_npu+++@dataclass+class DecoderCache:+    keys: list[torch.Tensor]+    values: list[torch.Tensor]+    length: int = 0+++class AscendDecoder:+    def __init__(self, module):+        config = module.config+        if config.model_type != "qwen3" or getattr(config, "use_sliding_window", False):+            raise ValueError("AscendDecoder requires a dense Qwen3 model with full attention")+        if config.hidden_act != "silu" or config.attention_dropout != 0:+            raise ValueError("AscendDecoder requires SiLU and zero attention dropout")+        self.module = module+        self.model = module.model+        self.config = config+        self.device = next(module.parameters()).device+        self.dtype = torch.bfloat16++    def new_cache(self, batch_size: int, capacity: int) -> DecoderCache:+        if batch_size <= 0 or capacity <= 0:+            raise ValueError("KV cache dimensions must be positive")+        shape = (batch_size, self.config.num_key_value_heads, capacity, self.config.head_dim)+        return DecoderCache(+            [torch.zeros(shape, device=self.device, dtype=self.dtype) for _ in self.model.layers],+            [torch.zeros(shape, device=self.device, dtype=self.dtype) for _ in self.model.layers],+        )++    @staticmethod+    def _norm(hidden, norm):+        return torch_npu.npu_rms_norm(+            hidden.to(norm.weight.dtype), norm.weight, epsilon=norm.variance_epsilon+        )[0]++    @staticmethod+    def linear(layer, hidden, weights=None):+        if weights is None:+            return layer(hidden)+        return F.linear(hidden, weights[layer.weight], layer.bias)++    def hidden(+        self,+        input_ids,+        attention_mask,+        position_ids=None,+        cache: DecoderCache | None = None,+        cache_position=None,+        linear_weights=None,+    ):+        batch_size, query_length = input_ids.shape+        offset = cache.length if cache is not None else 0+        key_length = offset + query_length+        if cache is not None and torch.is_grad_enabled():+            raise ValueError("KV caches are only supported for inference")+        if cache_position is not None:+            if cache is None or query_length != 1 or position_ids is None:+                raise ValueError("Indexed decoding requires a cache, one token and explicit positions")+            key_length = cache.keys[0].shape[2]+        elif cache is not None and key_length > cache.keys[0].shape[2]:+            raise ValueError("KV cache capacity exceeded")+        if position_ids is None:+            position_ids = attention_mask.long().cumsum(-1).sub(1).clamp_min(0)[:, offset:key_length]+        hidden = self.model.embed_tokens(input_ids)+        cos, sin = self.model.rotary_emb(hidden, position_ids)+        if cache_position is None:+            keys = torch.arange(key_length, device=input_ids.device)+            queries = torch.arange(offset, key_length, device=input_ids.device)+            masked = (keys[None, :] > queries[:, None])[None, None, :, :]+            masked = masked | ~attention_mask[:, None, None, :key_length].bool()+            # Left-padding queries are never consumed, but must have a finite+            # attention result so that their backward pass cannot propagate NaNs.+            masked = masked & ~((queries[:, None] == keys[None, :])[None, None, :, :])+        else:+            # Fixed-size decode uses a device-side mask and write index. Neither+            # the KV shape nor any captured host scalar changes between tokens.+            masked = ~attention_mask[:, None, None, :].bool()+        masked = masked.contiguous()+        head_dim = self.config.head_dim+        for index, layer in enumerate(self.model.layers):+            residual = hidden+            normalized = self._norm(hidden, layer.input_layernorm)+            attn = layer.self_attn+            query = self.linear(attn.q_proj, normalized, linear_weights).view(batch_size, query_length, -1, head_dim)+            key = self.linear(attn.k_proj, normalized, linear_weights).view(batch_size, query_length, -1, head_dim)+            value = self.linear(attn.v_proj, normalized, linear_weights).view(batch_size, query_length, -1, head_dim)+            query = self._norm(query, attn.q_norm).transpose(1, 2).contiguous()+            key = self._norm(key, attn.k_norm).transpose(1, 2).contiguous()+            value = value.transpose(1, 2).contiguous()+            query = torch_npu.npu_rotary_mul(query, cos[:, None], sin[:, None])+            key = torch_npu.npu_rotary_mul(key, cos[:, None], sin[:, None])+            # FP32 master modules keep the residual stream and normalization+            # in FP32. Attention, like the linear layers under autocast, uses+            # BF16 compute and BF16 KV storage.+            query, key, value = query.to(self.dtype), key.to(self.dtype), value.to(self.dtype)+            if cache is not None:+                if cache_position is None:+                    cache.keys[index][:, :, offset:key_length].copy_(key)+                    cache.values[index][:, :, offset:key_length].copy_(value)+                    if offset:+                        key = cache.keys[index][:, :, :key_length].contiguous()+                        value = cache.values[index][:, :, :key_length].contiguous()+                else:+                    write_index = cache_position.view(1, 1, 1, 1).expand_as(key)+                    cache.keys[index].scatter_(2, write_index, key)+                    cache.values[index].scatter_(2, write_index, value)+                    key, value = cache.keys[index], cache.values[index]+            attention = (+                torch_npu.npu_fusion_attention_v3 if cache_position is not None else torch_npu.npu_fusion_attention+            )+            attended = attention(+                query,+                key,+                value,+                self.config.num_attention_heads,+                "BNSD",+                atten_mask=masked,+                scale=attn.scaling,+                keep_prob=1.0,+            )[0]+            attended = attended.transpose(1, 2).reshape(batch_size, query_length, -1)+            hidden = residual + self.linear(attn.o_proj, attended, linear_weights)+            residual = hidden+            normalized = self._norm(hidden, layer.post_attention_layernorm)+            gate_up = torch.cat(+                (+                    self.linear(layer.mlp.gate_proj, normalized, linear_weights),+                    self.linear(layer.mlp.up_proj, normalized, linear_weights),+                ),+                dim=-1,+            )+            hidden = residual + self.linear(layer.mlp.down_proj, torch_npu.npu_swiglu(gate_up, dim=-1), linear_weights)+        if cache is not None and cache_position is None:+            cache.length = key_length+        return self._norm(hidden, self.model.norm)++    def log_probs(self, input_ids, attention_mask, response_length, temperature=1.0):+        hidden = self.hidden(input_ids, attention_mask)+        selected = hidden[:, -response_length - 1 : -1]+        # Do not materialize vocabulary logits for prompt tokens.+        logits = self.module.lm_head(selected).float() / temperature+        labels = input_ids[:, -response_length:]+        return -F.cross_entropy(logits.flatten(0, 1), labels.flatten(), reduction="none").view_as(labels)++    def values(self, input_ids, attention_mask, response_length):+        hidden = self.hidden(input_ids, attention_mask)+        return self.module.score(hidden[:, -response_length - 1 : -1]).squeeze(-1).float()++    def scores(self, input_ids, attention_mask):+        hidden = self.hidden(input_ids, attention_mask)+        # Batches are left padded, so the last token is the pooling token.+        return self.module.score(hidden[:, -1]).float()[:, -1]+++class GraphedDecode:+    """Replay a fixed-shape decode graph against the current actor weights.++    Only model computation is captured. Sampling remains outside the graph so+    normal device RNG semantics are preserved. Input buffers, KV caches and+    BF16 linear weights retain their storage addresses across online updates.+    The linear weights are refreshed from live masters at each update, avoiding+    a model-sized FP32-to-BF16 conversion on every generated token.+    """++    def __init__(self, decoder, batch_size, capacity):+        self.decoder = decoder+        self.cache = decoder.new_cache(batch_size, capacity)+        self.tokens = torch.zeros((batch_size, 1), dtype=torch.long, device=decoder.device)+        self.positions = torch.zeros_like(self.tokens)+        self.index = torch.zeros(1, dtype=torch.long, device=decoder.device)+        self.mask = torch.zeros((batch_size, capacity), dtype=torch.bool, device=decoder.device)+        self.linear_weights = {+            layer.weight: torch.empty_like(layer.weight, dtype=torch.bfloat16)+            for layer in decoder.module.modules()+            if isinstance(layer, torch.nn.Linear)+        }+        self.weight_versions = None+        self.graph = None+        self.output = None++    @property+    def weights_current(self):+        return self.weight_versions == tuple(parameter._version for parameter in self.linear_weights)++    @torch.no_grad()+    def refresh_weights(self):+        if not self.weights_current:+            for parameter, weight in self.linear_weights.items():+                weight.copy_(parameter)+            self.weight_versions = tuple(parameter._version for parameter in self.linear_weights)++    @torch.no_grad()+    def prefill(self, input_ids, attention_mask):+        self.refresh_weights()+        self.cache.length = 0+        self.prompt_length = input_ids.shape[1]+        self.prompt_lengths = attention_mask.long().sum(-1, keepdim=True)+        self.mask.zero_()+        self.mask[:, : self.prompt_length].copy_(attention_mask)+        hidden = self.decoder.hidden(input_ids, attention_mask, cache=self.cache, linear_weights=self.linear_weights)+        return self.decoder.linear(self.decoder.module.lm_head, hidden[:, -1], self.linear_weights)++    @torch.autocast("npu", dtype=torch.bfloat16, cache_enabled=False)+    def _forward(self):+        # Linear weights already use persistent BF16 storage. Keep any other+        # autocast conversions in the graph instead of retaining cached values+        # from the first capture.+        hidden = self.decoder.hidden(+            self.tokens,+            self.mask,+            self.positions,+            cache=self.cache,+            cache_position=self.index,+            linear_weights=self.linear_weights,+        )+        return self.decoder.linear(self.decoder.module.lm_head, hidden[:, -1], self.linear_weights)++    @torch.no_grad()+    def decode(self, tokens, response_index):+        position = self.prompt_length + response_index+        if position >= self.mask.shape[1]:+            raise ValueError("Decode position exceeds the KV cache capacity")+        self.tokens.copy_(tokens[:, None])+        self.positions.copy_(self.prompt_lengths + response_index)+        self.index.fill_(position)+        self.mask[:, position] = True+        if self.graph is None:+            stream = torch.npu.Stream(device=self.decoder.device)+            stream.wait_stream(torch.npu.current_stream(self.decoder.device))+            with torch.npu.stream(stream):+                for _ in range(3):+                    self._forward()+            torch.npu.current_stream(self.decoder.device).wait_stream(stream)+            self.graph = torch.npu.NPUGraph()+            with torch.npu.graph(self.graph, stream=stream):+                self.output = self._forward()+        self.graph.replay()+        return self.output+++def sample_top_k_top_p(logits, *, temperature, top_k, top_p, generator=None):+    """Sample the exact top-k then nucleus distribution on the device."""+    if temperature <= 0 or not 0 < top_p <= 1 or not 0 < top_k <= logits.shape[-1]:+        raise ValueError("Invalid sampling parameters")+    values, indices = torch.topk(logits.float() / temperature, top_k, dim=-1, sorted=True)+    probabilities = values.softmax(-1)+    remove = probabilities.cumsum(-1) > top_p+    remove[:, 1:] = remove[:, :-1].clone()+    remove[:, 0] = False+    probabilities = values.masked_fill(remove, -torch.inf).softmax(-1)+    selected = torch.multinomial(probabilities, 1, generator=generator)+    return indices.gather(-1, selected).squeeze(-1)diff --git a/verl/trainer/runtime/master_optimizer.py b/verl/trainer/runtime/master_optimizer.pynew file mode 100644index 0000000000000000000000000000000000000000..4a38c0f128077b2227960f7edcfec7d71be52af7--- /dev/null+++ b/verl/trainer/runtime/master_optimizer.py@@ -0,0 +1,76 @@+# Copyright 2026 The verl contributors+#+# 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.+"""Resident FP32 AdamW state for BF16 modules or FP32 modules under autocast."""++import torch+++class MasterAdamW:+    """Accumulate microbatch gradients in FP32 and round only after an update.++    Master weights, moments and gradients live on the compute device. An FP32+    module owns its masters directly; a BF16 module uses separate masters and+    receives rounded weights after each step. Actor and rollout can share the+    same compute module in either case.+    """++    def __init__(self, module, learning_rate, *, weight_decay=0.01):+        self.parameters = [parameter for parameter in module.parameters() if parameter.requires_grad]+        self.masters = [+            parameter if parameter.dtype == torch.float32 else torch.nn.Parameter(parameter.detach().float().clone())+            for parameter in self.parameters+        ]+        self.optimizer = torch.optim.AdamW(self.masters, lr=learning_rate, weight_decay=weight_decay, foreach=True)++    @torch.no_grad()+    def accumulate(self):+        for parameter, master in zip(self.parameters, self.masters, strict=True):+            if parameter is master:+                # Autocast already accumulates this parameter's gradient in+                # FP32, including accumulation across microbatches.+                continue+            if parameter.grad is not None:+                if master.grad is None:+                    master.grad = parameter.grad.float()+                else:+                    master.grad.add_(parameter.grad)+                parameter.grad = None++    @torch.no_grad()+    def step(self):+        norm = torch.nn.utils.clip_grad_norm_(self.masters, 1.0, error_if_nonfinite=True, foreach=True)+        self.optimizer.step()+        for parameter, master in zip(self.parameters, self.masters, strict=True):+            if parameter is not master:+                parameter.copy_(master)+        self.optimizer.zero_grad(set_to_none=True)+        return float(norm)++    def state_dict(self):+        return {+            "masters": [parameter.detach().cpu() for parameter in self.masters],+            "optimizer": self.optimizer.state_dict(),+        }++    @torch.no_grad()+    def load_state_dict(self, state):+        if len(state["masters"]) != len(self.masters):+            raise ValueError("Checkpoint master parameter count differs")+        for parameter, master, saved in zip(self.parameters, self.masters, state["masters"], strict=True):+            if master.shape != saved.shape:+                raise ValueError("Checkpoint master parameter shape differs")+            master.copy_(saved)+            if parameter is not master:+                parameter.copy_(master)+        self.optimizer.load_state_dict(state["optimizer"])diff --git a/verl/trainer/runtime/online_ppo.py b/verl/trainer/runtime/online_ppo.pynew file mode 100644index 0000000000000000000000000000000000000000..6be73168ed7ef5b416dd8436c850e4b2652362d1--- /dev/null+++ b/verl/trainer/runtime/online_ppo.py@@ -0,0 +1,585 @@+# Copyright 2026 The verl contributors+#+# 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.+"""Persistent, two-device online PPO with resident model and optimizer state.++The foreground process owns the control connection and both device execution+threads. There are no detached services or distributed process groups. The+actor is also the rollout policy; generation finishes before the single PPO+epoch and sees the committed weights on the next iteration.++Run with ``python -m verl.trainer.runtime.online_ppo --help`` for the socket+runtime interface. Inputs and sampling seeds are supplied only after models+have loaded and the runtime has sent ``ready``.+"""++import argparse+import hashlib+import json+import random+import socket+import time+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path++import numpy as np+import torch+import torch_npu  # noqa: F401+from transformers import (+    AutoConfig,+    AutoModelForCausalLM,+    AutoModelForSequenceClassification,+    AutoModelForTokenClassification,+    AutoTokenizer,+)++from verl.trainer.ppo.core_algos import compute_gae_advantage_return, compute_policy_loss, compute_value_loss+from verl.trainer.runtime.ascend_decoder import AscendDecoder, GraphedDecode, sample_top_k_top_p+from verl.trainer.runtime.master_optimizer import MasterAdamW+++def read_json(path):+    with Path(path).open(encoding="utf-8") as stream:+        value = json.load(stream)+    if not isinstance(value, dict):+        raise ValueError("Expected a JSON object")+    return value+++def write_json(path, value):+    path = Path(path)+    temporary = path.with_suffix(path.suffix + ".tmp")+    temporary.write_text(json.dumps(value, allow_nan=False, indent=2) + "\n", encoding="utf-8")+    temporary.replace(path)+++def pad_left(sequences, pad_id):+    length = max(map(len, sequences))+    ids = torch.full((len(sequences), length), pad_id, dtype=torch.long)+    mask = torch.zeros_like(ids, dtype=torch.bool)+    for row, sequence in enumerate(sequences):+        ids[row, -len(sequence) :] = torch.tensor(sequence, dtype=torch.long)+        mask[row, -len(sequence) :] = True+    return ids, mask+++def training_batch(prompts, responses, pad_id):+    prompt_ids, prompt_mask = pad_left(prompts, pad_id)+    response_length = max(map(len, responses))+    response_ids = torch.full((len(responses), response_length), pad_id, dtype=torch.long)+    response_mask = torch.zeros_like(response_ids, dtype=torch.bool)+    for row, response in enumerate(responses):+        response_ids[row, : len(response)] = torch.tensor(response, dtype=torch.long)+        response_mask[row, : len(response)] = True+    return {+        "input_ids": torch.cat((prompt_ids, response_ids), dim=-1),+        "attention_mask": torch.cat((prompt_mask, response_mask), dim=-1),+        "response_mask": response_mask.float(),+    }+++class FrozenObservation:+    """Observe every parameter's mutation counter and a bounded weight sample."""++    def __init__(self, module):+        self.module = module+        self.before = self.observe()++    @torch.no_grad()+    def observe(self):+        parameters = list(self.module.parameters())+        samples = [parameter.reshape(-1)[:: max(1, parameter.numel() // 8)][:8].float() for parameter in parameters]+        sample = torch.cat(samples).cpu().numpy().tobytes()+        return {+            "parameter_count": sum(parameter.numel() for parameter in parameters),+            "mutation_versions": [parameter._version for parameter in parameters],+            "sample_sha256": hashlib.sha256(sample).hexdigest(),+            "requires_grad": any(parameter.requires_grad for parameter in parameters),+        }++    def result(self):+        after = self.observe()+        unchanged = self.before == after and not after["requires_grad"]+        if not unchanged:+            raise RuntimeError("A frozen model changed during online PPO")+        return {"unchanged": unchanged, "before": self.before, "after": after}+++class OnlinePPO:+    def __init__(self, args, spec):+        self.args = args+        self.spec = spec+        self.algorithm = spec["algorithm"]+        self.sampling = spec["sampling"]+        devices = spec["resource_ceiling"]["device_ids"]+        if len(devices) != 2 or len(set(devices)) != 2 or any(+            type(device) is not int or not 0 <= device < torch.npu.device_count() for device in devices+        ):+            raise ValueError("The resident runtime requires two distinct projected Ascend devices")+        if spec["precision"] != {"model_compute": "bfloat16", "master_parameters": "float32"}:+            raise ValueError("The resident runtime requires BF16 compute and FP32 master parameters")+        if self.algorithm["actor_epochs"] != 1 or self.algorithm["critic_epochs"] != 1:+            raise ValueError("The resident runtime implements one PPO epoch per update")+        if (+            self.algorithm["advantage_estimator"] != "gae"+            or self.algorithm["reference_kl"]["placement"] != "token_reward"+        ):+            raise ValueError("The resident runtime requires GAE and reference KL in token rewards")+        if self.sampling["responses_per_prompt"] != 1:+            raise ValueError("The resident runtime generates one response per prompt")+        self.actor_device = torch.device(f"npu:{devices[0]}")+        self.auxiliary_device = torch.device(f"npu:{devices[1]}")+        self.executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="ppo-auxiliary")+        self.version = 0+        self.micro_batch_size = 32+        self.rollout = None+        torch.set_num_threads(4)+        torch.manual_seed(42)+        self.tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_path, local_files_only=True)+        self.reward_tokenizer = AutoTokenizer.from_pretrained(spec["reward_model_path"], local_files_only=True)+        self.pad_id = self.tokenizer.pad_token_id+        if self.pad_id is None:+            self.pad_id = self.tokenizer.eos_token_id+        options = {"local_files_only": True, "torch_dtype": torch.float32, "attn_implementation": "eager"}+        with torch.npu.device(self.actor_device):+            self.actor = AutoModelForCausalLM.from_pretrained(args.policy_model_path, **options).to(self.actor_device)+            self.actor.eval()+            self.actor_decoder = AscendDecoder(self.actor)+            self.actor_optimizer = MasterAdamW(self.actor, spec["actor_optimizer"]["learning_rate"])+        with torch.npu.device(self.auxiliary_device):+            self.reference = AutoModelForCausalLM.from_pretrained(args.policy_model_path, **options)+            self.reference.requires_grad_(False).eval().to(self.auxiliary_device)+            critic_config = AutoConfig.from_pretrained(args.auxiliary_model_path, local_files_only=True)+            critic_config.num_labels = 1+            critic_config.classifier_dropout = 0.0+            self.critic = AutoModelForTokenClassification.from_pretrained(+                args.auxiliary_model_path, config=critic_config, **options+            ).to(self.auxiliary_device)+            self.critic.eval()+            self.reward = AutoModelForSequenceClassification.from_pretrained(spec["reward_model_path"], **options)+            self.reward.requires_grad_(False).eval().to(self.auxiliary_device)+            self.reference_decoder = AscendDecoder(self.reference)+            self.critic_decoder = AscendDecoder(self.critic)+            self.reward_decoder = AscendDecoder(self.reward)+            self.critic_optimizer = MasterAdamW(self.critic, spec["critic_optimizer"]["learning_rate"])+            self.reference_observation = FrozenObservation(self.reference)+            self.reward_observation = FrozenObservation(self.reward)+        if spec.get("restart_checkpoint"):+            self.restore(Path(spec["restart_checkpoint"]))+        eos_ids = self.actor.generation_config.eos_token_id+        self.eos_ids = set(eos_ids if isinstance(eos_ids, list) else [eos_ids])+        print("Models and FP32 masters loaded", flush=True)++    @torch.no_grad()+    @torch.autocast("npu", dtype=torch.bfloat16)+    def generate(self, prompts):+        ids, mask = pad_left(prompts, self.pad_id)+        ids, mask = ids.to(self.actor_device), mask.to(self.actor_device)+        batch_size, prompt_length = ids.shape+        response_length = self.spec["measurement"]["max_response_tokens"]+        shape = (batch_size, prompt_length + response_length)+        if self.rollout is None or self.rollout.mask.shape != shape:+            self.rollout = GraphedDecode(self.actor_decoder, *shape)+        finished = torch.zeros(batch_size, device=self.actor_device, dtype=torch.bool)+        generated = []+        logits = self.rollout.prefill(ids, mask)+        for index in range(response_length):+            tokens = sample_top_k_top_p(+                logits,+                temperature=self.sampling["temperature"],+                top_k=self.sampling["top_k"],+                top_p=self.sampling["top_p"],+            )+            tokens = torch.where(finished, self.pad_id, tokens)+            generated.append(tokens)+            if not self.sampling["ignore_eos"]:+                for eos_id in self.eos_ids:+                    finished |= tokens == eos_id+            if index + 1 == response_length or ((index + 1) % 8 == 0 and bool(finished.all())):+                break+            logits = self.rollout.decode(tokens, index)+        output = torch.stack(generated, dim=-1).cpu().tolist()+        if not self.sampling["ignore_eos"]:+            for row, tokens in enumerate(output):+                end = next((index + 1 for index, token in enumerate(tokens) if token in self.eos_ids), len(tokens))+                output[row] = tokens[:end]+        return output++    @torch.no_grad()+    @torch.autocast("npu", dtype=torch.bfloat16)+    def actor_log_probs(self, batch):+        with torch.npu.device(self.actor_device):+            length = batch["response_mask"].shape[-1]+            output = []+            for start in range(0, len(batch["input_ids"]), self.micro_batch_size):+                stop = start + self.micro_batch_size+                output.append(+                    self.actor_decoder.log_probs(+                        batch["input_ids"][start:stop].to(self.actor_device),+                        batch["attention_mask"][start:stop].to(self.actor_device),+                        length,+                        self.sampling["temperature"],+                    ).cpu()+                )+            return torch.cat(output)++    @torch.no_grad()+    @torch.autocast("npu", dtype=torch.bfloat16)+    def auxiliary_scores(self, batch, reward_inputs):+        with torch.npu.device(self.auxiliary_device):+            length = batch["response_mask"].shape[-1]+            reference, values, rewards = [], [], []+            for start in range(0, len(batch["input_ids"]), self.micro_batch_size):+                stop = start + self.micro_batch_size+                ids = batch["input_ids"][start:stop].to(self.auxiliary_device)+                mask = batch["attention_mask"][start:stop].to(self.auxiliary_device)+                reference.append(+                    self.reference_decoder.log_probs(ids, mask, length, self.sampling["temperature"]).cpu()+                )+                values.append(self.critic_decoder.values(ids, mask, length).cpu())+                reward_ids, reward_mask = pad_left(reward_inputs[start:stop], self.pad_id)+                rewards.append(+                    self.reward_decoder.scores(+                        reward_ids.to(self.auxiliary_device), reward_mask.to(self.auxiliary_device)+                    ).cpu()+                )+            return torch.cat(reference), torch.cat(values), torch.cat(rewards)++    @torch.autocast("npu", dtype=torch.bfloat16)+    def update_actor(self, batch, old_log_probs, advantages):+        with torch.npu.device(self.actor_device):+            count = batch["response_mask"].sum().to(self.actor_device)+            length = batch["response_mask"].shape[-1]+            metrics = []+            for start in range(0, len(batch["input_ids"]), self.micro_batch_size):+                stop = start + self.micro_batch_size+                log_probs = self.actor_decoder.log_probs(+                    batch["input_ids"][start:stop].to(self.actor_device),+                    batch["attention_mask"][start:stop].to(self.actor_device),+                    length,+                    self.sampling["temperature"],+                )+                mask = batch["response_mask"][start:stop].to(self.actor_device)+                # The tensor-returning API keeps microbatch metrics on device.+                loss, clip_fraction, kl, _ = compute_policy_loss(+                    old_log_probs[start:stop].to(self.actor_device),+                    log_probs,+                    advantages[start:stop].to(self.actor_device),+                    mask,+                    cliprange=self.algorithm["actor_clip"],+                )+                weight = mask.sum() / count+                (loss * weight).backward()+                self.actor_optimizer.accumulate()+                metrics.append(torch.stack((loss.detach(), clip_fraction.detach(), kl.detach())) * weight)+            norm = self.actor_optimizer.step()+            if self.rollout is not None:+                self.rollout.refresh_weights()+            return norm, torch.stack(metrics).sum(0).cpu().tolist()++    @torch.autocast("npu", dtype=torch.bfloat16)+    def update_critic(self, batch, old_values, returns):+        with torch.npu.device(self.auxiliary_device):+            count = batch["response_mask"].sum().to(self.auxiliary_device)+            length = batch["response_mask"].shape[-1]+            metrics = []+            for start in range(0, len(batch["input_ids"]), self.micro_batch_size):+                stop = start + self.micro_batch_size+                values = self.critic_decoder.values(+                    batch["input_ids"][start:stop].to(self.auxiliary_device),+                    batch["attention_mask"][start:stop].to(self.auxiliary_device),+                    length,+                )+                mask = batch["response_mask"][start:stop].to(self.auxiliary_device)+                loss, clip_fraction = compute_value_loss(+                    values,+                    returns[start:stop].to(self.auxiliary_device),+                    old_values[start:stop].to(self.auxiliary_device),+                    mask,+                    self.algorithm["value_clip"],+                )+                weight = mask.sum() / count+                (loss * weight).backward()+                self.critic_optimizer.accumulate()+                metrics.append(torch.stack((loss.detach(), clip_fraction.detach())) * weight)+            norm = self.critic_optimizer.step()+            return norm, torch.stack(metrics).sum(0).cpu().tolist()++    def reward_inputs(self, messages, responses):+        output = []+        for chat, response in zip(messages, responses, strict=True):+            text = self.tokenizer.decode(response).replace(self.tokenizer.eos_token, "")+            reward_text = self.reward_tokenizer.apply_chat_template(+                [*chat, {"role": "assistant", "content": text}], tokenize=False, add_generation_prompt=False+            )+            bos = self.reward_tokenizer.bos_token+            if bos is not None and reward_text.startswith(bos):+                reward_text = reward_text[len(bos) :]+            output.append(self.reward_tokenizer.encode(reward_text, add_special_tokens=True))+        return output++    def run(self, input_path, sampling_seed):+        inputs = read_json(input_path)+        work = self.spec["resolved_work"]+        records = inputs["prompts"]+        if len(records) != work["trajectories_per_update"] or len({record["id"] for record in records}) != len(records):+            raise ValueError("Prompt coverage differs from the requested work")+        messages = [+            [+                {"role": "system", "content": inputs["system_prompt"]},+                {"role": "user", "content": record["question"]},+            ]+            for record in records+        ]+        prompts = [+            self.tokenizer.apply_chat_template(chat, tokenize=True, add_generation_prompt=True, return_dict=False)+            for chat in messages+        ]+        if any(not prompt or len(prompt) > self.spec["measurement"]["max_prompt_tokens"] for prompt in prompts):+            raise ValueError("A prompt exceeds the specified token limit")+        random.seed(sampling_seed)+        np.random.seed(sampling_seed % (2**32))+        torch.manual_seed(sampling_seed)+        torch.npu.manual_seed_all(sampling_seed)+        trajectory_records, step_metrics = [], []+        actor_grad_norms, critic_grad_norms = [], []+        started = time.monotonic()+        for _ in range(work["committed_updates"]):+            step_started = time.monotonic()+            rollout_version = self.version+            with torch.npu.device(self.actor_device):+                responses = self.generate(prompts)+            generated_at = time.monotonic()+            batch = training_batch(prompts, responses, self.pad_id)+            future = self.executor.submit(self.auxiliary_scores, batch, self.reward_inputs(messages, responses))+            old_log_probs = self.actor_log_probs(batch)+            reference_log_probs, values, scores = future.result()+            mask = batch["response_mask"]+            kl = (old_log_probs - reference_log_probs) * mask+            rewards = -self.algorithm["reference_kl"]["coefficient"] * kl+            ends = mask.sum(-1).long() - 1+            rewards[torch.arange(len(records)), ends] += scores+            advantages, returns = compute_gae_advantage_return(+                rewards, values, mask, self.algorithm["gamma"], self.algorithm["lambda"]+            )+            scored_at = time.monotonic()+            future = self.executor.submit(self.update_critic, batch, values, returns)+            actor_norm, actor_metrics = self.update_actor(batch, old_log_probs, advantages)+            critic_norm, critic_metrics = future.result()+            self.version += 1+            actor_grad_norms.append(actor_norm)+            critic_grad_norms.append(critic_norm)+            metrics = {+                "step": self.version,+                "rollout_policy_version": rollout_version,+                "actor/loss": actor_metrics[0],+                "actor/clip_fraction": actor_metrics[1],+                "actor/ppo_kl": actor_metrics[2],+                "actor/grad_norm": actor_norm,+                "critic/loss": critic_metrics[0],+                "critic/clip_fraction": critic_metrics[1],+                "critic/grad_norm": critic_norm,+                "critic/advantages/mean": float((advantages * mask).sum() / mask.sum()),+                "critic/advantages/abs_mean": float((advantages.abs() * mask).sum() / mask.sum()),+                "critic/returns/mean": float((returns * mask).sum() / mask.sum()),+                "reward/score_mean": float(scores.mean()),+                "reward/reference_kl": float(kl.sum() / mask.sum()),+                "response_tokens": int(mask.sum()),+                "timing/rollout": generated_at - step_started,+                "timing/scoring": scored_at - generated_at,+                "timing/update": time.monotonic() - scored_at,+            }+            step_metrics.append(metrics)+            trajectory_records.extend(+                {"update": self.version, "prompt_id": record["id"], "response_ids": response}+                for record, response in zip(records, responses, strict=True)+            )+            print(json.dumps(metrics, allow_nan=False), flush=True)+        ppo_seconds = time.monotonic() - started+        with torch.npu.device(self.auxiliary_device):+            reference_observation = self.reference_observation.result()+            reward_observation = self.reward_observation.result()+        result = {+            "status": "passed",+            "action": self.spec["action"],+            "committed_actor_updates": len(step_metrics),+            "committed_critic_updates": len(step_metrics),+            "accepted_trajectories": len(trajectory_records),+            "trajectory_records": trajectory_records,+            "step_metrics": step_metrics,+            "actor_grad_norms": actor_grad_norms,+            "critic_grad_norms": critic_grad_norms,+            "reference_policy_frozen": reference_observation["unchanged"],+            "reward_model_frozen": reward_observation["unchanged"],+            "frozen_model_observations": {"reference": reference_observation, "reward": reward_observation},+            "reported_ppo_seconds": ppo_seconds,+            "runtime_layout": {+                "placement": "resident_roles",+                "actor_device": str(self.actor_device),+                "rollout_device": str(self.actor_device),+                "reference_device": str(self.auxiliary_device),+                "critic_device": str(self.auxiliary_device),+                "reward_device": str(self.auxiliary_device),+                "rollout_engine": "shared_actor_with_graphed_kv_cache",+                "weight_transport": "local_bfloat16_copy_after_update",+                "rollout_weights_current": self.rollout.weights_current,+                "optimizer": "resident_fp32_master_adamw",+                "compute_precision": "bfloat16_autocast",+                "probe_precision": "float32_master_parameters",+                "micro_batch_size": self.micro_batch_size,+                "process_count": 1,+                "peak_memory_allocated_bytes": {+                    str(device): torch.npu.max_memory_allocated(device)+                    for device in (self.actor_device, self.auxiliary_device)+                },+            },+        }+        if self.spec["action"] == "correctness":+            checkpoint = Path(self.args.runtime_dir).parent / "checkpoints" / f"update-{self.version}"+            self.save(checkpoint)+            result["checkpoint_path"] = str(checkpoint)+            result["portable_actor_path"] = str(checkpoint / "portable-actor")+        write_json(Path(self.args.result_dir) / "run-result.json", result)++    def save(self, path):+        path.mkdir(parents=True, exist_ok=False)+        state = {+            "schema_version": 1,+            "policy_version": self.version,+            "actor": self.actor_optimizer.state_dict(),+            "critic": self.critic_optimizer.state_dict(),+            "algorithm": self.algorithm,+            "sampling": self.sampling,+            "torch_rng": torch.get_rng_state(),+            "npu_rng": torch.npu.get_rng_state_all(),+            "python_rng": random.getstate(),+            "numpy_rng": np.random.get_state(),+        }+        temporary = path / "training.pt.tmp"+        torch.save(state, temporary)+        temporary.replace(path / "training.pt")+        portable = path / "portable-actor"+        self.actor.save_pretrained(portable, safe_serialization=True)+        self.tokenizer.save_pretrained(portable)+        write_json(path / "complete.json", {"schema_version": 1, "policy_version": self.version})++    def restore(self, path):+        marker = read_json(path / "complete.json")+        state = torch.load(path / "training.pt", map_location="cpu", weights_only=False)+        if (+            state["schema_version"] != 1+            or state["policy_version"] != marker["policy_version"]+            or state["algorithm"] != self.algorithm+            or state["sampling"] != self.sampling+        ):+            raise ValueError("Restart checkpoint is incomplete or has a different PPO contract")+        with torch.npu.device(self.actor_device):+            self.actor_optimizer.load_state_dict(state["actor"])+        with torch.npu.device(self.auxiliary_device):+            self.critic_optimizer.load_state_dict(state["critic"])+        self.version = state["policy_version"]+        torch.set_rng_state(state["torch_rng"])+        torch.npu.set_rng_state_all(state["npu_rng"])+        random.setstate(state["python_rng"])+        np.random.set_state(state["numpy_rng"])+        print(f"Restored update {self.version} and both AdamW optimizers", flush=True)++    @torch.no_grad()+    def probe(self, request):+        if self.rollout is not None and not self.rollout.weights_current:+            raise RuntimeError("Rollout weights do not match the committed actor")+        prompt = self.tokenizer.encode(request["prompt"], add_special_tokens=True)+        continuation = self.tokenizer.encode(request["continuation"], add_special_tokens=False)+        if not prompt or not continuation:+            raise ValueError("Probe prompt and continuation must both tokenize to nonempty sequences")+        with torch.npu.device(self.actor_device):+            ids = torch.tensor([prompt + continuation], device=self.actor_device)+            mask = torch.ones_like(ids, dtype=torch.bool)+            # Score the live master module in its stored precision, matching+            # portable export. Training and rollout use BF16 autocast above;+            # rounding in BF16 kernels differs across CPU and NPU hardware.+            # The two roles share this module and are evaluated independently.+            outputs = []+            for _ in range(2):+                logits = self.actor(input_ids=ids, attention_mask=mask, use_cache=False).logits+                logits = logits[:, -len(continuation) - 1 : -1].float()+                selected = torch.log_softmax(logits, dim=-1).gather(-1, ids[:, -len(continuation) :, None])+                outputs.append(selected[0, :, 0].cpu().tolist())+            actor, rollout = outputs+        return {+            "type": "probe_result",+            "policy_version": self.version,+            "rollout_reported_version": self.version,+            "actor_log_probs": actor,+            "rollout_log_probs": rollout,+        }++    def close(self):+        self.executor.shutdown(wait=True, cancel_futures=True)+        for device in (self.actor_device, self.auxiliary_device):+            torch.npu.synchronize(device)+++def main():+    parser = argparse.ArgumentParser(description=__doc__)+    for argument in (+        "run-spec",+        "policy-model-path",+        "auxiliary-model-path",+        "tokenizer-path",+        "runtime-dir",+        "result-dir",+        "control-socket",+    ):+        parser.add_argument(f"--{argument}", required=True)+    args = parser.parse_args()+    runtime = None+    with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection:+        connection.connect(args.control_socket)+        stream = connection.makefile("rwb")++        def send(value):+            stream.write(json.dumps(value, allow_nan=False, separators=(",", ":")).encode() + b"\n")+            stream.flush()++        try:+            runtime = OnlinePPO(args, read_json(args.run_spec))+            send({"type": "ready"})+            started = False+            completed = False+            while True:+                line = stream.readline(1024 * 1024)+                if not line:+                    raise ConnectionError("The host closed the control connection")+                if not line.endswith(b"\n"):+                    raise ValueError("Control message exceeds the size limit")+                message = json.loads(line)+                if message["type"] == "start" and not started:+                    started = True+                    runtime.run(message["input_path"], message["sampling_seed"])+                    completed = True+                    send({"type": "completed"})+                elif message["type"] == "probe" and completed:+                    send(runtime.probe(message["request"]))+                elif message["type"] == "shutdown":+                    break+                else:+                    raise ValueError("Invalid control message or lifecycle transition")+        finally:+            if runtime is not None:+                runtime.close()+            stream.close()+++if __name__ == "__main__":+    main()diff --git a/verl/trainer/runtime/test_online_ppo.py b/verl/trainer/runtime/test_online_ppo.pynew file mode 100644index 0000000000000000000000000000000000000000..3ab02809b7ecbed84c375d9f4418ce9a9145fb0f--- /dev/null+++ b/verl/trainer/runtime/test_online_ppo.py@@ -0,0 +1,215 @@+# Copyright 2026 The verl contributors+#+# 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.+"""Focused checks for the resident runtime (CPU unless marked with an NPU skip)."""++import copy+import subprocess+import sys+import textwrap++import pytest+import torch+import torch.nn.functional as F+from transformers import Qwen3Config, Qwen3ForCausalLM++from verl.trainer.runtime.ascend_decoder import AscendDecoder, GraphedDecode, sample_top_k_top_p+from verl.trainer.runtime.master_optimizer import MasterAdamW+from verl.trainer.runtime.online_ppo import FrozenObservation, training_batch+++def test_response_masks_include_eos_and_exclude_padding():+    batch = training_batch([[5, 6], [7]], [[2], [3, 2]], pad_id=2)+    assert batch["input_ids"].tolist() == [[5, 6, 2, 2], [2, 7, 3, 2]]+    assert batch["attention_mask"].tolist() == [[True, True, True, False], [False, True, True, True]]+    assert batch["response_mask"].tolist() == [[1, 0], [1, 1]]+++@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float32])+def test_master_adamw_accumulation_and_restart(dtype):+    torch.manual_seed(3)+    model = torch.nn.Linear(4, 3).to(dtype)+    optimizer = MasterAdamW(model, 1e-3)+    reference = [torch.nn.Parameter(parameter.detach().float().clone()) for parameter in model.parameters()]+    expected = torch.optim.AdamW(reference, lr=1e-3, weight_decay=0.01, foreach=True)+    for _ in range(2):+        for parameter, master in zip(model.parameters(), reference, strict=True):+            gradient = torch.rand_like(parameter) / 20+            if parameter.grad is None:+                parameter.grad = gradient.clone()+            else:+                parameter.grad.add_(gradient)+            if master.grad is None:+                master.grad = gradient.float()+            else:+                master.grad.add_(gradient.float())+        optimizer.accumulate()+    torch.nn.utils.clip_grad_norm_(reference, 1.0, foreach=True)+    expected.step()+    optimizer.step()+    for actual, wanted in zip(optimizer.masters, reference, strict=True):+        torch.testing.assert_close(actual, wanted, rtol=0, atol=0)+    state = copy.deepcopy(optimizer.state_dict())+    restored_model = copy.deepcopy(model)+    restored = MasterAdamW(restored_model, 1e-3)+    restored.load_state_dict(state)+    for left, right in zip(model.parameters(), restored_model.parameters(), strict=True):+        gradient = torch.randn_like(left) / 20+        left.grad = gradient.clone()+        right.grad = gradient.clone()+    optimizer.accumulate()+    restored.accumulate()+    assert optimizer.step() == restored.step()+    for left, right in zip(optimizer.masters, restored.masters, strict=True):+        torch.testing.assert_close(left, right, rtol=0, atol=0)+    for left, right in zip(model.parameters(), restored_model.parameters(), strict=True):+        torch.testing.assert_close(left, right, rtol=0, atol=0)+++def test_nucleus_sampling_excludes_tokens_beyond_boundary():+    logits = torch.tensor([[5.0, 4.0, 3.0, 2.0, 1.0]]).expand(4096, -1)+    generator = torch.Generator().manual_seed(21)+    samples = sample_top_k_top_p(logits, temperature=1, top_k=3, top_p=0.8, generator=generator)+    assert set(samples.tolist()) == {0, 1}+    expected = torch.tensor([5.0, 4.0]).softmax(-1)[0]+    assert abs(float((samples == 0).float().mean() - expected)) < 0.03+    assert sample_top_k_top_p(logits[:1], temperature=1, top_k=1, top_p=0.1).item() == 0+++def test_frozen_observation_detects_mutation():+    model = torch.nn.Linear(4, 3).requires_grad_(False)+    observation = FrozenObservation(model)+    assert observation.result()["unchanged"]+    with torch.no_grad():+        model.weight[0, 0].add_(1)+    with pytest.raises(RuntimeError, match="frozen model changed"):+        observation.result()+++def test_generation_loads_roc_curve_only_when_used():+    program = textwrap.dedent(+        """+        import sys+        from types import SimpleNamespace+        from transformers.generation.candidate_generator import AssistedCandidateGenerator+        from transformers.utils import is_sklearn_available++        assert "sklearn.metrics" not in sys.modules+        if is_sklearn_available():+            generator = AssistedCandidateGenerator.__new__(AssistedCandidateGenerator)+            generator.assistant_generation_config = SimpleNamespace(+                num_assistant_tokens_schedule="constant", assistant_confidence_threshold=0.4+            )+            generator.matches = [0, 1, 0, 1, 0]+            generator.probs = [0.1, 0.9, 0.2, 0.8, 0.3, 0.7]+            generator.update_candidate_strategy(None, None, num_matches=1)+            assert "sklearn.metrics" in sys.modules+            assert generator.assistant_generation_config.assistant_confidence_threshold == 0.7+        """+    )+    subprocess.run([sys.executable, "-c", program], check=True, capture_output=True, text=True, timeout=120)+++@pytest.mark.skipif(not torch.npu.is_available(), reason="requires Ascend")+def test_master_adamw_on_npu():+    model = torch.nn.Linear(32, 16).to(dtype=torch.bfloat16, device="npu:0")+    optimizer = MasterAdamW(model, 1e-3)+    before = [parameter.detach().clone() for parameter in model.parameters()]+    inputs = torch.randn(8, 32, dtype=torch.bfloat16, device="npu:0")+    model(inputs).float().square().mean().backward()+    optimizer.accumulate()+    assert optimizer.step() > 0+    assert any(not torch.equal(left, right) for left, right in zip(before, model.parameters(), strict=True))+    for master in optimizer.masters:+        assert master.dtype == torch.float32 and master.device.type == "npu"+        state = optimizer.optimizer.state[master]+        assert state["exp_avg"].dtype == torch.float32 and state["exp_avg"].device.type == "npu"+        assert state["exp_avg_sq"].dtype == torch.float32 and state["exp_avg_sq"].device.type == "npu"+++@pytest.mark.skipif(not torch.npu.is_available(), reason="requires Ascend")+@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float32])+def test_ascend_decoder_forward_cache_and_backward(dtype):+    torch.manual_seed(18)+    config = Qwen3Config(+        vocab_size=128,+        hidden_size=128,+        intermediate_size=256,+        num_hidden_layers=2,+        num_attention_heads=4,+        num_key_value_heads=2,+        head_dim=32,+        attention_dropout=0,+    )+    config._attn_implementation = "eager"+    model = Qwen3ForCausalLM(config).to(dtype=dtype, device="npu:0").eval()+    adapter = AscendDecoder(model)+    ids = torch.tensor([[0, 0, 5, 6, 7, 8], [11, 12, 13, 14, 15, 16]], device="npu:0")+    mask = torch.tensor([[0, 0, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]], device="npu:0").bool()+    positions = mask.long().cumsum(-1).sub(1).clamp_min(0)+    with torch.no_grad(), torch.autocast("npu", dtype=torch.bfloat16):+        expected = model.model(ids, attention_mask=mask, position_ids=positions).last_hidden_state+        actual = adapter.hidden(ids, mask)+        torch.testing.assert_close(actual[mask], expected[mask], atol=0.04, rtol=0.04)+        cache = adapter.new_cache(2, 8)+        adapter.hidden(ids[:, :4], mask[:, :4], cache=cache)+        decoded = adapter.hidden(ids[:, 4:5], mask[:, :5], cache=cache)+        torch.testing.assert_close(decoded[:, 0], actual[:, 4], atol=0.04, rtol=0.04)+        decoded = adapter.hidden(ids[:, 5:], mask, cache=cache)+        torch.testing.assert_close(decoded[:, 0], actual[:, 5], atol=0.04, rtol=0.04)+    with torch.autocast("npu", dtype=torch.bfloat16):+        loss = -adapter.log_probs(ids, mask, response_length=2).mean()+    loss.backward()+    assert all(parameter.grad is not None for parameter in model.parameters())+    assert all(torch.isfinite(parameter.grad).all() for parameter in model.parameters())+    actual_gradient = torch.cat([parameter.grad.flatten().float() for parameter in model.parameters()])+    assert actual_gradient.norm() > 0+    model.zero_grad(set_to_none=True)+    with torch.autocast("npu", dtype=torch.bfloat16):+        logits = model(ids, attention_mask=mask, position_ids=positions, use_cache=False).logits+        expected_loss = F.cross_entropy(logits[:, -3:-1].float().flatten(0, 1), ids[:, -2:].flatten())+    expected_loss.backward()+    expected_gradient = torch.cat([parameter.grad.flatten().float() for parameter in model.parameters()])+    assert (actual_gradient - expected_gradient).norm() / expected_gradient.norm() < 0.03+++@pytest.mark.skipif(not torch.npu.is_available(), reason="requires Ascend")+def test_graphed_decode_uses_positions_and_updated_weights():+    torch.manual_seed(24)+    config = Qwen3Config(+        vocab_size=128,+        hidden_size=128,+        intermediate_size=256,+        num_hidden_layers=2,+        num_attention_heads=4,+        num_key_value_heads=2,+        head_dim=32,+        attention_dropout=0,+    )+    model = Qwen3ForCausalLM(config).to(dtype=torch.float32, device="npu:0").eval()+    adapter = AscendDecoder(model)+    graph = GraphedDecode(adapter, 2, 8)+    ids = torch.tensor([[0, 0, 5, 6, 7, 8], [11, 12, 13, 14, 15, 16]], device="npu:0")+    mask = torch.tensor([[0, 0, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]], device="npu:0").bool()+    with torch.no_grad():+        for update in range(2):+            if update:+                model.lm_head.weight.mul_(0.5)+                assert not graph.weights_current+            with torch.autocast("npu", dtype=torch.bfloat16):+                expected = model.lm_head(adapter.hidden(ids, mask))+                graph.prefill(ids[:, :4], mask[:, :4])+            assert graph.weights_current+            for index in range(2):+                actual = graph.decode(ids[:, 4 + index], index)+                torch.testing.assert_close(actual, expected[:, 4 + index], atol=0.04, rtol=0.04)