Claude Opus 5 · RL

R03 · PPO joint

Source review rejected

Qwen3-1.7B online PPO 2dev · Joint Optimization

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

01 / PROCESS MAP

Tool activity

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

Main agentClaude Opus 5 · 151 visible calls

InspectEditValidateExecuteBuildProfileRollbackOther
64Inspect
35Edit
29Validate
17Execute
1Profile
5Other

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 timeline94 groups · 151 calls

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

Main agent

  1. Inspect · Source & workspace

    Requested workspace inspection related to source & workspace.

    1 call · #0001–#0001

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

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

    3 calls · #0002–#0004

    Read <path>cd <path>ls -l -a <val> <val> <val> <val> <val> <path>wc -l <path> <path> <path> <path> <path>
  3. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0005–#0005

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

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

    1 call · #0006–#0006

    Read <path>
  5. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0007–#0007

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

    Requested file and log inspection related to task requirements.

    1 call · #0008–#0008

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

    Requested file and log inspection related to source & workspace.

    5 calls · #0009–#0013

    Read <path>
  8. Inspect · Device memory

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

    1 call · #0014–#0014

    date -uecho <flag>echo <val>envgrep -E <val>sort
    4 more command sketches
    <command> <args>head <flag>which <val>python3 -V
  9. Inspect · Source & workspace

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

    4 calls · #0015–#0018

    Read <path>cat <path> <n> > <path>head -n <n>echo <val>cd <path>python3 -c <script> <n> >& <path>
    8 more command sketches
    tail -n <n>python3 -c <script>ls -d <path> <n> > <path>ls <path>echo <flag>ls <path> <n> >& <path>ls -l -a <path>cat <path>
  10. Inspect · Benchmark & validation setup

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

    1 call · #0019–#0019

    cat <path>
  11. Inspect · Source & workspace

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

    1 call · #0020–#0020

    df -h <path> <path> <n> >& <path>echo <val>free -g<command> <args>cd <path>python3 -c <script> <n> >& <path>
    1 more command sketches
    tail -n <n>
  12. Inspect · Attention kernels

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

    1 call · #0021–#0021

    cd <path>python3 -c <script> <n> >& <path>tail -n <n>
  13. Validate · Device memory

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

    1 call · #0022–#0022

    mkdir -p <path>cat > <path> <script>cd <path>env <vars> timeout <n> <val> <path> <n> >& <path>tail -n <n>
  14. Inspect · Source & workspace

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

    1 call · #0023–#0023

    cat > <path> <script>cd <path>env <vars> timeout <n> <val> <path> <n> >& <path>tail -n <n>
  15. Execute · Attention kernels

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

    2 calls · #0024–#0025

    cat > <path> <script>cd <path>env <vars> timeout <n> <val> <path> <n> >& <path>tail -n <n>
  16. Inspect · Checkpoints & weight state

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

    1 call · #0026–#0026

    cat > <path> <script>cd <path>env <vars> timeout <n> <val> <path> <n> >& <path>tail -n <n>
  17. Inspect · Attention kernels

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

    1 call · #0027–#0027

    cat > <path> <script>cd <path>env <vars> timeout <n> <val> <path> <n> >& <path>tail -n <n>
  18. Inspect · Source & workspace

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

    1 call · #0028–#0028

    cat > <path> <script>cd <path>env <vars> timeout <n> <val> <path> <n> >& <path>tail -n <n>
  19. Inspect · Reward & policy updates

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

    8 calls · #0029–#0036

    cd <path>echo <val>grep -n <val> -A <n> <path>head -n <n>sed -n <val> <path>echo <path>
    13 more command sketches
    grep -r -n <val> -A <n> <path>tail -n <n> <path> <n> > <path>sed -n <val>grep -r -n <val> <path>grep -i -n <val>awk <path> <path>grep -n <val>ls <path>grep -r -l -n <val> <path>headtail -n <n> <path>grep -r -n <val> <path> --include <path>grep -r -n <val> <path> <path> --include <path>
  20. Other · Source & workspace

    Requested workspace file updates related to source & workspace.

    1 call · #0037–#0037

    mkdir -p <path>echo <val>date -u
  21. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0038–#0038

    Write <path>
  22. Inspect · Source & workspace

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

    1 call · #0039–#0039

    cat > <path> <script>cd <path>env <vars> timeout <n> <val> <path> <n> >& <path>tail -n <n>
  23. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0040–#0040

    Write <path>
  24. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0041–#0041

    Read <path>
  25. Edit · Source & workspace

    Requested code edits related to source & workspace.

    10 calls · #0042–#0051

    Write <path>Edit <path>
  26. Inspect · Rollout generation

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

    1 call · #0052–#0052

    cd <path>python3 -m <module> <script>echo <val>grep -n <val> <path>head
  27. Edit · Source & workspace

    Requested code edits related to source & workspace.

    3 calls · #0053–#0055

    Edit <path>
  28. Validate · Task requirements

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

    1 call · #0056–#0056

    cd <path>export <vars>rm -f <path> <n> > <path>timeout <n> <val> <path> <n> >& <path>tail -n <n>
  29. Edit · Source & workspace

    Requested code edits related to source & workspace.

    3 calls · #0057–#0059

    Write <path>Edit <path>
  30. Inspect · Source & workspace

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

    2 calls · #0060–#0061

    cd <path>grep -r -n <val> --include <path> --include <path> --include <val> <path>head -n <n>Read <path>
  31. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0062–#0062

    python3 - <script>
  32. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0063–#0063

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

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

    4 calls · #0064–#0067

    cd <path>rm -f <path> <n> > <path>timeout <n> <val> <path> <val> > <path> <n> >& <path>echo <val>python3 -c <script>date -u
    5 more command sketches
    echo <flag>lstail -n <n> <val> <n> > <path>grep -a -E <val> <val>tail -n <n>
  34. Validate · Reward & policy updates

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

    1 call · #0068–#0068

    cd <path>rm -f <path> <n> > <path>timeout <n> <val> <path> <val> > <path> <n> >& <path>echo <val>python3 -c <script>
  35. Inspect · Rollout generation

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

    1 call · #0069–#0069

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

    Requested file and log inspection related to source & workspace.

    1 call · #0070–#0070

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

    Requested source searches related to benchmark & validation setup.

    1 call · #0071–#0071

    cd <path>grep -a <val> <val>
  38. Inspect · Source & workspace

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

    2 calls · #0072–#0073

    cd <path>grep -n <val> <path>Read <path>
  39. Inspect · Runtime processes

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

    1 call · #0074–#0074

    cd <path>head -n <n> <path>grep -n <val>echo <path>grep -n <val> <path>head -n <n>
    4 more command sketches
    echo <val>env <vars><command> <args>tail -n <n>
  40. Other · Source & workspace

    Requested environment setup or inspection related to source & workspace.

    1 call · #0075–#0075

    env <vars>cd <path><command> <args>printf <val> <val> <val>
  41. Other · Runtime processes

    Requested environment setup or inspection related to runtime processes.

    1 call · #0076–#0076

    env <vars>cd <path><command> <args>
  42. Validate · Benchmark & validation setup

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

    1 call · #0077–#0077

    cat <path> <n> > <path>tail -n <n>echo <val>grep -a <val> <path> <n> > <path>date -u
  43. Execute · Benchmark & validation setup

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

    1 call · #0078–#0078

    cd <path>rm -f <path> <n> > <path>nohup <val> <n> <val> <path> <val> > <path> <n> >& <path>echo <val>sleep <n>date -u
  44. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0079–#0079

    cd <path>sed -n <path> <path>head -n <n>
  45. Execute · Benchmark & validation setup

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

    5 calls · #0080–#0084

    sleep <n>cd <path>python3 -c <script> <n> >& <path>tail -n <n>date -u<command> <args>
    9 more command sketches
    python3 -c <script>grep -a <val> <val>cat <path> <n> > <path>ls -l -a <val> <n> > <path>echo <val>grep -a <val> <val> <n> > <path>ps <flag> <args>grep -c <val>ls <path>
  46. Inspect · Task requirements

    Requested workspace inspection, script or workload execution and runtime inspection related to task requirements.

    1 call · #0085–#0085

    ls <path>echo <val>python3 -c <script>ps <flag> <args>grep <val>grep -v <val>
  47. Execute · Benchmark & validation setup

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

    1 call · #0086–#0086

    cd <path>rm -f <path> <n> > <path><command> <args>echo <val>sleep <n>tail -n <n> <path>
    2 more command sketches
    grep <flag> <args>date -u
  48. Execute · Reward & policy updates

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

    1 call · #0087–#0087

    <command> <args>sleep <n>cd <path>python3 -c <script>grep -a <val> <val>tail -n <n>
    1 more command sketches
    date -u
  49. Profile · Source & workspace

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

    1 call · #0088–#0088

    env <vars>cd <path><command> <args>awk <flag> <args>sort <flag>head -n <n>
  50. Inspect · Source & workspace

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

    2 calls · #0089–#0090

    env <vars>grep -n <val> <path>head -n <n>echo <val>grep -r -n <val> <path> <path> <n> > <path>cd <path>
    1 more command sketches
    sed -n <val>
  51. Inspect · Reward & policy updates

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

    1 call · #0091–#0091

    cd <path>grep -n <val> <flag> <args>echo <val>sed -n <val> <path>grep -n <val>
  52. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0092–#0092

    Read <path>
  53. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0093–#0093

    Edit <path>
  54. Inspect · Source & workspace

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

    2 calls · #0094–#0095

    cd <path>grep -n <val> <path>headRead <path>
  55. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0096–#0096

    Edit <path>
  56. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0097–#0097

    Read <path>
  57. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0098–#0098

    Edit <path>
  58. Inspect · Source & workspace

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

    1 call · #0099–#0099

    cd <path>grep -n <val> <path>sed -n <val>
  59. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0100–#0100

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

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

    2 calls · #0101–#0102

    cd <path>python3 -m <module> <script>echo <val>rm -f <path> <n> > <path><command> <args>sleep <n>
    4 more command sketches
    python3 -c <script> <n> >& <path>tail -n <n>date -utail -n <n> <path>
  61. Execute · Reward & policy updates

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

    1 call · #0103–#0103

    cd <path>rm -f <path> <n> > <path><command> <args>sleep <n>python3 -c <script>date -u
  62. Execute · Benchmark & validation setup

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

    1 call · #0104–#0104

    cat <path> <n> > <path>tail -n <n>date -u
  63. Execute · Reward & policy updates

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

    1 call · #0105–#0105

    <command> <args>sleep <n>python3 -c <script> <n> >& <path>tail -n <n>date -u
  64. Validate · Benchmark & validation setup

    Requested workspace file updates related to benchmark & validation setup.

    1 call · #0106–#0106

    cd <path>rm -f <path> <path> <n> > <path><command> <args>echo <val>date -u
  65. Inspect · Reward & policy updates

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

    2 calls · #0107–#0108

    cd <path>ls <path> <n> > <path>headecho <path>find <val> -name <path> <n> > <path>xargs <val> <flag> <args>
    3 more command sketches
    echo <val>grep -n <val> <flag> <args>head -n <n>
  66. Edit · Reward & policy updates

    Requested code edits related to reward & policy updates.

    4 calls · #0109–#0112

    Write <path>Edit <path>
  67. Validate · Benchmark & validation setup

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

    1 call · #0113–#0113

    grep -a <val> <path> <n> > <path>tail -n <n>echo <val>cd <path>sed -n <val> <path>date -u
  68. Inspect · Reward & policy updates

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

    3 calls · #0114–#0116

    cd <path>grep -r -n <val> <path> <path> <n> > <path>echo <val>sed -n <val> <path>grep -n <val> <flag>grep -n <val> <flag> <args>
    2 more command sketches
    echo <path>grep -n <val>
  69. Validate · Benchmark & validation setup

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

    4 calls · #0117–#0120

    grep -a <val> <path> <n> > <path>tail -n <n>ls <path> <n> > <path>date -u<command> <args>sleep <n>
    2 more command sketches
    python3 -c <script> <n> >& <path>cat <path> <n> > <path>
  70. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0121–#0121

    Read <path>
  71. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0122–#0122

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

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

    2 calls · #0123–#0124

    cd <path>python3 -m <module> <script> -q <n> >& <path>tail -n <n>python3 -m <module> <script> -q -p <val> <n> >& <path>grep <flag> <args>head -n <n>
  73. Inspect · Reward & policy updates

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

    1 call · #0125–#0125

    cd <path>sed -n <val> <path>echo <val>grep -r -n <val> <path>head -n <n>
  74. Edit · Reward & policy updates

    Requested code edits related to reward & policy updates.

    3 calls · #0126–#0128

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

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

    1 call · #0129–#0129

    cd <path>python3 -m <module> <script> -q -p <val> <n> >& <path>tail -n <n>
  76. Edit · Reward & policy updates

    Requested code edits related to reward & policy updates.

    1 call · #0130–#0130

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

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

    1 call · #0131–#0131

    cd <path>python3 -m <module> <script> <script> -q -p <val> <n> >& <path>tail -n <n>date -u
  78. Execute · Reward & policy updates

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

    1 call · #0132–#0132

    cd <path>rm -f <path> <n> > <path><command> <args>sleep <n>python3 -c <script> <n> >& <path>tail -n <n>
    1 more command sketches
    date -u
  79. Execute · Benchmark & validation setup

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

    1 call · #0133–#0133

    cat <path> <n> > <path>tail -n <n>date -u
  80. Execute · Reward & policy updates

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

    1 call · #0134–#0134

    <command> <args>sleep <n>python3 -c <script> <n> >& <path>tail -n <n>date -u
  81. Validate · Benchmark & validation setup

    Requested workspace file updates related to benchmark & validation setup.

    1 call · #0135–#0135

    cd <path>rm -f <path> <path> <n> > <path><command> <args>echo <val>date -u
  82. Inspect · Reward & policy updates

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

    1 call · #0136–#0136

    cd <path>git status <flag> <args>head -n <n>echo <val>wc -l <path> <path> <n> > <path>
  83. Validate · Rollout generation

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

    2 calls · #0137–#0138

    <command> <args>sleep <n>python3 -c <script> <n> >& <path>tail -n <n>date -u
  84. Validate · Benchmark & validation setup

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

    2 calls · #0139–#0140

    grep -a <val> <path> <n> > <path>tail -n <n>echo <val>tail -n <n> <path> <n> > <path>cut <flag>date -u
    5 more command sketches
    <command> <args>sleep <n>ls <path>tr <val> <val>echo
  85. Validate · Rollout generation

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

    1 call · #0141–#0141

    <command> <args>sleep <n>python3 -c <script>tail -n <n> <path>cut <flag>date -u
  86. Inspect · Runtime processes

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

    1 call · #0142–#0142

    cd <path>timeout <n> <val> <path> <val> > <path> <n> >& <path>echo <val>python3 -c <script> <n> >& <path>tail -n <n>date -u
  87. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0143–#0143

    cd <path>python3 -c <script>date -u
  88. Validate · Benchmark & validation setup

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

    1 call · #0144–#0144

    cd <path>rm -f <path> <n> > <path><command> <args>sleep <n>python3 -c <script> <n> >& <path>tail -n <n>
    1 more command sketches
    date -u
  89. Validate · Reward & policy updates

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

    1 call · #0145–#0145

    cd <path>python3 -c <script>
  90. Execute · Reward & policy updates

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

    1 call · #0146–#0146

    cd <path>python3 -c <script>echo <val>ps <flag> <args>grep -E <val>grep -v <val>
    1 more command sketches
    wc -l
  91. Edit · Device memory

    Requested code edits related to device memory.

    2 calls · #0147–#0148

    Write <path>
  92. Inspect · Device memory

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

    1 call · #0149–#0149

    cd <path>lsecho <val>cat <val> <n> > <path>head -n <n>
  93. Edit · Device memory

    Requested code edits related to device memory.

    1 call · #0150–#0150

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

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

    1 call · #0151–#0151

    cd <path>python3 -m <module> <script> <script>echo <val>git status <flag>head<command> <args>
    2 more command sketches
    python3 -c <script>date -u

03 / CANDIDATE ARTIFACT

Text patches & binary names

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

verl · 6 changed files

Base commit: 0b2151ec61de5d99e0811b01c09e43a99a23e69d

diff --git a/verl/trainer/runtime/__init__.py b/verl/trainer/runtime/__init__.pynew file mode 100644index 0000000000000000000000000000000000000000..9398178cca388e7f796fb0817227b7e6045ddc76--- /dev/null+++ b/verl/trainer/runtime/__init__.py@@ -0,0 +1,22 @@+# Copyright 2024 Bytedance Ltd. and/or its affiliates+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+#     http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""Lightweight framework-owned runtimes for fixed online RLHF workloads.++The modules in this package implement a single-process, colocated online PPO+runtime that keeps every model resident on the projected accelerators for the+whole run.  It is intended for small-model, short-sequence RLHF workloads where+the classic Ray + external-inference-engine + sharded-training process graph is+dominated by process startup, weight transport and offload/reload traffic+rather than by useful tensor work.+"""diff --git a/verl/trainer/runtime/_engine.py b/verl/trainer/runtime/_engine.pynew file mode 100644index 0000000000000000000000000000000000000000..45d950c26618daeebc77842ac36486db7fff66c2--- /dev/null+++ b/verl/trainer/runtime/_engine.py@@ -0,0 +1,220 @@+# Copyright 2024 Bytedance Ltd. and/or its affiliates+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+#     http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""Colocated single-process online PPO engine.++Design+------+The engine keeps every role resident on the projected accelerators for the+whole run and never moves weights between processes:++* ``actor``     - policy, float32 master parameters, bfloat16 compute, device 0.+* ``rollout``   - the *same* module as the actor.  Generation is performed with+  a batched incremental-decoding sampler that reads the live actor parameters,+  so there is no weight transport, no engine restart and no rollout/actor skew.+* ``reference`` - frozen bfloat16 snapshot of the initial policy, device 1.+* ``critic``    - value model, float32 master parameters, bfloat16 compute,+  device 1.+* ``reward``    - frozen sequence-classification reward model, device 1.++The PPO mathematics (token-level KL-in-reward, GAE, dual-clipped policy loss,+clipped value loss, ``token-mean`` aggregation, masked advantage whitening)+mirrors :mod:`verl.trainer.ppo.core_algos` so the training behaviour of the+supplied workload is preserved.+"""++from __future__ import annotations++import json+import math+import os+import shutil+import threading+import time+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++import torch+++# ---------------------------------------------------------------------------+# small tensor helpers (mirrors verl.utils.torch_functional semantics)+# ---------------------------------------------------------------------------+++def masked_mean(values: torch.Tensor, mask: torch.Tensor, axis: int | None = None) -> torch.Tensor:+    return (values * mask).sum(axis=axis) / mask.sum(axis=axis).clamp(min=1e-8)+++def masked_var(values: torch.Tensor, mask: torch.Tensor, unbiased: bool = True) -> torch.Tensor:+    """Masked variance, Bessel-corrected by default like ``verl.utils.torch_functional``.++    The correction matters for fidelity rather than magnitude: over a 2048-token+    mini-batch it scales the whitened advantages by only ~1.00024, but reference+    GAE whitens with the unbiased variance, so this keeps the two identical.+    """+    mean = masked_mean(values, mask)+    variance = masked_mean((values - mean) ** 2, mask)+    if unbiased:+        mask_sum = mask.sum()+        if mask_sum <= 1:+            raise ValueError("masked variance needs at least two unmasked elements")+        variance = variance * (mask_sum / (mask_sum - 1))+    return variance+++def masked_whiten(values: torch.Tensor, mask: torch.Tensor, epsilon: float = 1e-8) -> torch.Tensor:+    mean = masked_mean(values, mask)+    var = masked_var(values, mask)+    return (values - mean) * torch.rsqrt(var + epsilon)+++def clip_by_value(value: torch.Tensor, low: torch.Tensor, high: torch.Tensor) -> torch.Tensor:+    return torch.min(torch.max(value, low), high)+++def finite(value: float, default: float = 0.0) -> float:+    value = float(value)+    return value if math.isfinite(value) else default+++# ---------------------------------------------------------------------------+# configuration resolved from the launch-time run spec+# ---------------------------------------------------------------------------+++@dataclass+class EngineConfig:+    """Everything the engine needs, resolved from the host run spec."""++    action: str+    updates: int+    trajectories_per_update: int+    first_update_index: int+    max_prompt_tokens: int+    max_response_tokens: int+    temperature: float+    top_p: float+    top_k: int+    responses_per_prompt: int+    ignore_eos: bool+    gamma: float+    lam: float+    kl_coefficient: float+    kl_in_reward: bool+    actor_clip: float+    value_clip: float+    actor_epochs: int+    critic_epochs: int+    shuffle: bool+    actor_lr: float+    critic_lr: float+    policy_model_path: Path+    auxiliary_model_path: Path+    reward_model_path: Path+    tokenizer_path: Path+    restart_checkpoint: Path | None+    devices: tuple[int, ...]+    # execution plan (chosen by the framework, not part of the workload)+    actor_micro_batch: int = 8+    critic_micro_batch: int = 8+    logprob_micro_batch: int = 16+    reward_micro_batch: int = 32+    value_micro_batch: int = 32+    grad_clip: float = 1.0+    clip_ratio_c: float = 3.0+    eos_check_interval: int = 8++    @classmethod+    def from_run_spec(+        cls,+        spec: dict[str, Any],+        *,+        policy_model_path: Path,+        auxiliary_model_path: Path,+        tokenizer_path: Path,+    ) -> EngineConfig:+        algorithm = spec["algorithm"]+        sampling = spec["sampling"]+        measurement = spec["measurement"]+        work = spec["resolved_work"]+        action = str(spec["action"])+        reference_kl = algorithm.get("reference_kl", {}) or {}+        restart = spec.get("restart_checkpoint")+        devices = tuple(int(value) for value in spec.get("resource_ceiling", {}).get("device_ids", (0,)))+        return cls(+            action=action,+            updates=int(work["committed_updates"]),+            trajectories_per_update=int(work["trajectories_per_update"]),+            first_update_index=9 if action == "restart" else 1,+            max_prompt_tokens=int(measurement["max_prompt_tokens"]),+            max_response_tokens=int(measurement["max_response_tokens"]),+            temperature=float(sampling["temperature"]),+            top_p=float(sampling["top_p"]),+            top_k=int(sampling["top_k"]),+            responses_per_prompt=int(sampling["responses_per_prompt"]),+            ignore_eos=bool(sampling["ignore_eos"]),+            gamma=float(algorithm["gamma"]),+            lam=float(algorithm["lambda"]),+            kl_coefficient=float(reference_kl.get("coefficient", 0.0)),+            kl_in_reward=reference_kl.get("placement") == "token_reward",+            actor_clip=float(algorithm["actor_clip"]),+            value_clip=float(algorithm["value_clip"]),+            actor_epochs=int(algorithm["actor_epochs"]),+            critic_epochs=int(algorithm["critic_epochs"]),+            shuffle=bool(algorithm.get("shuffle", False)),+            actor_lr=float(spec["actor_optimizer"]["learning_rate"]),+            critic_lr=float(spec["critic_optimizer"]["learning_rate"]),+            policy_model_path=policy_model_path,+            auxiliary_model_path=auxiliary_model_path,+            reward_model_path=Path(spec["reward_model_path"]),+            tokenizer_path=tokenizer_path,+            restart_checkpoint=Path(restart) if restart else None,+            devices=devices or (0,),+        )++    @property+    def actor_device(self) -> str:+        return "npu:0"++    @property+    def auxiliary_device(self) -> str:+        # Place the frozen reference, the critic and the reward model on the+        # second projected device when one is available.  This keeps the actor+        # device free for float32 master parameters plus optimizer state.+        return "npu:1" if len(self.devices) > 1 else "npu:0"+++@dataclass+class RolloutBatch:+    """One update's worth of on-policy trajectories."""++    prompt_ids: torch.Tensor  # (B, P) left padded+    prompt_mask: torch.Tensor  # (B, P)+    response_ids: torch.Tensor  # (B, R) right padded+    response_mask: torch.Tensor  # (B, R) 1 up to and including the stop token+    old_log_probs: torch.Tensor  # (B, R)+    prompt_records: list[dict[str, Any]] = field(default_factory=list)++    @property+    def batch_size(self) -> int:+        return int(self.prompt_ids.shape[0])++    @property+    def full_ids(self) -> torch.Tensor:+        return torch.cat((self.prompt_ids, self.response_ids), dim=1)++    @property+    def full_mask(self) -> torch.Tensor:+        return torch.cat((self.prompt_mask, self.response_mask), dim=1)diff --git a/verl/trainer/runtime/_models.py b/verl/trainer/runtime/_models.pynew file mode 100644index 0000000000000000000000000000000000000000..752c22e433d4bdb7efb1b434921afef2046b6d38--- /dev/null+++ b/verl/trainer/runtime/_models.py@@ -0,0 +1,362 @@+# Copyright 2024 Bytedance Ltd. and/or its affiliates+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+#     http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""Model construction and the colocated rollout sampler.++Every role is built once, stays resident on its projected device for the whole+run, and is never sharded, offloaded or transported.  The rollout policy is the+actor module itself, so a policy refresh is a no-op: generation always reads the+live master parameters.+"""++from __future__ import annotations++import copy+import threading+from dataclasses import dataclass+from pathlib import Path+from typing import Any++import torch+import torch.nn as nn+import torch_npu  # noqa: F401 - registers the NPU backend++from ._engine import EngineConfig+++COMPUTE_DTYPE = torch.bfloat16+++class ValueModel(nn.Module):+    """Backbone plus scalar value head, mirroring a ``num_labels=1`` critic."""++    def __init__(self, backbone: nn.Module, hidden_size: int):+        super().__init__()+        self.backbone = backbone+        self.value_head = nn.Linear(hidden_size, 1, bias=False)+        # A zero-initialised head is deterministic and gives the usual PPO cold+        # start (v(s)=0), avoiding the random-init variance of a classification+        # head while keeping gradients non-degenerate.+        nn.init.zeros_(self.value_head.weight)++    def forward(+        self,+        input_ids: torch.Tensor,+        attention_mask: torch.Tensor,+        position_ids: torch.Tensor,+        response_length: int,+    ) -> torch.Tensor:+        """Return values for the ``response_length`` response positions."""+        hidden = self.backbone(+            input_ids=input_ids,+            attention_mask=attention_mask,+            position_ids=position_ids,+            use_cache=False,+        ).last_hidden_state+        # value of the state that produced response token t == hidden state at+        # the preceding position.+        window = hidden[:, -(response_length + 1) : -1, :]+        return self.value_head(window).squeeze(-1).float()+++@dataclass+class Roles:+    actor: nn.Module+    reference: nn.Module+    critic: ValueModel+    reward_module: nn.Module+    reward: nn.Module+    reward_score: nn.Module+    actor_device: torch.device+    auxiliary_device: torch.device+    reference_fingerprint: torch.Tensor+    reward_fingerprint: torch.Tensor+++def _position_ids(attention_mask: torch.Tensor) -> torch.Tensor:+    return (attention_mask.cumsum(dim=-1) - 1).clamp(min=0)+++def build_roles(config: EngineConfig, log) -> Roles:+    """Load every role, overlapping the two devices' work on two threads."""+    from transformers import AutoModel, AutoModelForCausalLM, AutoModelForSequenceClassification++    actor_device = torch.device(config.actor_device)+    auxiliary_device = torch.device(config.auxiliary_device)+    built: dict[str, Any] = {}+    errors: list[BaseException] = []++    def guard(name, fn):+        def runner():+            try:+                target = auxiliary_device if name == "auxiliary" else actor_device+                torch.npu.set_device(target.index or 0)+                fn()+            except BaseException as exc:  # noqa: BLE001 - reported by the caller+                errors.append(exc)++        return threading.Thread(target=runner, name=name, daemon=True)++    def build_policy():+        policy = AutoModelForCausalLM.from_pretrained(+            config.policy_model_path,+            local_files_only=True,+            dtype=COMPUTE_DTYPE,+            low_cpu_mem_usage=True,+            attn_implementation="sdpa",+        )+        policy.config.use_cache = True+        # The frozen reference is the *initial* policy; snapshot it on the host+        # before the actor is upcast so only one checkpoint read is needed.+        reference = copy.deepcopy(policy).to(auxiliary_device).eval()+        for parameter in reference.parameters():+            parameter.requires_grad_(False)+        actor = policy.to(actor_device).float()+        actor.gradient_checkpointing_disable()+        built["actor"] = actor+        built["reference"] = reference+        log("loaded policy actor (float32 master, bfloat16 compute) and frozen reference")++    def build_auxiliary():+        backbone = AutoModel.from_pretrained(+            config.auxiliary_model_path,+            local_files_only=True,+            dtype=COMPUTE_DTYPE,+            low_cpu_mem_usage=True,+            attn_implementation="sdpa",+        )+        backbone.config.use_cache = False+        critic = ValueModel(backbone, int(backbone.config.hidden_size))+        critic = critic.to(auxiliary_device).float()+        built["critic"] = critic+        reward = AutoModelForSequenceClassification.from_pretrained(+            config.reward_model_path,+            local_files_only=True,+            dtype=COMPUTE_DTYPE,+            low_cpu_mem_usage=True,+            attn_implementation="sdpa",+        )+        reward.config.use_cache = False+        reward = reward.to(auxiliary_device).eval()+        for parameter in reward.parameters():+            parameter.requires_grad_(False)+        built["reward"] = reward+        log("loaded critic (float32 master) and frozen sequence-classification reward model")++    threads = [guard("actor", build_policy), guard("auxiliary", build_auxiliary)]+    for thread in threads:+        thread.start()+    for thread in threads:+        thread.join()+    if errors:+        raise errors[0]++    reward = built["reward"]+    score = getattr(reward, "score", None)+    if score is None:+        raise RuntimeError("reward model does not expose a score head")+    reward_backbone = getattr(reward, "model", None)+    if reward_backbone is None:+        raise RuntimeError("reward model does not expose a backbone")++    return Roles(+        actor=built["actor"],+        reference=built["reference"],+        critic=built["critic"],+        reward_module=reward,+        reward=reward_backbone,+        reward_score=score,+        actor_device=actor_device,+        auxiliary_device=auxiliary_device,+        reference_fingerprint=_fingerprint(built["reference"]),+        reward_fingerprint=_fingerprint(reward),+    )+++@torch.no_grad()+def _fingerprint(module: nn.Module) -> torch.Tensor:+    """Cheap frozen-weight witness: per-parameter float64 sums."""+    values = [parameter.detach().double().sum() for parameter in module.parameters()]+    return torch.stack(values).cpu() if values else torch.zeros(1)+++@torch.no_grad()+def frozen_unchanged(module: nn.Module, fingerprint: torch.Tensor) -> bool:+    return bool(torch.equal(_fingerprint(module), fingerprint))+++# ---------------------------------------------------------------------------+# rollout: batched incremental decoding directly on the live actor parameters+# ---------------------------------------------------------------------------+++class Rollout:+    """Colocated rollout engine sharing the actor's live parameters."""++    def __init__(self, config: EngineConfig, roles: Roles, stop_ids: tuple[int, ...]):+        self.config = config+        self.roles = roles+        self.stop_ids = tuple(sorted(set(int(value) for value in stop_ids)))+        self.version = 0++    def report_version(self) -> int:+        """Rollout weight version.++        Generation reads the actor's live parameters, so the rollout policy is+        refreshed by construction and always reports the actor's version.+        """+        return self.version++    @torch.no_grad()+    def generate(+        self,+        prompt_ids: torch.Tensor,+        prompt_mask: torch.Tensor,+        *,+        seed: int,+    ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+        """Sample one continuation per prompt.++        Returns ``(response_ids, response_mask, log_probs)`` where the mask+        covers tokens up to and including the first stop token.+        """+        config = self.config+        actor = self.roles.actor+        device = self.roles.actor_device+        batch, prompt_length = prompt_ids.shape+        max_new = config.max_response_tokens+        torch.npu.manual_seed(int(seed))++        position_ids = _position_ids(prompt_mask)+        mask = torch.empty(+            (batch, prompt_length + max_new), dtype=prompt_mask.dtype, device=device+        )+        mask[:, :prompt_length] = prompt_mask+        mask[:, prompt_length:] = 1++        tokens: list[torch.Tensor] = []+        log_probs: list[torch.Tensor] = []+        alive = torch.ones((batch,), dtype=torch.bool, device=device)+        alive_flags: list[torch.Tensor] = []+        stop_tensor = torch.tensor(self.stop_ids, dtype=prompt_ids.dtype, device=device)++        with torch.autocast("npu", dtype=COMPUTE_DTYPE):+            outputs = actor(+                input_ids=prompt_ids,+                attention_mask=prompt_mask,+                position_ids=position_ids,+                use_cache=True,+            )+            cache = outputs.past_key_values+            logits = outputs.logits[:, -1, :]+            next_position = position_ids[:, -1:] + 1+            for step in range(max_new):+                token, log_prob = self._sample(logits)+                alive_flags.append(alive.clone())+                # a finished sequence emits padding that is masked out later+                tokens.append(token)+                log_probs.append(log_prob)+                hit = (token.unsqueeze(-1) == stop_tensor).any(dim=-1)+                alive = alive & ~hit+                if step + 1 >= max_new:+                    break+                if (step + 1) % config.eos_check_interval == 0 and not bool(alive.any()):+                    break+                outputs = actor(+                    input_ids=token.unsqueeze(-1),+                    attention_mask=mask[:, : prompt_length + step + 1],+                    position_ids=next_position,+                    past_key_values=cache,+                    use_cache=True,+                )+                cache = outputs.past_key_values+                logits = outputs.logits[:, -1, :]+                next_position = next_position + 1++        response_ids = torch.stack(tokens, dim=1)+        response_mask = torch.stack(alive_flags, dim=1).to(prompt_mask.dtype)+        response_log_probs = torch.stack(log_probs, dim=1)+        del cache+        return response_ids, response_mask, response_log_probs++    def _sample(self, logits: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+        """Temperature / top-k / top-p sampling with full-vocabulary log-probs."""+        config = self.config+        scaled = logits.float() / config.temperature+        top_values, top_indices = torch.topk(+            scaled, min(config.top_k, scaled.shape[-1]), dim=-1+        )+        probabilities = torch.softmax(top_values, dim=-1)+        cumulative = probabilities.cumsum(dim=-1)+        keep = (cumulative - probabilities) < config.top_p+        probabilities = probabilities * keep+        probabilities = probabilities / probabilities.sum(dim=-1, keepdim=True).clamp(min=1e-12)+        choice = torch.multinomial(probabilities, num_samples=1)+        token = top_indices.gather(-1, choice).squeeze(-1)+        log_partition = torch.logsumexp(scaled, dim=-1)+        log_prob = scaled.gather(-1, token.unsqueeze(-1)).squeeze(-1) - log_partition+        return token, log_prob+++def build_prompt_batch(+    config: EngineConfig,+    tokenizer,+    records: list[dict[str, Any]],+    system_prompt: str,+    device: torch.device,+) -> tuple[torch.Tensor, torch.Tensor]:+    """Tokenize the chat-templated prompts and left-pad them into one batch."""+    encoded: list[list[int]] = []+    for record in records:+        text = tokenizer.apply_chat_template(+            [+                {"role": "system", "content": system_prompt},+                {"role": "user", "content": record["question"]},+            ],+            tokenize=False,+            add_generation_prompt=True,+        )+        ids = tokenizer(text, add_special_tokens=False)["input_ids"]+        if len(ids) > config.max_prompt_tokens:+            raise RuntimeError(+                f"prompt {record.get('id')} exceeds max_prompt_tokens={config.max_prompt_tokens}"+            )+        encoded.append(ids)+    width = max(len(ids) for ids in encoded)+    pad_id = tokenizer.pad_token_id+    if pad_id is None:+        pad_id = tokenizer.eos_token_id+    prompt_ids = torch.full((len(encoded), width), int(pad_id), dtype=torch.long)+    prompt_mask = torch.zeros((len(encoded), width), dtype=torch.long)+    for row, ids in enumerate(encoded):+        prompt_ids[row, width - len(ids) :] = torch.tensor(ids, dtype=torch.long)+        prompt_mask[row, width - len(ids) :] = 1+    return prompt_ids.to(device), prompt_mask.to(device)+++def resolve_stop_ids(tokenizer, model_path: Path) -> tuple[int, ...]:+    stop: set[int] = set()+    if tokenizer.eos_token_id is not None:+        stop.add(int(tokenizer.eos_token_id))+    generation_config = model_path / "generation_config.json"+    if generation_config.is_file():+        import json++        value = json.loads(generation_config.read_text(encoding="utf-8")).get("eos_token_id")+        if isinstance(value, int):+            stop.add(int(value))+        elif isinstance(value, list):+            stop.update(int(item) for item in value if isinstance(item, int))+    if not stop:+        raise RuntimeError("no stop token is available for the rollout policy")+    return tuple(sorted(stop))diff --git a/verl/trainer/runtime/_ppo.py b/verl/trainer/runtime/_ppo.pynew file mode 100644index 0000000000000000000000000000000000000000..44cc3f8274e587b4266826b36ec01c585ea2a706--- /dev/null+++ b/verl/trainer/runtime/_ppo.py@@ -0,0 +1,332 @@+# Copyright 2024 Bytedance Ltd. and/or its affiliates+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+#     http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""PPO mathematics for the colocated runtime.++The formulas mirror :mod:`verl.trainer.ppo.core_algos` so the training+behaviour of the supplied workload is unchanged: token-level KL-in-reward,+GAE with masked advantage whitening, dual-clipped vanilla policy loss, clipped+value loss and ``token-mean`` loss aggregation.+"""++from __future__ import annotations++import torch+import torch.nn as nn++from ._engine import (+    EngineConfig,+    RolloutBatch,+    clip_by_value,+    masked_mean,+    masked_whiten,+)+from ._models import COMPUTE_DTYPE, Roles+++def _position_ids(attention_mask: torch.Tensor) -> torch.Tensor:+    return (attention_mask.cumsum(dim=-1) - 1).clamp(min=0)+++def _response_log_probs(+    backbone: nn.Module,+    head: nn.Module,+    input_ids: torch.Tensor,+    attention_mask: torch.Tensor,+    response_ids: torch.Tensor,+    temperature: float,+) -> torch.Tensor:+    """Log-probabilities of ``response_ids`` under the temperature-scaled policy.++    Only the response window is pushed through the language-model head, which+    keeps the vocabulary-sized tensor proportional to the response length rather+    than to the full sequence length.+    """+    response_length = int(response_ids.shape[1])+    hidden = backbone(+        input_ids=input_ids,+        attention_mask=attention_mask,+        position_ids=_position_ids(attention_mask),+        use_cache=False,+    ).last_hidden_state+    window = hidden[:, -(response_length + 1) : -1, :]+    logits = head(window).float() / temperature+    log_partition = torch.logsumexp(logits, dim=-1)+    selected = logits.gather(-1, response_ids.unsqueeze(-1)).squeeze(-1)+    return selected - log_partition+++@torch.no_grad()+def reference_log_probs(+    config: EngineConfig, roles: Roles, batch: RolloutBatch+) -> torch.Tensor:+    """Frozen-reference log-probabilities, evaluated on the auxiliary device."""+    device = roles.auxiliary_device+    input_ids = batch.full_ids.to(device)+    attention_mask = batch.full_mask.to(device)+    response_ids = batch.response_ids.to(device)+    outputs = []+    for start in range(0, batch.batch_size, config.logprob_micro_batch):+        stop = start + config.logprob_micro_batch+        outputs.append(+            _response_log_probs(+                roles.reference.model,+                roles.reference.lm_head,+                input_ids[start:stop],+                attention_mask[start:stop],+                response_ids[start:stop],+                config.temperature,+            )+        )+    return torch.cat(outputs, dim=0).to(batch.old_log_probs.device)+++@torch.no_grad()+def critic_values(config: EngineConfig, roles: Roles, batch: RolloutBatch) -> torch.Tensor:+    """Old values from the critic, evaluated on the auxiliary device."""+    device = roles.auxiliary_device+    input_ids = batch.full_ids.to(device)+    attention_mask = batch.full_mask.to(device)+    response_length = int(batch.response_ids.shape[1])+    roles.critic.eval()+    outputs = []+    with torch.autocast("npu", dtype=COMPUTE_DTYPE):+        for start in range(0, batch.batch_size, config.value_micro_batch):+            stop = start + config.value_micro_batch+            outputs.append(+                roles.critic(+                    input_ids=input_ids[start:stop],+                    attention_mask=attention_mask[start:stop],+                    position_ids=_position_ids(attention_mask[start:stop]),+                    response_length=response_length,+                )+            )+    values = torch.cat(outputs, dim=0)+    return values * batch.response_mask.to(device)+++@torch.no_grad()+def reward_scores(config: EngineConfig, roles: Roles, batch: RolloutBatch) -> torch.Tensor:+    """Frozen two-class reward-model score per trajectory (log-odds of chosen)."""+    device = roles.auxiliary_device+    input_ids = batch.full_ids.to(device)+    attention_mask = batch.full_mask.to(device)+    last_index = attention_mask.sum(dim=-1) - 1+    scores = []+    with torch.autocast("npu", dtype=COMPUTE_DTYPE):+        for start in range(0, batch.batch_size, config.reward_micro_batch):+            stop = start + config.reward_micro_batch+            chunk_mask = attention_mask[start:stop]+            hidden = roles.reward(+                input_ids=input_ids[start:stop],+                attention_mask=chunk_mask,+                position_ids=_position_ids(chunk_mask),+                use_cache=False,+            ).last_hidden_state+            index = last_index[start:stop]+            pooled = hidden[torch.arange(hidden.shape[0], device=device), index]+            logits = roles.reward_score(pooled).float()+            scores.append(logits[:, 1] - logits[:, 0])+    return torch.cat(scores, dim=0)+++def token_level_scores(+    scores: torch.Tensor, response_mask: torch.Tensor+) -> torch.Tensor:+    """Place each sequence score on its final valid response token."""+    result = torch.zeros_like(response_mask, dtype=torch.float32)+    lengths = response_mask.sum(dim=-1).long().clamp(min=1) - 1+    result[torch.arange(result.shape[0], device=result.device), lengths] = scores.to(+        result.dtype+    )+    return result * response_mask+++def apply_kl_penalty(+    config: EngineConfig,+    scores: torch.Tensor,+    old_log_probs: torch.Tensor,+    ref_log_probs: torch.Tensor,+    response_mask: torch.Tensor,+) -> tuple[torch.Tensor, float]:+    """Token-level ``k1`` KL penalty folded into the reward (verl semantics)."""+    if not config.kl_in_reward:+        return scores, 0.0+    kld = (old_log_probs - ref_log_probs) * response_mask+    rewards = scores - config.kl_coefficient * kld+    current_kl = float(torch.mean(masked_mean(kld, response_mask, axis=-1)).item())+    return rewards, current_kl+++def compute_gae(+    config: EngineConfig,+    token_rewards: torch.Tensor,+    values: torch.Tensor,+    response_mask: torch.Tensor,+) -> tuple[torch.Tensor, torch.Tensor]:+    """GAE with the reference implementation's observation-token handling."""+    with torch.no_grad():+        gamma = config.gamma+        lam = config.lam+        next_values = torch.zeros_like(values[:, 0])+        last_gae = torch.zeros_like(values[:, 0])+        reversed_advantages = []+        for step in reversed(range(int(token_rewards.shape[-1]))):+            delta = token_rewards[:, step] + gamma * next_values - values[:, step]+            candidate = delta + gamma * lam * last_gae+            mask = response_mask[:, step]+            next_values = values[:, step] * mask + (1 - mask) * next_values+            last_gae = candidate * mask + (1 - mask) * last_gae+            reversed_advantages.append(last_gae)+        advantages = torch.stack(reversed_advantages[::-1], dim=1)+        returns = advantages + values+        advantages = masked_whiten(advantages, response_mask)+    return advantages, returns+++def actor_update(+    config: EngineConfig,+    roles: Roles,+    batch: RolloutBatch,+    advantages: torch.Tensor,+    optimizer: torch.optim.Optimizer,+) -> dict[str, float]:+    """One PPO actor epoch over the update's mini-batch (one optimizer step)."""+    actor = roles.actor+    actor.train()+    device = roles.actor_device+    input_ids = batch.full_ids+    attention_mask = batch.full_mask+    response_ids = batch.response_ids+    response_mask = batch.response_mask.float()+    old_log_probs = batch.old_log_probs+    advantages = advantages.to(device)++    total_tokens = response_mask.sum().clamp(min=1.0)+    optimizer.zero_grad(set_to_none=True)+    statistics = {"pg_loss": 0.0, "ppo_kl": 0.0, "pg_clipfrac": 0.0, "pg_clipfrac_lower": 0.0}+    micro = max(1, config.actor_micro_batch)+    for start in range(0, batch.batch_size, micro):+        stop = start + micro+        chunk_mask = response_mask[start:stop]+        with torch.autocast("npu", dtype=COMPUTE_DTYPE):+            log_probs = _response_log_probs(+                actor.model,+                actor.lm_head,+                input_ids[start:stop],+                attention_mask[start:stop],+                response_ids[start:stop],+                config.temperature,+            )+        chunk_advantages = advantages[start:stop]+        negative_approx_kl = torch.clamp(+            log_probs - old_log_probs[start:stop], min=-20.0, max=20.0+        )+        ratio = torch.exp(negative_approx_kl)+        losses1 = -chunk_advantages * ratio+        losses2 = -chunk_advantages * torch.clamp(+            ratio, 1 - config.actor_clip, 1 + config.actor_clip+        )+        clipped1 = torch.maximum(losses1, losses2)+        losses3 = -chunk_advantages * config.clip_ratio_c+        clipped2 = torch.min(losses3, clipped1)+        per_token = torch.where(chunk_advantages < 0, clipped2, clipped1)+        # token-mean aggregation over the whole mini-batch: scale each micro+        # batch by its share of the mini-batch's valid tokens.+        loss = (per_token * chunk_mask).sum() / total_tokens+        loss.backward()+        with torch.no_grad():+            statistics["pg_loss"] += float((per_token * chunk_mask).sum().item())+            statistics["ppo_kl"] += float((-negative_approx_kl * chunk_mask).sum().item())+            statistics["pg_clipfrac"] += float(+                (torch.gt(losses2, losses1).float() * chunk_mask).sum().item()+            )+            statistics["pg_clipfrac_lower"] += float(+                (+                    torch.gt(clipped1, losses3).float()+                    * (chunk_advantages < 0).float()+                    * chunk_mask+                ).sum().item()+            )+    grad_norm = torch.nn.utils.clip_grad_norm_(actor.parameters(), max_norm=config.grad_clip)+    optimizer.step()+    optimizer.zero_grad(set_to_none=True)+    denominator = float(total_tokens.item())+    return {+        "actor/pg_loss": statistics["pg_loss"] / denominator,+        "actor/ppo_kl": statistics["ppo_kl"] / denominator,+        "actor/pg_clipfrac": statistics["pg_clipfrac"] / denominator,+        "actor/pg_clipfrac_lower": statistics["pg_clipfrac_lower"] / denominator,+        "actor/grad_norm": float(grad_norm.item()),+    }+++def critic_update(+    config: EngineConfig,+    roles: Roles,+    batch: RolloutBatch,+    values: torch.Tensor,+    returns: torch.Tensor,+    optimizer: torch.optim.Optimizer,+) -> dict[str, float]:+    """One clipped-value-loss critic epoch (one optimizer step)."""+    critic = roles.critic+    critic.train()+    device = roles.auxiliary_device+    input_ids = batch.full_ids.to(device)+    attention_mask = batch.full_mask.to(device)+    response_mask = batch.response_mask.float().to(device)+    values = values.to(device)+    returns = returns.to(device)+    response_length = int(batch.response_ids.shape[1])++    total_tokens = response_mask.sum().clamp(min=1.0)+    optimizer.zero_grad(set_to_none=True)+    accumulated = {"vf_loss": 0.0, "vf_clipfrac": 0.0, "vpred_sum": 0.0}+    micro = max(1, config.critic_micro_batch)+    for start in range(0, batch.batch_size, micro):+        stop = start + micro+        chunk_mask = response_mask[start:stop]+        with torch.autocast("npu", dtype=COMPUTE_DTYPE):+            predictions = critic(+                input_ids=input_ids[start:stop],+                attention_mask=attention_mask[start:stop],+                position_ids=_position_ids(attention_mask[start:stop]),+                response_length=response_length,+            )+        old = values[start:stop]+        target = returns[start:stop]+        clipped = clip_by_value(+            predictions, old - config.value_clip, old + config.value_clip+        )+        losses1 = (predictions - target) ** 2+        losses2 = (clipped - target) ** 2+        per_token = torch.max(losses1, losses2)+        loss = 0.5 * (per_token * chunk_mask).sum() / total_tokens+        loss.backward()+        with torch.no_grad():+            accumulated["vf_loss"] += float(0.5 * (per_token * chunk_mask).sum().item())+            accumulated["vf_clipfrac"] += float(+                (torch.gt(losses2, losses1).float() * chunk_mask).sum().item()+            )+            accumulated["vpred_sum"] += float((predictions * chunk_mask).sum().item())+    grad_norm = torch.nn.utils.clip_grad_norm_(critic.parameters(), max_norm=config.grad_clip)+    optimizer.step()+    optimizer.zero_grad(set_to_none=True)+    denominator = float(total_tokens.item())+    return {+        "critic/vf_loss": accumulated["vf_loss"] / denominator,+        "critic/vf_clipfrac": accumulated["vf_clipfrac"] / denominator,+        "critic/vpred/mean": accumulated["vpred_sum"] / denominator,+        "critic/grad_norm": float(grad_norm.item()),+    }diff --git a/verl/trainer/runtime/_runner.py b/verl/trainer/runtime/_runner.pynew file mode 100644index 0000000000000000000000000000000000000000..2d90ced17b39ae5c3d34199d288b05b1ec59e408--- /dev/null+++ b/verl/trainer/runtime/_runner.py@@ -0,0 +1,577 @@+# Copyright 2024 Bytedance Ltd. and/or its affiliates+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+#     http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""Orchestration for the colocated online PPO runtime."""++from __future__ import annotations++import json+import shutil+import threading+import time+from pathlib import Path+from typing import Any, Callable++import torch+import torch_npu  # noqa: F401 - registers the NPU backend++from . import _ppo+from ._engine import EngineConfig, RolloutBatch, finite, masked_mean+from ._models import (+    COMPUTE_DTYPE,+    Rollout,+    build_prompt_batch,+    build_roles,+    frozen_unchanged,+    resolve_stop_ids,+)+++ADAM_BETAS = (0.9, 0.999)+ADAM_EPS = 1e-8+WEIGHT_DECAY = 0.01+++def _in_background(device: torch.device, work: Callable[[], Any]) -> Callable[[], Any]:+    """Start ``work`` on its own thread bound to ``device``; return a joiner.++    The actor and critic updates touch disjoint modules, optimizers and devices,+    and both read only tensors computed before either one starts, so running+    them concurrently produces the same result as running them in sequence+    while overlapping the two devices' queues. The joiner re-raises whatever+    the thread raised, so a failure is never silently swallowed.+    """+    box: dict[str, Any] = {}++    def target() -> None:+        try:+            torch.npu.set_device(device.index or 0)+            box["value"] = work()+        except BaseException as error:  # noqa: BLE001 - surfaced by the joiner+            box["error"] = error++    thread = threading.Thread(target=target, name="critic-update", daemon=True)+    thread.start()++    def join() -> Any:+        thread.join()+        if "error" in box:+            raise box["error"]+        return box["value"]++    return join+++class OnlinePPORunner:+    def __init__(+        self,+        *,+        spec: dict[str, Any],+        policy_model_path: Path,+        auxiliary_model_path: Path,+        tokenizer_path: Path,+        runtime_dir: Path,+        result_dir: Path,+        log: Callable[[str], None],+    ):+        self.spec = spec+        self.runtime_dir = runtime_dir+        self.result_dir = result_dir+        self.log = log+        self.config = EngineConfig.from_run_spec(+            spec,+            policy_model_path=policy_model_path,+            auxiliary_model_path=auxiliary_model_path,+            tokenizer_path=tokenizer_path,+        )+        self.checkpoint_root = runtime_dir.parent / "checkpoints"+        self.roles = None+        self.rollout = None+        self.tokenizer = None+        self.actor_optimizer = None+        self.critic_optimizer = None+        self.policy_version = 0+        self._result: dict[str, Any] = {}++    # ------------------------------------------------------------------+    # setup+    # ------------------------------------------------------------------++    def prepare(self) -> None:+        from transformers import AutoTokenizer++        config = self.config+        torch.npu.set_device(0)+        self.log(+            f"projected devices={list(config.devices)} "+            f"actor={config.actor_device} auxiliary={config.auxiliary_device}"+        )+        self.tokenizer = AutoTokenizer.from_pretrained(+            config.tokenizer_path, local_files_only=True, use_fast=True+        )+        self.roles = build_roles(config, self.log)+        self.rollout = Rollout(+            config, self.roles, resolve_stop_ids(self.tokenizer, config.policy_model_path)+        )+        self.actor_optimizer = torch.optim.AdamW(+            self.roles.actor.parameters(),+            lr=config.actor_lr,+            betas=ADAM_BETAS,+            eps=ADAM_EPS,+            weight_decay=WEIGHT_DECAY,+        )+        self.critic_optimizer = torch.optim.AdamW(+            self.roles.critic.parameters(),+            lr=config.critic_lr,+            betas=ADAM_BETAS,+            eps=ADAM_EPS,+            weight_decay=WEIGHT_DECAY,+        )+        if config.restart_checkpoint is not None:+            self._restore(config.restart_checkpoint)+        else:+            self.policy_version = config.first_update_index - 1+        self.rollout.version = self.policy_version+        self.log(+            "roles resident; policy_version=%d actor_mem=%.1fGB aux_mem=%.1fGB"+            % (+                self.policy_version,+                torch.npu.memory_allocated(self.roles.actor_device.index or 0) / 1e9,+                torch.npu.memory_allocated(self.roles.auxiliary_device.index or 0) / 1e9,+            )+        )++    # ------------------------------------------------------------------+    # the fixed PPO work+    # ------------------------------------------------------------------++    def run(self, *, input_path: Path, sampling_seed: int) -> None:+        config = self.config+        started = time.monotonic()+        payload = json.loads(input_path.read_text(encoding="utf-8"))+        records = payload["prompts"]+        system_prompt = payload["system_prompt"]+        expected = config.trajectories_per_update+        if len(records) * config.responses_per_prompt != expected:+            raise RuntimeError(+                f"formal projection supplies {len(records)} prompts but "+                f"{expected} trajectories per update are required"+            )+        prompt_ids, prompt_mask = build_prompt_batch(+            config, self.tokenizer, records, system_prompt, self.roles.actor_device+        )+        self.log(+            f"formal projection: {len(records)} prompts, padded prompt width "+            f"{int(prompt_ids.shape[1])}, seed {sampling_seed}"+        )++        step_metrics: list[dict[str, float]] = []+        actor_grad_norms: list[float] = []+        critic_grad_norms: list[float] = []+        trajectory_records: list[dict[str, Any]] = []+        checkpoint_path: str | None = None+        portable_path: str | None = None++        for offset in range(config.updates):+            update = config.first_update_index + offset+            metrics, records_out = self._update(+                update=update,+                prompt_ids=prompt_ids,+                prompt_mask=prompt_mask,+                prompt_records=records,+                seed=sampling_seed + offset,+            )+            step_metrics.append(metrics)+            actor_grad_norms.append(metrics["actor/grad_norm"])+            critic_grad_norms.append(metrics["critic/grad_norm"])+            trajectory_records.extend(records_out)+            self.log(+                "update %d: resp_tokens=%d score=%.4f kl=%.6f adv=%.4f "+                "actor_gn=%.4f critic_gn=%.4f %.2fs"+                % (+                    update,+                    int(metrics["response_length/total"]),+                    metrics["critic/score/mean"],+                    metrics["actor/reward_kl_penalty"],+                    metrics["critic/advantages/mean"],+                    metrics["actor/grad_norm"],+                    metrics["critic/grad_norm"],+                    metrics["timing_s/step"],+                )+            )++        if config.action == "correctness":+            checkpoint_path, portable_path = self._save_restartable_checkpoint()++        ppo_seconds = time.monotonic() - started+        self._result = {+            "schema_version": 1,+            "status": "passed",+            "action": config.action,+            "committed_actor_updates": len(step_metrics),+            "committed_critic_updates": len(step_metrics),+            "accepted_trajectories": len(trajectory_records),+            "step_metrics": step_metrics,+            "actor_grad_norms": actor_grad_norms,+            "critic_grad_norms": critic_grad_norms,+            "trajectory_records": trajectory_records,+            "reward_model_frozen": frozen_unchanged(+                self.roles.reward_module, self.roles.reward_fingerprint+            ),+            "reference_policy_frozen": frozen_unchanged(+                self.roles.reference, self.roles.reference_fingerprint+            ),+            "reported_ppo_seconds": ppo_seconds,+            "policy_version": self.policy_version,+            "runtime_layout": self._runtime_layout(),+        }+        if checkpoint_path is not None:+            self._result["checkpoint_path"] = checkpoint_path+            self._result["portable_actor_path"] = portable_path+        self.result_dir.mkdir(parents=True, exist_ok=True)+        (self.result_dir / "run-result.json").write_text(+            json.dumps(self._result, indent=2, sort_keys=True, allow_nan=False) + "\n",+            encoding="utf-8",+        )+        self.log(f"PPO work complete in {ppo_seconds:.2f}s; run-result.json written")++    def _update(+        self,+        *,+        update: int,+        prompt_ids: torch.Tensor,+        prompt_mask: torch.Tensor,+        prompt_records: list[dict[str, Any]],+        seed: int,+    ) -> tuple[dict[str, float], list[dict[str, Any]]]:+        config = self.config+        roles = self.roles+        timings: dict[str, float] = {}+        step_started = time.monotonic()++        marker = time.monotonic()+        roles.actor.eval()+        response_ids, response_mask, old_log_probs = self.rollout.generate(+            prompt_ids, prompt_mask, seed=seed+        )+        timings["timing_s/gen"] = time.monotonic() - marker++        batch = RolloutBatch(+            prompt_ids=prompt_ids,+            prompt_mask=prompt_mask,+            response_ids=response_ids,+            response_mask=response_mask,+            old_log_probs=old_log_probs,+        )+        response_mask_float = response_mask.float()++        marker = time.monotonic()+        ref_log_probs = _ppo.reference_log_probs(config, roles, batch)+        timings["timing_s/ref"] = time.monotonic() - marker++        marker = time.monotonic()+        values = _ppo.critic_values(config, roles, batch).to(roles.actor_device)+        timings["timing_s/values"] = time.monotonic() - marker++        marker = time.monotonic()+        scores = _ppo.reward_scores(config, roles, batch).to(roles.actor_device)+        timings["timing_s/reward"] = time.monotonic() - marker++        marker = time.monotonic()+        token_scores = _ppo.token_level_scores(scores, response_mask_float)+        token_rewards, current_kl = _ppo.apply_kl_penalty(+            config, token_scores, old_log_probs, ref_log_probs, response_mask_float+        )+        advantages, returns = _ppo.compute_gae(+            config, token_rewards, values, response_mask_float+        )+        timings["timing_s/adv"] = time.monotonic() - marker++        # The critic (npu:1) and the actor (npu:0) are independent: disjoint+        # modules and optimizers, and both consume only tensors produced above.+        # Overlapping them keeps both devices busy instead of idling one while+        # the other trains, without changing either result.+        marker = time.monotonic()+        join_critic = _in_background(+            roles.auxiliary_device,+            lambda: _ppo.critic_update(+                config, roles, batch, values, returns, self.critic_optimizer+            ),+        )+        actor_metrics = _ppo.actor_update(+            config, roles, batch, advantages, self.actor_optimizer+        )+        timings["timing_s/update_actor"] = time.monotonic() - marker+        critic_metrics = join_critic()+        timings["timing_s/update_critic"] = time.monotonic() - marker++        # The rollout policy is the actor module, so the refreshed weights are+        # visible to generation immediately: the transport is a no-op.+        self.policy_version += 1+        self.rollout.version = self.policy_version+        timings["timing_s/update_weights"] = 0.0+        timings["timing_s/step"] = time.monotonic() - step_started++        lengths = response_mask.sum(dim=-1)+        with torch.no_grad():+            metrics = {+                "step": float(update),+                "training/global_step": float(update),+                **{key: finite(value) for key, value in actor_metrics.items()},+                **{key: finite(value) for key, value in critic_metrics.items()},+                "actor/reward_kl_penalty": finite(current_kl),+                "actor/reward_kl_penalty_coeff": float(config.kl_coefficient),+                "actor/policy_version": float(self.policy_version),+                "rollout/reported_version": float(self.rollout.report_version()),+                "critic/score/mean": finite(scores.mean().item()),+                "critic/rewards/mean": finite(+                    masked_mean(token_rewards, response_mask_float).item()+                ),+                "critic/advantages/mean": finite(+                    masked_mean(advantages, response_mask_float).item()+                ),+                "critic/returns/mean": finite(+                    masked_mean(returns, response_mask_float).item()+                ),+                "critic/values/mean": finite(+                    masked_mean(values, response_mask_float).item()+                ),+                "response_length/mean": finite(lengths.float().mean().item()),+                "response_length/total": float(int(lengths.sum().item())),+                "response/aborted_ratio": 0.0,+                **{key: finite(value) for key, value in timings.items()},+            }++        length_list = [int(value) for value in lengths.tolist()]+        response_list = response_ids.tolist()+        score_list = [finite(value) for value in scores.tolist()]+        records_out = []+        for row, record in enumerate(prompt_records):+            length = max(1, length_list[row])+            records_out.append(+                {+                    "update": update,+                    "prompt_id": record["id"],+                    "response_ids": [int(value) for value in response_list[row][:length]],+                    "response_length": length,+                    "reward_model_score": score_list[row],+                }+            )+        return metrics, records_out++    def _runtime_layout(self) -> dict[str, Any]:+        config = self.config+        return {+            "actor_strategy": "colocated_single_process_fp32_master",+            "actor_world_size": 1,+            "actor_device": config.actor_device,+            "actor_micro_batch_size_per_device": config.actor_micro_batch,+            "actor_parameter_offload": False,+            "actor_optimizer_offload": False,+            "critic_strategy": "colocated_single_process_fp32_master",+            "critic_world_size": 1,+            "critic_device": config.auxiliary_device,+            "critic_micro_batch_size_per_device": config.critic_micro_batch,+            "critic_parameter_offload": False,+            "critic_optimizer_offload": False,+            "rollout_engine": "colocated_incremental_decode",+            "rollout_shares_actor_parameters": True,+            "rollout_tensor_parallel_size": 1,+            "rollout_weight_transport": "none",+            "reference_device": config.auxiliary_device,+            "reference_precision": "bfloat16",+            "reward_model_device": config.auxiliary_device,+            "reward_model_tensor_parallel_size": 1,+            "compute_precision": "bfloat16",+            "master_parameter_precision": "float32",+            "placement": "colocated_resident",+            "process_graph": "single_foreground_process",+            "visible_devices": list(config.devices),+        }++    # ------------------------------------------------------------------+    # checkpoint / restart+    # ------------------------------------------------------------------++    def _save_restartable_checkpoint(self) -> tuple[str, str]:+        target = self.checkpoint_root / f"update-{self.policy_version}"+        if target.exists():+            shutil.rmtree(target)+        target.mkdir(parents=True)+        started = time.monotonic()+        torch.save(+            {+                "model": _cpu_state(self.roles.actor.state_dict()),+                "optimizer": _cpu_optimizer_state(self.actor_optimizer.state_dict()),+            },+            target / "actor.pt",+        )+        torch.save(+            {+                "model": _cpu_state(self.roles.critic.state_dict()),+                "optimizer": _cpu_optimizer_state(self.critic_optimizer.state_dict()),+            },+            target / "critic.pt",+        )+        (target / "runtime-state.json").write_text(+            json.dumps(+                {+                    "schema_version": 1,+                    "policy_version": self.policy_version,+                    "committed_actor_updates": self.policy_version,+                    "committed_critic_updates": self.policy_version,+                    "actor_learning_rate": self.config.actor_lr,+                    "critic_learning_rate": self.config.critic_lr,+                },+                indent=2,+                sort_keys=True,+            )+            + "\n",+            encoding="utf-8",+        )+        self.log(f"restartable checkpoint written in {time.monotonic() - started:.1f}s")+        portable = self._export_portable_actor(target / "portable-actor")+        return str(target), str(portable)++    def _export_portable_actor(self, target: Path) -> Path:+        """Transformers-compatible float32 export of the live actor."""+        started = time.monotonic()+        if target.exists():+            shutil.rmtree(target)+        target.mkdir(parents=True)+        actor = self.roles.actor+        # The checkpoint ships both `lm_head.weight` and `embed_tokens.weight`,+        # so Transformers keeps them untied.  Record that faithfully, otherwise+        # a reload would tie them and diverge from the live actor.+        actor.config.tie_word_embeddings = False+        actor.config.torch_dtype = "float32"+        actor.config.dtype = "float32"+        state = _cpu_state(actor.state_dict())+        actor.save_pretrained(+            target, state_dict=state, safe_serialization=True, max_shard_size="20GB"+        )+        self.tokenizer.save_pretrained(target)+        self.log(f"portable actor exported in {time.monotonic() - started:.1f}s")+        return target++    def _restore(self, checkpoint: Path) -> None:+        started = time.monotonic()+        state = json.loads((checkpoint / "runtime-state.json").read_text(encoding="utf-8"))+        actor_blob = torch.load(checkpoint / "actor.pt", map_location="cpu", weights_only=False)+        self.roles.actor.load_state_dict(actor_blob["model"])+        self.actor_optimizer.load_state_dict(actor_blob["optimizer"])+        del actor_blob+        critic_blob = torch.load(checkpoint / "critic.pt", map_location="cpu", weights_only=False)+        self.roles.critic.load_state_dict(critic_blob["model"])+        self.critic_optimizer.load_state_dict(critic_blob["optimizer"])+        del critic_blob+        self.policy_version = int(state["policy_version"])+        if self.policy_version + 1 != self.config.first_update_index:+            raise RuntimeError(+                f"checkpoint holds update {self.policy_version} but the runtime was "+                f"asked to commit update {self.config.first_update_index}"+            )+        self.log(+            f"reloaded update {self.policy_version} from {checkpoint} "+            f"in {time.monotonic() - started:.1f}s"+        )++    # ------------------------------------------------------------------+    # freshness probe+    # ------------------------------------------------------------------++    def probe(self, message: dict[str, Any]) -> dict[str, Any]:+        request = message.get("request") or {}+        prompt = request["prompt"]+        continuation = request["continuation"]+        prompt_ids = self.tokenizer.encode(prompt, add_special_tokens=True)+        continuation_ids = self.tokenizer.encode(continuation, add_special_tokens=False)+        if not prompt_ids or not continuation_ids:+            raise RuntimeError("probe tokenization is empty")+        actor_log_probs = self._actor_probe(prompt_ids, continuation_ids)+        rollout_log_probs = self._rollout_probe(prompt_ids, continuation_ids)+        return {+            "type": "probe_result",+            "policy_version": self.policy_version,+            "rollout_reported_version": self.rollout.report_version(),+            "actor_log_probs": actor_log_probs,+            "rollout_log_probs": rollout_log_probs,+            "continuation_token_ids": [int(value) for value in continuation_ids],+        }++    @torch.no_grad()+    def _actor_probe(self, prompt_ids: list[int], continuation_ids: list[int]) -> list[float]:+        """Full-sequence float32 scoring of the live actor parameters."""+        actor = self.roles.actor+        actor.eval()+        device = self.roles.actor_device+        input_ids = torch.tensor([prompt_ids + continuation_ids], dtype=torch.long, device=device)+        logits = actor(input_ids=input_ids, use_cache=False).logits[0].float()+        selected = []+        for offset, token_id in enumerate(continuation_ids):+            position = len(prompt_ids) - 1 + offset+            selected.append(+                float(torch.log_softmax(logits[position], dim=-1)[int(token_id)].item())+            )+        return selected++    @torch.no_grad()+    def _rollout_probe(self, prompt_ids: list[int], continuation_ids: list[int]) -> list[float]:+        """Incremental-decode scoring through the rollout path.++        The rollout policy holds no weights of its own: it reads the actor's+        live parameters, so this exercises the generation code path against the+        same tensors the actor probe uses.+        """+        actor = self.roles.actor+        actor.eval()+        device = self.roles.actor_device+        prompt = torch.tensor([prompt_ids], dtype=torch.long, device=device)+        outputs = actor(input_ids=prompt, use_cache=True)+        cache = outputs.past_key_values+        logits = outputs.logits[:, -1, :].float()+        selected = []+        for offset, token_id in enumerate(continuation_ids):+            selected.append(+                float(torch.log_softmax(logits[0], dim=-1)[int(token_id)].item())+            )+            if offset + 1 >= len(continuation_ids):+                break+            step = torch.tensor([[int(token_id)]], dtype=torch.long, device=device)+            outputs = actor(input_ids=step, past_key_values=cache, use_cache=True)+            cache = outputs.past_key_values+            logits = outputs.logits[:, -1, :].float()+        del cache+        return selected++    # ------------------------------------------------------------------++    def shutdown(self) -> None:+        self.roles = None+        self.rollout = None+        self.actor_optimizer = None+        self.critic_optimizer = None+++def _cpu_state(state: dict[str, Any]) -> dict[str, Any]:+    return {key: value.detach().to("cpu", copy=True) for key, value in state.items()}+++def _cpu_optimizer_state(state: dict[str, Any]) -> dict[str, Any]:+    moved = {"param_groups": state["param_groups"], "state": {}}+    for key, entry in state["state"].items():+        moved["state"][key] = {+            name: (value.detach().to("cpu", copy=True) if torch.is_tensor(value) else value)+            for name, value in entry.items()+        }+    return moveddiff --git a/verl/trainer/runtime/online_ppo.py b/verl/trainer/runtime/online_ppo.pynew file mode 100644index 0000000000000000000000000000000000000000..50600143a546ab6d81fbbf51ef535a8f507a76b1--- /dev/null+++ b/verl/trainer/runtime/online_ppo.py@@ -0,0 +1,176 @@+# Copyright 2024 Bytedance Ltd. and/or its affiliates+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+#     http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""Framework-owned online PPO runtime entrypoint.++Outer CLI::++    python -B -m verl.trainer.runtime.online_ppo \+        --run-spec PATH --policy-model-path PATH --auxiliary-model-path PATH \+        --tokenizer-path PATH --runtime-dir PATH --result-dir PATH \+        --control-socket PATH++The process connects to the host's Unix stream socket, becomes ``ready`` once+every role is resident on its projected device, performs the fixed PPO work on+the formal prompt projection, answers the host's freshness probe and shuts down+cleanly.++The runtime is deliberately a *single* foreground process: for this workload the+classic Ray + external-inference-engine + sharded-training graph spends most of+its wall clock on process startup, engine initialization, weight transport and+offload/reload traffic rather than on tensor work.  Colocating every role in one+process removes all of that while keeping the workload, the PPO mathematics and+the frozen-role contract unchanged.+"""++from __future__ import annotations++import os++# The allocator flag must be set before the NPU backend initialises.+os.environ.setdefault("PYTORCH_NPU_ALLOC_CONF", "expandable_segments:True")+os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")++import argparse  # noqa: E402+import json  # noqa: E402+import socket  # noqa: E402+import sys  # noqa: E402+import time  # noqa: E402+from pathlib import Path  # noqa: E402+from typing import Any  # noqa: E402++LAUNCH_MONOTONIC = time.monotonic()+++def log(message: str) -> None:+    print(f"[online_ppo +{time.monotonic() - LAUNCH_MONOTONIC:7.2f}s] {message}", flush=True)+++def parse_arguments(argv: list[str] | None = None) -> argparse.Namespace:+    parser = argparse.ArgumentParser(prog="verl.trainer.runtime.online_ppo")+    parser.add_argument("--run-spec", required=True, type=Path)+    parser.add_argument("--policy-model-path", required=True, type=Path)+    parser.add_argument("--auxiliary-model-path", required=True, type=Path)+    parser.add_argument("--tokenizer-path", required=True, type=Path)+    parser.add_argument("--runtime-dir", required=True, type=Path)+    parser.add_argument("--result-dir", required=True, type=Path)+    parser.add_argument("--control-socket", required=True, type=Path)+    return parser.parse_args(argv)+++class ControlChannel:+    """One compact JSON object per line over the host's Unix stream socket."""++    def __init__(self, path: Path, timeout: float = 600.0):+        deadline = time.monotonic() + timeout+        last: OSError | None = None+        while time.monotonic() < deadline:+            connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+            try:+                connection.connect(str(path))+            except OSError as error:  # host may not have bound yet+                connection.close()+                last = error+                time.sleep(0.05)+                continue+            self._connection = connection+            self._buffer = bytearray()+            return+        raise RuntimeError(f"could not connect to the host control socket: {last}")++    def send(self, value: dict[str, Any]) -> None:+        payload = json.dumps(value, allow_nan=False, separators=(",", ":")).encode("utf-8")+        self._connection.sendall(payload + b"\n")++    def receive(self) -> dict[str, Any]:+        while b"\n" not in self._buffer:+            chunk = self._connection.recv(65536)+            if not chunk:+                raise RuntimeError("host control connection closed")+            self._buffer.extend(chunk)+        line, _, rest = bytes(self._buffer).partition(b"\n")+        self._buffer = bytearray(rest)+        value = json.loads(line)+        if not isinstance(value, dict) or not isinstance(value.get("type"), str):+            raise RuntimeError("host control message is invalid")+        return value++    def close(self) -> None:+        try:+            self._connection.close()+        except OSError:+            pass+++def main(argv: list[str] | None = None) -> int:+    arguments = parse_arguments(argv)+    spec = json.loads(arguments.run_spec.read_text(encoding="utf-8"))+    channel = ControlChannel(arguments.control_socket)+    log(f"connected to host control socket; action={spec.get('action')}")+    try:+        from ._runner import OnlinePPORunner++        runner = OnlinePPORunner(+            spec=spec,+            policy_model_path=arguments.policy_model_path,+            auxiliary_model_path=arguments.auxiliary_model_path,+            tokenizer_path=arguments.tokenizer_path,+            runtime_dir=arguments.runtime_dir,+            result_dir=arguments.result_dir,+            log=log,+        )+        runner.prepare()+        channel.send({"type": "ready"})+        log("ready")++        request = channel.receive()+        if request.get("type") != "start":+            raise RuntimeError(f"unexpected host request before start: {request.get('type')}")+        runner.run(+            input_path=Path(request["input_path"]),+            sampling_seed=int(request["sampling_seed"]),+        )+        channel.send({"type": "completed"})+        log("completed")++        while True:+            request = channel.receive()+            kind = request.get("type")+            if kind == "probe":+                channel.send(runner.probe(request))+                log("answered freshness probe")+            elif kind == "shutdown":+                log("shutdown requested")+                break+            else:+                raise RuntimeError(f"unexpected host request: {kind}")+        runner.shutdown()+    finally:+        channel.close()+    log("exiting")+    return 0+++if __name__ == "__main__":+    try:+        code = main()+    except BaseException:  # noqa: BLE001 - always surface the traceback+        import traceback++        traceback.print_exc()+        sys.stdout.flush()+        sys.stderr.flush()+        os._exit(1)+    sys.stdout.flush()+    sys.stderr.flush()+    os._exit(code)