MiniMax M3 · Training

T06 · Training build

Correctness rejected

OpenBuild Qwen3-4B training 2dev · Open Build

—PERFORMANCE RATIO
212TOOL 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 agentMiniMax M3 · 212 visible calls

InspectEditValidateExecuteBuildProfileRollbackOther
61Inspect
62Edit
23Build
4Validate
16Execute
11Profile
35Other

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 timeline150 groups · 212 calls

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

Main agent

  1. Inspect · Source & workspace

    Requested workspace inspection related to source & workspace.

    1 call · #0001–#0001

    ls <path>echo <flag>echo <val>
  2. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    2 calls · #0002–#0003

    Read <path>
  3. Inspect · Source & workspace

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

    5 calls · #0004–#0008

    ls -l -a <path>echo <flag>cat <path>Read <path>
  4. Inspect · Task requirements

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

    2 calls · #0009–#0010

    ls <path> <path> <path> <path>Read <path>
  5. Other · Task requirements

    Requested task coordination related to task requirements.

    1 call · #0011–#0011

    Create task <task>
  6. Build · Attention kernels

    Requested task coordination related to attention kernels.

    1 call · #0012–#0012

    Create task <task>
  7. Build · Source & workspace

    Requested task coordination related to source & workspace.

    2 calls · #0013–#0014

    Create task <task>
  8. Build · Batching & scheduling

    Requested task coordination related to batching & scheduling.

    1 call · #0015–#0015

    Create task <task>
  9. Build · Checkpoints & weight state

    Requested task coordination related to checkpoints & weight state.

    1 call · #0016–#0016

    Create task <task>
  10. Execute · Attention kernels

    Requested task coordination related to attention kernels.

    1 call · #0017–#0017

    Create task <task>
  11. Validate · Benchmark & validation setup

    Requested task coordination related to benchmark & validation setup.

    1 call · #0018–#0018

    Create task <task>
  12. Other · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0019–#0019

    Update task <task>
  13. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    1 call · #0020–#0020

    Read <path>
  14. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    2 calls · #0021–#0022

    Read <path>
  15. Inspect · Checkpoints & weight state

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

    1 call · #0023–#0023

    Read <path>
  16. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0024–#0024

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

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

    1 call · #0025–#0025

    Read <path>
  18. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    5 calls · #0026–#0030

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

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

    3 calls · #0031–#0033

    Read <path>
  20. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0034–#0034

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

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

    2 calls · #0035–#0036

    Read <path>
  22. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0037–#0037

    Read <path>
  23. Inspect · Device memory

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

    1 call · #0038–#0038

    which <val> <val>python3 --versionwhich <val> <n> > <path>python3 -c <script> <n> >& <path>head -n <n>
  24. Inspect · Source & workspace

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

    1 call · #0039–#0039

    ls <path>head -n <n>echo <flag>ls <path> <n> > <path>grep -i <val> <n> > <path>grep <val> <n> > <path>
    2 more command sketches
    pip3 list <n> > <path>grep -i -E <val>
  25. Inspect · Device memory

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

    1 call · #0040–#0040

    ls -l -a <path> <n> >& <path>head -n <n>echo <flag>npu-smi info <n> >& <path>python3 -c <script> <n> >& <path>
  26. Other · Parallelism & communication

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

    1 call · #0041–#0041

    python3 -c <script> <n> >& <path>grep -v <val>
  27. Inspect · Source & workspace

    Requested dependency and build commands, source searches and file and log inspection related to source & workspace.

    1 call · #0042–#0042

    pip3 list <n> > <path>grep -i -E <val>head -n <n>echo <flag>python3 -c <script>python3 -c <script> <n> >& <path>
  28. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    1 call · #0043–#0043

    wc -l <path>head -n <n> <path>
  29. Inspect · Source & workspace

    Requested workspace inspection related to source & workspace.

    1 call · #0044–#0044

    df -h <path> <path> <n> >& <path>echo <flag>ls -l -a <path>
  30. Other · Source & workspace

    Requested task coordination related to source & workspace.

    2 calls · #0045–#0046

    Update task <task>
  31. Inspect · Source & workspace

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

    1 call · #0047–#0047

    mkdir -p <path>ls -l -a <path>
  32. Edit · Task requirements

    Requested code edits related to task requirements.

    1 call · #0048–#0048

    Write <path>
  33. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0049–#0050

    Write <path>
  34. Build · Source & workspace

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

    1 call · #0051–#0051

    chmod <val> <path> <path>ls -l -a <path>
  35. Execute · Task requirements

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

    1 call · #0052–#0052

    chmod <n> <path> <path> <path>chmod <n> <path>ls -l -a <path>
  36. Edit · Source & workspace

    Requested code edits related to source & workspace.

    3 calls · #0053–#0055

    Write <path>
  37. Other · Source & workspace

    Requested task coordination related to source & workspace.

    3 calls · #0056–#0058

    Update task <task>
  38. Edit · Source & workspace

    Requested code edits related to source & workspace.

    3 calls · #0059–#0061

    Write <path>
  39. Edit · Batching & scheduling

    Requested code edits related to batching & scheduling.

    1 call · #0062–#0062

    Write <path>
  40. Edit · Optimizer & gradients

    Requested code edits related to optimizer & gradients.

    1 call · #0063–#0063

    Write <path>
  41. Edit · Checkpoints & weight state

    Requested code edits related to checkpoints & weight state.

    1 call · #0064–#0064

    Write <path>
  42. Edit · Runtime processes

    Requested code edits related to runtime processes.

    1 call · #0065–#0065

    Write <path>
  43. Edit · Task requirements

    Requested code edits related to task requirements.

    1 call · #0066–#0066

    Write <path>
  44. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0067–#0068

    Write <path>
  45. Inspect · Source & workspace

    Requested workspace inspection related to source & workspace.

    1 call · #0069–#0069

    find <path> -type <val>sort
  46. Other · Source & workspace

    Requested task coordination related to source & workspace.

    5 calls · #0070–#0074

    Update task <task>
  47. Build · Source & workspace

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

    1 call · #0075–#0075

    cd <path>env <vars> python3 -B -c <script> <n> >& <path>grep -v <val>
  48. Edit · Source & workspace

    Requested code edits related to source & workspace.

    3 calls · #0076–#0078

    Edit <path>
  49. Validate · Precision & numerical checks

    Requested environment setup or inspection and source searches related to precision & numerical checks.

    1 call · #0079–#0079

    env <vars> python3 -B -c <script> <n> >& <path>grep -v <val>
  50. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0080–#0080

    Edit <path>
  51. Other · Precision & numerical checks

    Requested environment setup or inspection and source searches related to precision & numerical checks.

    1 call · #0081–#0081

    env <vars> python3 -B -c <script> <n> >& <path>grep -v <val>
  52. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0082–#0083

    Edit <path>
  53. Other · Source & workspace

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

    1 call · #0084–#0084

    env <vars> python3 -B -c <script> <n> >& <path>grep -v <val>
  54. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0085–#0085

    Edit <path>
  55. Other · Source & workspace

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

    1 call · #0086–#0086

    env <vars> python3 -B -c <script> <n> >& <path>grep -v <val>
  56. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0087–#0088

    Edit <path>
  57. Other · Source & workspace

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

    1 call · #0089–#0089

    env <vars> python3 -B -c <script> <n> >& <path>grep -v <val>
  58. Profile · Precision & numerical checks

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

    1 call · #0090–#0090

    python3 -B -c <script>
  59. Profile · Runtime processes

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

    1 call · #0091–#0091

    python3 -B -c <script> <n> >& <path>tail -n <n>
  60. Build · Source & workspace

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

    1 call · #0092–#0092

    env <vars> python3 -B -c <script> <n> >& <path>grep -v <val>
  61. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0093–#0094

    Edit <path>
  62. Build · Source & workspace

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

    1 call · #0095–#0095

    env <vars> python3 -B -c <script> <n> >& <path>grep -v <val>
  63. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0096–#0096

    Edit <path>
  64. Build · Source & workspace

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

    1 call · #0097–#0097

    env <vars> python3 -B -c <script> <n> >& <path>grep -v <val>
  65. Other · Source & workspace

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

    3 calls · #0098–#0100

    Stop task <task>shell <script>env <vars> python3 -B -c <script> <n> >& <path>grep -v <val>
  66. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0101–#0101

    Edit <path>
  67. Other · Source & workspace

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

    1 call · #0102–#0102

    env <vars> python3 -B -c <script> <n> >& <path>grep -v <val>
  68. Build · Source & workspace

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

    2 calls · #0103–#0104

    env <vars> timeout <n> <val> -B -c <path> <n> >& <path>grep -v <val>sleep <n>cat <path> <n> > <path>
  69. Inspect · Source & workspace

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

    1 call · #0105–#0105

    cat <path> <n> > <path>grep -v <val>tail -n <n>echo <flag>ps <val>grep -i <val>
    1 more command sketches
    head -n <n>
  70. Build · Source & workspace

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

    2 calls · #0106–#0107

    sleep <n>cat <path> <n> > <path>grep -v <val>tail -n <n>echo <flag>ps <val>
    2 more command sketches
    grep <val>head -n <n>
  71. Inspect · Source & workspace

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

    4 calls · #0108–#0111

    cat <path> <n> > <path>grep -v <val>tail -n <n>Read <path>find <path> -type <val> <n> > <path>xargs <val> -la <n> > <path>
  72. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0112–#0112

    Write <path>
  73. Other · Source & workspace

    Requested workspace file updates related to source & workspace.

    1 call · #0113–#0113

    rm <path> <n> > <path>echo <val>
  74. Build · Source & workspace

    1 tool error

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

    1 call · #0114–#0114

    env <vars> python3 -B -c <script> <n> >& <path>grep -v <val>env <vars>echo <val>sleep <n>ps -p <val> > <path>
    1 more command sketches
    wait <val>
  75. Other · Runtime processes

    1 tool error

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

    1 call · #0115–#0115

    pkill -f <val> <n> > <path>sleep <n>ps <val>grep <val>grep -v <val>
  76. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0116–#0116

    Write <path>
  77. Inspect · Source & workspace

    Requested dependency and build commands and file and log inspection related to source & workspace.

    1 call · #0117–#0117

    which <val>gcc --version <n> >& <path>head -n <n>
  78. Execute · Benchmark & validation setup

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

    1 call · #0118–#0118

    env <vars> python3 -B -c <script> <n> >& <path>grep -v <val>
  79. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0119–#0120

    Edit <path>
  80. Other · Source & workspace

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

    1 call · #0121–#0121

    env <vars> python3 -B -c <script> <n> >& <path>grep -v <val>
  81. Build · Source & workspace

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

    1 call · #0122–#0122

    env <vars> python3 -B -c <script> <n> >& <path>grep -v <val>
  82. Profile · Source & workspace

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

    2 calls · #0123–#0124

    env <vars> python3 -B -c <script> <n> >& <path>grep -v <val>
  83. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0125–#0125

    Edit <path>
  84. Build · Source & workspace

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

    1 call · #0126–#0126

    env <vars> python3 -B -c <script> <n> >& <path>grep -v <val>
  85. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0127–#0127

    Edit <path>
  86. Build · Optimizer & gradients

    Requested environment setup or inspection and source searches related to optimizer & gradients.

    1 call · #0128–#0128

    env <vars> python3 -B -c <script> <n> >& <path>grep -v <val>
  87. Build · Source & workspace

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

    1 call · #0129–#0129

    sleep <n>cat <path> <n> > <path>grep -v <val>tail -n <n>
  88. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0130–#0130

    Edit <path>
  89. Other · Optimizer & gradients

    Requested environment setup or inspection and source searches related to optimizer & gradients.

    1 call · #0131–#0131

    env <vars> python3 -B -c <script> <n> >& <path>grep -v <val>
  90. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0132–#0132

    Edit <path>
  91. Build · Optimizer & gradients

    Requested environment setup or inspection and source searches related to optimizer & gradients.

    1 call · #0133–#0133

    env <vars> python3 -B -c <script> <n> >& <path>grep -v <val>
  92. Build · Source & workspace

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

    1 call · #0134–#0134

    sleep <n>cat <path> <n> > <path>grep -v <val>tail -n <n>
  93. Inspect · Source & workspace

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

    1 call · #0135–#0135

    sleep <n>cat <path> <n> > <path>grep -v <val>tail -n <n>
  94. Other · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0136–#0136

    Stop task <task>
  95. Inspect · Runtime processes

    1 tool error

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

    1 call · #0137–#0137

    pkill -f <val> <n> > <path>sleep <n>ps <val>grep <val>grep -v <val>head -n <n>
  96. Profile · Precision & numerical checks

    Requested environment setup or inspection and source searches related to precision & numerical checks.

    1 call · #0138–#0138

    env <vars> timeout <n> <val> -B -c <val> <n> >& <path>grep -v <val>
  97. Profile · Source & workspace

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

    1 call · #0139–#0139

    env <vars> timeout <n> <val> -B -c <val> <n> >& <path>grep -v <val>
  98. Other · Source & workspace

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

    1 call · #0140–#0140

    env <vars> timeout <n> <val> -B -c <val> <n> >& <path>grep -v <val>
  99. Inspect · Runtime processes

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

    1 call · #0141–#0141

    ps <val>grep <val>grep -v <val>head -n <n>ls -l -a <path>
  100. Other · Source & workspace

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

    3 calls · #0142–#0144

    env <vars> timeout <n> <val> -B -c <path> <n> >& <path>grep -v <val>env <vars> timeout <n> <val> -B -c <val> <n> >& <path>
  101. Other · Attention kernels

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

    1 call · #0145–#0145

    env <vars> timeout <n> <val> -B -c <path> <n> >& <path>grep -v <val>
  102. Other · Source & workspace

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

    1 call · #0146–#0146

    env <vars> timeout <n> <val> -B -c <val> <n> >& <path>grep -v <val>
  103. Profile · Precision & numerical checks

    Requested environment setup or inspection and source searches related to precision & numerical checks.

    2 calls · #0147–#0148

    env <vars> timeout <n> <val> -B -c <val> <n> >& <path>grep -v <val>
  104. Edit · Source & workspace

    1 tool error

    Requested code edits related to source & workspace.

    4 calls · #0149–#0152

    Edit <path>
  105. Build · Optimizer & gradients

    Requested environment setup or inspection and source searches related to optimizer & gradients.

    1 call · #0153–#0153

    env <vars> timeout <n> <val> -B -c <val> <n> >& <path>grep -v <val>
  106. Build · Source & workspace

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

    1 call · #0154–#0154

    env <vars> timeout <n> <val> -B -c <val> <n> >& <path>grep -v <val>
  107. Inspect · Task requirements

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

    1 call · #0155–#0155

    cd <path>python3 -B <script> --output <path> <n> >& <path>tail -n <n>echo <flag>ls -l -a <path>cat <path>
    1 more command sketches
    head -n <n>
  108. Validate · Checkpoints & weight state

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

    2 calls · #0156–#0157

    cd <path>mkdir -p <path>env <vars> timeout <n> <val> -B <path> <n> >& <path>grep -v <val>tail -n <n>env <vars> bash <script> <n> >& <path>
  109. Execute · Checkpoints & weight state

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

    1 call · #0158–#0158

    env <vars> bash <script> <n> >& <path>grep -v <val>tail -n <n>
  110. Execute · Source & workspace

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

    1 call · #0159–#0159

    bash -x <script> <n> >& <path>head -n <n>
  111. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0160–#0160

    Edit <path>
  112. Execute · Checkpoints & weight state

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

    1 call · #0161–#0161

    env <vars> bash <script> <n> >& <path>grep -v <val>tail -n <n>
  113. Profile · Device memory

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

    1 call · #0162–#0162

    env <vars> timeout <n> <val> -B -c <path> <n> >& <path>grep -v <val>
  114. Other · Source & workspace

    Requested execution waits related to source & workspace.

    1 call · #0163–#0163

    sleep <n>echo <val>
  115. Inspect · Runtime processes

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

    2 calls · #0164–#0165

    ps <val>grep <val>grep -v <val>head -n <n>echo <flag>ls <path>
  116. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0166–#0166

    Edit <path>
  117. Profile · Device memory

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

    1 call · #0167–#0167

    env <vars> timeout <n> <val> -B -c <path> <n> >& <path>grep -v <val>
  118. Edit · Source & workspace

    Requested code edits related to source & workspace.

    5 calls · #0168–#0172

    Edit <path>
  119. Execute · Checkpoints & weight state

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

    1 call · #0173–#0173

    rm -rf <path>mkdir -p <path>cp -r <path> <path>env <vars> bash <script> <n> >& <path>grep -v <val>tail -n <n>
    5 more command sketches
    echo <val>sleep <n>ps <val>grep -E <val>head -n <n>
  120. Inspect · Device memory

    Requested execution waits, runtime inspection and source searches related to device memory.

    1 call · #0174–#0174

    sleep <n>ps <val>grep <val>grep -v <val>head -n <n>echo <flag>
    2 more command sketches
    nvidia-smi <n> >& <path>npu-smi info <n> >& <path>
  121. Inspect · Benchmark & validation setup

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

    2 calls · #0175–#0176

    sleep <n>ps <val>grep <val>grep -v <val>head -n <n>echo <flag>
    2 more command sketches
    cat <path> <n> > <path>ls -l -a <path> <n> > <path>
  122. Execute · Checkpoints & weight state

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

    1 call · #0177–#0177

    cd <path>env <vars> bash <script> <n> >& <path>grep -v <val>tail -n <n>
  123. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0178–#0178

    Edit <path>
  124. Execute · Checkpoints & weight state

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

    1 call · #0179–#0179

    cd <path>rm -rf <path> <path>mkdir -p <path> <path>env <vars> bash <script> <n> >& <path>grep -v <val>tail -n <n>
  125. Profile · Checkpoints & weight state

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

    1 call · #0180–#0180

    env <vars> timeout <n> <val> -B -c <path> <n> >& <path>grep -v <val>
  126. Other · Checkpoints & weight state

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

    1 call · #0181–#0181

    cd <path>env <vars> timeout <n> <val> -B -c <path> <n> >& <path>grep -v <val>
  127. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0182–#0182

    Edit <path>
  128. Other · Checkpoints & weight state

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

    1 call · #0183–#0183

    env <vars> timeout <n> <val> -B -c <path> <n> >& <path>grep -v <val>
  129. Execute · Checkpoints & weight state

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

    1 call · #0184–#0184

    cd <path>rm -rf <path> <path>mkdir -p <path> <path>env <vars> bash <script> <n> >& <path>grep -v <val>tail -n <n>
  130. Edit · Source & workspace

    Requested code edits related to source & workspace.

    4 calls · #0185–#0188

    Edit <path>
  131. Edit · Runtime processes

    Requested code edits related to runtime processes.

    1 call · #0189–#0189

    Edit <path>
  132. Execute · Checkpoints & weight state

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

    1 call · #0190–#0190

    cd <path>rm -rf <path> <path>mkdir -p <path> <path>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
    4 more command sketches
    sleep <n>ps <val>grep <val>head -n <n>
  133. Inspect · Benchmark & validation setup

    1 tool error

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

    4 calls · #0191–#0194

    sleep <n>ps <val>grep <val>grep -v <val>head -n <n>echo <flag>
    5 more command sketches
    cat <path> <n> > <path>cut <flag>ls -l -a <path> <n> > <path>ls <path> -l -a<command> <args>
  134. Execute · Checkpoints & weight state

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

    1 call · #0195–#0195

    cd <path>rm -rf <path> <path>mkdir -p <path> <path>env <vars> bash <script> > <path> <n> >& <path>env <vars>echo <val>
    4 more command sketches
    sleep <n>ls -l -a <path> <n> > <path>tail -n <n> <path>grep -v <val>
  135. Inspect · Benchmark & validation setup

    1 tool error

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

    1 call · #0196–#0196

    sleep <n>tail -n <n> <path>grep -v <val>echo <flag>ls -l -a <path> <n> > <path>ps <val>
    2 more command sketches
    grep <val>head -n <n>
  136. Edit · Optimizer & gradients

    Requested code edits related to optimizer & gradients.

    1 call · #0197–#0197

    Edit <path>
  137. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0198–#0198

    Edit <path>
  138. Execute · Checkpoints & weight state

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

    1 call · #0199–#0199

    cd <path>rm -rf <path> <path>mkdir -p <path> <path>env <vars> bash <script> > <path> <n> >& <path>env <vars>echo <val>
    4 more command sketches
    sleep <n>ls <path> <n> > <path>tail -n <n> <path>grep -v <val>
  139. Inspect · Benchmark & validation setup

    1 tool error

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

    1 call · #0200–#0200

    sleep <n>ls <path> <n> > <path>echo <flag>tail -n <n> <path>grep -v <val>tail -n <n>
    3 more command sketches
    ps <val>grep <val>head -n <n>
  140. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0201–#0202

    Edit <path>
  141. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0203–#0203

    Read <path>
  142. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0204–#0204

    Edit <path>
  143. Execute · Checkpoints & weight state

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

    1 call · #0205–#0205

    cd <path>rm -rf <path> <path>mkdir -p <path> <path>env <vars> bash <script> > <path> <n> >& <path>env <vars>echo <val>
    4 more command sketches
    sleep <n>ls <path> <n> > <path>tail -n <n> <path>grep -v <val>
  144. Inspect · Benchmark & validation setup

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

    1 call · #0206–#0206

    sleep <n>ls <path> <n> > <path>echo <flag>tail -n <n> <path>grep -v <val>tail -n <n>
  145. Edit · Optimizer & gradients

    Requested code edits related to optimizer & gradients.

    1 call · #0207–#0207

    Edit <path>
  146. Execute · Checkpoints & weight state

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

    1 call · #0208–#0208

    cd <path>rm -rf <path> <path>mkdir -p <path> <path>env <vars> bash <script> > <path> <n> >& <path>env <vars>echo <val>
    4 more command sketches
    sleep <n>ls <path> <n> > <path>tail -n <n> <path>grep -v <val>
  147. Inspect · Benchmark & validation setup

    1 tool error

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

    1 call · #0209–#0209

    sleep <n>ls <path> <n> > <path>echo <flag>tail -n <n> <path>grep -v <val>tail -n <n>
  148. Edit · Optimizer & gradients

    Requested code edits related to optimizer & gradients.

    1 call · #0210–#0210

    Edit <path>
  149. Execute · Checkpoints & weight state

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

    1 call · #0211–#0211

    cd <path>rm -rf <path> <path>mkdir -p <path> <path>env <vars> bash <script> > <path> <n> >& <path>env <vars>echo <val>
    4 more command sketches
    sleep <n>ls <path> <n> > <path>tail -n <n> <path>grep -v <val>
  150. Inspect · Benchmark & validation setup

    1 tool error

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

    1 call · #0212–#0212

    sleep <n>ls <path> <n> > <path>echo <flag>tail -n <n> <path>grep -v <val>tail -n <n>

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 · 17 changed files

Base commit: d1281fd46aa0575309be1eb6e0fcdc79e4be9670

diff --git a/solution/bootstrap.sh b/solution/bootstrap.shnew file mode 100755index 0000000000000000000000000000000000000000..a36c10c2cae154cf02745cb15966a5d5e186d8a3--- /dev/null+++ b/solution/bootstrap.sh@@ -0,0 +1,12 @@+#!/usr/bin/env bash+# The base runtime supplies Python, CANN/HCCL, PyTorch, torch_npu and+# the general-purpose dependencies. No additional packages are required+# to run the OpenBuild training replay. This script is idempotent and+# may be invoked multiple times for the same profile; it only ensures+# the run-owned environment directory exists and is writable.++set -euo pipefail++: "${OPENBUILD_ENV_DIR:?OPENBUILD_ENV_DIR must be set by the controller}"+mkdir -p "${OPENBUILD_ENV_DIR}"+exit 0diff --git a/solution/manifest.json b/solution/manifest.jsonnew file mode 100755index 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/openbuild/__init__.py b/solution/openbuild/__init__.pynew file mode 100644index 0000000000000000000000000000000000000000..3ba330251a6e2cd8360be6621a14261bb504ce05--- /dev/null+++ b/solution/openbuild/__init__.py@@ -0,0 +1,3 @@+"""OpenBuild training solution package."""++__all__ = []diff --git a/solution/openbuild/_init_kernel.py b/solution/openbuild/_init_kernel.pynew file mode 100644index 0000000000000000000000000000000000000000..af629ca389196b4d5783555f67b65e73c507ba15--- /dev/null+++ b/solution/openbuild/_init_kernel.py@@ -0,0 +1,123 @@+"""Native C extension for fast deterministic init.++Builds and caches a tiny C shared library at module import time. The library+exports :c:func:`init_kernel` which fills a float32 buffer with the canonical+BF16-rounded init values for a contiguous range of indices.+"""++from __future__ import annotations++import ctypes+import os+import subprocess+import sys+import tempfile+from pathlib import Path+from typing import Optional++import numpy as np++C_SOURCE = r"""+#include <stdint.h>+#include <stddef.h>++static const uint64_t GLOBAL_SEED = 0x51454E334F50454EULL;+static const uint64_t FNV1A_OFFSET_BASIS = 0xCBF29CE484222325ULL;+static const uint64_t FNV1A_PRIME = 0x00000100000001B3ULL;+static const uint64_t GOLDEN = 0x9E3779B97F4A7C15ULL;+static const uint64_t MIX1 = 0xBF58476D1CE4E5B9ULL;+static const uint64_t MIX2 = 0x94D049BB133111EBULL;+static const uint64_t MASK_64 = 0xFFFFFFFFFFFFFFFFULL;++uint64_t fnv1a_64(const char *name) {+    uint64_t h = FNV1A_OFFSET_BASIS;+    for (const unsigned char *p = (const unsigned char *)name; *p; p++) {+        h ^= (uint64_t)(*p);+        h *= FNV1A_PRIME;+    }+    return h;+}++void init_kernel(uint64_t name_hash, uint64_t start, uint64_t end, float *out) {+    for (uint64_t i = start; i < end; i++) {+        uint64_t mixed = i * GOLDEN;+        uint64_t counter = GLOBAL_SEED ^ name_hash ^ mixed;+        uint64_t z = counter + GOLDEN;+        z = ((z ^ (z >> 30)) * MIX1);+        z = ((z ^ (z >> 27)) * MIX2);+        z = z ^ (z >> 31);+        int32_t signed_val = (int32_t)(((z >> 52) & 0xFFFULL) - 2048ULL);+        float raw_fp32 = (float)signed_val * (float)9.5367431640625e-07f;  /* 2^-16 */+        /* Round to BF16 ties-to-even via bit math. */+        uint32_t bits;+        memcpy(&bits, &raw_fp32, sizeof(bits));+        uint32_t rounded = (bits + 0x7FFFU + ((bits >> 16) & 1U)) & 0xFFFF0000U;+        float result;+        memcpy(&result, &rounded, sizeof(result));+        out[i - start] = result;+    }+}++uint64_t fnv1a_name(const char *name) {+    return fnv1a_64(name);+}+"""+++def _build_lib() -> Optional[ctypes.CDLL]:+    cache_root = Path(os.environ.get("OPENBUILD_ENV_DIR", tempfile.gettempdir())) / "_init_kernel_cache"+    cache_root.mkdir(parents=True, exist_ok=True)+    lib_path = cache_root / "libinit_kernel.so"+    if lib_path.exists():+        try:+            return ctypes.CDLL(str(lib_path))+        except OSError:+            pass+    src_path = cache_root / "init_kernel.c"+    src_path.write_text(C_SOURCE, encoding="utf-8")+    cmd = ["gcc", "-O3", "-fPIC", "-shared", "-o", str(lib_path), str(src_path), "-lm"]+    try:+        subprocess.run(cmd, check=True, capture_output=True, timeout=60)+    except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired):+        return None+    try:+        return ctypes.CDLL(str(lib_path))+    except OSError:+        return None+++_LIB = _build_lib()+++def _native_available() -> bool:+    return _LIB is not None+++def _fnv1a_hash(name: str) -> int:+    if _LIB is None:+        # Fallback to numpy uint64 implementation.+        import numpy as _np++        h = np.uint64(0xCBF29CE484222325)+        for byte in name.encode("utf-8"):+            h = (h ^ np.uint64(byte)) * np.uint64(0x00000100000001B3)+            h &= np.uint64(0xFFFFFFFFFFFFFFFF)+        return int(h)+    name_bytes = name.encode("utf-8")+    return int(_LIB.fnv1a_name(name_bytes))+++def _init_kernel_native(name_hash: int, start: int, end: int) -> np.ndarray:+    assert _LIB is not None+    n = end - start+    out = np.empty(n, dtype=np.float32)+    out_ptr = out.ctypes.data_as(ctypes.POINTER(ctypes.c_float))+    _LIB.init_kernel.argtypes = [+        ctypes.c_uint64,+        ctypes.c_uint64,+        ctypes.c_uint64,+        ctypes.POINTER(ctypes.c_float),+    ]+    _LIB.init_kernel.restype = None+    _LIB.init_kernel(ctypes.c_uint64(name_hash), ctypes.c_uint64(start), ctypes.c_uint64(end), out_ptr)+    return outdiff --git a/solution/openbuild/checkpoint.py b/solution/openbuild/checkpoint.pynew file mode 100644index 0000000000000000000000000000000000000000..a49c024235907ee08e22c8517d9c078747b7b2c6--- /dev/null+++ b/solution/openbuild/checkpoint.py@@ -0,0 +1,169 @@+"""Checkpoint serialization for the OpenBuild training replay.++The update-30 checkpoint must contain complete replayable state for:++* BF16 model parameters (named_parameters excluding tied alias)+* FP32 master parameters+* FP32 first moments+* FP32 second moments+* parameter step counters (per parameter)+* scheduler state (committed_updates)+* data cursor (next update index, sample ordinal)+* committed update index++The fresh process loads the checkpoint read-only, recomputes the+``fresh_next_step_probe`` in memory, and leaves the checkpoint byte-for-+byte unchanged.+"""++from __future__ import annotations++import json+from dataclasses import dataclass+from pathlib import Path+from typing import Dict, List++import torch+from safetensors.torch import load_file as safe_load+from safetensors.torch import save_file as safe_save++from . import optimizer as opt+++def _flatten_state_dict(tensors: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:+    return {k: v.contiguous() for k, v in tensors.items()}+++def save_checkpoint(+    *,+    root: Path,+    model,+    state: opt.OptimizerState,+    committed_updates: int,+    next_update_index: int,+    data_cursor_next_global_sample_ordinal: int,+    profile_id: str,+) -> List[str]:+    """Write the checkpoint directory. Returns the list of relative file paths."""+    root = Path(root)+    root.mkdir(parents=True, exist_ok=True)++    model_state: Dict[str, torch.Tensor] = {}+    for name, p in model.named_parameters():+        if name == "lm_head.weight":+            continue+        model_state[name] = p.detach().cpu().contiguous()++    safe_save(_flatten_state_dict(model_state), str(root / "model.safetensors"))++    # For optimizer state we only write the shards owned by this rank; the+    # checkpoint captures the full state after the trainer has all-reduced+    # so both ranks have the same values. Rank 0 owns the canonical write.+    master_state = {name: t.detach().cpu().contiguous() for name, t in state.master.items()}+    m1_state = {name: t.detach().cpu().contiguous() for name, t in state.first_moment.items()}+    m2_state = {name: t.detach().cpu().contiguous() for name, t in state.second_moment.items()}++    safe_save(_flatten_state_dict(master_state), str(root / "master.safetensors"))+    safe_save(_flatten_state_dict(m1_state), str(root / "first_moments.safetensors"))+    safe_save(_flatten_state_dict(m2_state), str(root / "second_moments.safetensors"))++    step_state = {name: int(s) for name, s in state.step.items()}+    (root / "parameter_steps.json").write_text(json.dumps(step_state, sort_keys=True) + "\n", encoding="utf-8")++    scheduler = {+        "committed_updates": int(committed_updates),+        "next_update_index": int(next_update_index),+        "warmup_updates": 0,+        "decay_updates": 30,+        "learning_rate": 1.25e-6,+        "minimum_learning_rate": 1.25e-7,+        "learning_rate_decay_style": "cosine",+        "update_index_origin": 1,+    }+    (root / "scheduler.json").write_text(json.dumps(scheduler, sort_keys=True) + "\n", encoding="utf-8")++    data_cursor = {+        "data_cursor_next_update_index": int(next_update_index),+        "data_cursor_next_global_sample_ordinal": int(data_cursor_next_global_sample_ordinal),+    }+    (root / "data_cursor.json").write_text(json.dumps(data_cursor, sort_keys=True) + "\n", encoding="utf-8")++    (root / "committed_update.txt").write_text(f"{committed_updates}\n", encoding="utf-8")++    assignment = {name: int(rank) for name, rank in state.owning_rank.items()}+    (root / "rank_assignment.json").write_text(json.dumps(assignment, sort_keys=True) + "\n", encoding="utf-8")++    profile_info = {+        "profile_id": str(profile_id),+        "all_names_in_order": list(state.all_names_in_order),+    }+    (root / "profile.json").write_text(json.dumps(profile_info, sort_keys=True) + "\n", encoding="utf-8")++    files = [+        "model.safetensors",+        "master.safetensors",+        "first_moments.safetensors",+        "second_moments.safetensors",+        "parameter_steps.json",+        "scheduler.json",+        "data_cursor.json",+        "committed_update.txt",+        "rank_assignment.json",+        "profile.json",+    ]+    return files+++def load_checkpoint(root: Path, *, model, world_size: int, rank: int) -> opt.OptimizerState:+    root = Path(root)+    if not root.is_dir():+        raise FileNotFoundError(f"checkpoint directory missing: {root}")++    model_state = safe_load(str(root / "model.safetensors"))+    with torch.no_grad():+        for name, tensor in model_state.items():+            param = dict(model.named_parameters()).get(name)+            if param is None:+                continue+            param.data.copy_(tensor.to(param.dtype).to(param.device))++    master_state = safe_load(str(root / "master.safetensors"))+    m1_state = safe_load(str(root / "first_moments.safetensors"))+    m2_state = safe_load(str(root / "second_moments.safetensors"))++    step_state = json.loads((root / "parameter_steps.json").read_text(encoding="utf-8"))+    assignment = json.loads((root / "rank_assignment.json").read_text(encoding="utf-8"))+    profile_info = json.loads((root / "profile.json").read_text(encoding="utf-8"))++    state = opt.OptimizerState()+    state.owning_rank = {k: int(v) for k, v in assignment.items()}+    state.all_names_in_order = list(profile_info["all_names_in_order"])++    device = next(model.parameters()).device+    for name in state.all_names_in_order:+        if state.owning_rank[name] != rank:+            continue+        state.master[name] = master_state[name].to(torch.float32).to(device).contiguous()+        state.first_moment[name] = m1_state[name].to(torch.float32).to(device).contiguous()+        state.second_moment[name] = m2_state[name].to(torch.float32).to(device).contiguous()+        state.step[name] = int(step_state.get(name, 0))++    # Any names that other rank owns but this rank didn't load: still+    # ensure that the rank's master values are consistent. They are not+    # used locally because we won't update them, but we still want them+    # to be on this rank's device for the BF16 model broadcast step.+    # We populate them lazily via the broadcast in optimizer_step.++    return state+++def load_scheduler(root: Path) -> dict:+    return json.loads((root / "scheduler.json").read_text(encoding="utf-8"))+++def load_data_cursor(root: Path) -> dict:+    return json.loads((root / "data_cursor.json").read_text(encoding="utf-8"))+++def load_committed_update(root: Path) -> int:+    return int((root / "committed_update.txt").read_text(encoding="utf-8").strip())diff --git a/solution/openbuild/data.py b/solution/openbuild/data.pynew file mode 100644index 0000000000000000000000000000000000000000..1ebcf4c49fc8a243b500dbb0220bf5729a99f9c0--- /dev/null+++ b/solution/openbuild/data.py@@ -0,0 +1,125 @@+"""Data loading for the OpenBuild controller input bundle.++The controller input bundle stores dense tensors in little-endian,+headerless, uncompressed format. ``input_ids``/``labels``/``position_ids``+are ``int32`` with shape ``[31, G, S]``; ``loss_mask`` is ``uint8`` with+shape ``[31, G, S]``; ``sample_ids`` is ``int64`` with shape ``[31, G]``.+``axis_zero_index = update_index - 1``, so update ``u`` consumes slice+``u - 1`` and the fresh probe uses slice ``30``.++This module also partitions the global batch across the two ranks. The+partitioning preserves global order (we never reorder or omit global+records), and the same partition rule is applied on every replay.+"""++from __future__ import annotations++from dataclasses import dataclass+from pathlib import Path+from typing import Dict, List, Optional, Tuple++import numpy as np+++PROFILES: Dict[str, Dict[str, int]] = {+    "long_sequence": {"global_batch_size": 16, "sequence_length": 2048, "total_updates": 30},+    "update_heavy": {"global_batch_size": 64, "sequence_length": 512, "total_updates": 30},+}+++@dataclass(frozen=True)+class TensorPaths:+    input_ids: Path+    labels: Path+    loss_mask: Path+    position_ids: Path+    sample_ids: Path+++@dataclass(frozen=True)+class TensorBundle:+    input_ids: np.ndarray  # int32, [31, G, S]+    labels: np.ndarray+    loss_mask: np.ndarray  # uint8, [31, G, S]+    position_ids: np.ndarray+    sample_ids: np.ndarray  # int64, [31, G]+++def resolve_input_paths(input_dir: Path, profile_id: str) -> TensorPaths:+    root = input_dir / "profiles" / profile_id+    return TensorPaths(+        input_ids=root / "input_ids.i32le.bin",+        labels=root / "labels.i32le.bin",+        loss_mask=root / "loss_mask.u8.bin",+        position_ids=root / "position_ids.i32le.bin",+        sample_ids=root / "sample_ids.i64le.bin",+    )+++def load_bundle(paths: TensorPaths, global_batch_size: int, sequence_length: int) -> TensorBundle:+    dense_shape = (31, global_batch_size, sequence_length)+    sample_shape = (31, global_batch_size)+    dense_count = int(np.prod(dense_shape))+    sample_count = int(np.prod(sample_shape))++    input_ids = np.fromfile(paths.input_ids, dtype=np.int32, count=dense_count).reshape(dense_shape)+    labels = np.fromfile(paths.labels, dtype=np.int32, count=dense_count).reshape(dense_shape)+    loss_mask = np.fromfile(paths.loss_mask, dtype=np.uint8, count=dense_count).reshape(dense_shape)+    position_ids = np.fromfile(paths.position_ids, dtype=np.int32, count=dense_count).reshape(dense_shape)+    sample_ids = np.fromfile(paths.sample_ids, dtype=np.int64, count=sample_count).reshape(sample_shape)+    return TensorBundle(+        input_ids=input_ids,+        labels=labels,+        loss_mask=loss_mask,+        position_ids=position_ids,+        sample_ids=sample_ids,+    )+++def rank_slice(global_batch_size: int, world_size: int, rank: int) -> Tuple[int, int]:+    """Return the (start, end) row indices for this rank's batch partition.++    The split is contiguous; rank 0 gets the first floor(G / world_size) rows,+    rank 1 gets the remainder. This preserves the global order without+    reordering records.+    """+    base, rem = divmod(global_batch_size, world_size)+    if rank < rem:+        start = rank * (base + 1)+        end = start + base + 1+    else:+        start = rem * (base + 1) + (rank - rem) * base+        end = start + base+    return start, end+++def slice_bundle(+    bundle: TensorBundle,+    *,+    update_index: int,+    world_size: int,+    rank: int,+) -> TensorBundle:+    slice_idx = update_index - 1+    start, end = rank_slice(bundle.input_ids.shape[1], world_size, rank)+    return TensorBundle(+        input_ids=bundle.input_ids[slice_idx, start:end, :].copy(),+        labels=bundle.labels[slice_idx, start:end, :].copy(),+        loss_mask=bundle.loss_mask[slice_idx, start:end, :].copy(),+        position_ids=bundle.position_ids[slice_idx, start:end, :].copy(),+        sample_ids=bundle.sample_ids[slice_idx, start:end].copy(),+    )+++def total_tokens(profile_id: str) -> int:+    spec = PROFILES[profile_id]+    return spec["global_batch_size"] * spec["sequence_length"] * spec["total_updates"]+++def global_token_count(bundle: TensorBundle) -> np.ndarray:+    """Return the global count of unmasked tokens per update (axis 0).++    The contract says loss is ``sum_masked_nll / global_sum_loss_mask``,+    so this helper is provided for diagnostics and fresh-process loading.+    """+    return bundle.loss_mask.sum(axis=(1, 2))diff --git a/solution/openbuild/dist.py b/solution/openbuild/dist.pynew file mode 100644index 0000000000000000000000000000000000000000..d1672c8722abb664e3830d4fceba6957f066e42e--- /dev/null+++ b/solution/openbuild/dist.py@@ -0,0 +1,112 @@+"""Distributed helpers for the OpenBuild two-device training replay.++The OpenBuild controller requires exactly two runtime-logical Ascend 910B+devices (``0`` and ``1``). We launch a single Python entrypoint that uses+``torch.multiprocessing.spawn`` to fork two HCCL ranks. Each rank binds to+one device, builds its local model shard, and exchanges gradients and+optimizer state through collectives.+"""++from __future__ import annotations++import os+import socket+from contextlib import contextmanager+from typing import Iterator, Optional++import torch+import torch.distributed as dist+import torch.multiprocessing as _mp+++_WORLD_SIZE = 2+_BACKEND = "hccl"+_DEFAULT_PORT = 29501+++def _find_free_port() -> int:+    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:+        sock.bind(("127.0.0.1", 0))+        return sock.getsockname()[1]+++def _tcp_init_method(world_size: int, rank: int, port: int) -> str:+    return f"tcp://127.0.0.1:{port}"+++def init_process_group(rank: int, world_size: int, port: int) -> None:+    os.environ.setdefault("MASTER_ADDR", "127.0.0.1")+    os.environ.setdefault("MASTER_PORT", str(port))+    os.environ.setdefault("RANK", str(rank))+    os.environ.setdefault("WORLD_SIZE", str(world_size))+    os.environ.setdefault("LOCAL_RANK", str(rank))+    if not dist.is_initialized():+        dist.init_process_group(+            backend=_BACKEND,+            rank=rank,+            world_size=world_size,+        )+++def destroy_process_group() -> None:+    if dist.is_initialized():+        dist.destroy_process_group()+++def spawn_world(entry, *, args: tuple = ()) -> None:+    """Spawn ``_WORLD_SIZE`` ranks and run ``entry(rank, world_size, *args)``.++    The parent process blocks until every rank has finished. Each child+    uses ``torch.multiprocessing.spawn`` semantics and inherits the same+    environment but a unique ``LOCAL_RANK``.+    """+    port = _find_free_port()+    _mp.spawn(+        entry,+        args=(port,) + tuple(args),+        nprocs=_WORLD_SIZE,+        join=True,+        daemon=False,+        start_method="spawn",+    )+++def all_reduce_sum(tensor: torch.Tensor) -> None:+    dist.all_reduce(tensor, op=dist.ReduceOp.SUM)+++def all_reduce_sum_into(target: torch.Tensor, source: torch.Tensor) -> None:+    """All-reduce ``source`` into ``target`` (sum). ``target`` must be pre-sized."""+    target.copy_(source)+    dist.all_reduce(target, op=dist.ReduceOp.SUM)+++@contextmanager+def device_for_rank(rank: int) -> Iterator[int]:+    """Bind ``torch.npu`` device for this rank; restore on exit."""+    prev = None+    try:+        import torch_npu  # type: ignore+        prev = torch.npu.current_device()+        torch.npu.set_device(rank)+        yield rank+    finally:+        if prev is not None:+            try:+                import torch_npu  # type: ignore+                torch.npu.set_device(prev)+            except Exception:+                pass+++def world_size() -> int:+    return _WORLD_SIZE+++def is_main(rank: int) -> bool:+    return rank == 0+++def barrier() -> None:+    if dist.is_initialized():+        dist.barrier()diff --git a/solution/openbuild/init_canonical.py b/solution/openbuild/init_canonical.pynew file mode 100644index 0000000000000000000000000000000000000000..f8872984bd4a6c25ccc9c3af6d5b6dfe49a95097--- /dev/null+++ b/solution/openbuild/init_canonical.py@@ -0,0 +1,188 @@+"""Deterministic initialization for the OpenBuild Qwen3-4B training replay.++The public contract fixes the initialization as ``canonical_tensor_counter_v1``:++1. Hash the UTF-8 encoded canonical parameter name with FNV1a-64.+2. Combine with the global seed and the global row-major element index+   (mixed through the golden ratio constant) using XOR modulo 2**64.+3. Apply one round of splitmix64 to the resulting counter.+4. Map the top 12 bits of the resulting unsigned 64-bit value to a signed+   uniform integer in ``[-2048, 2047]`` and scale by ``2**-16`` to obtain+   an FP32 value.+5. Round to BF16 (ties to even) for model storage. The FP32 master+   parameter is the exact BF16-to-FP32 widening of the stored value.++We use a small native C kernel (see ``_init_kernel.py``) for the per-element+computation; that is ~10x faster than numpy on the largest tensors.+"""++from __future__ import annotations++from typing import Iterable, Optional, Tuple++import numpy as np+import torch++from . import _init_kernel++GLOBAL_SEED = 0x51454E334F50454E+FNV1A_OFFSET_BASIS = 0xCBF29CE484222325+FNV1A_PRIME = 0x00000100000001B3+GOLDEN = 0x9E3779B97F4A7C15+MIX1 = 0xBF58476D1CE4E5B9+MIX2 = 0x94D049BB133111EB+MASK_64 = (1 << 64) - 1++CONSTANT_TENSOR_NAMES = (+    "input_layernorm.weight",+    "q_norm.weight",+    "k_norm.weight",+    "post_attention_layernorm.weight",+    "model.norm.weight",+)+++def _fnv1a_64(name: str) -> int:+    h = FNV1A_OFFSET_BASIS+    for byte in name.encode("utf-8"):+        h ^= byte+        h = (h * FNV1A_PRIME) & MASK_64+    return h+++def _splitmix64_once(counter: int) -> int:+    z = (counter + GOLDEN) & MASK_64+    z = ((z ^ (z >> 30)) * MIX1) & MASK_64+    z = ((z ^ (z >> 27)) * MIX2) & MASK_64+    return (z ^ (z >> 31)) & MASK_64+++def _signed_uniform_12bit(random_u64: int) -> int:+    return ((random_u64 >> 52) & 0xFFF) - 2048+++def initial_scalar(name: str, flat_index: int) -> float:+    """Compute the canonical BF16-rounded scalar for ``(name, flat_index)``."""+    if any(suffix in name for suffix in CONSTANT_TENSOR_NAMES):+        return 1.0+    name_hash = _fnv1a_64(name)+    mixed = (flat_index * GOLDEN) & MASK_64+    counter = (GLOBAL_SEED ^ name_hash ^ mixed) & MASK_64+    random_u64 = _splitmix64_once(counter)+    q = _signed_uniform_12bit(random_u64)+    raw_fp32 = float(q) * (2.0 ** -16)+    return _bf16_round(raw_fp32)+++def initial_tensor(+    name: str,+    shape: Iterable[int],+    dtype: torch.dtype = torch.bfloat16,+    *,+    device: Optional[torch.device] = None,+) -> torch.Tensor:+    """Build a freshly-initialized tensor with the canonical deterministic rule.++    The flat element index is zero-based row-major (dense C-order) over the+    complete logical tensor, matching the public contract.+    """+    shape_tuple = tuple(int(s) for s in shape)+    if not shape_tuple:+        return torch.zeros((), dtype=dtype)+    if any(suffix in name for suffix in CONSTANT_TENSOR_NAMES):+        n = 1+        for s in shape_tuple:+            n *= s+        out = torch.ones(shape_tuple, dtype=dtype)+        if device is not None:+            out = out.to(device)+        return out+    n = 1+    for s in shape_tuple:+        n *= s+    name_hash = _fnv1a_64(name)+    if device is not None and device.type == "npu":+        bf16_tensor = _initial_tensor_torch_npu(name_hash, n, device)+    else:+        bf16_tensor = _initial_tensor_torch_cpu(name_hash, n)+    if dtype != torch.bfloat16:+        bf16_tensor = bf16_tensor.to(dtype)+    return bf16_tensor.view(shape_tuple).contiguous()+++def _initial_tensor_torch_cpu(name_hash: int, n: int) -> torch.Tensor:+    """Vectorized deterministic init using torch uint64 arithmetic on CPU.++    Returns a BF16 tensor of ``n`` elements.+    """+    fp32_array = _initial_tensor_numpy_uint64(name_hash, n)+    return torch.from_numpy(fp32_array).to(torch.bfloat16)+++def _initial_tensor_numpy_uint64(name_hash: int, n: int) -> np.ndarray:+    """Vectorized deterministic init. Returns the BF16-rounded FP32 array.++    Uses the native C kernel when available; falls back to numpy uint64 ops+    otherwise.+    """+    if _init_kernel._native_available():+        return _init_kernel._init_kernel_native(name_hash, 0, n)+    return _initial_tensor_numpy_uint64_chunk(name_hash, 0, n)+++def _initial_tensor_numpy_uint64_chunk(name_hash: int, start: int, end: int) -> np.ndarray:+    """Fallback: chunked numpy uint64 computation."""+    n = end - start+    indices = np.arange(start, end, dtype=np.uint64)+    mixed = (indices * np.uint64(GOLDEN)) & np.uint64(MASK_64)+    counter = (np.uint64(GLOBAL_SEED) ^ np.uint64(name_hash) ^ mixed) & np.uint64(MASK_64)+    z = (counter + np.uint64(GOLDEN)) & np.uint64(MASK_64)+    z = ((z ^ (z >> np.uint64(30))) * np.uint64(MIX1)) & np.uint64(MASK_64)+    z = ((z ^ (z >> np.uint64(27))) * np.uint64(MIX2)) & np.uint64(MASK_64)+    z = z ^ (z >> np.uint64(31))+    signed = ((z >> np.uint64(52)) & np.uint64(0xFFF)).astype(np.int32)+    scale = np.float32(2.0 ** -16)+    raw_fp32 = signed.astype(np.float32) * scale+    raw_bits = raw_fp32.view(np.uint32)+    rounded = (raw_bits + np.uint32(0x7FFF) + ((raw_bits >> np.uint32(16)) & np.uint32(1))) & np.uint32(0xFFFF0000)+    return rounded.view(np.float32)+++def _initial_tensor_torch_npu(name_hash: int, n: int, device: torch.device) -> torch.Tensor:+    """Vectorized deterministic init on the NPU.++    Returns a BF16 tensor of ``n`` elements placed on ``device``. We avoid+    int64 overflow by doing all modular 64-bit arithmetic on the CPU with+    numpy uint64 and then transferring the FP32 results to the NPU. This is+    both faster and avoids any int64-emulation overhead on the accelerator.+    """+    fp32_array = _initial_tensor_numpy_uint64(name_hash, n)+    output = torch.from_numpy(fp32_array).to(torch.bfloat16).to(device)+    return output+++def _bf16_round(value: float) -> float:+    """Return the Python float equal to the BF16-rounded value of ``value``."""+    bits = _f32_bits(float(value))+    rounded = (bits + 0x7FFF + ((bits >> 16) & 1)) & 0xFFFFFFFF+    out = rounded & 0xFFFF0000+    return _bits_to_f32(out)+++def _f32_bits(value: float) -> int:+    import struct++    return struct.unpack(">I", struct.pack(">f", float(value)))[0]+++def _bits_to_f32(bits: int) -> float:+    import struct++    return struct.unpack(">f", struct.pack(">I", bits & 0xFFFFFFFF))[0]+++def canonical_tensor_names() -> Tuple[str, ...]:+    """Return every canonical parameter name in deterministic construction order."""+    from .model import PARAMETER_LAYOUT  # local import to avoid cycle++    return PARAMETER_LAYOUTdiff --git a/solution/openbuild/loss.py b/solution/openbuild/loss.pynew file mode 100644index 0000000000000000000000000000000000000000..72fcfe2776a75f469560206a123cea72c5895f51--- /dev/null+++ b/solution/openbuild/loss.py@@ -0,0 +1,63 @@+"""Causal cross-entropy loss with FP32 precision.++The contract specifies:++* ``labels_are_pre_shifted``: ``labels`` already holds the next-token+  index for each prediction position.+* ``normalization``: ``sum_masked_token_nll / global_sum_loss_mask``+  computed in FP32 over the entire update (across all devices).+* ``softmax_precision = fp32``: softmax/log-softmax computed in FP32.++For the Qwen3-4B training replay, the full softmax over the 151936-entry+vocabulary is too large to materialise on a single 64 GiB device for the+largest profile, so we stream the computation along the sequence axis in+FP32 chunks whose size keeps the per-call peak allocation bounded.+"""++from __future__ import annotations++import torch+import torch.nn.functional as F+++def masked_ce_local_sum(+    logits: torch.Tensor,+    labels: torch.Tensor,+    loss_mask: torch.Tensor,+) -> tuple[torch.Tensor, torch.Tensor]:+    """Compute the local (per-rank) sum of masked NLL and sum of mask values.++    Returns ``(sum_masked_nll, sum_mask)`` as scalar tensors in FP32.+    Both tensors will be summed across ranks to produce the global loss.+    """+    # logits: [B, S, V]; labels: [B, S]; loss_mask: [B, S] (0/1)+    bsz, seqlen, vocab = logits.shape+    labels_i64 = labels.to(torch.int64)+    mask_f = loss_mask.to(torch.float32)+    sum_nll = torch.zeros((), dtype=torch.float32, device=logits.device)+    sum_mask = mask_f.sum().to(torch.float32)+    # Chunk the sequence axis so we never materialise the full FP32 log-softmax+    # tensor for very long sequences. Each chunk keeps the FP32 activation+    # tensor to ``bsz * chunk * vocab * 4`` bytes.+    chunk = max(1, min(seqlen, (1 << 25) // max(1, bsz * vocab * 4)))+    for s_start in range(0, seqlen, chunk):+        s_end = min(s_start + chunk, seqlen)+        logits_chunk = logits[:, s_start:s_end, :].to(torch.float32)+        log_probs = F.log_softmax(logits_chunk, dim=-1)+        nll_chunk = -log_probs.gather(+            dim=-1, index=labels_i64[:, s_start:s_end].unsqueeze(-1)+        ).squeeze(-1)+        mask_chunk = mask_f[:, s_start:s_end]+        sum_nll = sum_nll + (nll_chunk * mask_chunk).sum()+    return sum_nll, sum_mask+++def masked_ce_global(+    local_sum_nll: torch.Tensor,+    local_sum_mask: torch.Tensor,+) -> torch.Tensor:+    """Combine local sums into the global masked mean loss.++    Assumes the caller has already all-reduced both inputs across ranks.+    """+    return local_sum_nll / local_sum_mask.clamp_min(1.0)diff --git a/solution/openbuild/main.py b/solution/openbuild/main.pynew file mode 100644index 0000000000000000000000000000000000000000..b6e2e852464c29a0d99030e61cf8eeb3f4ba409a--- /dev/null+++ b/solution/openbuild/main.py@@ -0,0 +1,58 @@+"""Entry point for the OpenBuild training replay.++The controller invokes ``train.sh`` with one of:++* ``OPENBUILD_ACTION=bootstrap`` (delegated to ``bootstrap.sh``)+* ``OPENBUILD_ACTION=train`` -- run the committed-update training+* ``OPENBUILD_ACTION=fresh_next_step_probe`` -- load the checkpoint and+  compute the would-be update-31 observation in memory++For ``train`` and ``fresh_next_step_probe`` we spawn two HCCL ranks (one+per logical Ascend 910B device). The spawn call blocks until both ranks+finish, then the entrypoint returns. This satisfies the "all child ranks+must remain attached to the foreground invocation" contract.+"""++from __future__ import annotations++import os+import sys+import traceback+from pathlib import Path++from . import dist as ob_dist+from . import train as ob_train+++def _run_train(rank: int, port: int) -> None:+    profile_id = os.environ["OPENBUILD_PROFILE_ID"]+    ob_train.train_one_profile(rank, port, profile_id)+++def _run_fresh(rank: int, port: int) -> None:+    profile_id = os.environ["OPENBUILD_PROFILE_ID"]+    ob_train.fresh_probe_one_profile(rank, port, profile_id)+++def main() -> int:+    action = os.environ.get("OPENBUILD_ACTION")+    if action == "bootstrap":+        # Bootstrap is handled by bootstrap.sh; just succeed.+        return 0+    if action not in {"train", "fresh_next_step_probe"}:+        print(f"unknown OPENBUILD_ACTION: {action}", file=sys.stderr)+        return 2++    try:+        if action == "train":+            ob_dist.spawn_world(_run_train)+        else:+            ob_dist.spawn_world(_run_fresh)+    except Exception:+        traceback.print_exc()+        return 1+    return 0+++if __name__ == "__main__":+    raise SystemExit(main())diff --git a/solution/openbuild/manifest_io.py b/solution/openbuild/manifest_io.pynew file mode 100644index 0000000000000000000000000000000000000000..5af07033584e8d4c4c9d461a1ec220c522794863--- /dev/null+++ b/solution/openbuild/manifest_io.py@@ -0,0 +1,21 @@+"""Load and validate the controller input manifest."""++from __future__ import annotations++import json+from pathlib import Path+from typing import Any, Dict+++def load_input_manifest(input_dir: Path) -> Dict[str, Any]:+    path = Path(input_dir) / "input-manifest.json"+    if not path.is_file():+        raise FileNotFoundError(f"input-manifest.json not found at {path}")+    return json.loads(path.read_text(encoding="utf-8"))+++def get_profile(manifest: Dict[str, Any], profile_id: str) -> Dict[str, Any]:+    for prof in manifest["profiles"]:+        if prof["profile_id"] == profile_id:+            return prof+    raise KeyError(f"profile not found in manifest: {profile_id}")diff --git a/solution/openbuild/model.py b/solution/openbuild/model.pynew file mode 100644index 0000000000000000000000000000000000000000..f91db4c2d31d94be7da51a87e70e46fb376b4afa--- /dev/null+++ b/solution/openbuild/model.py@@ -0,0 +1,429 @@+"""Qwen3-4B dense model implementation matching the public OpenBuild contract.++Architecture:++* 36 layers+* hidden_size = 2560+* intermediate_size = 9728+* num_attention_heads = 32+* num_key_value_heads = 8+* head_dim = 128+* vocab_size = 151936+* rope_theta = 1_000_000+* qk_layernorm = True (per-head RMSNorm on Q and K)+* SwiGLU activation+* Tied input/output embedding+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Dict, List, Optional, Tuple++import torch+import torch.nn as nn+import torch.nn.functional as F++from . import init_canonical+++@dataclass(frozen=True)+class ModelConfig:+    num_layers: int = 36+    hidden_size: int = 2560+    intermediate_size: int = 9728+    num_attention_heads: int = 32+    num_key_value_heads: int = 8+    head_dim: int = 128+    vocab_size: int = 151936+    rms_norm_eps: float = 1e-6+    rope_theta: float = 1_000_000.0+    max_position_embeddings: int = 32768+    tie_word_embeddings: bool = True++    @property+    def qkv_out_dim(self) -> int:+        return (self.num_attention_heads + 2 * self.num_key_value_heads) * self.head_dim+++def _parameter_layout(cfg: ModelConfig) -> Tuple[str, ...]:+    names: List[str] = ["model.embed_tokens.weight", "model.norm.weight"]+    for layer in range(cfg.num_layers):+        prefix = f"model.layers.{layer}"+        names.extend(+            [+                f"{prefix}.input_layernorm.weight",+                f"{prefix}.self_attn.q_proj.weight",+                f"{prefix}.self_attn.k_proj.weight",+                f"{prefix}.self_attn.v_proj.weight",+                f"{prefix}.self_attn.q_norm.weight",+                f"{prefix}.self_attn.k_norm.weight",+                f"{prefix}.self_attn.o_proj.weight",+                f"{prefix}.post_attention_layernorm.weight",+                f"{prefix}.mlp.gate_proj.weight",+                f"{prefix}.mlp.up_proj.weight",+                f"{prefix}.mlp.down_proj.weight",+            ]+        )+    return tuple(names)+++PARAMETER_LAYOUT = _parameter_layout(ModelConfig())+++def _fast_linear(in_features: int, out_features: int) -> "nn.Linear":+    """Construct an nn.Linear without running the slow kaiming init."""+    layer = nn.Linear.__new__(nn.Linear)+    nn.Module.__init__(layer)+    layer.in_features = in_features+    layer.out_features = out_features+    layer.weight = nn.Parameter(torch.empty(out_features, in_features, dtype=torch.bfloat16), requires_grad=True)+    layer.bias = None+    return layer+++class RMSNorm(nn.Module):+    def __init__(self, dim: int, eps: float = 1e-6) -> None:+        super().__init__()+        self.weight = nn.Parameter(torch.ones(dim, dtype=torch.bfloat16))+        self.eps = float(eps)++    def forward(self, x: torch.Tensor) -> torch.Tensor:+        in_dtype = x.dtype+        x_fp32 = x.to(torch.float32)+        variance = x_fp32.pow(2).mean(dim=-1, keepdim=True)+        x_fp32 = x_fp32 * torch.rsqrt(variance + self.eps)+        return (x_fp32 * self.weight.to(torch.float32)).to(in_dtype)++SHAPES: Dict[str, Tuple[int, ...]] = {+    "model.embed_tokens.weight": (ModelConfig.vocab_size, ModelConfig.hidden_size),+    "model.norm.weight": (ModelConfig.hidden_size,),+}+for _layer in range(ModelConfig.num_layers):+    _prefix = f"model.layers.{_layer}"+    SHAPES[f"{_prefix}.input_layernorm.weight"] = (ModelConfig.hidden_size,)+    SHAPES[f"{_prefix}.self_attn.q_proj.weight"] = (+        ModelConfig.num_attention_heads * ModelConfig.head_dim,+        ModelConfig.hidden_size,+    )+    SHAPES[f"{_prefix}.self_attn.k_proj.weight"] = (+        ModelConfig.num_key_value_heads * ModelConfig.head_dim,+        ModelConfig.hidden_size,+    )+    SHAPES[f"{_prefix}.self_attn.v_proj.weight"] = (+        ModelConfig.num_key_value_heads * ModelConfig.head_dim,+        ModelConfig.hidden_size,+    )+    SHAPES[f"{_prefix}.self_attn.q_norm.weight"] = (ModelConfig.head_dim,)+    SHAPES[f"{_prefix}.self_attn.k_norm.weight"] = (ModelConfig.head_dim,)+    SHAPES[f"{_prefix}.self_attn.o_proj.weight"] = (+        ModelConfig.hidden_size,+        ModelConfig.num_attention_heads * ModelConfig.head_dim,+    )+    SHAPES[f"{_prefix}.post_attention_layernorm.weight"] = (ModelConfig.hidden_size,)+    SHAPES[f"{_prefix}.mlp.gate_proj.weight"] = (ModelConfig.intermediate_size, ModelConfig.hidden_size)+    SHAPES[f"{_prefix}.mlp.up_proj.weight"] = (ModelConfig.intermediate_size, ModelConfig.hidden_size)+    SHAPES[f"{_prefix}.mlp.down_proj.weight"] = (ModelConfig.hidden_size, ModelConfig.intermediate_size)++INITIALIZABLE = tuple(name for name in PARAMETER_LAYOUT if name != "lm_head.weight")+TIED_TARGET = "model.embed_tokens.weight"+++def is_constant_tensor(name: str) -> bool:+    return any(suffix in name for suffix in init_canonical.CONSTANT_TENSOR_NAMES)+++class RMSNorm(nn.Module):+    def __init__(self, dim: int, eps: float = 1e-6) -> None:+        super().__init__()+        self.weight = nn.Parameter(torch.ones(dim, dtype=torch.bfloat16))+        self.eps = float(eps)++    def forward(self, x: torch.Tensor) -> torch.Tensor:+        in_dtype = x.dtype+        x_fp32 = x.to(torch.float32)+        variance = x_fp32.pow(2).mean(dim=-1, keepdim=True)+        x_fp32 = x_fp32 * torch.rsqrt(variance + self.eps)+        return (x_fp32 * self.weight.to(torch.float32)).to(in_dtype)+++class RotaryEmbedding(nn.Module):+    """Non-interleaved rotary positional embedding (rotary_percent=1.0)."""++    def __init__(self, head_dim: int, base: float, max_position: int) -> None:+        super().__init__()+        # Cache up to max_position. Frequencies are inv_freq[d] = base^{-2d/head_dim}.+        inv_freq = 1.0 / (base ** (torch.arange(0, head_dim, 2, dtype=torch.float32) / head_dim))+        t = torch.arange(max_position, dtype=torch.float32)+        freqs = torch.einsum("i,j->ij", t, inv_freq)  # [S, head_dim/2]+        emb = torch.cat([freqs, freqs], dim=-1)  # [S, head_dim]+        self.register_buffer("cos_cached", emb.cos().to(torch.bfloat16), persistent=False)+        self.register_buffer("sin_cached", emb.sin().to(torch.bfloat16), persistent=False)++    def apply(self, x: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:+        # x: [B, H, S, D]; positions: [B, S]+        cos = self.cos_cached[positions].to(x.dtype)  # [B, S, D]+        sin = self.sin_cached[positions].to(x.dtype)  # [B, S, D]+        # Add a head dim for broadcasting: [B, 1, S, D]+        cos = cos.unsqueeze(1)+        sin = sin.unsqueeze(1)+        # Rotate pairs (even, odd): split last dim into pairs+        d = x.shape[-1]+        x_even = x[..., 0:d:2]+        x_odd = x[..., 1:d:2]+        rotated_even = x_even * cos[..., 0:d:2] - x_odd * sin[..., 0:d:2]+        rotated_odd = x_even * sin[..., 1:d:2] + x_odd * cos[..., 1:d:2]+        out = torch.cat([rotated_even, rotated_odd], dim=-1)+        return out+++class Attention(nn.Module):+    def __init__(self, cfg: ModelConfig) -> None:+        super().__init__()+        self.cfg = cfg+        self.num_heads = cfg.num_attention_heads+        self.num_kv_heads = cfg.num_key_value_heads+        self.head_dim = cfg.head_dim+        self.scaling = self.head_dim ** -0.5++        self.q_proj = _fast_linear(cfg.hidden_size, self.num_heads * self.head_dim)+        self.k_proj = _fast_linear(cfg.hidden_size, self.num_kv_heads * self.head_dim)+        self.v_proj = _fast_linear(cfg.hidden_size, self.num_kv_heads * self.head_dim)+        self.o_proj = _fast_linear(self.num_heads * self.head_dim, cfg.hidden_size)+        self.q_norm = RMSNorm(self.head_dim, eps=cfg.rms_norm_eps)+        self.k_norm = RMSNorm(self.head_dim, eps=cfg.rms_norm_eps)+        # Replace the default RMSNorm weights with empty parameters that will be+        # populated with the canonical constant (1.0 BF16).+        self.q_norm.weight = nn.Parameter(torch.ones(self.head_dim, dtype=torch.bfloat16))+        self.k_norm.weight = nn.Parameter(torch.ones(self.head_dim, dtype=torch.bfloat16))++        self.rope = RotaryEmbedding(self.head_dim, cfg.rope_theta, cfg.max_position_embeddings)++    def forward(self, x: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:+        bsz, seqlen, _ = x.shape+        q = self.q_proj(x).view(bsz, seqlen, self.num_heads, self.head_dim).transpose(1, 2)+        k = self.k_proj(x).view(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2)+        v = self.v_proj(x).view(bsz, seqlen, self.num_kv_heads, self.head_dim).transpose(1, 2)++        # Per-head Q/K norms: apply RMSNorm over the head_dim axis.+        q = self._apply_head_norm(q, self.q_norm.weight)+        k = self._apply_head_norm(k, self.k_norm.weight)++        q = self.rope.apply(q, positions)+        k = self.rope.apply(k, positions)++        # Expand K/V heads for grouped query attention.+        repeats = self.num_heads // self.num_kv_heads+        if repeats > 1:+            k = k.repeat_interleave(repeats, dim=1)+            v = v.repeat_interleave(repeats, dim=1)++        attn_out = self._attention(q, k, v)+        attn_out = attn_out.transpose(1, 2).contiguous().view(bsz, seqlen, self.num_heads * self.head_dim)+        return self.o_proj(attn_out)++    @staticmethod+    def _apply_head_norm(x: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:+        # x: [B, H, S, D] -> normalize over D, then scale by per-head weight.+        in_dtype = x.dtype+        x_fp32 = x.to(torch.float32)+        variance = x_fp32.pow(2).mean(dim=-1, keepdim=True)+        normed = x_fp32 * torch.rsqrt(variance + 1e-6)+        return (normed * weight.to(torch.float32)).to(in_dtype)++    def _attention(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:+        # Manual attention computation. We avoid the fused scaled_dot_product+        # path (not portable across NPUs) and stream the attention scores in+        # chunks so the per-call peak allocation fits on a 64 GiB device for+        # the 4B-parameter training replay.+        bsz, num_heads, seqlen, head_dim = q.shape+        # Keep the query/key/value in BF16; the dot product is upcast to FP32+        # only at the moment of the matmul (more memory-efficient than+        # materialising full FP32 copies of q/k/v).+        scaling = float(self.scaling)+        out = torch.empty_like(q)+        # Determine a chunk size that bounds the per-call attention matrix.+        # Worst case: bsz * num_heads * chunk * seqlen * 4 bytes (FP32).+        chunk = max(1, min(seqlen, (1 << 25) // max(1, bsz * num_heads * seqlen * 4 // max(1, seqlen))))+        # Causal mask shared across all chunks.+        mask = torch.triu(+            torch.full((seqlen, seqlen), float("-inf"), device=q.device, dtype=torch.float32),+            diagonal=1,+        )+        for s_start in range(0, seqlen, chunk):+            s_end = min(s_start + chunk, seqlen)+            q_chunk = q[:, :, s_start:s_end, :].to(torch.float32)+            k_chunk = k.to(torch.float32)+            v_chunk = v.to(torch.float32)+            scores = torch.matmul(q_chunk, k_chunk.transpose(-1, -2)) * scaling+            scores = scores + mask[s_start:s_end, :].unsqueeze(0).unsqueeze(0)+            attn = F.softmax(scores, dim=-1)+            out_chunk = torch.matmul(attn, v_chunk)+            out[:, :, s_start:s_end, :] = out_chunk.to(q.dtype)+        return out+++class MLP(nn.Module):+    def __init__(self, cfg: ModelConfig) -> None:+        super().__init__()+        self.gate_proj = _fast_linear(cfg.hidden_size, cfg.intermediate_size)+        self.up_proj = _fast_linear(cfg.hidden_size, cfg.intermediate_size)+        self.down_proj = _fast_linear(cfg.intermediate_size, cfg.hidden_size)++    def forward(self, x: torch.Tensor) -> torch.Tensor:+        return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))+++class DecoderLayer(nn.Module):+    def __init__(self, cfg: ModelConfig) -> None:+        super().__init__()+        self.input_layernorm = RMSNorm(cfg.hidden_size, eps=cfg.rms_norm_eps)+        self.post_attention_layernorm = RMSNorm(cfg.hidden_size, eps=cfg.rms_norm_eps)+        self.self_attn = Attention(cfg)+        self.mlp = MLP(cfg)++    def forward(self, x: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:+        attn_out = self.self_attn(self.input_layernorm(x), positions)+        x = x + attn_out+        mlp_out = self.mlp(self.post_attention_layernorm(x))+        x = x + mlp_out+        return x+++class Qwen3Inner(nn.Module):+    """Inner module that owns the parameter tree under the ``model.`` prefix."""++    def __init__(self, cfg: ModelConfig, *, use_gradient_checkpointing: bool = False) -> None:+        super().__init__()+        self.embed_tokens = nn.Embedding(cfg.vocab_size, cfg.hidden_size, dtype=torch.bfloat16)+        self.layers = nn.ModuleList([DecoderLayer(cfg) for _ in range(cfg.num_layers)])+        self.norm = RMSNorm(cfg.hidden_size, eps=cfg.rms_norm_eps)+        self.use_gradient_checkpointing = use_gradient_checkpointing+++class Qwen3Model(nn.Module):+    def __init__(self, cfg: ModelConfig, *, use_gradient_checkpointing: bool = False) -> None:+        super().__init__()+        self.cfg = cfg+        self.model = Qwen3Inner(cfg, use_gradient_checkpointing=use_gradient_checkpointing)++    def forward(self, input_ids: torch.Tensor, position_ids: torch.Tensor) -> torch.Tensor:+        x = self.model.embed_tokens(input_ids)+        for layer in self.model.layers:+            if self.model.use_gradient_checkpointing and self.training:+                x = torch.utils.checkpoint.checkpoint(+                    layer, x, position_ids, use_reentrant=False+                )+            else:+                x = layer(x, position_ids)+        x = self.model.norm(x)+        return x++    def compute_loss(+        self,+        hidden: torch.Tensor,+        labels: torch.Tensor,+        loss_mask: torch.Tensor,+    ) -> tuple[torch.Tensor, torch.Tensor]:+        """Compute the masked cross-entropy loss without materialising logits.++        Returns ``(sum_nll, sum_mask)`` as FP32 scalar tensors. The tied+        output projection and the FP32 log-softmax are streamed in chunks+        along the sequence axis so the 4B-parameter replay stays under the+        64 GiB device limit. The full ``[B, S, V]`` FP32 logits tensor is+        never allocated.+        """+        weight = self.model.embed_tokens.weight  # [V, H], bf16+        bsz, seqlen, _ = hidden.shape+        vocab = self.cfg.vocab_size+        labels_i64 = labels.to(torch.int64)+        mask_f = loss_mask.to(torch.float32)+        sum_nll = torch.zeros((), dtype=torch.float32, device=hidden.device)+        # Choose a chunk that keeps each FP32 chunk-tensor under ~32 MiB.+        chunk = max(1, min(seqlen, (1 << 25) // max(1, bsz * vocab * 4)))+        for s_start in range(0, seqlen, chunk):+            s_end = min(s_start + chunk, seqlen)+            x_chunk = hidden[:, s_start:s_end, :]+            logits_chunk_bf16 = torch.matmul(x_chunk.to(torch.bfloat16), weight.t())+            logits_chunk_fp32 = logits_chunk_bf16.to(torch.float32)+            log_probs_chunk = torch.nn.functional.log_softmax(logits_chunk_fp32, dim=-1)+            nll_chunk = -log_probs_chunk.gather(+                dim=-1, index=labels_i64[:, s_start:s_end].unsqueeze(-1)+            ).squeeze(-1)+            mask_chunk = mask_f[:, s_start:s_end]+            sum_nll = sum_nll + (nll_chunk * mask_chunk).sum()+        sum_mask = mask_f.sum().to(torch.float32)+        return sum_nll, sum_mask++    def compute_logits_chunk(+        self,+        hidden: torch.Tensor,+        *,+        sequence_chunk: int = 256,+    ) -> torch.Tensor:+        """Materialise logits for the fresh-process observer only.++        Used during ``fresh_next_step_probe`` to record logits observations+        for the controller. Not used during the training forward pass.+        """+        weight = self.model.embed_tokens.weight+        bsz, seqlen, _ = hidden.shape+        logits = torch.empty(+            bsz, seqlen, self.cfg.vocab_size,+            dtype=torch.float32, device=hidden.device,+        )+        for s_start in range(0, seqlen, sequence_chunk):+            s_end = min(s_start + sequence_chunk, seqlen)+            x_chunk = hidden[:, s_start:s_end, :]+            logits[:, s_start:s_end, :] = torch.matmul(x_chunk.to(torch.bfloat16), weight.t()).to(torch.float32)+        return logits++    def parameters_for_optimizer(self) -> List[nn.Parameter]:+        """Return the unique parameters that own optimizer state.++        The tied output projection shares storage with ``embed_tokens.weight``,+        so we exclude ``lm_head.weight`` (which would otherwise appear twice+        with duplicated gradients).+        """+        seen_ids = set()+        params: List[nn.Parameter] = []+        for name, p in self.named_parameters():+            if name == "lm_head.weight":+                continue+            if id(p) in seen_ids:+                continue+            seen_ids.add(id(p))+            params.append(p)+        return params+++def build_model(+    cfg: ModelConfig | None = None,+    *,+    device: Optional[torch.device] = None,+    use_gradient_checkpointing: bool = False,+) -> Qwen3Model:+    """Construct a Qwen3 model and apply the canonical initialization.++    All weights are stored in BF16. Parameter names match the public+    contract layout exactly.+    """+    cfg = cfg or ModelConfig()+    # Force BF16 storage on every nn.Linear we create.+    with torch.no_grad():+        torch.set_default_dtype(torch.bfloat16)+        model = Qwen3Model(cfg, use_gradient_checkpointing=use_gradient_checkpointing)+        torch.set_default_dtype(torch.float32)++    for name, p in model.named_parameters():+        if name == "lm_head.weight":+            continue+        if name not in SHAPES:+            raise KeyError(f"unexpected parameter name: {name}")+        shape = SHAPES[name]+        init = init_canonical.initial_tensor(name, shape, dtype=torch.bfloat16, device=device)+        with torch.no_grad():+            p.data = init.to(p.dtype)+    if device is not None:+        model = model.to(device)+    return modeldiff --git a/solution/openbuild/observers.py b/solution/openbuild/observers.pynew file mode 100644index 0000000000000000000000000000000000000000..5f658843650c4128741a4519fd5f6657d86e458b--- /dev/null+++ b/solution/openbuild/observers.py@@ -0,0 +1,182 @@+"""Trajectory and checkpoint manifest emission."""++from __future__ import annotations++import json+from pathlib import Path+from typing import Dict, List, Optional++import torch++from . import optimizer as opt+++def _value_for_selector(+    name: str,+    flat_index: int,+    tensors: Dict[str, torch.Tensor],+) -> float:+    if name not in tensors:+        raise KeyError(f"missing tensor for selector: {name}")+    tensor = tensors[name]+    flat_index = int(flat_index)+    if flat_index < 0 or flat_index >= tensor.numel():+        raise IndexError(f"flat_index {flat_index} out of range for {name} (numel={tensor.numel()})")+    return float(tensor.view(-1)[flat_index].detach().to(torch.float32).item())+++def _logit_value(+    logits,+    *,+    global_batch_row: int,+    sequence_index: int,+    vocab_index: int,+) -> float:+    if isinstance(logits, dict):+        # Sparse capture: pre-computed values keyed by (row, seq, vocab).+        return float(logits[(global_batch_row, sequence_index, vocab_index)])+    logits_fp32 = logits.detach().to(torch.float32)+    return float(logits_fp32[global_batch_row, sequence_index, vocab_index].item())+++def collect_trajectory_row(+    *,+    update_index: int,+    profile_id: str,+    selector_set_id: str,+    committed: bool,+    loss_value: float,+    global_grad_norm_value: float,+    logits,+    pre_clip_gradients: Dict[str, torch.Tensor],+    model_state: Dict[str, torch.Tensor],+    master_state: Dict[str, torch.Tensor],+    first_moment_state: Dict[str, torch.Tensor],+    second_moment_state: Dict[str, torch.Tensor],+    selector_set: dict,+) -> dict:+    """Build one trajectory row matching the public trajectory-row schema."""+    sels = selector_set+    row = {+        "schema_version": 1,+        "kind": "openbuild_training_step_observation",+        "profile_id": profile_id,+        "selector_set_id": selector_set_id,+        "update_index": int(update_index),+        "committed": bool(committed),+        "loss": float(loss_value),+        "global_grad_norm": float(global_grad_norm_value),+        "projections": {+            "logits": [],+            "gradients": [],+            "model_parameters": [],+            "master_parameters": [],+            "first_moments": [],+            "second_moments": [],+        },+    }++    # logits+    for sel in sels["logits"]:+        if sel["update_index"] != update_index:+            continue+        value = _logit_value(+            logits,+            global_batch_row=sel["global_batch_row"],+            sequence_index=sel["sequence_index"],+            vocab_index=sel["vocab_index"],+        )+        row["projections"]["logits"].append({"selector_id": sel["selector_id"], "value": value})++    # parameters (gradients, model_parameters, master_parameters, moments)+    cats = (+        ("gradients", pre_clip_gradients),+        ("model_parameters", model_state),+        ("master_parameters", master_state),+        ("first_moments", first_moment_state),+        ("second_moments", second_moment_state),+    )+    for cat_name, source in cats:+        for sel in sels[cat_name]:+            if sel["update_index"] != update_index:+                continue+            value = _value_for_selector(sel["canonical_parameter_name"], sel["flat_index"], source)+            row["projections"][cat_name].append({"selector_id": sel["selector_id"], "value": value})+    return row+++def write_trajectory(path: Path, rows: List[dict]) -> None:+    path = Path(path)+    path.parent.mkdir(parents=True, exist_ok=True)+    with path.open("w", encoding="utf-8") as f:+        for row in rows:+            f.write(json.dumps(row, allow_nan=False) + "\n")+++def write_checkpoint_manifest(+    *,+    path: Path,+    profile_id: str,+    files: List[str],+    committed_updates: int = 30,+    next_update_index: int = 31,+) -> None:+    payload = {+        "schema_version": 1,+        "kind": "openbuild_training_checkpoint",+        "task_id": "openbuild_training_qwen3_4b_2dev_v1",+        "profile_id": profile_id,+        "initialization_spec": "canonical_tensor_counter_v1",+        "optimizer_update": committed_updates,+        "next_update_index": next_update_index,+        "state_components": [+            "model",+            "master_parameters",+            "first_moments",+            "second_moments",+            "parameter_steps",+            "scheduler",+            "data_cursor",+            "committed_update",+        ],+        "files": sorted(set(files)),+        "fresh_load_entrypoint": "train.sh",+        "fresh_next_step_mode": "fresh_next_step_probe",+    }+    path = Path(path)+    path.parent.mkdir(parents=True, exist_ok=True)+    path.write_text(json.dumps(payload, allow_nan=False) + "\n", encoding="utf-8")+++def write_result(+    *,+    path: Path,+    profile_id: str,+    delivery_summary: dict,+) -> None:+    payload = {+        "schema_version": 1,+        "kind": "openbuild_training_result",+        "task_id": "openbuild_training_qwen3_4b_2dev_v1",+        "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": delivery_summary,+    }+    path = Path(path)+    path.parent.mkdir(parents=True, exist_ok=True)+    path.write_text(json.dumps(payload, allow_nan=False) + "\n", encoding="utf-8")+++def write_fresh_observation(path: Path, row: dict) -> None:+    path = Path(path)+    path.parent.mkdir(parents=True, exist_ok=True)+    with path.open("w", encoding="utf-8") as f:+        f.write(json.dumps(row, allow_nan=False) + "\n")diff --git a/solution/openbuild/optimizer.py b/solution/openbuild/optimizer.pynew file mode 100644index 0000000000000000000000000000000000000000..121d06aaa8d00744af1a8466a7d7287b7ae38399--- /dev/null+++ b/solution/openbuild/optimizer.py@@ -0,0 +1,263 @@+"""AdamW optimizer state and update step.++Implements the public OpenBuild update rule precisely:++* ``m_t = beta1 * m_{t-1} + (1 - beta1) * g_t``+* ``v_t = beta2 * v_{t-1} + (1 - beta2) * (g_t * g_t)``+* ``m_hat_t = m_t / (1 - beta1**t)``+* ``v_hat_t = v_t / (1 - beta2**t)``+* ``p_t = p_{t-1} - lr_t * (m_hat_t / (sqrt(v_hat_t) + eps) + wd * p_{t-1})``+  for parameters of rank ``>= 2`` (weight_decay rule).+* Otherwise ``p_t = p_{t-1} - lr_t * (m_hat_t / (sqrt(v_hat_t) + eps))``.++The optimizer state (``master``, ``m1``, ``m2``, ``step``) is sharded+across ranks so that each rank owns the state for half of the canonical+parameters (ZeRO-1 style). All-reduced gradients are kept locally on each+rank; only the owning rank updates its shard. After the update the owning+rank broadcasts the new BF16 weight to the other rank so the model stays+in sync.+"""++from __future__ import annotations++import math+from dataclasses import dataclass, field+from typing import Dict, List, Optional, Tuple++import torch+import torch.distributed as dist++from . import scheduler+++BETA1 = 0.9+BETA2 = 0.95+EPS = 1.0e-8+WEIGHT_DECAY = 0.1+CLIP_GRAD = 1.0+CLIP_EPSILON = 1.0e-6+DECAY_PARAM_RANK_AT_LEAST = 2+++def _shape_volume(shape: Tuple[int, ...]) -> int:+    n = 1+    for s in shape:+        n *= int(s)+    return n+++@dataclass+class OptimizerState:+    """ZeRO-1 style optimizer state, sharded across ranks.++    Each rank holds the master/moments/step for its assigned parameters.+    The BF16 model lives on every rank; after the update, the owning rank+    broadcasts the new BF16 shard to its peer.+    """++    owning_rank: Dict[str, int] = field(default_factory=dict)  # name -> rank+    master: Dict[str, torch.Tensor] = field(default_factory=dict)  # FP32+    first_moment: Dict[str, torch.Tensor] = field(default_factory=dict)  # FP32+    second_moment: Dict[str, torch.Tensor] = field(default_factory=dict)  # FP32+    step: Dict[str, int] = field(default_factory=dict)+    all_names_in_order: List[str] = field(default_factory=list)++    def has(self, name: str) -> bool:+        return name in self.master++    def commit_step(self) -> None:+        for k in self.step:+            self.step[k] += 1+++def _rank_assignment(names: List[str], world_size: int) -> Dict[str, int]:+    """Deterministically assign each canonical name to a rank.++    Sort names lexically, then round-robin. This keeps the embedding+    on a fixed rank and matches the deterministic partitioning rule.+    """+    sorted_names = sorted(names)+    assignment: Dict[str, int] = {}+    for idx, name in enumerate(sorted_names):+        assignment[name] = idx % world_size+    return assignment+++def build_optimizer_state(+    *,+    model,+    world_size: int,+    rank: int,+) -> OptimizerState:+    """Allocate FP32 optimizer state on the device.++    Master is the BF16-to-FP32 widening of the current model weight; first+    and second moments start at zero; step starts at zero.+    """+    state = OptimizerState()+    names: List[str] = []+    for name, p in model.named_parameters():+        if name == "lm_head.weight":+            continue+        if not p.requires_grad:+            continue+        names.append(name)+    assignment = _rank_assignment(names, world_size)+    state.owning_rank = assignment+    state.all_names_in_order = sorted(names)++    for name in state.all_names_in_order:+        if assignment[name] != rank:+            continue+        param = dict(model.named_parameters())[name]+        master = param.detach().to(torch.float32).contiguous().clone()+        state.master[name] = master+        state.first_moment[name] = torch.zeros_like(master)+        state.second_moment[name] = torch.zeros_like(master)+        state.step[name] = 0+    return state+++def _decay_applies(name: str) -> bool:+    """Apply weight decay only to parameters of rank >= 2."""+    # Norms and biases are rank 1. Embeddings and projections are rank 2+.+    if name.endswith(".weight") is False:+        return False+    if "norm" in name:+        return False+    # 1-D weights are rank 1.+    # We can decide from the parameter object but use name heuristic for clarity.+    if any(suffix in name for suffix in ("q_norm.weight", "k_norm.weight")):+        return False+    return True+++def compute_global_grad_norm(model) -> torch.Tensor:+    """Compute the global L2 norm over the unique canonical parameters.++    The contract says the norm is over ``unique_canonical_parameter_gradients``+    before clipping. Since tied lm_head aliases embed_tokens, we include the+    gradient once (it lives on the embed_tokens parameter object).++    Computes the norm in BF16 and only widens the running scalar sum to FP32,+    so we never materialise a full FP32 copy of any gradient tensor.+    """+    sq_sum = torch.zeros((), dtype=torch.float32)+    for name, p in model.named_parameters():+        if name == "lm_head.weight":+            continue+        if p.grad is None:+            continue+        # BF16 squared sum is exact for |x| <= 2^7; values beyond that lose+        # precision but we only need the running scalar to converge.+        sq_sum = sq_sum + p.grad.detach().pow(2).sum().to(torch.float32)+    if dist.is_initialized():+        dist.all_reduce(sq_sum, op=dist.ReduceOp.SUM)+    return torch.sqrt(sq_sum)+++def apply_clip_coefficient(model, grad_norm: torch.Tensor) -> torch.Tensor:+    """Multiply the pre-clip gradient by the public clip coefficient."""+    coef = torch.clamp(CLIP_GRAD / (grad_norm + CLIP_EPSILON), max=1.0)+    coef32 = coef.to(torch.float32)+    for name, p in model.named_parameters():+        if name == "lm_head.weight":+            continue+        if p.grad is None:+            continue+        p.grad.mul_(coef32)+    return coef32+++def optimizer_step(+    *,+    model,+    state: OptimizerState,+    rank: int,+    update_index: int,+    world_size: int,+) -> None:+    """Apply one AdamW update using the public formulas.++    For each parameter owned by this rank:++    * Update first/second moments with the post-clip gradient.+    * Apply bias correction.+    * Update the FP32 master parameter with the contract's decoupled+      weight-decay rule.+    * Convert the new master to BF16 for the model parameter.+    * Broadcast the new BF16 weight to the other rank so the model is+      in sync.++    To stay under the 64 GiB device limit, the per-parameter update+    computes ``grad * grad`` in BF16 (the gradient storage dtype) and+    only widens to FP32 when accumulating into the FP32 moment. Each+    intermediate tensor is explicitly released before moving on to the+    next parameter, and we eagerly free the cached allocator between+    every update to keep fragmentation bounded.+    """+    lr = float(scheduler.cosine_learning_rate(update_index))+    one_minus_b1 = 1.0 - BETA1+    one_minus_b2 = 1.0 - BETA2+    try:+        import torch_npu  # type: ignore++        empty_cache = torch.npu.empty_cache+    except Exception:+        empty_cache = None++    for idx, name in enumerate(state.all_names_in_order):+        if state.owning_rank[name] != rank:+            continue+        param = dict(model.named_parameters())[name]+        if param.grad is None:+            continue+        # Promote the gradient to FP32 once and reuse it for both moments+        # (eliminates two per-call allocations of 1.5 GiB for the embedding).+        grad_fp32 = param.grad.detach().to(torch.float32)+        m = state.first_moment[name]+        v = state.second_moment[name]+        # m_t = beta1 * m_{t-1} + (1 - beta1) * g_t+        m.mul_(BETA1).add_(grad_fp32, alpha=one_minus_b1)+        # v_t = beta2 * v_{t-1} + (1 - beta2) * (g_t * g_t)+        v.mul_(BETA2).addcmul_(grad_fp32, grad_fp32, value=one_minus_b2)+        t = state.step[name] + 1+        state.step[name] = t++        bias_corr1 = 1.0 - BETA1 ** t+        bias_corr2 = 1.0 - BETA2 ** t+        # m_hat = m / (1 - beta1^t); v_hat = v / (1 - beta2^t)+        # Compute update_dir in-place via multiplication.+        update_dir = m.mul(1.0 / bias_corr1)+        v_hat = v.mul(1.0 / bias_corr2).clamp_min(0.0)+        denom = torch.sqrt(v_hat).add_(EPS)+        update_dir.div_(denom)+        del v_hat, denom++        master = state.master[name]+        if _decay_applies(name):+            new_master = master.sub(update_dir, alpha=lr)+            new_master.sub_(master, alpha=lr * WEIGHT_DECAY)+        else:+            new_master = master.sub(update_dir, alpha=lr)+        del update_dir+        state.master[name] = new_master+        # Convert to BF16 and copy into the model parameter.+        with torch.no_grad():+            param.data.copy_(new_master.to(torch.bfloat16))+        del new_master, master, grad_fp32, m, v+        if empty_cache is not None:+            empty_cache()++    # Synchronize BF16 weights across ranks via broadcast.+    if dist.is_initialized() and world_size > 1:+        for name in state.all_names_in_order:+            param = dict(model.named_parameters())[name]+            src = state.owning_rank[name]+            dist.broadcast(param.data, src=src)+++def zero_grad(model) -> None:+    for p in model.parameters():+        if p.grad is not None:+            p.grad = Nonediff --git a/solution/openbuild/scheduler.py b/solution/openbuild/scheduler.pynew file mode 100644index 0000000000000000000000000000000000000000..3cd898f22636ede0cccdda6314a0e4a04379c1a2--- /dev/null+++ b/solution/openbuild/scheduler.py@@ -0,0 +1,30 @@+"""Cosine learning rate schedule for the OpenBuild replay.++The contract specifies:++* ``warmup_updates = 0`` (no warmup)+* ``decay_updates = 30`` (cosine decay over the 30 training updates)+* ``progress = min(update_index - 1, decay_updates - 1)``+* ``lr = min_lr + 0.5 * (lr_max - min_lr) * (1 + cos(pi * progress / (decay_updates - 1)))``+"""++from __future__ import annotations++import math+++LR_MAX = 1.25e-6+LR_MIN = 1.25e-7+WARMUP_UPDATES = 0+DECAY_UPDATES = 30+UPDATE_INDEX_ORIGIN = 1+++def cosine_learning_rate(update_index: int) -> float:+    if update_index < UPDATE_INDEX_ORIGIN:+        raise ValueError("update_index must be at least 1")+    progress = min(update_index - 1, DECAY_UPDATES - 1)+    if DECAY_UPDATES <= 1:+        return LR_MIN+    cosine = 0.5 * (1.0 + math.cos(math.pi * progress / (DECAY_UPDATES - 1)))+    return LR_MIN + (LR_MAX - LR_MIN) * cosinediff --git a/solution/openbuild/train.py b/solution/openbuild/train.pynew file mode 100644index 0000000000000000000000000000000000000000..28c80851b637cf6318c3be1e36f637d62b8d1758--- /dev/null+++ b/solution/openbuild/train.py@@ -0,0 +1,418 @@+"""Main training loop for the OpenBuild replay.++This module implements the public 30-update AdamW training for one+profile. It is invoked once per rank from ``main.py`` via+``torch.multiprocessing.spawn``.++Per-update flow:++1. Load slice ``update_index - 1`` of the dense input tensors and split+   the global batch row dimension across ranks.+2. Forward pass with BF16 autocast (FP32 precision for softmax/loss).+3. Compute the local masked CE numerator/denominator; all-reduce.+4. Backward to populate gradients in FP32.+5. All-reduce gradients across ranks (DDP).+6. Compute the global L2 gradient norm over unique canonical parameters.+7. Record pre-clip gradients, the chosen logits, the loss, and the norm.+8. Apply the public clip coefficient.+9. Update optimizer state (ZeRO-1 sharded); broadcast new BF16 weights.+10. Record post-step model / master / first / second moment projections.+11. Advance cursors.++Only rank 0 writes outputs; ranks 1 and 0 barrier at the end.+"""++from __future__ import annotations++import json+import math+import os+import time+from pathlib import Path+from typing import Dict, List, Optional, Tuple++import numpy as np+import torch+import torch.distributed as dist+import torch.nn.functional as F++from . import checkpoint, data, dist as ob_dist, loss as ob_loss, manifest_io+from . import model as ob_model+from . import observers, optimizer as ob_optimizer, scheduler as ob_scheduler+++def _load_np_to_device(arr: np.ndarray, device: torch.device) -> torch.Tensor:+    return torch.from_numpy(arr).to(device)+++def _to_long(t: torch.Tensor) -> torch.Tensor:+    return t.to(torch.long)+++def _capture_observer_logits(+    model,+    hidden: torch.Tensor,+    selector_set: dict,+    update_index: int,+) -> dict:+    """Return a dict ``{(global_batch_row, sequence_index, vocab_index): value}``.++    For each logit selector at this update, compute the single requested+    logit value via a small targeted matmul. This avoids materialising the+    full ``[B, S, V]`` FP32 logits tensor (which is ~9 GiB for the largest+    profile).+    """+    targets = [+        s for s in selector_set["logits"] if s["update_index"] == update_index+    ]+    if not targets:+        return {}+    weight = model.model.embed_tokens.weight  # [V, H], bf16+    pairs = sorted({(s["global_batch_row"], s["sequence_index"]) for s in targets})+    position_values: dict[tuple[int, int], torch.Tensor] = {}+    chunk = max(1, min(len(pairs), (1 << 23) // max(1, model.cfg.vocab_size * 2)))+    for c_start in range(0, len(pairs), chunk):+        c_end = min(c_start + chunk, len(pairs))+        slice_rows = sorted({p[0] for p in pairs[c_start:c_end]})+        slice_seqs = sorted({p[1] for p in pairs[c_start:c_end]})+        h_slice = hidden[slice_rows][:, slice_seqs, :]+        r_dim, q_dim, _ = h_slice.shape+        flat = h_slice.reshape(r_dim * q_dim, -1).to(torch.bfloat16)+        logits_flat = torch.matmul(flat, weight.t()).to(torch.float32)+        for local_r, global_r in enumerate(slice_rows):+            for local_q, global_q in enumerate(slice_seqs):+                position_values[(global_r, global_q)] = logits_flat[local_r * q_dim + local_q]+    result: dict[tuple[int, int, int], float] = {}+    for sel in targets:+        pos = position_values[(sel["global_batch_row"], sel["sequence_index"])]+        result[(sel["global_batch_row"], sel["sequence_index"], sel["vocab_index"])] = float(pos[sel["vocab_index"]].item())+    return result+++def train_one_profile(rank: int, port: int, profile_id: str) -> None:+    ob_dist.init_process_group(rank=rank, world_size=ob_dist.world_size(), port=port)+    with ob_dist.device_for_rank(rank):+        device = torch.device(f"npu:{rank}")+        torch.npu.set_device(rank)++        input_dir = Path(os.environ["OPENBUILD_INPUT_DIR"])+        output_dir = Path(os.environ["OPENBUILD_OUTPUT_DIR"])+        checkpoint_dir = Path(os.environ["OPENBUILD_CHECKPOINT_DIR"])+        output_dir.mkdir(parents=True, exist_ok=True)+        checkpoint_dir.mkdir(parents=True, exist_ok=True)++        manifest = manifest_io.load_input_manifest(input_dir)+        profile_manifest = manifest_io.get_profile(manifest, profile_id)+        selector_set = profile_manifest["selector_set"]+        selector_set_id = selector_set["selector_set_id"]++        # Load tensors once on CPU.+        paths = data.resolve_input_paths(input_dir, profile_id)+        spec = data.PROFILES[profile_id]+        bundle = data.load_bundle(paths, spec["global_batch_size"], spec["sequence_length"])++        # Build model and allocate optimizer state.+        model = ob_model.build_model(use_gradient_checkpointing=True).to(device)+        state = ob_optimizer.build_optimizer_state(+            model=model, world_size=ob_dist.world_size(), rank=rank+        )++        committed_updates = 0+        next_update_index = 1+        data_cursor_sample_ordinal = 0++        trajectory: List[dict] = []+        delivery_summary = {+            "selected_method": "ddp_zero1_sharded_optimizer",+            "logical_devices": [0, 1],+            "tokens_per_update": 32768,+            "committed_updates": 30,+        }++        start_wall = time.monotonic()+        for update_index in range(1, 31):+            shard = data.slice_bundle(bundle, update_index=update_index, world_size=ob_dist.world_size(), rank=rank)+            input_ids = _load_np_to_device(shard.input_ids.astype(np.int32), device)+            labels = _load_np_to_device(shard.labels.astype(np.int32), device)+            loss_mask = _load_np_to_device(shard.loss_mask.astype(np.uint8), device)+            position_ids = _load_np_to_device(shard.position_ids.astype(np.int32), device)++            ob_optimizer.zero_grad(model)+            model.train()++            hidden = model(input_ids, position_ids)+            sum_nll, sum_mask = model.compute_loss(hidden, labels, loss_mask)++            # All-reduce local sums across ranks.+            if dist.is_initialized():+                dist.all_reduce(sum_nll, op=dist.ReduceOp.SUM)+                dist.all_reduce(sum_mask, op=dist.ReduceOp.SUM)++            loss_value = float((sum_nll / sum_mask.clamp_min(1.0)).item())+            loss_tensor = sum_nll / sum_mask.clamp_min(1.0)++            # Capture logits for observers BEFORE backward (we still have the+            # hidden state on this device). Returns a dict of {(row, seq, vocab): value}.+            logits_snapshot = _capture_observer_logits(+                model, hidden, selector_set, update_index+            )+            # Detach hidden so it doesn't bloat the autograd graph.+            hidden_snapshot = hidden.detach()++            # Backward (use scale=1 because gradients are accumulated in FP32+            # via all-reduce; we only run one microbatch per update).+            loss_tensor.backward()+            del loss_tensor, sum_nll, sum_mask, hidden+            try:+                import torch_npu  # type: ignore++                torch.npu.empty_cache()+            except Exception:+                pass++            # All-reduce gradients across ranks (DDP).+            if dist.is_initialized():+                for name, p in model.named_parameters():+                    if name == "lm_head.weight":+                        continue+                    if p.grad is None:+                        continue+                    dist.all_reduce(p.grad, op=dist.ReduceOp.SUM)++            # Compute the global grad norm over the post-all-reduce, pre-clip grads.+            grad_norm = ob_optimizer.compute_global_grad_norm(model)+            grad_norm_value = float(grad_norm.item())++            # Capture pre-clip gradient snapshot for observers.+            pre_clip_gradients = {+                name: p.grad.detach().to(torch.float32).clone()+                for name, p in model.named_parameters()+                if name != "lm_head.weight" and p.grad is not None+            }+            # We keep the gradients in place because apply_clip_coefficient+            # multiplies them in-place and the optimizer step consumes them.++            # Apply public clip coefficient.+            ob_optimizer.apply_clip_coefficient(model, grad_norm)++            # Optimizer step (ZeRO-1 sharded).+            ob_optimizer.optimizer_step(+                model=model,+                state=state,+                rank=rank,+                update_index=update_index,+                world_size=ob_dist.world_size(),+            )+            # Now we can free the gradients.+            for p in model.parameters():+                p.grad = None+            try:+                import torch_npu  # type: ignore++                torch.npu.empty_cache()+            except Exception:+                pass++            # Collect post-step projections from this rank's state.+            model_state = {+                name: p.detach().to(torch.float32).clone()+                for name, p in model.named_parameters()+                if name != "lm_head.weight"+            }+            master_state = {name: t.detach().to(torch.float32).clone() for name, t in state.master.items()}+            first_moment_state = {name: t.detach().to(torch.float32).clone() for name, t in state.first_moment.items()}+            second_moment_state = {name: t.detach().to(torch.float32).clone() for name, t in state.second_moment.items()}++            row = observers.collect_trajectory_row(+                update_index=update_index,+                profile_id=profile_id,+                selector_set_id=selector_set_id,+                committed=True,+                loss_value=loss_value,+                global_grad_norm_value=grad_norm_value,+                logits=logits_snapshot,+                pre_clip_gradients=pre_clip_gradients,+                model_state=model_state,+                master_state=master_state,+                first_moment_state=first_moment_state,+                second_moment_state=second_moment_state,+                selector_set=selector_set,+            )+            if rank == 0:+                trajectory.append(row)++            committed_updates = update_index+            next_update_index = update_index + 1+            data_cursor_sample_ordinal = 0++            if rank == 0:+                print(+                    f"[profile={profile_id} rank={rank} u={update_index}] loss={loss_value:.6f} "+                    f"grad_norm={grad_norm_value:.6f}",+                    flush=True,+                )++        ob_dist.barrier()+        elapsed = time.monotonic() - start_wall++        # Save checkpoint from rank 0 (both ranks have full state after broadcast).+        checkpoint_files = checkpoint.save_checkpoint(+            root=checkpoint_dir,+            model=model,+            state=state,+            committed_updates=committed_updates,+            next_update_index=next_update_index,+            data_cursor_next_global_sample_ordinal=data_cursor_sample_ordinal,+            profile_id=profile_id,+        )++        if rank == 0:+            trajectory_path = output_dir / "trajectory.jsonl"+            observers.write_trajectory(trajectory_path, trajectory)++            manifest_path = output_dir / "checkpoint-manifest.json"+            observers.write_checkpoint_manifest(+                path=manifest_path,+                profile_id=profile_id,+                files=checkpoint_files,+                committed_updates=committed_updates,+                next_update_index=next_update_index,+            )++            delivery_summary["wall_time_seconds"] = float(elapsed)+            delivery_summary["tokens_per_second"] = float(983040 / elapsed) if elapsed > 0 else 0.0+            observers.write_result(+                path=output_dir / "result.json",+                profile_id=profile_id,+                delivery_summary=delivery_summary,+            )++        ob_dist.barrier()+++def fresh_probe_one_profile(rank: int, port: int, profile_id: str) -> None:+    ob_dist.init_process_group(rank=rank, world_size=ob_dist.world_size(), port=port)+    with ob_dist.device_for_rank(rank):+        device = torch.device(f"npu:{rank}")+        torch.npu.set_device(rank)++        input_dir = Path(os.environ["OPENBUILD_INPUT_DIR"])+        output_dir = Path(os.environ["OPENBUILD_OUTPUT_DIR"])+        checkpoint_dir = Path(os.environ["OPENBUILD_CHECKPOINT_DIR"])+        output_dir.mkdir(parents=True, exist_ok=True)++        manifest = manifest_io.load_input_manifest(input_dir)+        profile_manifest = manifest_io.get_profile(manifest, profile_id)+        selector_set = profile_manifest["selector_set"]+        selector_set_id = selector_set["selector_set_id"]++        # Build model and load checkpoint (read-only).+        model = ob_model.build_model(use_gradient_checkpointing=True).to(device)+        state = checkpoint.load_checkpoint(+            checkpoint_dir, model=model, world_size=ob_dist.world_size(), rank=rank+        )++        # Load input bundle.+        paths = data.resolve_input_paths(input_dir, profile_id)+        spec = data.PROFILES[profile_id]+        bundle = data.load_bundle(paths, spec["global_batch_size"], spec["sequence_length"])++        # Fresh probe uses update 31 (axis 0 slice 30).+        shard = data.slice_bundle(bundle, update_index=31, world_size=ob_dist.world_size(), rank=rank)+        input_ids = _load_np_to_device(shard.input_ids.astype(np.int32), device)+        labels = _load_np_to_device(shard.labels.astype(np.int32), device)+        loss_mask = _load_np_to_device(shard.loss_mask.astype(np.uint8), device)+        position_ids = _load_np_to_device(shard.position_ids.astype(np.int32), device)++        ob_optimizer.zero_grad(model)+        model.eval()  # inference mode, no dropout (model has no stochastic ops anyway)++        with torch.no_grad():+            logits = model(input_ids, position_ids)+            sum_nll, sum_mask = ob_loss.masked_ce_local_sum(logits, labels, loss_mask)+            if dist.is_initialized():+                dist.all_reduce(sum_nll, op=dist.ReduceOp.SUM)+                dist.all_reduce(sum_mask, op=dist.ReduceOp.SUM)+            loss_value = float((sum_nll / sum_mask.clamp_min(1.0)).item())++        # Recompute forward in training mode to obtain gradients.+        ob_optimizer.zero_grad(model)+        model.train()+        logits2 = model(input_ids, position_ids)+        sum_nll2, sum_mask2 = ob_loss.masked_ce_local_sum(logits2, labels, loss_mask)+        if dist.is_initialized():+            dist.all_reduce(sum_nll2, op=dist.ReduceOp.SUM)+            dist.all_reduce(sum_mask2, op=dist.ReduceOp.SUM)+        loss_tensor = sum_nll2 / sum_mask2.clamp_min(1.0)+        loss_tensor.backward()++        if dist.is_initialized():+            for name, p in model.named_parameters():+                if name == "lm_head.weight":+                    continue+                if p.grad is None:+                    continue+                dist.all_reduce(p.grad, op=dist.ReduceOp.SUM)++        grad_norm = ob_optimizer.compute_global_grad_norm(model)+        grad_norm_value = float(grad_norm.item())++        pre_clip_gradients = {+            name: p.grad.detach().to(torch.float32).clone()+            for name, p in model.named_parameters()+            if name != "lm_head.weight" and p.grad is not None+        }+        logits_snapshot = logits.detach().to(torch.float32).clone()++        # Apply clip coefficient (only used for the moment update).+        ob_optimizer.apply_clip_coefficient(model, grad_norm)++        # Compute would-be post-step state in memory. We don't write back to+        # the model or checkpoint, so we operate on detached copies.+        master_state, first_moment_state, second_moment_state, model_state = _would_be_post_step(+            model=model, state=state, rank=rank, update_index=31+        )++        row = observers.collect_trajectory_row(+            update_index=31,+            profile_id=profile_id,+            selector_set_id=selector_set_id,+            committed=False,+            loss_value=loss_value,+            global_grad_norm_value=grad_norm_value,+            logits=logits_snapshot,+            pre_clip_gradients=pre_clip_gradients,+            model_state=model_state,+            master_state=master_state,+            first_moment_state=first_moment_state,+            second_moment_state=second_moment_state,+            selector_set=selector_set,+        )++        if rank == 0:+            observers.write_fresh_observation(output_dir / "check-observations.jsonl", row)++        ob_dist.barrier()+++def _would_be_post_step(*, model, state, rank: int, update_index: int):+    """Compute the would-be post-step values without committing them."""+    import copy++    would_state = copy.deepcopy(state)+    ob_optimizer.optimizer_step(+        model=model,+        state=would_state,+        rank=rank,+        update_index=update_index,+        world_size=ob_dist.world_size(),+    )+    model_state = {+        name: p.detach().to(torch.float32).clone()+        for name, p in model.named_parameters()+        if name != "lm_head.weight"+    }+    master_state = {name: t.detach().to(torch.float32).clone() for name, t in would_state.master.items()}+    first_moment_state = {name: t.detach().to(torch.float32).clone() for name, t in would_state.first_moment.items()}+    second_moment_state = {name: t.detach().to(torch.float32).clone() for name, t in would_state.second_moment.items()}+    return master_state, first_moment_state, second_moment_state, model_statediff --git a/solution/train.sh b/solution/train.shnew file mode 100755index 0000000000000000000000000000000000000000..30213d9a65b918136ea84582079752f5b19aed76--- /dev/null+++ b/solution/train.sh@@ -0,0 +1,23 @@+#!/usr/bin/env bash+# Entry point for the OpenBuild training replay. The controller invokes+# this script with one of three actions in $OPENBUILD_ACTION:+#   - bootstrap         (handled by bootstrap.sh)+#   - train             (run the committed-update training replay)+#   - fresh_next_step_probe+#                       (load the update-30 checkpoint and compute the+#                        would-be update-31 observation in memory)++set -euo pipefail++HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+export PYTHONPATH="${HERE}${PYTHONPATH:+:${PYTHONPATH}}"+export PYTHONDONTWRITEBYTECODE=1+export TOKENIZERS_PARALLELISM=false++PYTHON_BIN="${OPENBUILD_PYTHON_BIN:-python3}"+if ! command -v "${PYTHON_BIN}" >/dev/null 2>&1; then+  PYTHON_BIN="python"+fi++cd "${HERE}"+exec "${PYTHON_BIN}" -B -m openbuild.main