DeepSeek-V4-Pro · Training

T06 · Training build

Correctness rejected

OpenBuild Qwen3-4B training 2dev · Open Build

—PERFORMANCE RATIO
166TOOL 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 agentDeepSeek-V4-Pro · 166 visible calls

InspectEditValidateExecuteBuildProfileRollbackOther
70Inspect
1Build
5Validate
25Execute
8Profile
57Other

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 timeline128 groups · 166 calls

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

Main agent

  1. Inspect · Task requirements

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

    1 call · #0001–#0001

    echo <val>ls -l -a <val>cat <path>echo <flag>
  2. Inspect · Source & workspace

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

    1 call · #0002–#0002

    find <path> -maxdepth <n> -type <val>sortsed -n <val>echo <flag>
  3. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    1 call · #0003–#0003

    cat <path>echo <val>
  4. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0004–#0004

    <command> <args>sed -n <val> <val>
  5. Other · Task requirements

    Requested script or workload execution related to task requirements.

    1 call · #0005–#0005

    python3 - <script>
  6. Inspect · Source & workspace

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

    10 calls · #0006–#0015

    wc -l <path>sed -n <val> <path>grep -n <val> <path>bash <script> <n> >& <path>head -c <n>echo
    1 more command sketches
    echo <val>
  7. Validate · Benchmark & validation setup

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

    1 call · #0016–#0016

    bash <script> <n> >& <path>head -c <n>echoecho <val>
  8. Other · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0017–#0017

    python3 - <script>
  9. Inspect · Source & workspace

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

    1 call · #0018–#0018

    cd <path>env <vars> bash <script>echo <val>ls -l -a <val> <n> > <path>truecat <path> <n> > <path>
  10. Inspect · Device memory

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

    1 call · #0019–#0019

    cat <val>echonpu-smi infosed -n <val>
  11. Other · Device memory

    Requested runtime inspection related to device memory.

    1 call · #0020–#0020

    which <val>npu-smi infoecho <val>
  12. Inspect · Checkpoints & weight state

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

    1 call · #0021–#0021

    cat <path>echo <val>
  13. Other · Task requirements

    Requested script or workload execution related to task requirements.

    1 call · #0022–#0022

    python3 - <script>
  14. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0023–#0023

    sed -n <val> <path>
  15. Other · Precision & numerical checks

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

    1 call · #0024–#0024

    python3 - <script>
  16. Other · Task requirements

    Requested script or workload execution related to task requirements.

    1 call · #0025–#0025

    python3 - <script>
  17. Inspect · Source & workspace

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

    2 calls · #0026–#0027

    find <path> -maxdepth <n> <val> -iname <val> -o -iname <val> -o -iname <val> <args>sed -n <val>find <path> -maxdepth <n> -type <val> <flag> <args>sortls -l -a <path>
  18. Other · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0028–#0028

    cd <path>python3 - <script>
  19. Other · Parallelism & communication

    Requested script or workload execution related to parallelism & communication.

    1 call · #0029–#0029

    python3 - <script>
  20. Other · Precision & numerical checks

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

    1 call · #0030–#0030

    python3 - <script>
  21. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0031–#0031

    sed -n <val> <path>
  22. Inspect · Parallelism & communication

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

    2 calls · #0032–#0033

    cat > <path> <script>python3 -c <script>export <vars>env <vars> python3 <script> > <path> <n> >& <path>env <vars>wait <val>
    3 more command sketches
    echo <val> <val> <val>echo <val>cat <path>
  23. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0034–#0034

    python3 - <script>
  24. Other · Precision & numerical checks

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

    1 call · #0035–#0035

    python3 - <script>
  25. Inspect · Source & workspace

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

    1 call · #0036–#0036

    <command> <args>sed -n <val>free -gdf -h <path> <path>
  26. Inspect · Dependencies & build setup

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

    3 calls · #0037–#0039

    python3 -m <module> <val> <val> <val> <n> >& <path>head -n <n>python3 -m <module> <val> <val> --no-deps -d <path> <n> >& <path>ls -l -a <path> <n> > <path>echo <val>timeout <n> <val> <val> <val> --no-deps -d <path> <n> >& <path>
    5 more command sketches
    tail -n <n>pip <val> <val> <n> > <path>headenvgrep -i <val>
  27. Inspect · Attention kernels

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

    2 calls · #0040–#0041

    python3 - <script>grep -n <val> <path>head -n <n>sed -n <val> <path>
  28. Inspect · Source & workspace

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

    2 calls · #0042–#0043

    sed -n <val> <path>python3 - <script>
  29. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0044–#0044

    python3 - <script>
  30. Inspect · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0045–#0045

    python3 - <script>
  31. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0046–#0046

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

    Requested script or workload execution related to source & workspace.

    1 call · #0047–#0047

    python3 - <script>
  33. Other · Optimizer & gradients

    Requested script or workload execution related to optimizer & gradients.

    2 calls · #0048–#0049

    python3 - <script>
  34. Other · Precision & numerical checks

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

    2 calls · #0050–#0051

    python3 - <script>
  35. Inspect · Dependencies & build setup

    Requested file and log inspection and workspace inspection related to dependencies & build setup.

    2 calls · #0052–#0053

    cat <path>find <path> -maxdepth <n> -iname <val> -o -iname <val>sed -n <val>ls <path> <n> > <path>headfind <path> -type <val>
    2 more command sketches
    du <flag> <args>find <path> -name <val> <n> > <path>
  36. Profile · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0054–#0054

    python3 - <script>
  37. Profile · Source & workspace

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

    1 call · #0055–#0055

    mkdir -p <path>python3 -m <module> -e <path> <path>python3 - <script>
  38. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    10 calls · #0056–#0065

    python3 - <script>
  39. Other · Checkpoints & weight state

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

    1 call · #0066–#0066

    python3 - <script>
  40. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    2 calls · #0067–#0068

    python3 - <script>
  41. Execute · Attention kernels

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

    1 call · #0069–#0069

    mkdir -p <path>cat > <path> <script>chmod <val> <path> <path>ls -l -a <path>
  42. Inspect · Precision & numerical checks

    Requested file and log inspection related to precision & numerical checks.

    1 call · #0070–#0070

    cat > <path> <script>
  43. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    2 calls · #0071–#0072

    python3 - <script>
  44. Profile · Checkpoints & weight state

    Requested file and log inspection and script or workload execution related to checkpoints & weight state.

    1 call · #0073–#0073

    cat > <path> <script>python3 -m <module> <script>echo <val>
  45. Profile · Attention kernels

    Requested script or workload execution and source searches related to attention kernels.

    1 call · #0074–#0074

    python3 - <script>python3 -m <module> <script>echo <val>grep -n <val> <flag> <args>
  46. Inspect · Task requirements

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

    1 call · #0075–#0075

    rm -rf <path>python3 <script> --output <path>ls -l -a <path>cat <path>head -n <n>
  47. Inspect · Checkpoints & weight state

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

    1 call · #0076–#0076

    rm -rf <path> <path>mkdir -p <path> <path>cd <path><command> <args>env <vars>echo <val>
    2 more command sketches
    tail -n <n> <path>ls -l -h <path>
  48. Inspect · Source & workspace

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

    2 calls · #0077–#0078

    python3 - <script>grep -n <val> <path>head -n <n>sed -n <val> <path>
  49. Profile · Checkpoints & weight state

    Requested script or workload execution and file and log inspection related to checkpoints & weight state.

    1 call · #0079–#0079

    python3 - <script>python3 -m <module> <script>echo <val>sed -n <val> <path>
  50. Execute · Checkpoints & weight state

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

    1 call · #0080–#0080

    rm -rf <path> <path>mkdir -p <path> <path>cd <path>env <vars> timeout <n> <val> <val> <path> <path> <path> <path> <val> <val> <args>echo <val> > <path>sleep <n>
    4 more command sketches
    tail -n <n> <path>echo <flag>ps -o <val> -g <val> <path> <n> > <path>head -n <n>
  51. Execute · Source & workspace

    Requested execution waits, runtime inspection and source searches related to source & workspace.

    1 call · #0081–#0081

    sleep <n>ps <flag>grep -E <path>grep -v <val>tail -n <n> <path>ls -l -a <path> <path>
  52. Inspect · Device memory

    Requested execution waits, runtime inspection and file and log inspection related to device memory.

    1 call · #0082–#0082

    sleep <n>ps -o <val> -p <val> <n> > <path>tail -n <n> <path>npu-smi infogrep <flag> <args>
  53. Other · Precision & numerical checks

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

    1 call · #0083–#0083

    python3 - <script>
  54. Other · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0084–#0084

    python3 - <script>python3 -m <module> <script>echo <val>
  55. Execute · Checkpoints & weight state

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

    1 call · #0085–#0085

    rm -rf <path> <path>mkdir -p <path> <path>cd <path>env <vars> nohup <val> <val> <path> <path> <path> <path> <val> <val> <val> <args>echo <val>
  56. Inspect · Device memory

    Requested execution waits, file and log inspection and runtime inspection related to device memory.

    1 call · #0086–#0086

    sleep <n>tail -n <n> <path>ps <flag>grep <path>grep -v <val>npu-smi info
    1 more command sketches
    grep <flag> <args>
  57. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0087–#0087

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

    Requested script or workload execution related to source & workspace.

    1 call · #0088–#0088

    python3 - <script>
  59. Inspect · Device memory

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

    1 call · #0089–#0089

    cat > <path> <script>python3 <script>
  60. Inspect · Source & workspace

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

    1 call · #0090–#0090

    grep -n <val> <path>head
  61. Other · Device memory

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

    1 call · #0091–#0091

    python3 - <script>grep -n <val> <path>
  62. Execute · Checkpoints & weight state

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

    1 call · #0092–#0092

    rm -rf <path> <path>mkdir -p <path> <path>cd <path>env <vars> nohup <val> <val> <path> <path> <path> <path> <val> <val> <val> <args>echo <val>sleep <n>
    1 more command sketches
    tail -n <n> <path>
  63. Other · Device memory

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

    1 call · #0093–#0093

    python3 - <script>grep -n <val> <path>
  64. Execute · Checkpoints & weight state

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

    1 call · #0094–#0094

    rm -rf <path> <path>mkdir -p <path> <path>cd <path>env <vars> nohup <val> <val> <path> <path> <path> <path> <val> <val> <val> <args>echo <val>sleep <n>
    3 more command sketches
    grep -E <val> <path>head -n <n>tail -n <n> <path>
  65. Other · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0095–#0095

    python3 - <script>
  66. Execute · Checkpoints & weight state

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

    1 call · #0096–#0096

    rm -rf <path> <path>mkdir -p <path> <path>cd <path>env <vars> nohup <val> <val> <path> <path> <path> <path> <val> <val> <val> <args>echo <val>sleep <n>
    2 more command sketches
    grep -E <val> <path>head -n <n>
  67. Other · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0097–#0097

    python3 - <script>python3 -m <module> <script>echo <val>
  68. Execute · Checkpoints & weight state

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

    1 call · #0098–#0098

    rm -rf <path> <path>mkdir -p <path> <path>cd <path>env <vars> nohup <val> <val> <path> <path> <path> <path> <val> <val> <val> <args>echo <val>sleep <n>
    5 more command sketches
    tail -n <n> <path>echo <flag>cat <path> <n> > <path>head -c <n>echo
  69. Inspect · Device memory

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

    1 call · #0099–#0099

    cat > <path> <script>python3 <script>
  70. Other · Device memory

    Requested script or workload execution related to device memory.

    1 call · #0100–#0100

    python3 - <script>python3 -m <module> <script>echo <val>
  71. Execute · Checkpoints & weight state

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

    1 call · #0101–#0101

    rm -rf <path> <path>mkdir -p <path> <path>cd <path>env <vars> nohup <val> <val> <path> <path> <path> <path> <val> <val> <val> <args>echo <val>sleep <n>
    2 more command sketches
    grep -E <val> <path>head -n <n>
  72. Inspect · Device memory

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

    1 call · #0102–#0102

    grep -E <val> <path>head -n <n>
  73. Build · Parallelism & communication

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

    1 call · #0103–#0103

    python3 - <script>python3 -m <module> <script>echo <val>grep -n <val> <path>
  74. Inspect · Source & workspace

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

    1 call · #0104–#0104

    sed -n <val> <path>grep -n <val> <flag> <args>head -n <n>
  75. Other · Source & workspace

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

    1 call · #0105–#0105

    python3 - <script>python3 -m <module> <script>grep -n <val> <path>true
  76. Execute · Checkpoints & weight state

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

    1 call · #0106–#0106

    rm -rf <path> <path>mkdir -p <path> <path>cd <path>env <vars> nohup <val> <val> <path> <path> <path> <path> <val> <val> <val> <args>echo <val>sleep <n>
    1 more command sketches
    tail -n <n> <path>
  77. Inspect · Source & workspace

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

    1 call · #0107–#0107

    sleep <n>tail -n <n> <path>grep -v -E <val>tail -n <n>echo <flag>ps <flag>
    4 more command sketches
    grep <path>grep -v <val>cat <path> <n> > <path>head -c <n>
  78. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0108–#0108

    python3 - <script>
  79. Other · Optimizer & gradients

    Requested script or workload execution related to optimizer & gradients.

    1 call · #0109–#0109

    python3 - <script>python3 -m <module> <script>echo <val>
  80. Execute · Checkpoints & weight state

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

    2 calls · #0110–#0111

    rm -rf <path> <path>mkdir -p <path> <path>cd <path>env <vars> nohup <val> <val> <path> <path> <path> <path> <val> <val> <val> <args>echo <val>sleep <n>
    5 more command sketches
    grep -E <val> <path>tail -n <n>tailecho <flag>cat <path>
  81. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0112–#0112

    python3 - <script>python3 -m <module> <script>echo <val>
  82. Execute · Checkpoints & weight state

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

    1 call · #0113–#0113

    rm -rf <path> <path>mkdir -p <path> <path>cd <path>env <vars> nohup <val> <val> <path> <path> <path> <path> <val> <val> <val> <args>echo <val>sleep <n>
    7 more command sketches
    grep -E <val> <path>tailecho <flag>cat <path>tail -n <n>python3 -m <module>sed -n <val>
  83. Execute · Device memory

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

    1 call · #0114–#0114

    npu-smi infotail -n <n>ps <flag>grep -E <path>grep -v <val>free -g
    1 more command sketches
    head
  84. Other · Device memory

    Requested runtime inspection related to device memory.

    1 call · #0115–#0115

    npu-smi infoecho <val>
  85. Inspect · Source & workspace

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

    1 call · #0116–#0116

    ps -p <n> -o <val>ps <flag>grep <n>grep -v <val>ls -l <path> <n> > <path>head
  86. Inspect · Device memory

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

    1 call · #0117–#0117

    kill <flag> <args>truesleep <n>ps -p <val> -o <val>npu-smi infotail -n <n>
  87. Execute · Checkpoints & weight state

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

    1 call · #0118–#0118

    rm -rf <path> <path>mkdir -p <path> <path>cd <path>env <vars> nohup <val> <val> <path> <path> <path> <path> <val> <val> <val> <args>echo <val>sleep <n>
    6 more command sketches
    grep -E <val> <path>tail -n <n>echo <flag>cat <path> <n> > <path>python3 -m <module> <n> > <path>sed -n <val>
  88. Inspect · Source & workspace

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

    1 call · #0119–#0119

    ps <flag>grep <path>grep -v <val>tail -n <n> <path>echo <flag>ls -l <path>
    4 more command sketches
    cat <path> <n> > <path>tail -n <n>python3 -m <module>sed -n <val>
  89. Inspect · Optimizer & gradients

    Requested script or workload execution related to optimizer & gradients.

    1 call · #0120–#0120

    python3 - <script>
  90. Execute · Checkpoints & weight state

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

    1 call · #0121–#0121

    rm -rf <path> <path>mkdir -p <path> <path>cd <path>env <vars> nohup <val> <val> <path> <path> <path> <path> <val> <val> <val> <args>echo <val>sleep <n>
    2 more command sketches
    grep -E <val> <path>tail -n <n>
  91. Other · Task requirements

    Requested script or workload execution related to task requirements.

    1 call · #0122–#0122

    python3 - <script>
  92. Other · Optimizer & gradients

    Requested script or workload execution related to optimizer & gradients.

    1 call · #0123–#0123

    python3 - <script>python3 -m <module> <script>echo <val>
  93. Execute · Checkpoints & weight state

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

    1 call · #0124–#0124

    rm -rf <path> <path>mkdir -p <path> <path>cd <path>env <vars> nohup <val> <val> <path> <path> <path> <path> <val> <val> <val> <args>echo <val>sleep <n>
    2 more command sketches
    grep -E <val> <path>tail -n <n>
  94. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0125–#0125

    python3 - <script>
  95. Profile · Batching & scheduling

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

    1 call · #0126–#0126

    python3 - <script>python3 -m <module> <script>echo <val>grep -n <val> <path>head -n <n>
  96. Execute · Checkpoints & weight state

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

    2 calls · #0127–#0128

    rm -rf <path> <path>mkdir -p <path> <path>cd <path>env <vars> nohup <val> <val> <path> <path> <path> <path> <val> <val> <val> <args>echo <val>sleep <n>
    3 more command sketches
    grep -E <val> <path>tail -n <n>cat <path> <n> > <path>
  97. Other · Source & workspace

    Requested tool activity related to source & workspace.

    1 call · #0129–#0129

    date -udateecho <val> <val> <val> <val> <val> -d <val> <val> <val>
  98. Execute · Checkpoints & weight state

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

    1 call · #0130–#0130

    rm -rf <path> <path>mkdir -p <path> <path>cd <path>env <vars> nohup <val> <val> <path> <path> <path> <path> <val> <val> <val> <args>echo <val>sleep <n>
    4 more command sketches
    grep -E <val> <path>tail -n <n>echo <flag>python3 - <script>
  99. Profile · Optimizer & gradients

    Requested script or workload execution related to optimizer & gradients.

    1 call · #0131–#0131

    python3 - <script>
  100. Inspect · Optimizer & gradients

    Requested script or workload execution related to optimizer & gradients.

    3 calls · #0132–#0134

    python3 - <script>
  101. Other · Optimizer & gradients

    Requested script or workload execution related to optimizer & gradients.

    1 call · #0135–#0135

    python3 - <script>python3 -m <module> <script>echo <val>
  102. Execute · Checkpoints & weight state

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

    1 call · #0136–#0136

    rm -rf <path> <path>mkdir -p <path> <path>cd <path>env <vars> nohup <val> <val> <path> <path> <path> <path> <val> <val> <val> <args>echo <val>sleep <n>
    2 more command sketches
    grep -E <val> <path>tail -n <n>
  103. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0137–#0137

    python3 - <script>
  104. Other · Optimizer & gradients

    Requested script or workload execution related to optimizer & gradients.

    1 call · #0138–#0138

    python3 - <script>
  105. Execute · Runtime processes

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

    1 call · #0139–#0139

    cat > <path> <script>chmod <val> <path>python3 -m <module> <script>echo <val>
  106. Execute · Checkpoints & weight state

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

    1 call · #0140–#0140

    rm -rf <path> <path>mkdir -p <path> <path>cd <path>env <vars> nohup <val> <val> <path> <path> <path> <path> <val> <val> <val> <args>echo <val>sleep <n>
    4 more command sketches
    tail -n <n> <path>echo <flag>cat <path> <n> > <path>tail -n <n>
  107. Inspect · Checkpoints & weight state

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

    1 call · #0141–#0141

    python3 - <script>python3 -m <module> <script>echo <val>grep -n <val> <path>head -n <n>
  108. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0142–#0142

    sed -n <val> <path>
  109. Inspect · Device memory

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

    1 call · #0143–#0143

    python3 - <script>python3 -m <module> <script>grep -n <val> <path>head -n <n>
  110. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0144–#0144

    sed -n <val> <path>
  111. Other · Optimizer & gradients

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

    1 call · #0145–#0145

    python3 - <script>python3 -m <module> <script>grep -n <val> <path>true
  112. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0146–#0146

    python3 - <script>
  113. Validate · Benchmark & validation setup

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

    2 calls · #0147–#0148

    bash <script> <n> >& <path>tail -n <n>echo <val>bash <script>cat <path> <n> > <path>tail -c <n>
  114. Inspect · Source & workspace

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

    1 call · #0149–#0149

    find <path> -maxdepth <n> -type <val> <flag> <args>sortdu <flag> <args>python3 -m <module> <script>
  115. Other · Source & workspace

    Requested tool activity related to source & workspace.

    1 call · #0150–#0150

    date -u
  116. Execute · Device memory

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

    1 call · #0151–#0151

    ps <flag>grep -E <val>grep -v <val>truenpu-smi infotail -n <n>
  117. Inspect · Device memory

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

    2 calls · #0152–#0153

    npu-smi infotail -n <n>timeout <n> <val> <val> > <path> <n> > <path>echo <val>cat <path>tail -n <n> <path>
  118. Inspect · Checkpoints & weight state

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

    1 call · #0154–#0154

    grep -n <val> <path>sed -n <val> <path>
  119. Profile · Batching & scheduling

    Requested script or workload execution related to batching & scheduling.

    1 call · #0155–#0155

    python3 - <script>python3 -m <module> <script>echo <val>
  120. Inspect · Source & workspace

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

    1 call · #0156–#0156

    python3 -m <module> <script>bash <script>echo <val>cat <path> <n> > <path>tail -c <n>
  121. Inspect · Task requirements

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

    1 call · #0157–#0157

    cd <path>git status --shortfind <val> -maxdepth <n> -type <val> <flag> <args>sortcat <path>date -u
  122. Inspect · Source & workspace

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

    3 calls · #0158–#0160

    grep -n <val> <path>sed -n <val> <path>
  123. Other · Task requirements

    Requested script or workload execution related to task requirements.

    1 call · #0161–#0161

    cd <path>python3 -B - <script>
  124. Validate · Benchmark & validation setup

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

    1 call · #0162–#0162

    bash <script> > <path> <n> > <path>echo <val>tail -c <n> <path>echocat <path>
  125. Inspect · Source & workspace

    Requested workspace inspection related to source & workspace.

    1 call · #0163–#0163

    find <path> -maxdepth <n> -type <val> <flag> <args>sortdu <flag> <args>
  126. Other · Parallelism & communication

    Requested script or workload execution related to parallelism & communication.

    1 call · #0164–#0164

    python3 - <script>python3 -m <module> <script>echo <val>
  127. Validate · Benchmark & validation setup

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

    1 call · #0165–#0165

    python3 -m <module> <script>bash <script> > <path> <n> > <path>echo <val>tail -c <n> <path>date -u
  128. Execute · Source & workspace

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

    1 call · #0166–#0166

    ps <flag>grep -E <path>grep -v <val>true

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.

openbuild_solution · 7 changed files

Base commit: d1281fd46aa0575309be1eb6e0fcdc79e4be9670

diff --git a/solution/bootstrap.sh b/solution/bootstrap.shnew file mode 100755index 0000000000000000000000000000000000000000..b2a176caa8d8c5bb22c733245bb99fb8881dca92--- /dev/null+++ b/solution/bootstrap.sh@@ -0,0 +1,4 @@+#!/usr/bin/env bash+set -euo pipefail+cd "$(dirname "${BASH_SOURCE[0]}")"+exec python3 -B bootstrap_main.pydiff --git a/solution/bootstrap_main.py b/solution/bootstrap_main.pynew file mode 100644index 0000000000000000000000000000000000000000..f061111aa7ba22824319a177f7074d150d976ce3--- /dev/null+++ b/solution/bootstrap_main.py@@ -0,0 +1,157 @@+from __future__ import annotations++import json+import os+import shutil+import sys+import time+from concurrent.futures import ProcessPoolExecutor+from pathlib import Path++import numpy as np+import torch++from model_spec import PARAM_SPECS, N_PARAM_ELEMENTS++MASK_64 = np.uint64((1 << 64) - 1)+GOLDEN = np.uint64(0x9E3779B97F4A7C15)+MIX1 = np.uint64(0xBF58476D1CE4E5B9)+MIX2 = np.uint64(0x94D049BB133111EB)+SEED = np.uint64(0x51454E334F50454E)+FNV_OFFSET = np.uint64(0xCBF29CE484222325)+FNV_PRIME = np.uint64(0x00000100000001B3)+CHUNK_ELEMENTS = 16_000_000+BF16_ONE = np.uint16(0x3F80)+++def fnv1a64(name: str) -> int:+    value = int(FNV_OFFSET)+    for byte in name.encode("utf-8"):+        value ^= byte+        value = (value * int(FNV_PRIME)) & 0xFFFFFFFFFFFFFFFF+    return value+++def _write_bf16_file(path: Path, values: np.ndarray) -> None:+    tensor = torch.from_numpy(values.astype(np.float32)).bfloat16()+    tensor.view(torch.int16).numpy().astype("<i2", copy=False).tofile(path)+++def generate_random_part(spec: dict, part_path: Path) -> None:+    """Generate one canonical random tensor exactly as specified."""+    numel = spec["numel"]+    name_hash = np.uint64(fnv1a64(spec["name"]))+    with part_path.open("wb") as handle:+        generated = 0+        while generated < numel:+            count = min(CHUNK_ELEMENTS, numel - generated)+            index = np.arange(generated, generated + count, dtype=np.uint64)+            counter = SEED ^ name_hash ^ (index * GOLDEN)+            z = counter + GOLDEN+            z = (z ^ (z >> np.uint64(30))) * MIX1+            z = (z ^ (z >> np.uint64(27))) * MIX2+            random_u64 = z ^ (z >> np.uint64(31))+            q = ((random_u64 >> np.uint64(52)) & np.uint64(0xFFF)).astype(+                np.int64+            ) - np.int64(2048)+            fp32 = q.astype(np.float32) * np.float32(2.0**-16)+            tensor = torch.from_numpy(fp32).bfloat16()+            bits = tensor.view(torch.int16).numpy().astype("<i2", copy=False)+            bits.tofile(handle)+            generated += count+            del index, counter, z, random_u64, q, fp32, tensor, bits+++def generate_constant_part(spec: dict, part_path: Path) -> None:+    chunks = max(1, spec["numel"] // CHUNK_ELEMENTS)+    with part_path.open("wb") as handle:+        remaining = spec["numel"]+        while remaining:+            count = min(CHUNK_ELEMENTS, remaining)+            arr = np.full(count, BF16_ONE, dtype="<u2")+            arr.tofile(handle)+            remaining -= count+++def main() -> int:+    action = os.environ.get("OPENBUILD_ACTION")+    if action not in {"bootstrap", "train"}:+        print(f"bootstrap_main invoked for unexpected action {action!r}", file=sys.stderr)+        return 2++    env_dir = Path(os.environ["OPENBUILD_ENV_DIR"])+    env_dir.mkdir(parents=True, exist_ok=True)+    initial_dir = env_dir / "initial"+    model_path = initial_dir / "model.bf16.bin"+    params_path = initial_dir / "params.json"+    complete_path = env_dir / "bootstrap-complete.json"++    if complete_path.is_file() and model_path.is_file() and params_path.is_file():+        expected_size = N_PARAM_ELEMENTS * 2+        if model_path.stat().st_size == expected_size:+            return 0++    if initial_dir.exists():+        shutil.rmtree(initial_dir)+    initial_dir.mkdir(parents=True)+    parts_dir = env_dir / "initial-parts"+    shutil.rmtree(parts_dir, ignore_errors=True)+    parts_dir.mkdir(parents=True)++    specs = PARAM_SPECS+    part_paths = [parts_dir / f"tensor-{index:04d}.bin" for index in range(len(specs))]++    started = time.time()+    # Saturating the many available Kunpeng cores makes the deterministic+    # 64-bit splitmix initialization substantially faster than one CPU core.+    workers = min(96, len(specs))+    with ProcessPoolExecutor(max_workers=workers) as pool:+        futures = []+        for spec, part_path in zip(specs, part_paths, strict=True):+            if spec["constant"]:+                futures.append(pool.submit(generate_constant_part, spec, part_path))+            else:+                futures.append(pool.submit(generate_random_part, spec, part_path))+        for future in futures:+            future.result()++    with model_path.open("wb") as output:+        for part_path in part_paths:+            with part_path.open("rb") as part:+                shutil.copyfileobj(part, output, length=1024 * 1024)++    params_path.write_text(+        json.dumps(+            {+                "schema_version": 1,+                "n_elements": N_PARAM_ELEMENTS,+                "dtype": "bf16",+                "byte_order": "little",+                "parameters": PARAM_SPECS,+            },+            allow_nan=False,+            separators=(",", ":"),+        )+        + "\n",+        encoding="utf-8",+    )+    shutil.rmtree(parts_dir, ignore_errors=True)+    complete_path.write_text(+        json.dumps(+            {+                "schema_version": 1,+                "status": "complete",+                "model_bytes": model_path.stat().st_size,+                "generation_seconds": time.time() - started,+            },+            allow_nan=False,+            separators=(",", ":"),+        )+        + "\n",+        encoding="utf-8",+    )+    return 0+++if __name__ == "__main__":+    raise SystemExit(main())diff --git a/solution/manifest.json b/solution/manifest.jsonnew file mode 100644index 0000000000000000000000000000000000000000..0d5ba8f2123fd9125d23e7cdbf3624b37c1ee658--- /dev/null+++ b/solution/manifest.json@@ -0,0 +1,10 @@+{+  "schema_version": 1,+  "kind": "openbuild_training_solution",+  "task_id": "openbuild_training_qwen3_4b_2dev_v1",+  "entrypoints": {+    "bootstrap": "bootstrap.sh",+    "train": "train.sh"+  },+  "offline_bootstrap": true+}diff --git a/solution/model_spec.py b/solution/model_spec.pynew file mode 100644index 0000000000000000000000000000000000000000..a71867e1685227f72730181675235c1e275ccc05--- /dev/null+++ b/solution/model_spec.py@@ -0,0 +1,78 @@+"""Frozen Qwen3-4B-Base architecture and canonical parameter layout."""+from __future__ import annotations++VOCAB_SIZE = 151_936+HIDDEN_SIZE = 2560+FFN_SIZE = 9728+NUM_LAYERS = 36+NUM_HEADS = 32+NUM_KV_HEADS = 8+HEAD_DIM = 128+MAX_POSITIONS = 32_768+RMS_EPS = 1e-6+ROPE_BASE = 1_000_000+ROPE_INTERLEAVED = False++# AdamW contract+BETA1 = 0.9+BETA2 = 0.95+ADAM_EPS = 1e-8+LR = 1.25e-6+MIN_LR = 1.25e-7+WEIGHT_DECAY = 0.1+CLIP_GRAD = 1.0+CLIP_EPS = 1e-6+WARMUP_UPDATES = 0+DECAY_UPDATES = 30+++def _build_specs() -> list[dict]:+    specs: list[dict] = []+    offset = 0++    def add(name: str, shape: tuple[int, ...], *, constant: bool) -> None:+        nonlocal offset+        numel = 1+        for dim in shape:+            numel *= dim+        specs.append(+            {+                "name": name,+                "shape": list(shape),+                "numel": numel,+                "offset": offset,+                "constant": constant,+                "weight_decay": len(shape) >= 2,+            }+        )+        offset += numel++    add("model.embed_tokens.weight", (VOCAB_SIZE, HIDDEN_SIZE), constant=False)+    for layer in range(NUM_LAYERS):+        base = f"model.layers.{layer}"+        add(f"{base}.self_attn.q_proj.weight", (NUM_HEADS * HEAD_DIM, HIDDEN_SIZE), constant=False)+        add(f"{base}.self_attn.k_proj.weight", (NUM_KV_HEADS * HEAD_DIM, HIDDEN_SIZE), constant=False)+        add(f"{base}.self_attn.v_proj.weight", (NUM_KV_HEADS * HEAD_DIM, HIDDEN_SIZE), constant=False)+        add(f"{base}.self_attn.o_proj.weight", (HIDDEN_SIZE, NUM_HEADS * HEAD_DIM), constant=False)+        add(f"{base}.mlp.gate_proj.weight", (FFN_SIZE, HIDDEN_SIZE), constant=False)+        add(f"{base}.mlp.up_proj.weight", (FFN_SIZE, HIDDEN_SIZE), constant=False)+        add(f"{base}.mlp.down_proj.weight", (HIDDEN_SIZE, FFN_SIZE), constant=False)+        add(f"{base}.input_layernorm.weight", (HIDDEN_SIZE,), constant=True)+        add(f"{base}.self_attn.q_norm.weight", (HEAD_DIM,), constant=True)+        add(f"{base}.self_attn.k_norm.weight", (HEAD_DIM,), constant=True)+        add(f"{base}.post_attention_layernorm.weight", (HIDDEN_SIZE,), constant=True)+    add("model.norm.weight", (HIDDEN_SIZE,), constant=True)++    return specs+++PARAM_SPECS = _build_specs()+PARAM_BY_NAME = {spec["name"]: spec for spec in PARAM_SPECS}+N_PARAM_ELEMENTS = PARAM_SPECS[-1]["offset"] + PARAM_SPECS[-1]["numel"]++# lm_head is a tied alias and is never a distinct canonical parameter.+ALIAS_TARGETS = {"lm_head.weight": "model.embed_tokens.weight"}++# Flat index boundaries for the two equal rank shards.  N_PARAM_ELEMENTS is+# deliberately an even integer for this architecture.+SHARD_BOUNDARIES = (0, N_PARAM_ELEMENTS // 2, N_PARAM_ELEMENTS)diff --git a/solution/train.py b/solution/train.pynew file mode 100644index 0000000000000000000000000000000000000000..b46cf30dc5626a55b90aec036139e4742c1cdf18--- /dev/null+++ b/solution/train.py@@ -0,0 +1,969 @@+from __future__ import annotations++import argparse+import json+import math+import os+import struct+import sys+import time+from pathlib import Path+from typing import Any++import numpy as np+import torch+import torch.distributed as dist+import torch.nn as nn+import torch.nn.functional as F+import torch_npu  # noqa: F401  (registers the Ascend backend)+from torch.utils.checkpoint import checkpoint as gradient_checkpoint++from model_spec import (+    ADAM_EPS,+    BETA1,+    BETA2,+    CLIP_EPS,+    CLIP_GRAD,+    DECAY_UPDATES,+    FFN_SIZE,+    HEAD_DIM,+    HIDDEN_SIZE,+    LR,+    MIN_LR,+    N_PARAM_ELEMENTS,+    NUM_HEADS,+    NUM_KV_HEADS,+    NUM_LAYERS,+    PARAM_BY_NAME,+    PARAM_SPECS,+    ROPE_BASE,+    RMS_EPS,+    SHARD_BOUNDARIES,+    VOCAB_SIZE,+    WEIGHT_DECAY,+)++TASK_ID = "openbuild_training_qwen3_4b_2dev_v1"+SELECTOR_CATEGORIES = (+    "logits",+    "gradients",+    "model_parameters",+    "master_parameters",+    "first_moments",+    "second_moments",+)+TRAINING_UPDATES = 30+FRESH_UPDATE = 31+++def _f32(value: float) -> float:+    return struct.unpack(">f", struct.pack(">f", float(value)))[0]+++def _bf16_round(value: float) -> float:+    bits = struct.unpack(">I", struct.pack(">f", _f32(value)))[0]+    rounded = (bits + 0x7FFF + ((bits >> 16) & 1)) & 0xFFFFFFFF+    return struct.unpack(">f", struct.pack(">I", rounded & 0xFFFF0000))[0]+++# ---------------------------------------------------------------------------+# Input ABI+# ---------------------------------------------------------------------------++def _load_json(path: Path) -> dict[str, Any]:+    with path.open("r", encoding="utf-8") as handle:+        return json.load(handle)+++def load_input_manifest() -> tuple[dict[str, Any], dict[str, Any]]:+    root = Path(os.environ["OPENBUILD_INPUT_DIR"])+    manifest = _load_json(root / "input-manifest.json")+    profile_id = os.environ["OPENBUILD_PROFILE_ID"]+    profile = next(p for p in manifest["profiles"] if p["profile_id"] == profile_id)+    return manifest, profile+++def _tensor_dtype(descriptor: dict[str, Any]) -> np.dtype:+    return {+        "int32": np.dtype("<i4"),+        "int64": np.dtype("<i8"),+        "uint8": np.dtype("u1"),+    }[descriptor["dtype"]]+++def load_input_tensors(profile: dict[str, Any]) -> tuple[dict[str, np.ndarray], int]:+    """Load the 30 committed update slices, never the fresh slice 30."""+    root = Path(os.environ["OPENBUILD_INPUT_DIR"])+    tensors: dict[str, np.ndarray] = {}+    for name, descriptor in profile["tensors"].items():+        path = root / descriptor["path"]+        if path.stat().st_size != descriptor["byte_length"]:+            raise RuntimeError(f"input tensor size differs: {profile['profile_id']}/{name}")+        dense_shape = tuple(int(x) for x in descriptor["shape"])+        committed_shape = (30, *dense_shape[1:])+        count = int(np.prod(committed_shape))+        array = np.fromfile(path, dtype=_tensor_dtype(descriptor), count=count).reshape(+            committed_shape+        )+        tensors[name] = array+    return tensors, profile["global_batch_size"]+++def load_input_slice(+    profile: dict[str, Any], update_index: int+) -> dict[str, np.ndarray]:+    """Read exactly one update slice from the headerless tensor files."""+    root = Path(os.environ["OPENBUILD_INPUT_DIR"])+    tensors: dict[str, np.ndarray] = {}+    for name, descriptor in profile["tensors"].items():+        path = root / descriptor["path"]+        if path.stat().st_size != descriptor["byte_length"]:+            raise RuntimeError(f"input tensor size differs: {profile['profile_id']}/{name}")+        dense_shape = tuple(int(x) for x in descriptor["shape"])+        slice_shape = dense_shape[1:]+        count = int(np.prod(slice_shape))+        offset = int(update_index - 1) * count * np.dtype(_tensor_dtype(descriptor)).itemsize+        array = np.fromfile(+            path, dtype=_tensor_dtype(descriptor), count=count, offset=offset+        ).reshape(slice_shape)+        tensors[name] = array+    return tensors+++def update_slice(tensors: dict[str, np.ndarray], update_index: int) -> dict[str, np.ndarray]:+    axis = update_index - 1+    result: dict[str, np.ndarray] = {}+    for name, array in tensors.items():+        if array.ndim == 3:+            result[name] = array[axis]+        elif array.ndim == 2:+            result[name] = array[axis]+        else:+            result[name] = array+    return result+++def _npu(tensor: Any, *, dtype: torch.dtype | None = None) -> torch.Tensor:+    if isinstance(tensor, torch.Tensor):+        if tensor.device.type == "npu":+            return tensor+        result = tensor.npu()+    else:+        result = torch.from_numpy(np.ascontiguousarray(tensor)).npu()+    if dtype is not None:+        result = result.to(dtype)+    return result+++# ---------------------------------------------------------------------------+# Model+# ---------------------------------------------------------------------------++class FlatQwen3(nn.Module):+    def __init__(self, weight: torch.Tensor):+        super().__init__()+        self.weight = nn.Parameter(weight)++    def forward(+        self,+        input_ids: torch.Tensor,+        position_ids: torch.Tensor,+        cos: torch.Tensor,+        sin: torch.Tensor,+        causal_mask: torch.Tensor,+    ) -> torch.Tensor:+        flat = self.weight+        embed = _param_view(flat, "model.embed_tokens.weight")+        hidden = F.embedding(input_ids, embed)+        for layer_idx in range(NUM_LAYERS):+            hidden = gradient_checkpoint(+                _block_impl,+                hidden,+                flat,+                layer_idx,+                cos,+                sin,+                causal_mask,+                use_reentrant=False,+            )+        hidden = _rms_norm(hidden, _param_view(flat, "model.norm.weight"), RMS_EPS)+        # Tied output projection.  This is the same Parameter storage, so the+        # backward of lm_head and embed_tokens accumulates into one flat grad.+        return F.linear(hidden, embed)+++def _param_view(flat: torch.Tensor, name: str) -> torch.Tensor:+    spec = PARAM_BY_NAME[name]+    return flat.narrow(0, spec["offset"], spec["numel"]).view(spec["shape"])+++def _rms_norm(x: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor:+    input_dtype = x.dtype+    xf = x.float()+    variance = xf.pow(2).mean(-1, keepdim=True)+    xf = xf * torch.rsqrt(variance + eps)+    return weight * xf.to(input_dtype)+++def _rotate_half(x: torch.Tensor) -> torch.Tensor:+    half = x.shape[-1] // 2+    return torch.cat((-x[..., half:], x[..., :half]), dim=-1)+++def _apply_rotary(q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor):+    cos = cos.unsqueeze(1)+    sin = sin.unsqueeze(1)+    q_embed = (q * cos) + (_rotate_half(q) * sin)+    k_embed = (k * cos) + (_rotate_half(k) * sin)+    return q_embed, k_embed+++def _block_impl(+    hidden: torch.Tensor,+    flat: torch.Tensor,+    layer_idx: int,+    cos: torch.Tensor,+    sin: torch.Tensor,+    causal_mask: torch.Tensor,+) -> torch.Tensor:+    batch, seq_len, _ = hidden.shape+    base = f"model.layers.{layer_idx}"+    residual = hidden++    # Pre-attention RMSNorm + self attention.+    hidden = _rms_norm(+        hidden, _param_view(flat, f"{base}.input_layernorm.weight"), RMS_EPS+    )+    q = F.linear(hidden, _param_view(flat, f"{base}.self_attn.q_proj.weight"))+    k = F.linear(hidden, _param_view(flat, f"{base}.self_attn.k_proj.weight"))+    v = F.linear(hidden, _param_view(flat, f"{base}.self_attn.v_proj.weight"))+    q = q.view(batch, seq_len, NUM_HEADS, HEAD_DIM).transpose(1, 2)+    k = k.view(batch, seq_len, NUM_KV_HEADS, HEAD_DIM).transpose(1, 2)+    v = v.view(batch, seq_len, NUM_KV_HEADS, HEAD_DIM).transpose(1, 2)++    q = _rms_norm(q, _param_view(flat, f"{base}.self_attn.q_norm.weight"), RMS_EPS)+    k = _rms_norm(k, _param_view(flat, f"{base}.self_attn.k_norm.weight"), RMS_EPS)+    q, k = _apply_rotary(q, k, cos, sin)++    # GQA expansion, bf16 score matmul, fp32 softmax per contract.+    k_expanded = k.repeat_interleave(NUM_HEADS // NUM_KV_HEADS, dim=1)+    v_expanded = v.repeat_interleave(NUM_HEADS // NUM_KV_HEADS, dim=1)+    scores = torch.matmul(q, k_expanded.transpose(-1, -2)) * (HEAD_DIM**-0.5)+    scores = scores + causal_mask+    # F.softmax on mixed bf16/fp32 inputs requests a very large NPU workspace+    # at sequence length 2048.  The mathematically identical fp32 softmax+    # below keeps the attention-softmax precision contract without that+    # workspace and is explicit about every intermediate.+    scores_f = scores.float()+    scores_f = scores_f - torch.max(scores_f, dim=-1, keepdim=True).values+    exp_scores = torch.exp(scores_f)+    probs = (exp_scores / exp_scores.sum(dim=-1, keepdim=True)).to(hidden.dtype)+    attn = torch.matmul(probs, v_expanded)+    attn = attn.transpose(1, 2).contiguous().view(batch, seq_len, NUM_HEADS * HEAD_DIM)+    attn = F.linear(attn, _param_view(flat, f"{base}.self_attn.o_proj.weight"))+    hidden = residual + attn++    # Pre-MLP RMSNorm + SwiGLU MLP.+    residual = hidden+    hidden = _rms_norm(+        hidden, _param_view(flat, f"{base}.post_attention_layernorm.weight"), RMS_EPS+    )+    gate = F.linear(hidden, _param_view(flat, f"{base}.mlp.gate_proj.weight"))+    up = F.linear(hidden, _param_view(flat, f"{base}.mlp.up_proj.weight"))+    down = F.linear(F.silu(gate) * up, _param_view(flat, f"{base}.mlp.down_proj.weight"))+    hidden = residual + down+    return hidden+++def make_rope(position_ids: torch.Tensor, device: torch.device) -> tuple[torch.Tensor, torch.Tensor]:+    positions = position_ids.float()+    index = torch.arange(0, HEAD_DIM, 2, device=device, dtype=torch.float32)+    inv_freq = 1.0 / (ROPE_BASE ** (index / HEAD_DIM))+    freqs = positions.unsqueeze(-1) * inv_freq+    emb = torch.cat((freqs, freqs), dim=-1)+    return emb.cos().bfloat16(), emb.sin().bfloat16()+++def make_causal_mask(seq_len: int, device: torch.device) -> torch.Tensor:+    mask = torch.full(+        (seq_len, seq_len),+        float("-inf"),+        device=device,+        dtype=torch.bfloat16,+    )+    return torch.triu(mask, diagonal=1).unsqueeze(0).unsqueeze(0)+++# ---------------------------------------------------------------------------+# Initial / checkpoint state loading+# ---------------------------------------------------------------------------++def load_initial_flat_model(rank: int) -> tuple[nn.Parameter, list[dict[str, Any]]]:+    env_dir = Path(os.environ["OPENBUILD_ENV_DIR"])+    params_path = env_dir / "initial" / "params.json"+    model_path = env_dir / "initial" / "model.bf16.bin"+    if not params_path.is_file() or not model_path.is_file():+        raise RuntimeError("bootstrap did not produce the initial model cache")+    metadata = _load_json(params_path)+    if metadata["n_elements"] != N_PARAM_ELEMENTS:+        raise RuntimeError("cached initial model size differs")+    if model_path.stat().st_size != N_PARAM_ELEMENTS * 2:+        raise RuntimeError("cached initial model byte size differs")+    mapped = torch.from_file(+        str(model_path), shared=False, size=N_PARAM_ELEMENTS, dtype=torch.bfloat16+    )+    return nn.Parameter(mapped.npu()), metadata["parameters"]+++def load_checkpoint_state(rank: int):+    checkpoint_dir = Path(os.environ["OPENBUILD_CHECKPOINT_DIR"])+    state = _load_json(checkpoint_dir / "state.json")+    if state["n_elements"] != N_PARAM_ELEMENTS:+        raise RuntimeError("checkpoint model size differs")++    mapped = torch.from_file(+        str(checkpoint_dir / "model.bf16.bin"),+        shared=False,+        size=N_PARAM_ELEMENTS,+        dtype=torch.bfloat16,+    )+    weight = nn.Parameter(mapped.npu())+    half = N_PARAM_ELEMENTS // 2++    def load_raw(name: str) -> torch.Tensor:+        path = checkpoint_dir / f"{name}.rank{rank}.f32.bin"+        return torch.from_file(str(path), shared=False, size=half, dtype=torch.float32).npu()++    master = load_raw("master")+    first = load_raw("mom1")+    second = load_raw("mom2")+    return weight, master, first, second, state+++# ---------------------------------------------------------------------------+# Optimizer and observation helpers+# ---------------------------------------------------------------------------++def learning_rate_for(update_index: int) -> float:+    progress = min(update_index - 1, DECAY_UPDATES - 1)+    value = MIN_LR + 0.5 * (LR - MIN_LR) * (+        1.0 + math.cos(math.pi * progress / (DECAY_UPDATES - 1))+    )+    return _f32(value)+++def clip_coefficient(global_norm: float) -> float:+    return _f32(min(1.0, CLIP_GRAD / (float(global_norm) + CLIP_EPS)))+++def global_norm_chunked(tensor: torch.Tensor, chunk_elements: int = 128 * 1024 * 1024) -> float:+    total = torch.zeros((), device=tensor.device, dtype=torch.float32)+    for start in range(0, tensor.numel(), chunk_elements):+        end = min(start + chunk_elements, tensor.numel())+        segment = tensor.narrow(0, start, end - start)+        total.add_(segment.pow(2).sum())+    return math.sqrt(float(total.item()))+++def _selector_index(spec: dict[str, Any], selector: dict[str, Any]) -> int:+    return spec["offset"] + int(selector["flat_index"])+++def _owner_and_local(tensor: torch.Tensor, rank: int, global_index: int):+    half = N_PARAM_ELEMENTS // 2+    owner = 0 if global_index < half else 1+    if rank == owner:+        return owner, float(tensor[global_index - owner * half].item())+    return owner, 0.0+++def gather_shard_value(tensor: torch.Tensor, rank: int, global_index: int) -> float:+    owner, value = _owner_and_local(tensor, rank, global_index)+    carrier = torch.tensor([value], dtype=torch.float32, device=tensor.device)+    dist.broadcast(carrier, src=owner)+    return float(carrier.item())+++def build_selector_maps(profile: dict[str, Any]):+    selector_set = profile["selector_set"]+    by_update: dict[int, dict[str, list[dict[str, Any]]]] = {}+    for category in SELECTOR_CATEGORIES:+        for selector in selector_set[category]:+            update_index = int(selector["update_index"])+            by_update.setdefault(update_index, {}).setdefault(category, []).append(selector)+    return by_update+++def collect_logits_for_update(+    logits: torch.Tensor,+    global_batch_row: int,+    micro_global_rows: list[int],+    seq_index: int,+    vocab_index: int,+    values: dict[str, float],+    selector: dict[str, Any],+) -> None:+    try:+        local_row = micro_global_rows.index(global_batch_row)+    except ValueError:+        return+    values[selector["selector_id"]] = float(+        logits[local_row, int(seq_index), int(vocab_index)].item()+    )+++def projection_rows(+    selector_maps: dict[int, dict[str, list[dict[str, Any]]]],+    update_index: int,+    values: dict[str, float],+    profile_id: str,+    selector_set_id: str,+    *,+    committed: bool,+    source_update: int | None = None,+    loss: float,+    global_grad_norm: float,+) -> dict[str, Any]:+    projections: dict[str, list[dict[str, Any]]] = {}+    for category in SELECTOR_CATEGORIES:+        projections[category] = []+        for selector in selector_maps.get(update_index, {}).get(category, []):+            selector_id = selector["selector_id"]+            if selector_id not in values:+                raise RuntimeError(f"missing projection value for {selector_id}")+            projections[category].append(+                {"selector_id": selector_id, "value": values[selector_id]}+            )+    row: dict[str, Any] = {+        "schema_version": 1,+        "kind": (+            "openbuild_training_step_observation"+            if committed+            else "openbuild_training_fresh_process_observation"+        ),+        "profile_id": profile_id,+        "selector_set_id": selector_set_id,+        "update_index": update_index,+        "committed": committed,+        "loss": loss,+        "global_grad_norm": global_grad_norm,+        "projections": projections,+    }+    if not committed:+        row["source_optimizer_update"] = source_update+    return row+++def save_raw_fp32(tensor: torch.Tensor, path: Path) -> None:+    tensor.cpu().numpy().astype("<f4", copy=False).tofile(path)+++def save_raw_bf16(tensor: torch.Tensor, path: Path) -> None:+    tensor.cpu().view(torch.int16).numpy().astype("<i2", copy=False).tofile(path)+++def write_json(path: Path, payload: dict[str, Any]) -> None:+    path.write_text(+        json.dumps(payload, allow_nan=False, separators=(",", ":")) + "\n",+        encoding="utf-8",+    )+++def write_jsonl_line(path: Path, row: dict[str, Any]) -> None:+    with path.open("a", encoding="utf-8") as handle:+        handle.write(json.dumps(row, allow_nan=False, separators=(",", ":")) + "\n")+++# ---------------------------------------------------------------------------+# One update+# ---------------------------------------------------------------------------++def run_one_update(+    *,+    rank: int,+    model: FlatQwen3,+    master_shard: torch.Tensor,+    first_shard: torch.Tensor,+    second_shard: torch.Tensor,+    profile: dict[str, Any],+    selector_set_id: str,+    update_index: int,+    local_global_rows: list[int],+    ids_slice: torch.Tensor,+    labels_slice: torch.Tensor,+    mask_slice: torch.Tensor,+    positions_slice: torch.Tensor,+    selector_maps: dict[int, dict[str, list[dict[str, Any]]]],+    micro_batch_size: int,+) -> tuple[float, float, dict[str, float]]:+    device = model.weight.device+    global_batch_size = profile["global_batch_size"]+    seq_len = profile["sequence_length"]+    global_count = global_batch_size * seq_len+    local_count = int(ids_slice.shape[0])+    if global_count <= 0:+        raise RuntimeError("update has no masked tokens")++    model.weight.grad = None+    loss_sum = torch.zeros((), device=device, dtype=torch.float32)+    values: dict[str, float] = {}++    ids_slice = ids_slice.to(device=device, dtype=torch.long)+    labels_slice = labels_slice.to(device=device, dtype=torch.long)+    positions_slice = positions_slice.to(device=device, dtype=torch.long)+    mask_slice = mask_slice.to(device=device, dtype=torch.bool)++    causal_mask = make_causal_mask(seq_len, device)++    # Local samples are contiguous and ordered.  Each rank walks its own+    # records in global order and accumulates the fp32 global-mean gradient.+    micros = list(range(0, local_count, micro_batch_size))+    for local_start in micros:+        local_end = min(local_start + micro_batch_size, local_count)+        rows = local_global_rows[local_start:local_end]+        micro_ids = ids_slice[local_start:local_end]+        micro_labels = labels_slice[local_start:local_end]+        micro_positions = positions_slice[local_start:local_end]+        micro_mask = mask_slice[local_start:local_end]+        micro_labels = micro_labels.masked_fill(~micro_mask, -100)+        micro_cos, micro_sin = make_rope(micro_positions, device)++        logits = model(micro_ids, micro_positions, micro_cos, micro_sin, causal_mask)+        for selector in selector_maps.get(update_index, {}).get("logits", []):+            collect_logits_for_update(+                logits,+                int(selector["global_batch_row"]),+                rows,+                int(selector["sequence_index"]),+                int(selector["vocab_index"]),+                values,+                selector,+            )++        nll_sum = F.cross_entropy(+            logits.float().reshape(-1, VOCAB_SIZE),+            micro_labels.reshape(-1),+            ignore_index=-100,+            reduction="sum",+        )+        loss_sum = loss_sum + nll_sum+        (nll_sum / global_count).backward()++        if model.weight.grad is None:+            raise RuntimeError("backward produced no model gradient")++        # Drop graph references before the next micro pass.  Autograd+        # accumulates the local micro gradients in the flat bf16 grad while+        # the fp32 global buffer is built only after the last micro pass.+        del logits, nll_sum, micro_ids, micro_labels, micro_positions, micro_mask++    dist.all_reduce(loss_sum, op=dist.ReduceOp.SUM)+    loss = float((loss_sum / global_count).item())++    # Logit selectors may live in either rank's contiguous half of the global+    # batch.  Exchange those few scalar values before the rank-0 writer+    # assembles the observation row.+    local_half_rows = global_batch_size // 2+    for selector in selector_maps.get(update_index, {}).get("logits", []):+        selector_id = selector["selector_id"]+        owner = 0 if int(selector["global_batch_row"]) < local_half_rows else 1+        local_value = values.get(selector_id, 0.0) if rank == owner else 0.0+        carrier = torch.tensor([local_value], dtype=torch.float32, device=device)+        dist.broadcast(carrier, src=owner)+        values[selector_id] = float(carrier.item())++    grad_accum = model.weight.grad.float()+    model.weight.grad = None++    # Chunked all-reduce: each rank contributes its accumulated fp32 gradient+    # of the global mean loss; summing both ranks gives the global-mean grad.+    chunk_elements = 256 * 1024 * 1024+    for start in range(0, grad_accum.numel(), chunk_elements):+        end = min(start + chunk_elements, grad_accum.numel())+        dist.all_reduce(grad_accum.narrow(0, start, end - start), op=dist.ReduceOp.SUM)++    grad_norm = global_norm_chunked(grad_accum)+    # Pre-clip gradient projections come from the fully reduced fp32 grad.+    for selector in selector_maps.get(update_index, {}).get("gradients", []):+        index = _selector_index(PARAM_BY_NAME[selector["canonical_parameter_name"]], selector)+        values[selector["selector_id"]] = float(grad_accum[index].item())++    # Global clipping coefficient, then fp32 AdamW on the rank's optimizer shard.+    coefficient = clip_coefficient(grad_norm)+    grad_accum.mul_(coefficient)+    lr = learning_rate_for(update_index)+    bias1 = _f32(1.0 - BETA1 ** update_index)+    bias2 = _f32(1.0 - BETA2 ** update_index)+    beta1_f = _f32(BETA1)+    beta2_f = _f32(BETA2)+    eps_f = _f32(ADAM_EPS)+    wd_f = _f32(WEIGHT_DECAY)++    shard_start = SHARD_BOUNDARIES[rank]+    shard_end = SHARD_BOUNDARIES[rank + 1]++    with torch.no_grad():+        for spec in PARAM_SPECS:+            g0 = max(spec["offset"], shard_start)+            g1 = min(spec["offset"] + spec["numel"], shard_end)+            if g0 >= g1:+                continue+            l0 = g0 - shard_start+            l1 = g1 - shard_start+            grad = grad_accum.narrow(0, g0, g1 - g0)+            m = first_shard.narrow(0, l0, l1 - l0)+            v = second_shard.narrow(0, l0, l1 - l0)+            p = master_shard.narrow(0, l0, l1 - l0)++            m.mul_(beta1_f).add_(grad, alpha=_f32(1.0 - BETA1))+            v.mul_(beta2_f).addcmul_(grad, grad, value=_f32(1.0 - BETA2))+            m_hat = m / bias1+            v_hat = v / bias2+            denominator = torch.sqrt(torch.clamp_min(v_hat, 0.0)) + eps_f+            direction = m_hat / denominator+            if spec["weight_decay"]:+                direction = direction + (wd_f * p)+            p.add_(direction, alpha=-lr)++            # Convert this rank's updated fp32 shard to bf16 model storage.+            model.weight.narrow(0, g0, g1 - g0).copy_(p.bfloat16())+    del grad_accum++    # Exchange the two updated bf16 shards so both ranks keep full model replicas.+    half = N_PARAM_ELEMENTS // 2+    first_half = model.weight.narrow(0, 0, half)+    second_half = model.weight.narrow(0, half, half)+    dist.broadcast(first_half, src=0)+    dist.broadcast(second_half, src=1)++    # Post-step observations.+    for category, tensor in (+        ("model_parameters", model.weight),+        ("master_parameters", master_shard),+        ("first_moments", first_shard),+        ("second_moments", second_shard),+    ):+        for selector in selector_maps.get(update_index, {}).get(category, []):+            index = _selector_index(+                PARAM_BY_NAME[selector["canonical_parameter_name"]], selector+            )+            if category == "model_parameters":+                values[selector["selector_id"]] = float(model.weight[index].item())+            else:+                values[selector["selector_id"]] = gather_shard_value(+                    tensor, rank, index+                )+    return loss, grad_norm, values+++# ---------------------------------------------------------------------------+# Training / fresh probe drivers+# ---------------------------------------------------------------------------++def _step_state_defaults(profile: dict[str, Any]) -> dict[str, int | list[int]]:+    return {+        "committed_updates": 0,+        "scheduler_next_update_index": 1,+        "data_cursor_next_update_index": 1,+        "data_cursor_next_global_sample_ordinal": 0,+        "parameter_steps": [0 for _ in PARAM_SPECS],+    }+++def advance_step_state(state: dict[str, Any], global_batch_size: int) -> None:+    state["committed_updates"] += 1+    state["scheduler_next_update_index"] += 1+    state["data_cursor_next_update_index"] += 1+    state["data_cursor_next_global_sample_ordinal"] += global_batch_size+    state["parameter_steps"] = [int(x) + 1 for x in state["parameter_steps"]]+++def save_checkpoint(+    *,+    rank: int,+    model: FlatQwen3,+    master_shard: torch.Tensor,+    first_shard: torch.Tensor,+    second_shard: torch.Tensor,+    profile: dict[str, Any],+    step_state: dict[str, Any],+    checkpoint_dir: Path,+) -> None:+    if rank == 0:+        save_raw_bf16(model.weight, checkpoint_dir / "model.bf16.bin")+    save_raw_fp32(master_shard, checkpoint_dir / f"master.rank{rank}.f32.bin")+    save_raw_fp32(first_shard, checkpoint_dir / f"mom1.rank{rank}.f32.bin")+    save_raw_fp32(second_shard, checkpoint_dir / f"mom2.rank{rank}.f32.bin")+    dist.barrier()+    if rank == 0:+        state = {+            "schema_version": 1,+            "profile_id": profile["profile_id"],+            "n_elements": N_PARAM_ELEMENTS,+            "dtype": "bf16",+            "optimizer_update": 30,+            "next_update_index": 31,+            "parameters": PARAM_SPECS,+            **step_state,+        }+        write_json(checkpoint_dir / "state.json", state)+++def write_checkpoint_manifest(profile_id: str, output_dir: Path) -> None:+    files = sorted(+        [+            "model.bf16.bin",+            "master.rank0.f32.bin",+            "master.rank1.f32.bin",+            "mom1.rank0.f32.bin",+            "mom1.rank1.f32.bin",+            "mom2.rank0.f32.bin",+            "mom2.rank1.f32.bin",+            "state.json",+        ]+    )+    write_json(+        output_dir / "checkpoint-manifest.json",+        {+            "schema_version": 1,+            "kind": "openbuild_training_checkpoint",+            "task_id": TASK_ID,+            "profile_id": profile_id,+            "initialization_spec": "canonical_tensor_counter_v1",+            "optimizer_update": 30,+            "next_update_index": 31,+            "state_components": [+                "model",+                "master_parameters",+                "first_moments",+                "second_moments",+                "parameter_steps",+                "scheduler",+                "data_cursor",+                "committed_update",+            ],+            "files": files,+            "fresh_load_entrypoint": "train.sh",+            "fresh_next_step_mode": "fresh_next_step_probe",+        },+    )+++def write_result(profile_id: str, output_dir: Path, summary: dict[str, Any]) -> None:+    write_json(+        output_dir / "result.json",+        {+            "schema_version": 1,+            "kind": "openbuild_training_result",+            "task_id": TASK_ID,+            "profile_id": profile_id,+            "status": "completed",+            "optimizer_updates": 30,+            "consumed_tokens": 983040,+            "logical_device_ids": [0, 1],+            "trajectory_path": "trajectory.jsonl",+            "trajectory_rows": 30,+            "checkpoint_manifest_path": "checkpoint-manifest.json",+            "checkpoint_committed": True,+            "all_ranks_exited": True,+            "delivery_summary": summary,+        },+    )+++def train_main(rank: int, profile: dict[str, Any]) -> int:+    tensors, global_batch_size = load_input_tensors(profile)+    selector_set = profile["selector_set"]+    selector_set_id = selector_set["selector_set_id"]+    selector_maps = build_selector_maps(profile)+    output_dir = Path(os.environ["OPENBUILD_OUTPUT_DIR"])+    checkpoint_dir = Path(os.environ["OPENBUILD_CHECKPOINT_DIR"])+    trajectory_path = output_dir / "trajectory.jsonl"+    if rank == 0:+        trajectory_path.unlink(missing_ok=True)++    weight, _ = load_initial_flat_model(rank)+    model = FlatQwen3(weight).npu()+    half = N_PARAM_ELEMENTS // 2+    shard_start = SHARD_BOUNDARIES[rank]+    shard_end = SHARD_BOUNDARIES[rank + 1]+    master_shard = torch.zeros(half, device=f"npu:{rank}", dtype=torch.float32)+    first_shard = torch.zeros(half, device=f"npu:{rank}", dtype=torch.float32)+    second_shard = torch.zeros(half, device=f"npu:{rank}", dtype=torch.float32)++    # Initial master is the exact bf16-to-fp32 widening of the public model.+    with torch.no_grad():+        master_shard.copy_(model.weight[shard_start:shard_end].float())++    step_state = _step_state_defaults(profile)+    local_half = global_batch_size // 2+    local_global_rows = list(range(rank * local_half, (rank + 1) * local_half))+    if profile["sequence_length"] >= 2048:+        micro_batch_size = 1+    else:+        micro_batch_size = 4++    dist.barrier()+    for update_index in range(1, TRAINING_UPDATES + 1):+        step = update_slice(tensors, update_index)+        local_half_rows = local_half+        step = {+            "input_ids": step["input_ids"][rank * local_half_rows:(rank + 1) * local_half_rows],+            "labels": step["labels"][rank * local_half_rows:(rank + 1) * local_half_rows],+            "loss_mask": step["loss_mask"][rank * local_half_rows:(rank + 1) * local_half_rows],+            "position_ids": step["position_ids"][rank * local_half_rows:(rank + 1) * local_half_rows],+            "sample_ids": step["sample_ids"][rank * local_half_rows:(rank + 1) * local_half_rows],+        }+        loss, grad_norm, values = run_one_update(+            rank=rank,+            model=model,+            master_shard=master_shard,+            first_shard=first_shard,+            second_shard=second_shard,+            profile=profile,+            selector_set_id=selector_set_id,+            update_index=update_index,+            local_global_rows=local_global_rows,+            ids_slice=torch.from_numpy(step["input_ids"]).to(torch.long),+            labels_slice=torch.from_numpy(step["labels"]).to(torch.long),+            mask_slice=torch.from_numpy(step["loss_mask"]),+            positions_slice=torch.from_numpy(step["position_ids"]).to(torch.long),+            selector_maps=selector_maps,+            micro_batch_size=micro_batch_size,+        )+        advance_step_state(step_state, global_batch_size)+        if rank == 0:+            row = projection_rows(+                selector_maps,+                update_index,+                values,+                profile["profile_id"],+                selector_set_id,+                committed=True,+                loss=loss,+                global_grad_norm=grad_norm,+            )+            write_jsonl_line(trajectory_path, row)+        dist.barrier()++    save_checkpoint(+        rank=rank,+        model=model,+        master_shard=master_shard,+        first_shard=first_shard,+        second_shard=second_shard,+        profile=profile,+        step_state=step_state,+        checkpoint_dir=checkpoint_dir,+    )+    if rank == 0:+        write_checkpoint_manifest(profile["profile_id"], output_dir)+        write_result(+            profile["profile_id"],+            output_dir,+            {+                "implementation": "flat-bf16-data-parallel-zero1",+                "micro_batch_size": micro_batch_size,+                "optimizer_shards": 2,+            },+        )+    dist.barrier()+    return 0+++def fresh_main(rank: int, profile: dict[str, Any]) -> int:+    step, global_batch_size = load_input_slice(profile, FRESH_UPDATE), profile["global_batch_size"]+    selector_set = profile["selector_set"]+    selector_set_id = selector_set["selector_set_id"]+    selector_maps = build_selector_maps(profile)+    output_dir = Path(os.environ["OPENBUILD_OUTPUT_DIR"])++    weight, master_shard, first_shard, second_shard, checkpoint_state = (+        load_checkpoint_state(rank)+    )+    if checkpoint_state["committed_updates"] != 30:+        raise RuntimeError("checkpoint committed update differs")+    model = FlatQwen3(weight).npu()+    local_half = global_batch_size // 2+    local_global_rows = list(range(rank * local_half, (rank + 1) * local_half))+    micro_batch_size = 1 if profile["sequence_length"] >= 2048 else 4++    step = {+        "input_ids": step["input_ids"][rank * local_half:(rank + 1) * local_half],+        "labels": step["labels"][rank * local_half:(rank + 1) * local_half],+        "loss_mask": step["loss_mask"][rank * local_half:(rank + 1) * local_half],+        "position_ids": step["position_ids"][rank * local_half:(rank + 1) * local_half],+        "sample_ids": step["sample_ids"][rank * local_half:(rank + 1) * local_half],+    }+    loss, grad_norm, values = run_one_update(+        rank=rank,+        model=model,+        master_shard=master_shard,+        first_shard=first_shard,+        second_shard=second_shard,+        profile=profile,+        selector_set_id=selector_set_id,+        update_index=FRESH_UPDATE,+        local_global_rows=local_global_rows,+        ids_slice=torch.from_numpy(step["input_ids"]).to(torch.long),+        labels_slice=torch.from_numpy(step["labels"]).to(torch.long),+        mask_slice=torch.from_numpy(step["loss_mask"]),+        positions_slice=torch.from_numpy(step["position_ids"]).to(torch.long),+        selector_maps=selector_maps,+        micro_batch_size=micro_batch_size,+    )+    # In-memory would-be step.  Do not write a checkpoint or advance state.+    if rank == 0:+        row = projection_rows(+            selector_maps,+            FRESH_UPDATE,+            values,+            profile["profile_id"],+            selector_set_id,+            committed=False,+            source_update=30,+            loss=loss,+            global_grad_norm=grad_norm,+        )+        path = output_dir / "check-observations.jsonl"+        path.unlink(missing_ok=True)+        write_jsonl_line(path, row)+    dist.barrier()+    return 0+++def main() -> int:+    parser = argparse.ArgumentParser(add_help=False)+    parser.add_argument("--rank", type=int, required=True)+    parser.add_argument("--world-size", type=int, required=True)+    args = parser.parse_args()++    rank = args.rank+    world_size = args.world_size+    if world_size != 2 or rank not in (0, 1):+        raise RuntimeError("this solution uses exactly two runtime-logical ranks")++    torch.npu.set_device(rank)+    dist.init_process_group(+        backend="hccl",+        init_method="env://",+        rank=rank,+        world_size=world_size,+    )+    try:+        _, profile = load_input_manifest()+        action = os.environ["OPENBUILD_ACTION"]+        if action == "train":+            status = train_main(rank, profile)+        elif action == "fresh_next_step_probe":+            status = fresh_main(rank, profile)+        else:+            raise RuntimeError(f"unexpected action {action!r}")+        dist.barrier()+    finally:+        dist.destroy_process_group()+    return status+++if __name__ == "__main__":+    raise SystemExit(main())diff --git a/solution/train.sh b/solution/train.shnew file mode 100755index 0000000000000000000000000000000000000000..c9ca93df2831ea85628f81d7b0b9fb3e2ebd06fe--- /dev/null+++ b/solution/train.sh@@ -0,0 +1,15 @@+#!/usr/bin/env bash+set -euo pipefail+cd "$(dirname "${BASH_SOURCE[0]}")"++if [[ "${OPENBUILD_ACTION:-}" == "bootstrap" ]]; then+  exec python3 -B bootstrap_main.py+fi++if [[ "${OPENBUILD_ACTION}" != "train" && "${OPENBUILD_ACTION}" != "fresh_next_step_probe" ]]; then+  echo "unknown OPENBUILD_ACTION: ${OPENBUILD_ACTION:-}" >&2+  exit 2+fi++export PYTHONUNBUFFERED=1+exec python3 -B train_supervisor.pydiff --git a/solution/train_supervisor.py b/solution/train_supervisor.pynew file mode 100644index 0000000000000000000000000000000000000000..aecb14d44c291c96a003d662249be28510803e79--- /dev/null+++ b/solution/train_supervisor.py@@ -0,0 +1,106 @@+from __future__ import annotations++import os+import signal+import socket+import subprocess+import sys+import time++RANKS = (0, 1)+++def _free_port() -> int:+    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:+        sock.bind(("127.0.0.1", 0))+        return int(sock.getsockname()[1])+++def _terminate(procs: list[subprocess.Popen]) -> None:+    for proc in procs:+        if proc.poll() is None:+            try:+                proc.terminate()+            except OSError:+                pass+++def main() -> int:+    action = os.environ.get("OPENBUILD_ACTION")+    if action not in {"train", "fresh_next_step_probe"}:+        print(f"train_supervisor received unexpected action {action!r}", file=sys.stderr)+        return 2++    env = dict(os.environ)+    env["MASTER_ADDR"] = env.get("MASTER_ADDR", "127.0.0.1")+    env["MASTER_PORT"] = env.get("MASTER_PORT") or str(_free_port())+    env["WORLD_SIZE"] = str(len(RANKS))++    procs: list[subprocess.Popen] = []+    for rank in RANKS:+        rank_env = dict(env)+        rank_env["RANK"] = str(rank)+        procs.append(+            subprocess.Popen(+                [sys.executable, "-B", "train.py", "--rank", str(rank), "--world-size", str(len(RANKS))],+                cwd=os.path.dirname(os.path.abspath(__file__)),+                env=rank_env,+                stdin=subprocess.DEVNULL,+            )+        )++    def forward_signal(signum, _frame):+        for proc in procs:+            if proc.poll() is None:+                try:+                    proc.send_signal(signum)+                except OSError:+                    pass++    old_handlers = {+        signum: signal.signal(signum, forward_signal)+        for signum in (signal.SIGTERM, signal.SIGINT)+    }+    try:+        first_failure = None+        while True:+            running = [proc for proc in procs if proc.poll() is None]+            if not running:+                break+            failed = [proc for proc in procs if proc.poll() is not None and proc.returncode != 0]+            if failed and first_failure is None:+                first_failure = failed[0].returncode+                _terminate(running)+                deadline = time.monotonic() + 60.0+                for proc in procs:+                    if proc.poll() is None:+                        try:+                            proc.wait(timeout=max(0.01, deadline - time.monotonic()))+                        except subprocess.TimeoutExpired:+                            proc.kill()+            time.sleep(0.2)+        if first_failure is not None:+            return int(first_failure)+        return 0+    finally:+        for signum, handler in old_handlers.items():+            signal.signal(signum, handler)+        for proc in procs:+            if proc.poll() is None:+                _terminate([proc])+        for proc in procs:+            try:+                proc.wait(timeout=10.0)+            except subprocess.TimeoutExpired:+                try:+                    proc.kill()+                except OSError:+                    pass+                try:+                    proc.wait(timeout=10.0)+                except subprocess.TimeoutExpired:+                    pass+++if __name__ == "__main__":+    raise SystemExit(main())