Inspect · Source & workspace
Requested workspace inspection and file and log inspection related to source & workspace.
1 call · #0001–#0001
echo <val>ls -l -a <path> <n> > <path>head -n <n>Claude Fable 5.1 · RL
OpenBuild Qwen3-1.7B online GRPO 2dev · Open Build
01 / PROCESS MAP
Each row shows one agent’s tool events in its own recorded order. Colors show broad activities; bar widths do not represent duration.
Main agentClaude Fable 5.1 · 136 visible calls
02 / EVENT SEQUENCE
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.
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>.
Requested workspace inspection and file and log inspection related to source & workspace.
1 call · #0001–#0001
echo <val>ls -l -a <path> <n> > <path>head -n <n>Requested file and log inspection related to task requirements.
2 calls · #0002–#0003
cat <path>Requested workspace inspection and file and log inspection related to source & workspace.
2 calls · #0004–#0005
ls <flag> <args>head -n <n>cat <val>echo <flag>ls -l -a <val>find <val> -type <val>wc -lRequested workspace inspection and file and log inspection related to device memory.
1 call · #0006–#0006
ls -l -a <path> <n> >& <path>echo <flag>cat <path> <n> >& <path>Requested file and log inspection related to source & workspace.
1 call · #0007–#0007
cd <val>echo <path>cat <path>echoRequested file and log inspection related to benchmark & validation setup.
1 call · #0008–#0008
cd <path><command> <args>cat <val>echoRequested file and log inspection related to source & workspace.
1 call · #0009–#0009
cd <path><command> <args>cat <val>echoRequested file and log inspection related to task requirements.
2 calls · #0010–#0011
cd <path><command> <args>cat <val>echoRequested file and log inspection related to source & workspace.
1 call · #0012–#0012
sed -n <val> <path>Requested runtime inspection, file and log inspection and workspace inspection related to device memory.
1 call · #0013–#0013
echo <val><command> <args>uname -aecho <path>free -ghead <flag>ls -l -a <path> <path> <path> <path> <n> >& <path>head -n <n>df -henvgrep -i -E <val>sortRequested script or workload execution and file and log inspection related to attention kernels.
1 call · #0014–#0014
echo <val>which -a <val> <val>python3 -V<command> <args>head <flag>echo <path>python3 -c <script> <n> >& <path>head -n <n>Requested workspace inspection, file and log inspection and dependency and build commands related to checkpoints & weight state.
1 call · #0015–#0015
echo <val>find <path> -maxdepth <n> -iname <val> <flag> <args>head -n <n>echo <path>ls -l -a <path> <n> > <path>echo <flag>headls <path> <n> > <path>cat <path> <n> > <path>pip <val> <val> <n> > <path>Requested file and log inspection related to source & workspace.
4 calls · #0016–#0019
sed -n <val> <path>wc -l <path>Requested environment setup or inspection, workspace inspection and file and log inspection related to checkpoints & weight state.
1 call · #0020–#0020
env <vars>ls -l -a <val>echo <val>cat <path> <n> > <path>head -c <n> <path> <n> > <path>echoRequested script or workload execution and file and log inspection related to attention kernels.
1 call · #0021–#0021
cd <path>timeout <n> <val> -c <path> <n> >& <path>tail -n <n>Requested script or workload execution and file and log inspection related to dependencies & build setup.
1 call · #0022–#0022
python3 -m <module> <val> <n> > <path>sed -n <val>echo <val>python3 -c <script> <n> >& <path>tail -n <n>Requested environment setup or inspection, source searches and file and log inspection related to source & workspace.
1 call · #0023–#0023
envgrep -E <val>sortecho <val>cat <path> <n> > <path>head -n <n>ls -l -a <path> <n> > <path>ls -l -a <val> <n> > <path>Requested file and log inspection, code edits and script or workload execution related to device memory.
1 call · #0024–#0024
cd <path>cat > <path> <script>sed -i <path> <path>timeout <n> <val> <path> > <path> <n> >& <path>env <vars>sleep <n>echo <val>npu-smi info <n> >& <path>tail -n <n>cat <path>wait <val> <n> > <path>Requested script or workload execution and file and log inspection related to source & workspace.
1 call · #0025–#0025
cd <path>timeout <n> <val> -c <path> <n> >& <path>tail -n <n>Requested script or workload execution and file and log inspection related to attention kernels.
1 call · #0026–#0026
cd <path>timeout <n> <val> -c <val> <n> >& <path>tail -n <n>Requested script or workload execution and file and log inspection related to source & workspace.
2 calls · #0027–#0028
cd <path>timeout <n> <val> -c <path> <n> >& <path>tail -n <n><command> <args>echo <val>Requested file and log inspection, environment setup or inspection and source searches related to parallelism & communication.
1 call · #0029–#0029
cd <path>cat > <path> <script>export <vars><command> <args>env <vars> timeout <n> <val> <path>grep -E <val>head -n <n>Requested file and log inspection, environment setup or inspection and source searches related to attention kernels.
1 call · #0030–#0030
cat > <path> <script>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v -E <val>tail -n <n>Requested workspace file updates, file and log inspection and script or workload execution related to reward & policy updates.
1 call · #0031–#0031
mkdir -p <path>cat > <path> <script>echo <val>python3 -c <script>Requested script or workload execution related to task requirements.
1 call · #0032–#0032
cd <path>python3 -c <script>Requested file and log inspection, workspace file updates and workspace inspection related to reward & policy updates.
1 call · #0033–#0033
cd <path>cat > <path> <script>chmod <val> <path> <path> <path>ls -l -aecho <flag>python3 -c <script>Requested workspace file updates, file and log inspection and workspace inspection related to task requirements.
1 call · #0034–#0034
cd <path>touch <path>cat > <path> <script>ls -l -apython3 -m <module> <script> <script> <script> <script>echo <val>Requested file and log inspection, environment setup or inspection and source searches related to reward & policy updates.
1 call · #0035–#0035
cat > <path> <script>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v -E <path>tail -n <n>Requested file and log inspection, environment setup or inspection and source searches related to attention kernels.
1 call · #0036–#0036
cat > <path> <script>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v -E <path>tail -n <n>Requested file and log inspection and script or workload execution related to checkpoints & weight state.
1 call · #0037–#0037
cat > <path> <script>python3 -m <module> <script> <script> <script>echo <val>Requested file and log inspection, environment setup or inspection and source searches related to attention kernels.
1 call · #0038–#0038
cat > <path> <script>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v -E <path>tail -n <n>Requested file and log inspection, workspace file updates and workspace inspection related to optimizer & gradients.
1 call · #0039–#0039
cd <path>cat > <path> <script>chmod <val> <path> <path>ls -l -a <path>sed -i <path> <path>cat <path>Requested file and log inspection and script or workload execution related to source & workspace.
1 call · #0040–#0040
cd <path>cat > <path> <script>python3 -m <module> <script>echo <val>Requested file and log inspection and script or workload execution related to checkpoints & weight state.
1 call · #0041–#0041
cat > <path> <script>python3 -m <module> <script>echo <val>Requested file and log inspection related to source & workspace.
1 call · #0042–#0042
cat <path>Requested file and log inspection, environment setup or inspection and source searches related to attention kernels.
1 call · #0043–#0043
cat > <path> <script>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v -E <path>tail -n <n>Requested script or workload execution, source searches and file and log inspection related to rollout generation.
1 call · #0044–#0044
python3 - <script>python3 -m <module> <script>grep -n <val> <path>headecho <val>Requested file and log inspection and script or workload execution related to runtime processes.
1 call · #0045–#0045
cat > <path> <script>python3 -m <module> <script>echo <val>Requested file and log inspection and script or workload execution related to checkpoints & weight state.
1 call · #0046–#0046
cat > <path> <script>python3 -m <module> <script>echo <val>Requested file and log inspection related to source & workspace.
1 call · #0047–#0047
cat <path>Requested script or workload execution and file and log inspection related to checkpoints & weight state.
1 call · #0048–#0048
python3 - <script>python3 -m <module> <script> <script>echo <val>cd <path>bash <script> <n> >& <path>tail -n <n>Requested workspace inspection and file and log inspection related to source & workspace.
1 call · #0049–#0049
cd <path>echo <val>find <path> -type <val> <flag> <args>sort <flag>awk <path><command> <args>find <path> -type <val>wc -lfind <path> -name <val> -o -name <val>headRequested environment setup or inspection, file and log inspection and workspace inspection related to rollout generation.
1 call · #0050–#0050
env <vars>cat > <path> <script>ls -l -a <val>echo <flag>cat <path>Requested execution waits, environment setup or inspection and file and log inspection related to benchmark & validation setup.
1 call · #0051–#0051
sleep <n>env <vars>echo <val>tail -n <n> <val> <n> > <path>echotail -n <n> <path> <n> > <path>ls -l -a <val> <n> > <path>Requested script or workload execution, source searches and file and log inspection related to parallelism & communication.
1 call · #0052–#0052
cd <path>python3 - <script>python3 -m <module> <script>echo <val>grep -n <val> <path>head -n <n><command> <args>tail -n <n>Requested execution waits, environment setup or inspection and file and log inspection related to device memory.
1 call · #0053–#0053
sleep <n>env <vars>echo <val>tail -n <n> <val> <n> > <path>echotail -n <n> <path> <n> > <path>npu-smi info <n> >& <path>sed -n <path>head -n <n>Requested script or workload execution related to attention kernels.
1 call · #0054–#0054
cd <path>python3 - <script>Requested source searches and file and log inspection related to checkpoints & weight state.
1 call · #0055–#0055
cd <path>echo <val><command> <args>grep -n <val> <val>head -n <n>grep <flag> <args>echogrep -n <val> <path> <path>echo <path>grep -n <val> <path>headgrep -r -n -E <val> <path>grep -n -E <val> <path>Requested environment setup or inspection, file and log inspection and script or workload execution related to benchmark & validation setup.
1 call · #0056–#0056
env <vars>echo <val>cat <val>echopython3 -c <script> <n> >& <path>tail -n <n> <path> <n> > <path>echo <path>grep -E <val> <path> <n> > <path>tail -n <n>Requested script or workload execution and file and log inspection related to checkpoints & weight state.
1 call · #0057–#0057
python3 - <script>python3 -m <module> <script>echo <val>cd <path><command> <args>tail -n <n>Requested script or workload execution related to reward & policy updates.
1 call · #0058–#0058
echo <val>python3 -c <script>echo <path>Requested workspace file updates, workspace inspection and file and log inspection related to benchmark & validation setup.
2 calls · #0059–#0060
rm -rf <path>mkdir -p <path>cp -a <path> <path>find <path> -type <val>wc -lecho <val>cd <path>git status <flag>head -n <n>env <vars><command> <args>sleep <n>tail -c <n> <val> <n> > <path>echogrep -E <val> <path> <n> > <path>tail -n <n>grep -i -E <val> <path> <path> <n> > <path>Requested environment setup or inspection, source searches and file and log inspection related to checkpoints & weight state.
1 call · #0061–#0061
env <vars>echo <val>grep -c <val> <val> <n> > <path>grep -E <val> <path> <n> > <path>tail -n <n>ls <flag> <args>grep -E <val>du <flag> <args>ls -l -a <path> <n> > <path>headgrep -i -l -E <val> <path> <n> > <path>Requested script or workload execution related to source & workspace.
1 call · #0062–#0062
python3 -c <script>Requested environment setup or inspection, execution waits and file and log inspection related to benchmark & validation setup.
2 calls · #0063–#0064
env <vars><command> <args>sleep <n>echo <val>tail -c <n> <val>echogrep -E <val> <path> <n> > <path>tail -n <n>stat -c <val> <path> <path> <n> > <path>grep -c <val> <path> <n> > <path>Requested workspace file updates and script or workload execution related to checkpoints & weight state.
1 call · #0065–#0065
rm -rf <path>mkdir -p <path>cp -a <path> <path>echo <path>python3 -c <script>Requested file and log inspection and script or workload execution related to attention kernels.
1 call · #0066–#0066
cd <path>cat > <path> <script>python3 -m <module> <script>echo <val>Requested script or workload execution, source searches and file and log inspection related to rollout generation.
1 call · #0067–#0067
python3 - <script>python3 -m <module> <script> <script>echo <val>grep -n <val> <path>headRequested file and log inspection, environment setup or inspection and source searches related to attention kernels.
1 call · #0068–#0068
cat > <path> <script>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v -E <path>tail -n <n>Requested environment setup or inspection, execution waits and file and log inspection related to source & workspace.
1 call · #0069–#0069
env <vars><command> <args>sleep <n>echo <val>cat <val> <n> > <path>tail -n <n>Requested script or workload execution, workspace inspection and file and log inspection related to rollout generation.
1 call · #0070–#0070
python3 -c <script>cd <path>echo <path>find <path> -type <val> <flag> <args>awk <path>echo <val><command> <args>echogrep -n <val> <path>sed -n <path> <path>grep -n <val> <path> <path>Requested script or workload execution, environment setup or inspection and source searches related to source & workspace.
2 calls · #0071–#0072
cd <path>python3 - <script>python3 -m <module> <script> <script>echo <val>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v -E <path>tail -n <n>env <vars><command> <args>sleep <n>tail -n <n> <val> <n> > <path>Requested script or workload execution related to batching & scheduling.
1 call · #0073–#0073
cd <path>python3 - <script>Requested workspace file updates, workspace inspection and source searches related to benchmark & validation setup.
2 calls · #0074–#0075
cd <path>cp -a <path> <path>rm -f <path>rm -rf <path> <val>echo <val>find <path> -type <val>sortgrep -r -n <val> <path>grep -c <val> <path>python3 -m <module> <script><command> <args>tail -n <n>env <vars>sleep <n>tail -c <n> <val> <n> > <path>echogrep -E <val> <path> <n> > <path>Requested script or workload execution, workspace inspection and file and log inspection related to source & workspace.
1 call · #0076–#0076
python3 -c <script>cd <path>echo <val>find <path> -type <val> <flag> <args>sort <flag>awk <path>echo <path><command> <args>git status <flag> <args>head -n <n>Requested environment setup or inspection, file and log inspection and script or workload execution related to rollout generation.
1 call · #0077–#0077
env <vars>cat > <path> <script>python3 - <script>ls <flag> <args>echo <flag>cat <path>Requested workspace inspection and workspace file updates related to benchmark & validation setup.
1 call · #0078–#0078
cd <val>echo <val>ls -l -aecho<command> <args>du <flag> <args>rm -rf <val> <val> <val> <val> <val> <val> <val> <val> <val> <val> <args>ls -l -a <val> <n> > <path>Requested file and log inspection, script or workload execution and environment setup or inspection related to reward & policy updates.
1 call · #0079–#0079
cd <path>cat > <path> <script>python3 -m <module> <script>echo <val>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v -E <path>tail -n <n>Requested environment setup or inspection, execution waits and file and log inspection related to source & workspace.
1 call · #0080–#0080
env <vars><command> <args>sleep <n>echo <path>tail -n <n> <val> <n> > <path>Requested script or workload execution related to benchmark & validation setup.
1 call · #0081–#0081
cd <path>python3 - <script>Requested script or workload execution, runtime inspection and source searches related to device memory.
1 call · #0082–#0082
python3 -c <script>echo <path>ps <flag> <args>grep -E <val>grep -v <val>echo <val>npu-smi info <n> >& <path>sed -n <path>head -n <n>ls -l -a <path> <n> > <path>Requested workspace file updates, source searches and file and log inspection related to benchmark & validation setup.
1 call · #0083–#0083
cd <path>rm -f <path>rm -rf <val>echo <val>grep -r -n <val> <path>cd <val>rm -rf <val> <val> <val> <val> <val> <val> <val> <path><command> <args>tail -n <n>echorm -rf <val> <val> <val> <val> <val> <val> <val> <path> <n> > <path>bash <script> > <path> <n> > <path>python3 -c <script>Requested environment setup or inspection, execution waits and file and log inspection related to source & workspace.
1 call · #0084–#0084
env <vars><command> <args>sleep <n>echo <val>cat <val> <n> > <path>tail -n <n>Requested script or workload execution related to source & workspace.
1 call · #0085–#0085
python3 -c <script>Requested workspace inspection, file and log inspection and repository inspection related to source & workspace.
1 call · #0086–#0086
cd <path>echo <val>find <path> -type <val> <flag> <args>sort <flag>awk <path>echo <path><command> <args>git status <flag> <args>git status <flag>awk <val>grep -v <path>Requested source searches, file and log inspection and script or workload execution related to runtime processes.
1 call · #0087–#0087
cd <path>echo <val>grep -r -n <val> <path>echogrep -r -n -E <val> <path>wc -l <path>sort -npython3 -m <module> <script>rm -rf <val>grep -n -E <val> <path>grep -i -E <val>echo <path>Requested environment setup or inspection, source searches and file and log inspection related to benchmark & validation setup.
1 call · #0088–#0088
env <vars>echo <val>grep -c <val> <val> <n> > <path>tail -c <n> <val> <n> > <path>echogrep -E <val> <path> <n> > <path>tail -n <n>ls <flag> <args>Requested environment setup or inspection, script or workload execution and file and log inspection related to checkpoints & weight state.
1 call · #0089–#0089
env <vars>python3 - <script>cat > <path> <script>ls <flag> <args>echo <flag>cat <path>Requested environment setup or inspection, source searches and file and log inspection related to device memory.
1 call · #0090–#0090
env <vars>echo <val>grep -c <val> <val> <n> > <path>truetail -c <n> <val> <n> > <path>echols <flag> <args>npu-smi info <n> >& <path>sed -n <path>grep -E <val>head -n <n>Requested script or workload execution, environment setup or inspection and source searches related to benchmark & validation setup.
2 calls · #0091–#0092
python3 -c <script>env <vars>echo <val>grep -c <val> <val> <n> > <path>truels <flag> <args>tail -c <n> <val> <n> > <path>Requested environment setup or inspection related to reward & policy updates.
1 call · #0093–#0093
cd <path>env <vars> python3 - <script>Requested environment setup or inspection related to checkpoints & weight state.
1 call · #0094–#0094
cd <path>env <vars> python3 - <script>Requested environment setup or inspection, execution waits and source searches related to runtime processes.
1 call · #0095–#0095
cd <path><command> <args>env <vars>sleep <n>grep -F <val>grep -v <val>awk <val>head <flag>echo <val>python3 -c <script> <val> <val> <val>echo <flag>env <vars> bash <script>echo <path>rm -rf <val> <val>rm -rf <val> <path>Requested environment setup or inspection related to reward & policy updates.
1 call · #0096–#0096
cd <path>env <vars> python3 - <script>Requested environment setup or inspection, source searches and workspace inspection related to device memory.
1 call · #0097–#0097
env <vars>echo <val>grep -c <val> <val> <n> > <path>truels <flag> <args>tail -c <n> <val> <n> > <path>npu-smi info <n> >& <path>sed -n <path>grep -E <val>head -n <n>python3 -c <script>Requested environment setup or inspection and workspace file updates related to runtime processes.
1 call · #0098–#0098
cd <path><command> <args>env <vars> python3 - <val> <val> <script>rm -rf <val> <val> <val> <path>Requested environment setup or inspection related to reward & policy updates.
1 call · #0099–#0099
cd <path>env <vars> python3 - <script>Requested environment setup or inspection, source searches and workspace inspection related to benchmark & validation setup.
1 call · #0100–#0100
env <vars>echo <val>grep -c <val> <val> <n> > <path>truels <flag> <args>tail -c <n> <val> <n> > <path>grep -E <val> <path> <n> > <path>tail -n <n>grep <flag> <args>echo <n>python3 -c <script>Requested environment setup or inspection related to task requirements.
1 call · #0101–#0101
cd <path>env <vars> python3 - <script>Requested environment setup or inspection, source searches and workspace inspection related to source & workspace.
1 call · #0102–#0102
env <vars>echo <val>grep -c <val> <val> <n> > <path>truels <flag> <args>sed -n <path> <val> <n> > <path>tail -n <n>python3 -c <script>Requested environment setup or inspection related to reward & policy updates.
1 call · #0103–#0103
cd <path>env <vars> python3 - <script>Requested environment setup or inspection, source searches and workspace inspection related to device memory.
1 call · #0104–#0104
env <vars>echo <val>grep -c <val> <val> <n> > <path>truels <flag> <args>sed -n <path> <val> <n> > <path>tail -n <n>npu-smi info <n> >& <path>sed -n <path>grep -E <val>head -n <n>python3 -c <script>Requested file and log inspection and script or workload execution related to reward & policy updates.
1 call · #0105–#0105
cat > <path> <script>cd <path>timeout <n> <val> <path> <val> <n> >& <path>tail -n <n>Requested environment setup or inspection, execution waits and file and log inspection related to reward & policy updates.
1 call · #0106–#0106
env <vars><command> <args>sleep <n>echo <val>cat <val> <n> > <path>tail -n <n>echogrep -E <val> <path> <n> > <path>Requested environment setup or inspection related to reward & policy updates.
1 call · #0107–#0107
cd <path>env <vars> python3 - <script>Requested environment setup or inspection, source searches and file and log inspection related to device memory.
1 call · #0108–#0108
env <vars>echo <val>grep -c <val> <val> <n> > <path>truetail -c <n> <val> <n> > <path>echogrep -E <val> <path> <n> > <path>tail -n <n>npu-smi info <n> >& <path>sed -n <path>grep -E <val>head -n <n>python3 -c <script>Requested script or workload execution related to benchmark & validation setup.
1 call · #0109–#0109
cd <path>python3 - <script>Requested environment setup or inspection related to checkpoints & weight state.
1 call · #0110–#0110
cd <path>env <vars> python3 - <script>Requested environment setup or inspection and file and log inspection related to benchmark & validation setup.
1 call · #0111–#0111
env <vars>echo <val>cat <val> <n> > <path>tail -n <n>Requested script or workload execution and file and log inspection related to benchmark & validation setup.
1 call · #0112–#0112
timeout <n> <val> <path> <val> <n> >& <path>tail -n <n>Requested script or workload execution related to checkpoints & weight state.
1 call · #0113–#0113
python3 -c <script>Requested workspace inspection, file and log inspection and repository inspection related to source & workspace.
1 call · #0114–#0114
cd <path>echo <val>find <path> -type <val> <flag> <args>sort <flag>awk <path>echo <path><command> <args>git status <flag> <args>git status <flag>awk <val>grep -v <path>truesed <path>Requested environment setup or inspection, file and log inspection and workspace inspection related to checkpoints & weight state.
1 call · #0115–#0115
env <vars>cat > <path> <script>ls <flag> <args>echo <flag>cat <path>Requested environment setup or inspection, source searches and file and log inspection related to device memory.
1 call · #0116–#0116
env <vars>echo <val>grep -c <val> <val> <n> > <path>truetail -c <n> <val> <n> > <path>echogrep -E <val> <path> <n> > <path>tail -n <n>grep <flag> <args>echo <n>npu-smi info <n> >& <path>sed -n <path>grep -E <val>head -n <n>python3 -c <script>Requested environment setup or inspection related to checkpoints & weight state.
1 call · #0117–#0117
cd <path>env <vars> python3 - <script>Requested environment setup or inspection, execution waits and file and log inspection related to checkpoints & weight state.
2 calls · #0118–#0119
env <vars><command> <args>sleep <n>echo <val>cat <val> <n> > <path>tail -n <n>echogrep -E <val> <path> <n> > <path>grep -c <val> <val> <n> > <path>truetail -c <n> <val> <n> > <path>echo <path>du <flag> <args>npu-smi info <n> >& <path>sed -n <path>grep -E <val>head -n <n>python3 -c <script>Requested file and log inspection and source searches related to checkpoints & weight state.
1 call · #0120–#0120
cd <path>echo <val>sed -n <path> <path>echogrep -n <val> <path> <path>grep -n <val> <path> <path> <n> > <path>head -n <n>Requested environment setup or inspection related to checkpoints & weight state.
1 call · #0121–#0121
cd <path>env <vars> python3 - <script>Requested environment setup or inspection, source searches and file and log inspection related to reward & policy updates.
1 call · #0122–#0122
env <vars>echo <val>grep -c <val> <val> <n> > <path>truetail -c <n> <val> <n> > <path>echogrep -E <val> <path> <n> > <path>tail -n <n>ls -l -a <path> <n> > <path>python3 -c <script>npu-smi info <n> >& <path>sed -n <path>grep -E <val>head -n <n>Requested environment setup or inspection related to reward & policy updates.
1 call · #0123–#0123
cd <path>env <vars> python3 - <script>Requested environment setup or inspection, source searches and file and log inspection related to device memory.
1 call · #0124–#0124
env <vars>echo <val>grep -c <val> <val> <n> > <path>truecat <val> <n> > <path>tail -n <n>npu-smi info <n> >& <path>sed -n <path>grep -E <val>head -n <n>python3 -c <script>Requested workspace inspection, file and log inspection and repository inspection related to source & workspace.
1 call · #0125–#0125
cd <path>echo <val>echo <path>find <path> -type <val> <flag> <args>awk <path><command> <args>find <path> <flag> <args>sortgit status <flag> <args>sed <path>truegit status <flag>awk <val>grep -v <path>Requested environment setup or inspection, execution waits and file and log inspection related to checkpoints & weight state.
1 call · #0126–#0126
env <vars><command> <args>sleep <n>echo <val>cat <val> <n> > <path>tail -n <n>Requested file and log inspection and source searches related to rollout generation.
1 call · #0127–#0127
cd <path>echo <val>sed -n <path> <path>echogrep -n <val> <path>grep -n <path> <path>head -n <n>Requested script or workload execution, workspace inspection and file and log inspection related to device memory.
1 call · #0128–#0128
python3 -c <script>echo <val>ls -l -a <path> <n> > <path>head -n <n>npu-smi info <n> >& <path>sed -n <path>grep -E <val>Requested environment setup or inspection related to reward & policy updates.
1 call · #0129–#0129
cd <path>env <vars> python3 - <script>Requested workspace file updates, workspace inspection and file and log inspection related to device memory.
1 call · #0130–#0130
cd <val>rm -rf <val> <val> <val> <val> <val> <val> <val> <n> > <path>rm -f <path> <path> <path> <n> > <path>echo <val>ls -l -a <path>sed <path>ls -l -a <val> <n> > <path>ps <flag> <args>grep -E <val>grep -v <val>npu-smi info <n> >& <path>sed -n <path>cd <path>Requested script or workload execution related to checkpoints & weight state.
1 call · #0131–#0131
cd <path>python3 - <script>Requested workspace inspection, file and log inspection and script or workload execution related to benchmark & validation setup.
2 calls · #0132–#0133
echo <val>diff -r <path> <path>echocd <path>find <path> -type <val>sortxargs <val>sed <path>python3 -c <script>Requested environment setup or inspection, workspace file updates and workspace inspection related to reward & policy updates.
1 call · #0134–#0134
env <vars>rm -rf <val>mkdir -p <val><command> <args>test -f <path>cp <path> <path>echo <val>ls -l -a <val>sed <path>python3 -c <script>echocd <val>rm -rf <val> <val> <val> <val> <val> <val> <val> <n> > <path>rm -f <path> <path> <path> <n> > <path>rm -f <path> <n> > <path>cd <path>bash <script> > <path> <n> > <path>ls <flag> <args>npu-smi info <n> >& <path>sed -n <path>grep -E <val>Requested workspace inspection, file and log inspection and script or workload execution related to benchmark & validation setup.
1 call · #0135–#0135
echo <val>ls -l -a <path> <n> > <path>sed <path>python3 -c <script>Requested environment setup or inspection, execution waits and file and log inspection related to source & workspace.
1 call · #0136–#0136
env <vars><command> <args>sleep <n>echo <val>cat <val> <n> > <path>tail -n <n>03 / CANDIDATE ARTIFACT
Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
Base commit: d1281fd46aa0575309be1eb6e0fcdc79e4be9670
@@ -0,0 +1,11 @@+#!/usr/bin/env bash+# Offline, idempotent bootstrap.+#+# The delivery is pure Python on top of the base runtime (torch, torch_npu,+# transformers, safetensors, tokenizers). Nothing is installed and the neutral+# base Python surface is deliberately left untouched: bootstrap only verifies+# that the required base modules import and prepares run-owned directories.+set -euo pipefail+cd "${OPENBUILD_SOLUTION_DIR:-$(dirname "$(readlink -f "$0")")}"+mkdir -p "${OPENBUILD_ENV_DIR:?}" "${OPENBUILD_STATE_DIR:?}"+exec python3 -m ob.bootstrap_main@@ -0,0 +1,7 @@+#!/usr/bin/env bash+# Stop every solution-owned worker process group and release declared ports.+# Safe to call repeatedly, including when nothing is running.+set -uo pipefail+cd "${OPENBUILD_SOLUTION_DIR:-$(dirname "$(readlink -f "$0")")}"+python3 -m ob.cleanup_main || true+exit 0@@ -0,0 +1,7 @@+#!/usr/bin/env bash+# Scored entrypoint. Deliberately imports no ML stack: the already-warm+# per-device workers own the model, tokenizer and optimizer, so the timed+# process only drives them over a local socket.+set -euo pipefail+cd "${OPENBUILD_SOLUTION_DIR:-$(dirname "$(readlink -f "$0")")}"+exec python3 -m ob.driver_main "$@"@@ -0,0 +1,13 @@+{+ "schema_version": 1,+ "kind": "openbuild_rl_solution",+ "task_id": "openbuild_rl_qwen3_1_7b_online_grpo_rlvr_2dev_v1",+ "model": "Qwen/Qwen3-1.7B",+ "offline_replay": true,+ "framework": "openbuild-hybrid-grpo: self-contained colocated GRPO/RLVR stack on torch_npu (custom batched rollout sampler, HCCL data-parallel full-parameter actor, FP32 master AdamW)",+ "bootstrap": "bootstrap.sh",+ "prepare": "prepare.sh",+ "execute": "execute.sh",+ "probe": "probe.sh",+ "cleanup": "cleanup.sh"+}@@ -0,0 +1,45 @@+"""Offline bootstrap verification.++Deliberately does not install anything: the delivery is pure Python on top of+the neutral base runtime, and the task requires the base Python surface to be+unchanged by bootstrap.+"""++from __future__ import annotations++import importlib.util+import json+import os+import sys++REQUIRED = ("torch", "torch_npu", "transformers", "safetensors", "tokenizers", "numpy")+++def main() -> int:+ missing = [name for name in REQUIRED if importlib.util.find_spec(name) is None]+ if missing:+ print(+ json.dumps({"status": "failed", "missing_base_modules": missing}, sort_keys=True),+ file=sys.stderr,+ )+ return 1+ for name in ("OPENBUILD_ENV_DIR", "OPENBUILD_STATE_DIR"):+ path = os.environ.get(name)+ if path:+ os.makedirs(path, exist_ok=True)+ print(+ json.dumps(+ {+ "status": "ready",+ "installed": [],+ "base_modules_present": list(REQUIRED),+ "offline": os.environ.get("OPENBUILD_OFFLINE") == "1",+ },+ sort_keys=True,+ )+ )+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())@@ -0,0 +1,91 @@+"""Stop solution-owned worker process groups and release declared ports."""++from __future__ import annotations++import errno+import json+import os+import signal+import socket+import time+from pathlib import Path+++def _state_path() -> Path:+ return Path(os.environ.get("OPENBUILD_STATE_DIR", "/tmp")) / "workers.json"+++def _group_alive(pgid: int) -> bool:+ try:+ os.killpg(pgid, 0)+ except ProcessLookupError:+ return False+ except PermissionError:+ return True+ except OSError as exc:+ return exc.errno != errno.ESRCH+ return True+++def _port_free(port: int) -> bool:+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:+ probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ try:+ probe.bind(("127.0.0.1", port))+ except OSError:+ return False+ return True+++def main() -> int:+ path = _state_path()+ record: dict = {}+ if path.is_file():+ try:+ record = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ record = {}+ pgids = [int(value) for value in record.get("process_group_ids", [])]+ ports = [int(value) for value in record.get("ports", [])]+ for pgid in pgids:+ if _group_alive(pgid):+ try:+ os.killpg(pgid, signal.SIGTERM)+ except OSError:+ pass+ deadline = time.monotonic() + 25.0+ while time.monotonic() < deadline and any(_group_alive(value) for value in pgids):+ time.sleep(0.2)+ for pgid in pgids:+ if _group_alive(pgid):+ try:+ os.killpg(pgid, signal.SIGKILL)+ except OSError:+ pass+ deadline = time.monotonic() + 20.0+ while time.monotonic() < deadline and (+ any(_group_alive(value) for value in pgids)+ or not all(_port_free(value) for value in ports)+ ):+ time.sleep(0.2)+ stopped = not any(_group_alive(value) for value in pgids)+ released = all(_port_free(value) for value in ports)+ if stopped and released:+ path.unlink(missing_ok=True)+ print(+ json.dumps(+ {+ "status": "stopped" if stopped and released else "incomplete",+ "process_groups": pgids,+ "ports": ports,+ "process_groups_stopped": stopped,+ "ports_released": released,+ },+ sort_keys=True,+ )+ )+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())@@ -0,0 +1,345 @@+"""Scored online GRPO/RLVR driver.++This is the process the task times. It imports no ML stack: the warm per-device+workers own the model, the optimizer and the rollout engine, so the timed+interval contains only real online work.++Per update the driver+ 1. derives the published per-request seeds for the current rollout policy,+ 2. fans the prompt groups out across the workers and generates responses,+ 3. scores every response with the task-owned verifier,+ 4. computes group-relative advantages,+ 5. drives one synchronized full-parameter actor update, which is also the+ rollout policy refresh because rollout and training are colocated.+"""++from __future__ import annotations++import argparse+import json+import os+import statistics+import sys+import time+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path++from .gmath import group_advantages, request_seed+from .obio import write_checkpoint_manifest, write_json, write_result, write_trajectories+from .proto import connect+from .reward import RewardClient++RESPONSES_PER_PROMPT = 4+FRESHNESS_TOKENS = 16+OLD_LOGPROB_TOKENS = 16+METRIC_KEYS = ("policy_loss", "approx_kl", "clip_fraction", "global_grad_norm", "parameter_projection")+++def log(message: str) -> None:+ print(f"[driver] {message}", file=sys.stderr, flush=True)+++class Driver:+ def __init__(self, output_dir: Path):+ self.output_dir = output_dir+ state_dir = Path(os.environ["OPENBUILD_STATE_DIR"])+ inventory = json.loads((state_dir / "workers.json").read_text(encoding="utf-8"))+ self.worker_ports = inventory["worker_ports"]+ self.device_ids = inventory["device_ids"]+ self.channels = [connect(port) for port in self.worker_ports]+ self.pool = ThreadPoolExecutor(max_workers=max(len(self.channels), 1))+ self.reward = RewardClient(+ os.environ["OPENBUILD_REWARD_URL"], os.environ["OPENBUILD_REWARD_TOKEN"]+ )+ surface = self.channels[0].request({"op": "describe"})+ self.surface = surface+ self.policy_version = int(surface["policy_version"])+ self.committed_update = int(surface["committed_update"])++ # ---------- worker fan-out ----------++ def broadcast(self, payloads: list[dict]) -> list[dict]:+ return list(self.pool.map(lambda pair: pair[0].request(pair[1]), zip(self.channels, payloads)))++ def split(self, items: list) -> list[list]:+ count = len(self.channels)+ size = (len(items) + count - 1) // count+ return [items[index * size : (index + 1) * size] for index in range(count)]++ # ---------- one update ----------++ def run_update(+ self, update: int, prompts: list[dict], base_seed: int, *, capture_old_logprobs: bool = False+ ) -> dict:+ version = self.policy_version+ requests = []+ for prompt in sorted(prompts, key=lambda item: item["ordinal"]):+ for response_ordinal in range(RESPONSES_PER_PROMPT):+ requests.append(+ {+ "prompt_id": prompt["id"],+ "prompt_ordinal": int(prompt["ordinal"]),+ "response_ordinal": response_ordinal,+ "seed": request_seed(+ base_seed, update, version, int(prompt["ordinal"]), response_ordinal+ ),+ "system_prompt": prompt["system_prompt"],+ "question": prompt["question"],+ }+ )+ shards = self.split(requests)+ started = time.monotonic()+ replies = self.broadcast([{"op": "rollout", "requests": shard} for shard in shards])+ records: list[dict] = []+ for shard_index, reply in enumerate(replies):+ for local_index, record in enumerate(reply["records"]):+ record = dict(record)+ record["shard"] = shard_index+ record["local_index"] = local_index+ records.append(record)+ rollout_seconds = time.monotonic() - started++ rewards = self.reward.score([(row["prompt_id"], row["response_text"]) for row in records])+ for row, value in zip(records, rewards, strict=True):+ row["reward"] = float(value)++ grouped: dict[str, list[dict]] = {}+ for row in records:+ grouped.setdefault(row["prompt_id"], []).append(row)+ for rows in grouped.values():+ rows.sort(key=lambda item: item["response_ordinal"])+ for row, advantage in zip(+ rows, group_advantages([row["reward"] for row in rows]), strict=True+ ):+ row["advantage"] = float(advantage)++ # Captured before the actor update so it compares the rollout log+ # probabilities against the actor *before* its update.+ old_logprob_check = None+ if update == 1 or capture_old_logprobs:+ old_logprob_check = self.old_logprob_check(update, records)++ global_tokens = sum(len(row["response_token_ids"]) for row in records)+ payloads = []+ for shard_index in range(len(self.channels)):+ shard = [row for row in records if row["shard"] == shard_index]+ shard.sort(key=lambda item: item["local_index"])+ payloads.append(+ {+ "op": "train",+ "advantages": [row["advantage"] for row in shard],+ "global_tokens": global_tokens,+ }+ )+ train_started = time.monotonic()+ reports = self.broadcast(payloads)+ train_seconds = time.monotonic() - train_started+ self.policy_version = int(reports[0]["policy_version"])+ self.committed_update = update+ projection = self.channels[0].request({"op": "projection"})["parameter_projection"]+ metrics = {+ "policy_loss": reports[0]["policy_loss"],+ "approx_kl": reports[0]["approx_kl"],+ "clip_fraction": reports[0]["clip_fraction"],+ "global_grad_norm": reports[0]["global_grad_norm"],+ "parameter_projection": projection,+ "rollout_seconds": round(rollout_seconds, 3),+ "train_seconds": round(train_seconds, 3),+ "consumed_response_tokens": global_tokens,+ "reward_mean": round(statistics.fmean(row["reward"] for row in records), 4),+ }+ log(+ f"update {update}: rollout {rollout_seconds:.1f}s train {train_seconds:.1f}s "+ f"tokens {global_tokens} reward {metrics['reward_mean']} loss {metrics['policy_loss']:.5f}"+ )+ return {+ "records": records,+ "metrics": metrics,+ "trajectory_version": version,+ "old_logprob_check": old_logprob_check,+ }++ # ---------- evidence ----------++ def old_logprob_check(self, update: int, records: list[dict]) -> dict:+ """Rollout old log probabilities against the actor before its update."""+ row = records[0]+ reply = self.channels[0].request(+ {"op": "actor_logprobs", "index": row["local_index"], "limit": OLD_LOGPROB_TOKENS}+ )+ return {+ "update": update,+ "prompt_id": row["prompt_id"],+ "actor_logprobs": [float(value) for value in reply["logprobs"]],+ "rollout_logprobs": [float(value) for value in row["old_logprobs"][:OLD_LOGPROB_TOKENS]],+ }++ def freshness(self, update: int, records: list[dict]) -> dict:+ """Post-update agreement between the rollout path and the actor path."""+ row = records[0]+ rollout = self.channels[0].request(+ {"op": "rollout_path_logprobs", "index": row["local_index"], "limit": FRESHNESS_TOKENS}+ )+ actor = self.channels[0].request(+ {"op": "actor_logprobs", "index": row["local_index"], "limit": FRESHNESS_TOKENS}+ )+ return {+ "update": update,+ "policy_version": self.policy_version,+ "prompt_id": row["prompt_id"],+ "actor_logprobs": [float(value) for value in actor["logprobs"]],+ "rollout_logprobs": [float(value) for value in rollout["logprobs"]],+ }++ # ---------- lifecycle ----------++ def save_checkpoint(self) -> str | None:+ directory = self.output_dir / "checkpoint"+ replies = self.broadcast([{"op": "save", "directory": str(directory)}] * len(self.channels))+ files: list[str] = []+ for reply in replies:+ files.extend(reply["files"])+ write_checkpoint_manifest(directory, files)+ return "checkpoint/manifest.json"++ def close(self) -> None:+ self.pool.shutdown(wait=False)+ for channel in self.channels:+ channel.close()+++def trajectory_rows(update: int, version: int, records: list[dict]) -> list[dict]:+ rows = []+ for row in records:+ rows.append(+ {+ "update": update,+ "prompt_id": row["prompt_id"],+ "prompt_ordinal": row["prompt_ordinal"],+ "response_ordinal": row["response_ordinal"],+ "request_seed": row["request_seed"],+ "generating_policy_version": version,+ "response_token_ids": row["response_token_ids"],+ "response_text": row["response_text"],+ "old_logprobs": row["old_logprobs"],+ "reward": row["reward"],+ "advantage": row["advantage"],+ }+ )+ rows.sort(key=lambda item: (item["prompt_ordinal"], item["response_ordinal"]))+ return rows+++def main() -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--input-manifest", required=True)+ parser.add_argument("--output-dir", required=True)+ args = parser.parse_args()+ manifest = json.loads(Path(args.input_manifest).read_text(encoding="utf-8"))+ output_dir = Path(args.output_dir)+ output_dir.mkdir(parents=True, exist_ok=True)+ action = os.environ.get("OPENBUILD_ACTION", "measurement")+ restart = manifest.get("kind") == "openbuild_rl_restart_input"+ base_seed = int(manifest["seed"])+ prompts = manifest["prompts"]++ driver = Driver(output_dir)+ try:+ initial_projection = driver.channels[0].request({"op": "projection"})["parameter_projection"]+ observations = {+ "initial": {+ "parameter_projection": initial_projection,+ "policy_version": driver.policy_version,+ "committed_update": driver.committed_update,+ },+ "updates": {},+ "freshness": [],+ "old_logprob_checks": [],+ "logical_parameter_count": int(driver.surface["logical_parameter_count"]),+ "parameter_tensor_count": int(driver.surface["parameter_tensor_count"]),+ "compute_dtype": driver.surface["compute_dtype"],+ "optimizer_state_dtypes": driver.surface["optimizer_state_dtypes"],+ "logical_device_ids": driver.device_ids,+ "world_size": len(driver.channels),+ }+ events: list[dict] = []+ all_rows: list[dict] = []+ consumed = 0++ if restart:+ first = int(manifest["source_checkpoint_update"])+ target = int(manifest["target_update"])+ outcome = driver.run_update(target, prompts, base_seed, capture_old_logprobs=True)+ version = outcome["trajectory_version"]+ rows = trajectory_rows(target, version, outcome["records"])+ all_rows.extend(rows)+ consumed = sum(len(row["response_token_ids"]) for row in rows)+ events.append(+ {+ "update": target,+ "trajectory": version,+ "actor_before": first,+ "actor_after": target,+ "rollout_after_sync": driver.policy_version,+ "lag": first - version,+ }+ )+ observations["updates"][str(target)] = outcome["metrics"]+ observations["restart"] = {+ "parameter_projection": initial_projection,+ "source_checkpoint_update": first,+ "resumed_policy_version": version,+ }+ observations["old_logprob_checks"].append(outcome["old_logprob_check"])+ observations["freshness"].append(driver.freshness(target, outcome["records"]))+ committed_updates = target+ else:+ total_updates = int(manifest["committed_updates"])+ freshness_updates = {1, total_updates}+ for update in range(1, total_updates + 1):+ outcome = driver.run_update(update, prompts, base_seed)+ version = outcome["trajectory_version"]+ rows = trajectory_rows(update, version, outcome["records"])+ all_rows.extend(rows)+ consumed += sum(len(row["response_token_ids"]) for row in rows)+ events.append(+ {+ "update": update,+ "trajectory": version,+ "actor_before": update - 1,+ "actor_after": update,+ "rollout_after_sync": driver.policy_version,+ "lag": (update - 1) - version,+ }+ )+ observations["updates"][str(update)] = outcome["metrics"]+ if outcome["old_logprob_check"] is not None:+ observations["old_logprob_checks"].append(outcome["old_logprob_check"])+ if update in freshness_updates:+ observations["freshness"].append(driver.freshness(update, outcome["records"]))+ committed_updates = total_updates++ checkpoint_path = None+ if action == "correctness" and not restart:+ checkpoint_path = driver.save_checkpoint()++ write_trajectories(output_dir / "trajectories.jsonl", all_rows)+ write_json(output_dir / "observations.json", observations)+ write_result(+ output_dir / "result.json",+ action="restart" if restart else action,+ committed_updates=committed_updates,+ accepted_trajectories=len(all_rows),+ consumed_response_tokens=consumed,+ logical_device_ids=driver.device_ids,+ policy_versions=events,+ checkpoint_manifest_path=checkpoint_path,+ )+ log(f"completed {committed_updates} updates, {len(all_rows)} trajectories, {consumed} tokens")+ finally:+ driver.close()+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())@@ -0,0 +1,109 @@+"""Reference GRPO/RLVR mathematics.++Pure-Python, dependency-free implementations of the published contract+mathematics. The same helpers back both the fixed-trajectory algorithm probe+and the online trainer so that the two can never disagree.++Conventions follow the published contract exactly:++* group advantages use *sample* standard deviation (``statistics.stdev``,+ ddof=1) with an additive epsilon, and collapse to zeros when the group+ reward standard deviation is exactly zero;+* the policy loss is the token-mean clipped surrogate with no critic, no+ reference KL and no entropy bonus;+* ``approx_kl`` is the k3 estimator ``exp(-log_ratio) + log_ratio - 1``;+* ``clip_fraction`` counts tokens whose ratio leaves ``[1-low, 1+high]``.+"""++from __future__ import annotations++import math+import statistics+from typing import Iterable, Sequence++GROUP_EPSILON = 1e-6+CLIP_LOW = 0.2+CLIP_HIGH = 0.2+++def group_advantages(rewards: Sequence[float], epsilon: float = GROUP_EPSILON) -> list[float]:+ """Group-relative advantages for one prompt group."""+ values = [float(value) for value in rewards]+ mean = statistics.fmean(values)+ std = statistics.stdev(values)+ if std == 0:+ return [0.0] * len(values)+ return [(value - mean) / (std + epsilon) for value in values]+++def token_terms(+ advantage: float,+ old_logprobs: Iterable[float],+ current_logprobs: Iterable[float],+ clip_low: float = CLIP_LOW,+ clip_high: float = CLIP_HIGH,+) -> tuple[list[float], list[float], list[float]]:+ """Per-token (loss, approx_kl, clipped) terms for one response."""+ losses: list[float] = []+ kls: list[float] = []+ clipped: list[float] = []+ for old, current in zip(old_logprobs, current_logprobs, strict=True):+ log_ratio = float(current) - float(old)+ ratio = math.exp(log_ratio)+ unclipped = ratio * advantage+ bounded = min(max(ratio, 1.0 - clip_low), 1.0 + clip_high) * advantage+ losses.append(-min(unclipped, bounded))+ kls.append(math.exp(-log_ratio) + log_ratio - 1.0)+ clipped.append(1.0 if ratio < 1.0 - clip_low or ratio > 1.0 + clip_high else 0.0)+ return losses, kls, clipped+++def probe_result(probe: dict) -> dict:+ """Evaluate the fixed-trajectory algorithm probe."""+ epsilon = float(probe["group_normalization_epsilon"])+ low = float(probe["clip_ratio_low"])+ high = float(probe["clip_ratio_high"])+ grouped: list[list[float]] = []+ losses: list[float] = []+ kls: list[float] = []+ clipped: list[float] = []+ for group in probe["groups"]:+ advantages = group_advantages(group["rewards"], epsilon)+ grouped.append(advantages)+ for advantage, old_row, current_row in zip(+ advantages, group["old_logprobs"], group["current_logprobs"], strict=True+ ):+ if not old_row or len(old_row) != len(current_row):+ raise ValueError("algorithm probe logprob rows are invalid")+ row_losses, row_kls, row_clipped = token_terms(+ advantage, old_row, current_row, low, high+ )+ losses.extend(row_losses)+ kls.extend(row_kls)+ clipped.extend(row_clipped)+ return {+ "schema_version": 1,+ "kind": "openbuild_rl_algorithm_probe_result",+ "probe_id": probe["probe_id"],+ "advantages": grouped,+ "policy_loss": statistics.fmean(losses),+ "approx_kl": statistics.fmean(kls),+ "clip_fraction": statistics.fmean(clipped),+ }+++def request_seed(+ base_seed: int,+ update: int,+ policy_version: int,+ prompt_ordinal: int,+ response_ordinal: int,+) -> int:+ """Published per-request seed derivation."""+ return (+ int(base_seed)+ + int(update) * 100000+ + int(policy_version) * 10000+ + int(prompt_ordinal) * 4+ + int(response_ordinal)+ )@@ -0,0 +1,100 @@+"""Output artifact writers for the scored run."""++from __future__ import annotations++import json+import os+from pathlib import Path+from typing import Any, Iterable++TASK_ID = "openbuild_rl_qwen3_1_7b_online_grpo_rlvr_2dev_v1"++TRAJECTORY_FIELDS = (+ "update",+ "prompt_id",+ "prompt_ordinal",+ "response_ordinal",+ "request_seed",+ "generating_policy_version",+ "response_token_ids",+ "response_text",+ "old_logprobs",+ "reward",+ "advantage",+)+++def _atomic_write(path: Path, text: str) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ temporary = path.with_name(path.name + ".tmp")+ with temporary.open("w", encoding="utf-8") as handle:+ handle.write(text)+ handle.flush()+ os.fsync(handle.fileno())+ temporary.replace(path)+++def write_json(path: Path, value: dict[str, Any]) -> None:+ _atomic_write(path, json.dumps(value, allow_nan=False, indent=2, sort_keys=True) + "\n")+++def write_trajectories(path: Path, rows: Iterable[dict[str, Any]]) -> None:+ lines = []+ for row in rows:+ record = {name: row[name] for name in TRAJECTORY_FIELDS}+ lines.append(json.dumps(record, allow_nan=False, separators=(",", ":"), sort_keys=True))+ _atomic_write(path, "\n".join(lines) + "\n")+++def write_result(+ path: Path,+ *,+ action: str,+ committed_updates: int,+ accepted_trajectories: int,+ consumed_response_tokens: int,+ logical_device_ids: list[int],+ policy_versions: list[dict[str, int]],+ checkpoint_manifest_path: str | None,+) -> None:+ write_json(+ path,+ {+ "schema_version": 1,+ "kind": "openbuild_rl_result",+ "task_id": TASK_ID,+ "status": "completed",+ "action": action,+ "committed_updates": int(committed_updates),+ "accepted_trajectories": int(accepted_trajectories),+ "consumed_response_tokens": int(consumed_response_tokens),+ "logical_device_ids": [int(value) for value in logical_device_ids],+ "policy_versions": policy_versions,+ "trajectory_path": "trajectories.jsonl",+ "observation_path": "observations.json",+ "checkpoint_manifest_path": checkpoint_manifest_path,+ },+ )+++def write_checkpoint_manifest(root: Path, files: list[str]) -> None:+ write_json(+ root / "manifest.json",+ {+ "schema_version": 1,+ "kind": "openbuild_rl_checkpoint",+ "task_id": TASK_ID,+ "committed_update": 8,+ "next_update": 9,+ "state_components": [+ "model",+ "optimizer",+ "scheduler",+ "committed_update",+ "policy_version",+ "data_cursor",+ "rng",+ ],+ "files": sorted(files),+ },+ )@@ -0,0 +1,126 @@+"""Untimed preparation: start the device workers, warm them, report ready.++Everything expensive lives here so that the scored ``execute.sh`` process does+no model loading, no tokenizer loading and no kernel compilation. The workers+outlive this process; their process groups and ports are declared in+``ready.json`` so the task can verify that ``cleanup.sh`` reclaims them.+"""++from __future__ import annotations++import json+import os+import subprocess+import sys+import time+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path++from .proto import connect++WARMUP_SEQUENCES = 16+++def log(message: str) -> None:+ print(f"[prepare] {message}", file=sys.stderr, flush=True)+++def main() -> int:+ solution_dir = Path(os.environ.get("OPENBUILD_SOLUTION_DIR", ".")).resolve()+ state_dir = Path(os.environ["OPENBUILD_STATE_DIR"])+ state_dir.mkdir(parents=True, exist_ok=True)+ port_base = int(os.environ["OPENBUILD_PORT_BASE"])+ devices = [value for value in os.environ.get("OPENBUILD_DEVICE_IDS", "0").split(",") if value]+ world_size = max(len(devices), 1)+ worker_ports = [port_base + index for index in range(world_size)]+ store_port = port_base + world_size+ for stale in state_dir.glob("worker-*.ready"):+ stale.unlink(missing_ok=True)++ environment = dict(os.environ)+ environment["PYTHONUNBUFFERED"] = "1"+ environment.setdefault("PYTORCH_NPU_ALLOC_CONF", "expandable_segments:True")+ processes = []+ for rank in range(world_size):+ process = subprocess.Popen(+ [+ sys.executable,+ "-m",+ "ob.worker",+ "--rank",+ str(rank),+ "--world-size",+ str(world_size),+ "--port",+ str(worker_ports[rank]),+ "--store-port",+ str(store_port),+ ],+ cwd=str(solution_dir),+ env=environment,+ stdin=subprocess.DEVNULL,+ stdout=sys.stderr.fileno(),+ stderr=sys.stderr.fileno(),+ start_new_session=True,+ )+ processes.append(process)+ log(f"launched rank {rank} pid {process.pid} port {worker_ports[rank]}")++ # Record the worker inventory immediately so cleanup can reclaim the+ # process groups even if preparation later fails.+ inventory = {+ "process_group_ids": [process.pid for process in processes],+ "ports": sorted({*worker_ports, store_port}),+ "worker_ports": worker_ports,+ "store_port": store_port,+ "world_size": world_size,+ "device_ids": [int(value) for value in devices] or [0],+ }+ (state_dir / "workers.json").write_text(json.dumps(inventory, sort_keys=True) + "\n", encoding="utf-8")++ deadline = time.monotonic() + 780.0+ for rank, process in enumerate(processes):+ marker = state_dir / f"worker-{rank}.ready"+ while time.monotonic() < deadline and not marker.is_file():+ if process.poll() is not None:+ raise SystemExit(f"worker rank {rank} exited with {process.returncode}")+ time.sleep(0.1)+ if not marker.is_file():+ raise SystemExit(f"worker rank {rank} did not become ready in time")++ channels = [connect(port) for port in worker_ports]+ try:+ for rank, channel in enumerate(channels):+ channel.request({"op": "ping"})+ log(f"rank {rank} responding")+ started = time.monotonic()+ with ThreadPoolExecutor(max_workers=len(channels)) as pool:+ reports = list(+ pool.map(+ lambda channel: channel.request({"op": "warmup", "batch": WARMUP_SEQUENCES}),+ channels,+ )+ )+ log(f"warmup complete in {time.monotonic() - started:.1f}s: {reports}")+ describe = channels[0].request({"op": "describe"})+ log(f"model surface: {describe}")+ finally:+ for channel in channels:+ channel.close()++ ready = {+ "status": "ready",+ "process_group_ids": inventory["process_group_ids"],+ "ports": inventory["ports"],+ "world_size": world_size,+ "logical_device_ids": inventory["device_ids"],+ "worker_ports": worker_ports,+ }+ path = state_dir / "ready.json"+ path.write_text(json.dumps(ready, indent=2, sort_keys=True) + "\n", encoding="utf-8")+ log(f"ready: {ready}")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())@@ -0,0 +1,32 @@+"""Fixed-trajectory algorithm probe entrypoint."""++from __future__ import annotations++import argparse+import json+from pathlib import Path++from .gmath import probe_result+++def main() -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--input-manifest", required=True)+ parser.add_argument("--output", required=True)+ args = parser.parse_args()+ probe = json.loads(Path(args.input_manifest).read_text(encoding="utf-8"))+ if probe.get("kind") != "openbuild_rl_algorithm_probe" or probe.get("schema_version") != 1:+ raise SystemExit("algorithm probe identity is invalid")+ result = probe_result(probe)+ output = Path(args.output)+ output.parent.mkdir(parents=True, exist_ok=True)+ output.write_text(+ json.dumps(result, allow_nan=False, indent=2, sort_keys=True) + "\n",+ encoding="utf-8",+ )+ print(json.dumps({"probe_id": result["probe_id"], "status": "completed"}, sort_keys=True))+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())@@ -0,0 +1,57 @@+"""Newline-delimited JSON framing over a local stream socket."""++from __future__ import annotations++import json+import socket+++class Channel:+ """Length-agnostic newline-delimited JSON channel."""++ def __init__(self, sock: socket.socket):+ self.sock = sock+ self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)+ self._reader = sock.makefile("rb")++ def send(self, payload: dict) -> None:+ line = json.dumps(payload, allow_nan=False, separators=(",", ":")).encode("utf-8")+ self.sock.sendall(line + b"\n")++ def receive(self) -> dict:+ line = self._reader.readline()+ if not line:+ raise ConnectionError("worker channel closed")+ return json.loads(line)++ def request(self, payload: dict) -> dict:+ self.send(payload)+ reply = self.receive()+ if reply.get("status") != "ok":+ raise RuntimeError(f"worker error: {reply.get('error')}\n{reply.get('traceback', '')}")+ return reply++ def close(self) -> None:+ try:+ self._reader.close()+ finally:+ try:+ self.sock.close()+ except OSError:+ pass+++def connect(port: int, timeout: float = 600.0) -> Channel:+ import time++ deadline = time.monotonic() + timeout+ last: Exception | None = None+ while time.monotonic() < deadline:+ try:+ sock = socket.create_connection(("127.0.0.1", port), timeout=30.0)+ sock.settimeout(None)+ return Channel(sock)+ except OSError as exc:+ last = exc+ time.sleep(0.1)+ raise ConnectionError(f"unable to reach worker on port {port}: {last}")@@ -0,0 +1,43 @@+"""Client for the task-owned verifier reward service."""++from __future__ import annotations++import json+import urllib.error+import urllib.request+++class RewardClient:+ def __init__(self, url: str, token: str, timeout: float = 120.0):+ self.url = url.rstrip("/") + "/score_batch"+ self.token = token+ self.timeout = timeout++ def score(self, items: list[tuple[str, str]]) -> list[float]:+ """Score (prompt_id, response_text) pairs, preserving request order."""+ if not items:+ return []+ payload = json.dumps(+ {"items": [{"prompt_id": pid, "response_text": text} for pid, text in items]}+ ).encode("utf-8")+ request = urllib.request.Request(+ self.url,+ data=payload,+ headers={+ "Authorization": f"Bearer {self.token}",+ "Content-Type": "application/json",+ },+ method="POST",+ )+ last: Exception | None = None+ for _ in range(3):+ try:+ with urllib.request.urlopen(request, timeout=self.timeout) as response:+ body = json.loads(response.read())+ rewards = body["rewards"]+ if not isinstance(rewards, list) or len(rewards) != len(items):+ raise ValueError("reward service returned an unexpected batch size")+ return [float(value) for value in rewards]+ except (urllib.error.URLError, TimeoutError, ValueError, KeyError) as exc:+ last = exc+ raise RuntimeError(f"reward service call failed: {last}")@@ -0,0 +1,61 @@+"""Seeded top-k / top-p sampling.++Every response has its own published request seed, so randomness is drawn from+one CPU generator per sequence (one uniform per decode step) and applied on the+device with a batched inverse-CDF over the truncated distribution. This keeps+per-request reproducibility while leaving the heavy work batched.+"""++from __future__ import annotations++import torch+++def build_generators(seeds: list[int]) -> list[torch.Generator]:+ generators = []+ for seed in seeds:+ generator = torch.Generator(device="cpu")+ generator.manual_seed(int(seed) & 0x7FFFFFFFFFFFFFFF)+ generators.append(generator)+ return generators+++def step_uniforms(generators: list[torch.Generator]) -> torch.Tensor:+ return torch.stack(+ [torch.rand(1, generator=generator, dtype=torch.float32)[0] for generator in generators]+ )+++def sample_step(+ logits: torch.Tensor,+ uniforms: torch.Tensor,+ *,+ temperature: float,+ top_p: float,+ top_k: int,+) -> tuple[torch.Tensor, torch.Tensor]:+ """Sample one token per row and return (token_ids, logprob_of_token).++ The returned log probability is the log of the *untruncated* softmax over+ the temperature-scaled logits, which is the sampling policy's own log+ probability for the emitted token.+ """+ scaled = logits.float() / float(temperature)+ full_logprobs = torch.log_softmax(scaled, dim=-1)+ k = min(int(top_k), scaled.shape[-1])+ values, indices = torch.topk(scaled, k, dim=-1)+ probs = torch.softmax(values, dim=-1)+ cumulative = probs.cumsum(dim=-1)+ keep = (cumulative - probs) < float(top_p)+ keep[..., 0] = True+ probs = probs * keep+ probs = probs / probs.sum(dim=-1, keepdim=True)+ cumulative = probs.cumsum(dim=-1)+ cumulative[..., -1] = 1.0+ position = torch.searchsorted(+ cumulative.contiguous(), uniforms.to(cumulative.device).unsqueeze(-1).contiguous()+ )+ position = position.clamp_(max=k - 1)+ tokens = indices.gather(-1, position).squeeze(-1)+ logprobs = full_logprobs.gather(-1, tokens.unsqueeze(-1)).squeeze(-1)+ return tokens, logprobs@@ -0,0 +1,700 @@+"""Per-device rollout + training worker.++One worker owns one Ascend logical device. It holds the BF16 policy used for+both rollout and training (colocated, so a committed actor update *is* the+rollout refresh) plus the FP32 master parameters and FP32 AdamW state.++The scored driver process never imports torch: it drives these workers over a+local socket, so model load, tokenizer load, kernel warmup and NPU graph+capture all happen in the untimed prepare phase.+"""++from __future__ import annotations++import argparse+import json+import os+import socket+import sys+import traceback+from pathlib import Path++import torch+import torch_npu # noqa: F401 (registers the NPU backend)+import torch.distributed as dist++from .gmath import CLIP_HIGH, CLIP_LOW+from .proto import Channel+from .sampler import build_generators, sample_step, step_uniforms++TEMPERATURE = 0.7+TOP_P = 0.8+TOP_K = 20+MAX_RESPONSE_TOKENS = 256+LEARNING_RATE = 1e-6+WEIGHT_DECAY = 0.01+BETAS = (0.9, 0.999)+CLIP_GRAD = 1.0+MICRO_SEQUENCES = 8+LOGIT_CHUNK = 4096+ALLREDUCE_BUCKET_ELEMENTS = 64 * 1024 * 1024+++def log(message: str) -> None:+ print(f"[worker] {message}", file=sys.stderr, flush=True)+++class Worker:+ def __init__(self, rank: int, world_size: int, port: int, store_port: int):+ self.rank = rank+ self.world_size = world_size+ self.port = port+ self.store_port = store_port+ self.device = f"npu:{rank}"+ torch.npu.set_device(rank)+ self.model_path = os.environ["OPENBUILD_MODEL_PATH"]+ self.tokenizer_path = os.environ.get("OPENBUILD_TOKENIZER_PATH") or self.model_path+ self.eos_ids: set[int] = set()+ self.last_rollout: list[dict] = []+ self.committed_update = 0+ self.policy_version = 0+ self.data_cursor = 0+ self._load()++ # ---------- setup ----------++ def _load(self) -> None:+ from transformers import AutoTokenizer, Qwen3ForCausalLM++ self.tokenizer = AutoTokenizer.from_pretrained(+ self.tokenizer_path, local_files_only=True, trust_remote_code=True+ )+ model = Qwen3ForCausalLM.from_pretrained(+ self.model_path,+ dtype=torch.bfloat16,+ attn_implementation="sdpa",+ local_files_only=True,+ )+ self.model = model.to(self.device)+ self.model.eval()+ self.model.config.use_cache = True+ self.params = [p for p in self.model.parameters() if p.requires_grad]+ self.pad_id = self.tokenizer.pad_token_id+ if self.pad_id is None:+ self.pad_id = self.tokenizer.eos_token_id+ eos = self.tokenizer.eos_token_id+ generation = getattr(self.model, "generation_config", None)+ candidates = []+ if isinstance(eos, int):+ candidates.append(eos)+ if generation is not None and generation.eos_token_id is not None:+ value = generation.eos_token_id+ candidates.extend(value if isinstance(value, (list, tuple)) else [value])+ self.eos_ids = {int(value) for value in candidates}+ # FP32 master parameters and FP32 AdamW state.+ self.master = [p.detach().float().clone() for p in self.params]+ for tensor in self.master:+ tensor.requires_grad_(True)+ self.optimizer = torch.optim.AdamW(+ self.master,+ lr=LEARNING_RATE,+ weight_decay=WEIGHT_DECAY,+ betas=BETAS,+ eps=1e-8,+ foreach=True,+ )+ self.scratch = torch.zeros(ALLREDUCE_BUCKET_ELEMENTS, dtype=torch.float32, device=self.device)+ if self.world_size > 1:+ dist.init_process_group(+ backend="hccl",+ init_method=f"tcp://127.0.0.1:{self.store_port}",+ rank=self.rank,+ world_size=self.world_size,+ )+ checkpoint = os.environ.get("OPENBUILD_RESTART_CHECKPOINT")+ if checkpoint:+ self._restore(Path(checkpoint))+ log(f"rank {self.rank} loaded on {self.device}")++ # ---------- helpers ----------++ def _prompt_ids(self, system_prompt: str, question: str) -> list[int]:+ text = self.tokenizer.apply_chat_template(+ [+ {"role": "system", "content": system_prompt},+ {"role": "user", "content": question},+ ],+ tokenize=False,+ add_generation_prompt=True,+ enable_thinking=False,+ )+ return list(self.tokenizer(text, add_special_tokens=False)["input_ids"])++ def _left_padded(self, rows: list[list[int]]) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, list[int]]:+ width = max(len(row) for row in rows)+ ids = torch.full((len(rows), width), self.pad_id, dtype=torch.long)+ mask = torch.zeros((len(rows), width), dtype=torch.long)+ offsets = []+ for index, row in enumerate(rows):+ start = width - len(row)+ offsets.append(start)+ ids[index, start:] = torch.tensor(row, dtype=torch.long)+ mask[index, start:] = 1+ ids = ids.to(self.device)+ mask = mask.to(self.device)+ positions = (mask.cumsum(-1) - 1).clamp(min=0)+ return ids, mask, positions, offsets++ def parameter_projection(self) -> float:+ with torch.no_grad():+ total = torch.zeros((), dtype=torch.float64, device=self.device)+ for index, tensor in enumerate(self.params):+ total += float(index + 1) * tensor.detach().float().sum().double()+ return float(total.item())++ # ---------- rollout ----------++ @torch.no_grad()+ def rollout(self, requests: list[dict], max_new_tokens: int = MAX_RESPONSE_TOKENS) -> list[dict]:+ from transformers.cache_utils import DynamicCache++ if not requests:+ self.last_rollout = []+ return []+ prompts = [self._prompt_ids(item["system_prompt"], item["question"]) for item in requests]+ ids, mask, positions, _ = self._left_padded(prompts)+ batch = len(requests)+ generators = build_generators([int(item["seed"]) for item in requests])+ cache = DynamicCache()+ output = self.model(+ input_ids=ids,+ attention_mask=mask,+ position_ids=positions,+ past_key_values=cache,+ use_cache=True,+ )+ logits = output.logits[:, -1]+ tokens: list[list[int]] = [[] for _ in range(batch)]+ logprobs: list[list[float]] = [[] for _ in range(batch)]+ finished = [False] * batch+ step_positions = positions[:, -1:]+ for _ in range(max_new_tokens):+ uniforms = step_uniforms(generators).to(self.device)+ sampled, sampled_logprobs = sample_step(+ logits, uniforms, temperature=TEMPERATURE, top_p=TOP_P, top_k=TOP_K+ )+ token_list = sampled.tolist()+ logprob_list = sampled_logprobs.tolist()+ for index in range(batch):+ if finished[index]:+ continue+ tokens[index].append(int(token_list[index]))+ logprobs[index].append(float(logprob_list[index]))+ if int(token_list[index]) in self.eos_ids:+ finished[index] = True+ if all(finished):+ break+ feed = sampled.unsqueeze(-1)+ mask = torch.cat([mask, torch.ones(batch, 1, dtype=mask.dtype, device=self.device)], -1)+ step_positions = step_positions + 1+ output = self.model(+ input_ids=feed,+ attention_mask=mask,+ position_ids=step_positions,+ past_key_values=cache,+ use_cache=True,+ )+ logits = output.logits[:, -1]+ records = []+ for index, item in enumerate(requests):+ if not tokens[index]:+ # Degenerate guard: a response must carry at least one token.+ tokens[index] = [int(self.tokenizer.eos_token_id)]+ logprobs[index] = [0.0]+ text = self.tokenizer.decode(tokens[index], skip_special_tokens=True)+ records.append(+ {+ "prompt_id": item["prompt_id"],+ "prompt_ordinal": item["prompt_ordinal"],+ "response_ordinal": item["response_ordinal"],+ "request_seed": int(item["seed"]),+ "prompt_ids": prompts[index],+ "response_token_ids": tokens[index],+ "old_logprobs": logprobs[index],+ "response_text": text,+ }+ )+ self.last_rollout = records+ return [+ {+ key: record[key]+ for key in (+ "prompt_id",+ "prompt_ordinal",+ "response_ordinal",+ "request_seed",+ "response_token_ids",+ "old_logprobs",+ "response_text",+ )+ }+ for record in records+ ]++ # ---------- log probabilities ----------++ def _selected_logprobs(+ self, rows: list[dict], *, grad: bool+ ) -> tuple[torch.Tensor, list[int]]:+ """Teacher-forced actor log probabilities for the response tokens."""+ sequences = [list(row["prompt_ids"]) + list(row["response_token_ids"]) for row in rows]+ ids, mask, positions, offsets = self._left_padded(sequences)+ context = torch.enable_grad() if grad else torch.no_grad()+ with context:+ hidden = self.model.model(+ input_ids=ids, attention_mask=mask, position_ids=positions+ ).last_hidden_state+ gather_rows: list[int] = []+ gather_cols: list[int] = []+ targets: list[int] = []+ lengths: list[int] = []+ for index, row in enumerate(rows):+ start = offsets[index] + len(row["prompt_ids"])+ response = row["response_token_ids"]+ lengths.append(len(response))+ for step, token in enumerate(response):+ gather_rows.append(index)+ gather_cols.append(start + step - 1)+ targets.append(int(token))+ flat_index = torch.tensor(gather_rows, device=self.device) * hidden.shape[1] + torch.tensor(+ gather_cols, device=self.device+ )+ selected = hidden.reshape(-1, hidden.shape[-1]).index_select(0, flat_index)+ target = torch.tensor(targets, device=self.device)+ pieces = []+ for start in range(0, selected.shape[0], LOGIT_CHUNK):+ chunk = selected[start : start + LOGIT_CHUNK]+ logits = self.model.lm_head(chunk).float() / TEMPERATURE+ pieces.append(+ torch.log_softmax(logits, dim=-1)+ .gather(-1, target[start : start + LOGIT_CHUNK].unsqueeze(-1))+ .squeeze(-1)+ )+ return torch.cat(pieces), lengths++ @torch.no_grad()+ def actor_logprobs(self, rows: list[dict], limit: int | None = None) -> list[float]:+ values, _ = self._selected_logprobs(rows, grad=False)+ result = [float(value) for value in values.tolist()]+ return result if limit is None else result[:limit]++ @torch.no_grad()+ def rollout_path_logprobs(self, index: int, limit: int | None = None) -> dict:+ """Log probabilities of a recorded response through the *rollout* path.++ Freshness evidence: this walks the incremental KV-cache decode path that+ the rollout engine itself uses, with the weights as they stand now. The+ driver compares it against the teacher-forced actor path, so agreement+ demonstrates that the rollout policy reflects the committed update.+ """+ from transformers.cache_utils import DynamicCache++ row = self.last_rollout[index]+ response = list(row["response_token_ids"])+ count = len(response) if limit is None else min(int(limit), len(response))+ ids, mask, positions, _ = self._left_padded([list(row["prompt_ids"])])+ cache = DynamicCache()+ output = self.model(+ input_ids=ids,+ attention_mask=mask,+ position_ids=positions,+ past_key_values=cache,+ use_cache=True,+ )+ logits = output.logits[:, -1]+ step_positions = positions[:, -1:]+ values: list[float] = []+ for step in range(count):+ logprobs = torch.log_softmax(logits.float() / TEMPERATURE, dim=-1)+ values.append(float(logprobs[0, int(response[step])].item()))+ if step + 1 >= count:+ break+ feed = torch.tensor([[int(response[step])]], dtype=torch.long, device=self.device)+ mask = torch.cat([mask, torch.ones(1, 1, dtype=mask.dtype, device=self.device)], -1)+ step_positions = step_positions + 1+ output = self.model(+ input_ids=feed,+ attention_mask=mask,+ position_ids=step_positions,+ past_key_values=cache,+ use_cache=True,+ )+ logits = output.logits[:, -1]+ return {"logprobs": values, "response_token_ids": response[:count]}++ # ---------- training ----------++ def train(self, advantages: list[float], global_tokens: int) -> dict:+ rows = self.last_rollout+ if len(rows) != len(advantages):+ raise ValueError("advantage count does not match the local rollout")+ for tensor in self.master:+ tensor.grad = None+ for tensor in self.params:+ tensor.grad = None+ loss_sum = torch.zeros((), dtype=torch.float64, device=self.device)+ kl_sum = torch.zeros((), dtype=torch.float64, device=self.device)+ clip_sum = torch.zeros((), dtype=torch.float64, device=self.device)+ token_total = 0+ scale = 1.0 / max(int(global_tokens), 1)+ for start in range(0, len(rows), MICRO_SEQUENCES):+ micro = rows[start : start + MICRO_SEQUENCES]+ micro_advantages = advantages[start : start + MICRO_SEQUENCES]+ current, lengths = self._selected_logprobs(micro, grad=True)+ old_values: list[float] = []+ advantage_values: list[float] = []+ for row, advantage, length in zip(micro, micro_advantages, lengths, strict=True):+ old_values.extend(float(value) for value in row["old_logprobs"])+ advantage_values.extend([float(advantage)] * length)+ old = torch.tensor(old_values, dtype=torch.float32, device=self.device)+ advantage = torch.tensor(advantage_values, dtype=torch.float32, device=self.device)+ log_ratio = current - old+ ratio = torch.exp(log_ratio)+ bounded = torch.clamp(ratio, 1.0 - CLIP_LOW, 1.0 + CLIP_HIGH)+ per_token = -torch.minimum(ratio * advantage, bounded * advantage)+ (per_token.sum() * scale).backward()+ with torch.no_grad():+ loss_sum += per_token.detach().double().sum()+ kl_sum += (torch.exp(-log_ratio) + log_ratio - 1.0).detach().double().sum()+ clip_sum += (+ ((ratio < 1.0 - CLIP_LOW) | (ratio > 1.0 + CLIP_HIGH)).double().sum()+ )+ token_total += int(sum(lengths))+ with torch.no_grad():+ for source, target in zip(self.params, self.master, strict=True):+ grad = source.grad+ if target.grad is None:+ target.grad = torch.zeros_like(target)+ if grad is not None:+ target.grad.copy_(grad)+ source.grad = None+ # HCCL does not implement float64 collectives, so the local+ # float64 accumulators are reduced as float32. The sums are O(1e4)+ # at most, which float32 carries far inside the metric tolerances.+ statistics = torch.stack(+ [+ loss_sum,+ kl_sum,+ clip_sum,+ torch.tensor(float(token_total), dtype=torch.float64, device=self.device),+ ]+ ).float()+ if self.world_size > 1:+ self._allreduce_gradients()+ dist.all_reduce(statistics, op=dist.ReduceOp.SUM)+ tokens = max(float(statistics[3].item()), 1.0)+ grad_norm = torch.nn.utils.clip_grad_norm_(self.master, CLIP_GRAD)+ self.optimizer.step()+ with torch.no_grad():+ for source, target in zip(self.params, self.master, strict=True):+ source.copy_(target)+ self.committed_update += 1+ self.policy_version += 1+ self.data_cursor += len(rows)+ return {+ "policy_loss": float(statistics[0].item()) / tokens,+ "approx_kl": float(statistics[1].item()) / tokens,+ "clip_fraction": float(statistics[2].item()) / tokens,+ "global_grad_norm": float(grad_norm),+ "consumed_tokens": int(tokens),+ "policy_version": self.policy_version,+ }++ def _allreduce_gradients(self) -> None:+ bucket: list[torch.Tensor] = []+ used = 0+ for tensor in self.master:+ grad = tensor.grad+ if grad is None:+ continue+ if used + grad.numel() > self.scratch.numel() and bucket:+ self._flush_bucket(bucket, used)+ bucket, used = [], 0+ if grad.numel() > self.scratch.numel():+ dist.all_reduce(grad, op=dist.ReduceOp.SUM)+ continue+ bucket.append(grad)+ used += grad.numel()+ if bucket:+ self._flush_bucket(bucket, used)++ def _flush_bucket(self, bucket: list[torch.Tensor], used: int) -> None:+ view = self.scratch[:used]+ offset = 0+ for grad in bucket:+ view[offset : offset + grad.numel()].copy_(grad.reshape(-1))+ offset += grad.numel()+ dist.all_reduce(view, op=dist.ReduceOp.SUM)+ offset = 0+ for grad in bucket:+ grad.reshape(-1).copy_(view[offset : offset + grad.numel()])+ offset += grad.numel()++ # ---------- warmup ----------++ def warmup(self, batch: int) -> dict:+ question = "A box has 9 rows of 7 oranges. How many oranges are in the box?"+ system = "Solve the problem in at most three short sentences."+ requests = [+ {+ "prompt_id": "warmup",+ "prompt_ordinal": 0,+ "response_ordinal": index % 4,+ "seed": 12345 + index,+ "system_prompt": system,+ "question": question,+ }+ for index in range(max(batch, 1))+ ]+ self.rollout(requests, max_new_tokens=24)+ rows = self.last_rollout+ # Warm the training path, the all-reduce buckets and the AdamW kernels+ # without perturbing the policy: zero grads, zero learning rate and+ # zero weight decay leave every parameter and moment bit-identical.+ for tensor in self.master:+ tensor.grad = torch.zeros_like(tensor)+ current, _ = self._selected_logprobs(rows[: min(len(rows), MICRO_SEQUENCES)], grad=True)+ current.sum().backward()+ for tensor in self.params:+ tensor.grad = None+ for tensor in self.master:+ tensor.grad.zero_()+ if self.world_size > 1:+ self._allreduce_gradients()+ dist.all_reduce(torch.zeros(4, dtype=torch.float32, device=self.device))+ # Snapshot the optimizer state before touching it. A fresh policy has+ # no state yet and is restored to having none; after a checkpoint+ # restart the restored AdamW moments and step counters are put back+ # bit-for-bit, so warming the kernels cannot disturb resumed training.+ snapshot: dict[int, dict] = {}+ for tensor in self.master:+ state = self.optimizer.state.get(tensor)+ if state:+ snapshot[id(tensor)] = {+ key: (value.detach().clone() if torch.is_tensor(value) else value)+ for key, value in state.items()+ }+ groups = self.optimizer.param_groups+ saved = [(group["lr"], group["weight_decay"]) for group in groups]+ for group in groups:+ group["lr"] = 0.0+ group["weight_decay"] = 0.0+ torch.nn.utils.clip_grad_norm_(self.master, CLIP_GRAD)+ # With lr == 0 and weight decay == 0 an AdamW step leaves every+ # parameter bit-identical; only the kernels are compiled and cached.+ self.optimizer.step()+ for group, (lr, decay) in zip(groups, saved, strict=True):+ group["lr"] = lr+ group["weight_decay"] = decay+ for tensor in self.master:+ recorded = snapshot.get(id(tensor))+ if recorded is None:+ self.optimizer.state.pop(tensor, None)+ else:+ state = self.optimizer.state.get(tensor, {})+ for key, value in recorded.items():+ current = state.get(key)+ if torch.is_tensor(value) and torch.is_tensor(current):+ current.copy_(value)+ else:+ state[key] = value+ tensor.grad = None+ self.last_rollout = []+ torch.npu.synchronize()+ return {+ "reserved_gib": round(torch.npu.memory_reserved() / 2**30, 2),+ "allocated_gib": round(torch.npu.memory_allocated() / 2**30, 2),+ }++ # ---------- checkpoint ----------++ def save(self, directory: str) -> list[str]:+ # Gradients are all-reduced and every rank applies the same update, so+ # the ranks hold bit-identical weights and optimizer state. Only rank 0+ # writes, which halves checkpoint I/O; restore falls back to rank 0.+ if self.rank != 0:+ return []+ root = Path(directory)+ root.mkdir(parents=True, exist_ok=True)+ model_name = f"model-rank{self.rank}.pt"+ optimizer_name = f"optimizer-rank{self.rank}.pt"+ state_name = f"trainer-state-rank{self.rank}.json"+ torch.save({name: tensor.detach().cpu() for name, tensor in self.model.state_dict().items()}, root / model_name)+ torch.save(+ {+ "optimizer": self.optimizer.state_dict(),+ "master": [tensor.detach().cpu() for tensor in self.master],+ },+ root / optimizer_name,+ )+ (root / state_name).write_text(+ json.dumps(+ {+ "committed_update": self.committed_update,+ "next_update": self.committed_update + 1,+ "policy_version": self.policy_version,+ "data_cursor": self.data_cursor,+ "rank": self.rank,+ "world_size": self.world_size,+ "learning_rate": LEARNING_RATE,+ "torch_rng_state": torch.random.get_rng_state().tolist(),+ },+ sort_keys=True,+ )+ + "\n",+ encoding="utf-8",+ )+ return [model_name, optimizer_name, state_name]++ def _restore(self, root: Path) -> None:+ model_file = root / f"model-rank{self.rank}.pt"+ if not model_file.is_file():+ model_file = root / "model-rank0.pt"+ optimizer_file = root / f"optimizer-rank{self.rank}.pt"+ if not optimizer_file.is_file():+ optimizer_file = root / "optimizer-rank0.pt"+ state_file = root / f"trainer-state-rank{self.rank}.json"+ if not state_file.is_file():+ state_file = root / "trainer-state-rank0.json"+ payload = torch.load(model_file, map_location="cpu", weights_only=False)+ self.model.load_state_dict({name: tensor for name, tensor in payload.items()})+ self.model.to(self.device)+ self.params = [p for p in self.model.parameters() if p.requires_grad]+ optimizer_payload = torch.load(optimizer_file, map_location="cpu", weights_only=False)+ self.master = [tensor.to(self.device).requires_grad_(True) for tensor in optimizer_payload["master"]]+ self.optimizer = torch.optim.AdamW(+ self.master,+ lr=LEARNING_RATE,+ weight_decay=WEIGHT_DECAY,+ betas=BETAS,+ eps=1e-8,+ foreach=True,+ )+ self.optimizer.load_state_dict(optimizer_payload["optimizer"])+ state = json.loads(state_file.read_text(encoding="utf-8"))+ self.committed_update = int(state["committed_update"])+ self.policy_version = int(state["policy_version"])+ self.data_cursor = int(state["data_cursor"])+ log(f"rank {self.rank} restored from update {self.committed_update}")++ # ---------- serving ----------++ def serve(self) -> None:+ listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ listener.bind(("127.0.0.1", self.port))+ listener.listen(4)+ ready = Path(os.environ["OPENBUILD_STATE_DIR"]) / f"worker-{self.rank}.ready"+ ready.write_text(json.dumps({"pid": os.getpid(), "port": self.port}), encoding="utf-8")+ log(f"rank {self.rank} listening on {self.port}")+ while True:+ connection, _ = listener.accept()+ channel = Channel(connection)+ try:+ while True:+ request = channel.receive()+ operation = request.get("op")+ try:+ if operation == "stop":+ channel.send({"status": "ok"})+ channel.close()+ listener.close()+ return+ channel.send({"status": "ok", **self.dispatch(operation, request)})+ except Exception as exc: # surfaced to the driver+ channel.send(+ {+ "status": "error",+ "error": f"{type(exc).__name__}: {exc}",+ "traceback": traceback.format_exc(limit=8),+ }+ )+ except (ConnectionError, OSError, json.JSONDecodeError):+ pass+ finally:+ channel.close()++ def dispatch(self, operation: str | None, request: dict) -> dict:+ if operation == "ping":+ return {"rank": self.rank, "pid": os.getpid()}+ if operation == "warmup":+ return self.warmup(int(request.get("batch", MICRO_SEQUENCES)))+ if operation == "rollout":+ return {+ "records": self.rollout(+ request["requests"], int(request.get("max_new_tokens", MAX_RESPONSE_TOKENS))+ )+ }+ if operation == "actor_logprobs":+ rows = request.get("rows")+ if rows is None:+ index = int(request.get("index", 0))+ limit = request.get("limit")+ selected = [self.last_rollout[index]]+ return {"logprobs": self.actor_logprobs(selected, limit)}+ return {"logprobs": self.actor_logprobs(rows, request.get("limit"))}+ if operation == "rollout_logprobs":+ index = int(request.get("index", 0))+ limit = request.get("limit")+ row = self.last_rollout[index]+ values = [float(value) for value in row["old_logprobs"]]+ return {+ "logprobs": values if limit is None else values[: int(limit)],+ "response_token_ids": row["response_token_ids"],+ "prompt_ids": row["prompt_ids"],+ }+ if operation == "rollout_path_logprobs":+ return self.rollout_path_logprobs(int(request.get("index", 0)), request.get("limit"))+ if operation == "train":+ return self.train(+ [float(value) for value in request["advantages"]], int(request["global_tokens"])+ )+ if operation == "projection":+ return {"parameter_projection": self.parameter_projection()}+ if operation == "describe":+ return {+ "logical_parameter_count": int(sum(p.numel() for p in self.params)),+ "parameter_tensor_count": len(self.params),+ "compute_dtype": str(next(iter(self.params)).dtype).rsplit(".", 1)[-1],+ "optimizer_state_dtypes": sorted(+ {+ str(value.dtype).rsplit(".", 1)[-1]+ for state in self.optimizer.state.values()+ for value in state.values()+ if torch.is_tensor(value) and value.is_floating_point()+ }+ | {str(self.master[0].dtype).rsplit(".", 1)[-1]}+ ),+ "committed_update": self.committed_update,+ "policy_version": self.policy_version,+ "device": self.device,+ }+ if operation == "save":+ return {"files": self.save(request["directory"])}+ raise ValueError(f"unknown worker operation: {operation}")+++def main() -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--rank", type=int, required=True)+ parser.add_argument("--world-size", type=int, required=True)+ parser.add_argument("--port", type=int, required=True)+ parser.add_argument("--store-port", type=int, required=True)+ args = parser.parse_args()+ worker = Worker(args.rank, args.world_size, args.port, args.store_port)+ worker.serve()+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())@@ -0,0 +1,6 @@+#!/usr/bin/env bash+# Load the model, start the per-device workers, warm every timed code path,+# then report ready. Nothing here is inside the scored timing window.+set -euo pipefail+cd "${OPENBUILD_SOLUTION_DIR:-$(dirname "$(readlink -f "$0")")}"+exec python3 -m ob.prepare_main@@ -0,0 +1,5 @@+#!/usr/bin/env bash+# Fixed-trajectory algorithm probe: pure-Python contract mathematics, no device.+set -euo pipefail+cd "${OPENBUILD_SOLUTION_DIR:-$(dirname "$(readlink -f "$0")")}"+exec python3 -m ob.probe_main "$@"