Claude Opus 5 · Training

T06 · Training build

Valid

OpenBuild Qwen3-4B training 2dev · Open Build

3.16×PERFORMANCE RATIO
141TOOL EVENTS
1TEXT PATCHES
0BINARY NAMES

01 / PROCESS MAP

Tool activity

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

Main agentClaude Opus 5 · 141 visible calls

InspectEditValidateExecuteBuildProfileRollbackOther
50Inspect
45Edit
1Build
25Validate
10Execute
1Profile
9Other

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 timeline83 groups · 141 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 and file and log inspection related to source & workspace.

    2 calls · #0001–#0002

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

    Requested file and log inspection related to task requirements.

    2 calls · #0003–#0004

    Read <path>
  3. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0005–#0005

    Read <path>
  4. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    2 calls · #0006–#0007

    cd <path>wc -c <path> <path> <path> <path> <path>Read <path>
  5. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0008–#0008

    cd <path><command> <args>cat <val>
  6. Inspect · Device memory

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

    1 call · #0009–#0009

    which <val>python3 -Vecho <flag><command> <args>head <flag>echo <val>
    2 more command sketches
    python3 -c <script> <n> >& <path>tail -n <n>
  7. Inspect · Task requirements

    Requested file and log inspection related to task requirements.

    1 call · #0010–#0010

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

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

    1 call · #0011–#0011

    cd <path><command> <args>cat <val>
  9. Inspect · Source & workspace

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

    8 calls · #0012–#0019

    Read <path>cd <path>diff <path> <path>wc -l <path>grep -n <val> <path>head -n <n>
  10. Other · Task requirements

    Requested script or workload execution related to task requirements.

    1 call · #0020–#0020

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

    Requested environment setup or inspection, source searches and runtime inspection related to parallelism & communication.

    1 call · #0021–#0021

    envgrep -i -E <val>sortecho <val>free -gdf -h <path> <path> <path> <n> >& <path>
    1 more command sketches
    <command> <args>
  12. Other · Attention kernels

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

    1 call · #0022–#0022

    cd <path>python3 -c <script> <n> >& <path>grep -v <val>
  13. Execute · Attention kernels

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

    1 call · #0023–#0023

    mkdir -p <path>cat > <path> <script>cd <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>
  14. Execute · Parallelism & communication

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

    1 call · #0024–#0024

    cat > <path> <script>cd <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>
  15. Execute · Device memory

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

    1 call · #0025–#0025

    cat > <path> <script>cd <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>
  16. Validate · Benchmark & validation setup

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

    1 call · #0026–#0026

    cat > <path> <script>cd <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>
  17. Inspect · Source & workspace

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

    2 calls · #0027–#0028

    Read <path>mkdir -p <path>ls -l -a <path>
  18. Edit · Source & workspace

    Requested code edits related to source & workspace.

    3 calls · #0029–#0031

    Write <path>Edit <path>
  19. Inspect · Attention kernels

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

    2 calls · #0032–#0033

    cat > <path> <script>cd <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>
  20. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0034–#0034

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

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

    1 call · #0035–#0035

    date -uecho <val>ls <path> <n> > <path>echo <flag>cat <path> <n> > <path>head -n <n>
  22. Inspect · Source & workspace

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

    1 call · #0036–#0036

    ls -l -a <path> <path> <n> >& <path>echo <flag>find <path> -maxdepth <n> -iname <val> -o -maxdepth <n> -iname <val> <n> <args>head -n <n>
  23. Other · Source & workspace

    Requested script or workload execution related to source & workspace.

    1 call · #0037–#0037

    cd <path><command> <args>echo <val>nohup <val> -B <path> --output <path> > <path> <n> >& <path>
  24. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0038–#0038

    Write <path>
  25. Inspect · Task requirements

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

    1 call · #0039–#0039

    cat <path> <n> >& <path>tail -n <n>echo <val>find <path> -maxdepth <n>head -n <n>python3 -c <script> <n> >& <path>
  26. Other · Task requirements

    Requested script or workload execution related to task requirements.

    1 call · #0040–#0040

    cd <path>python3 -c <script>
  27. Other · Batching & scheduling

    Requested script or workload execution related to batching & scheduling.

    1 call · #0041–#0041

    cd <path>python3 -c <script>
  28. Inspect · Checkpoints & weight state

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

    1 call · #0042–#0042

    cd <path><command> <args>python3 -c <script>head -n <n>
  29. Other · Attention kernels

    Requested script or workload execution related to attention kernels.

    1 call · #0043–#0043

    cd <path>python3 -c <script>
  30. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0044–#0044

    Write <path>
  31. Edit · Runtime processes

    Requested code edits related to runtime processes.

    1 call · #0045–#0045

    Write <path>
  32. Inspect · Source & workspace

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

    2 calls · #0046–#0047

    Read <path>cd <path>grep -n -E <val> <path>
  33. Inspect · Device memory

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

    1 call · #0048–#0048

    date -upython3 -c <script>npu-smi info <n> >& <path>head -n <n>
  34. Inspect · Source & workspace

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

    2 calls · #0049–#0050

    cd <path>grep <flag> <args>sort -u <flag> <args>awk <flag> <args>sort -uecho <val>
    1 more command sketches
    sed -n <val> <path>
  35. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0051–#0052

    Edit <path>
  36. Edit · Checkpoints & weight state

    Requested code edits related to checkpoints & weight state.

    1 call · #0053–#0053

    Write <path>
  37. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    2 calls · #0054–#0055

    Read <path>cd <path>sed -n <val> <path>
  38. Edit · Runtime processes

    Requested code edits related to runtime processes.

    4 calls · #0056–#0059

    Edit <path>
  39. Inspect · Source & workspace

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

    1 call · #0060–#0060

    cd <path>grep -n -E <val> <path>echo <val>sed -n <path> <path>
  40. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0061–#0062

    Write <path>
  41. Edit · Task requirements

    Requested code edits related to task requirements.

    1 call · #0063–#0063

    Write <path>
  42. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0064–#0065

    Write <path>
  43. Build · Task requirements

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

    1 call · #0066–#0066

    cd <path>chmod <val> <path> <path>chmod <n> <val>chmod <n> <path> <val>ls -l -a <path> <val>python3 -m <module> <script>
    1 more command sketches
    echo <val>
  44. Execute · Source & workspace

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

    1 call · #0067–#0067

    chmod <n> <path> <path>rm -rf <path>ls -l <path> <path>
  45. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0068–#0068

    Write <path>
  46. Inspect · Source & workspace

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

    1 call · #0069–#0069

    cd <path>timeout <n> <val> -B <path> <val> <n> >& <path>tail -n <n>
  47. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0070–#0070

    Write <path>
  48. Execute · Benchmark & validation setup

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

    1 call · #0071–#0071

    cd <path>timeout <n> <val> -B <path> <n> >& <path>grep -v <val>tail -n <n>
  49. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0072–#0072

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

    Requested code edits related to source & workspace.

    3 calls · #0073–#0075

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

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

    4 calls · #0076–#0079

    cd <path>timeout <n> <val> -B <path> <n> >& <path>grep -v -i -E <val>tail -n <n>sed -n <val> <path>
  52. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0080–#0080

    Edit <path>
  53. Edit · Benchmark & validation setup

    Requested code edits related to benchmark & validation setup.

    2 calls · #0081–#0082

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

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

    1 call · #0083–#0083

    chmod <val> <path>rm -rf <path>timeout <n> <val> <path> <n> >& <path>grep -v -i -E <val>tail -n <n>
  55. Edit · Source & workspace

    Requested code edits related to source & workspace.

    5 calls · #0084–#0088

    Edit <path>
  56. Validate · Benchmark & validation setup

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

    1 call · #0089–#0089

    rm -rf <path>timeout <n> <val> <path> <n> >& <path>grep -v -i -E <val>tail -n <n>
  57. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0090–#0091

    Edit <path>
  58. Validate · Parallelism & communication

    Requested workspace file updates, script or workload execution and source searches related to parallelism & communication.

    1 call · #0092–#0092

    rm -rf <path>timeout <n> <val> <path> <n> >& <path>grep -v -i -E <val>tail -n <n>
  59. Edit · Source & workspace

    Requested code edits related to source & workspace.

    5 calls · #0093–#0097

    Edit <path>
  60. Validate · Benchmark & validation setup

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

    1 call · #0098–#0098

    rm -rf <path>timeout <n> <val> <path> <n> >& <path>grep -v -i -E <val>tail -n <n>
  61. Edit · Checkpoints & weight state

    Requested code edits related to checkpoints & weight state.

    2 calls · #0099–#0100

    Edit <path>
  62. Validate · Checkpoints & weight state

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

    1 call · #0101–#0101

    rm -rf <path>timeout <n> <val> <path> <n> >& <path>grep -v -i -E <val>tail -n <n>echo <val>ls -l -a <path> <n> > <path>
    1 more command sketches
    head
  63. Validate · Benchmark & validation setup

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

    1 call · #0102–#0102

    date -upython3 -c <script>echo <val>
  64. Validate · Checkpoints & weight state

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

    1 call · #0103–#0103

    cd <path>env <vars> timeout <n> <val> <path> <n> >& <path>grep -v -i -E <val>tail -n <n>echo <val>cat <path> <n> > <path>
    2 more command sketches
    python3 -m <module> <n> > <path>head -n <n>
  65. Validate · Benchmark & validation setup

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

    7 calls · #0104–#0110

    cd <path>export <vars>nohup <val> <path> > <path> <n> >& <path>echo <val>sleep <n>tail -n <n> <path>
    20 more command sketches
    tail -n <n> <path> <n> > <path>pgrep <flag> <args>head -n <n>date -upython3 -c <script>wc -c <path>tail -c <n> <path>echols <flag> <args><command> <args>head <flag>echo <flag>find <val> -name <val> -exec <val> -l <val>pgrep -c -f <val> <n> > <path>grep -h <val> <path> <n> > <path>tail -n <n>echo <path>ls <path> <n> > <path>env <vars>cat <path>
  66. Inspect · Task requirements

    Requested source searches and file and log inspection related to task requirements.

    1 call · #0111–#0111

    cd <path>grep -r -n <val> <path> <path> <path> <path> <n> > <path>head -n <n>
  67. Profile · Benchmark & validation setup

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

    1 call · #0112–#0112

    pgrep <flag> <args>grep -v <val>head -n <n>echo <flag><command> <args>head <flag>
    3 more command sketches
    ls <val>echo <val>python3 -m <module> <path> <n> > <path>
  68. Edit · Runtime processes

    Requested code edits related to runtime processes.

    1 call · #0113–#0113

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

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

    1 call · #0114–#0114

    cd <path><command> <args>python3 -c <script>
  70. Validate · Benchmark & validation setup

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

    4 calls · #0115–#0118

    cd <path>export <vars>rm -f <path>nohup <val> <path> > <path> <n> >& <path>echo <val>date -u
    9 more command sketches
    python3 -c <script><command> <args>head <flag>env <vars>grep -h <val> <path> <n> > <path>tail -n <n>echo <path>cat <path>sleep <n>
  71. Inspect · Checkpoints & weight state

    1 tool error

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

    3 calls · #0119–#0121

    cd <path>grep -n <val> <path>echo <val><command> <args>head -n <n>cut <flag> <args>
    1 more command sketches
    sed -n <val> <path>
  72. Other · Checkpoints & weight state

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

    1 call · #0122–#0122

    cd <path>awk <val> <path>
  73. Inspect · Checkpoints & weight state

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

    1 call · #0123–#0123

    cd <path>sed -n <path> <path>head -n <n>
  74. Edit · Checkpoints & weight state

    Requested code edits related to checkpoints & weight state.

    2 calls · #0124–#0125

    Edit <path>
  75. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0126–#0126

    Edit <path>
  76. Validate · Benchmark & validation setup

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

    5 calls · #0127–#0131

    cd <path>export <vars>rm -f <path>nohup <val> <path> > <path> <n> >& <path>echo <val>date -u
    9 more command sketches
    sleep <n>python3 -c <script><command> <args>head <flag>env <vars>grep -h <val> <path> <n> > <path>tail -n <n>echo <path>cat <path>
  77. Execute · Benchmark & validation setup

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

    3 calls · #0132–#0134

    cd <path>export <vars>rm -f <path>nohup <val> <path> > <path> <n> >& <path>echo <val>date -u
    9 more command sketches
    sleep <n>python3 -c <script><command> <args>head <flag>grep -h <val> <path> <n> > <path>tail -n <n>echo <path>cat <path>env <vars>
  78. Inspect · Task requirements

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

    1 call · #0135–#0135

    cd <path>echo <val>du <flag> <args>find <path> -type <val>sortls -l <path> <path> <val>
    5 more command sketches
    cat <val>git status <flag> <args>headgit diff --stat <flag> <args>tail -n <n>
  79. Execute · Benchmark & validation setup

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

    2 calls · #0136–#0137

    sleep <n>date -upython3 -c <script>echo <path>echo <val>cat <path>
    4 more command sketches
    <command> <args>head <flag>grep -h <val> <path> <n> > <path>tail -n <n>
  80. Validate · Benchmark & validation setup

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

    1 call · #0138–#0138

    cd <path>export <vars>echo <val>timeout <n> <val> <path> <n> >& <path>tail -c <n>echo
  81. Inspect · Runtime processes

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

    1 call · #0139–#0139

    cd <path>export <vars>echo <val>timeout <n> <val> <path> <n> >& <path>tail -c <n>echo
    3 more command sketches
    pgrep -c -f <val> <n> > <path>echo <n>cat <path>
  82. Inspect · Device memory

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

    1 call · #0140–#0140

    pgrep <flag> <args>grep -v <val>echo <val>npu-smi info <n> >& <path>grep -E <path>head -n <n>
  83. Inspect · Source & workspace

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

    1 call · #0141–#0141

    cd <path>find <path> -name <val> <flag> <args>sortecho <val>du <flag> <args>git status <flag>

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

Base commit: d1281fd46aa0575309be1eb6e0fcdc79e4be9670

diff --git a/solution/bootstrap.sh b/solution/bootstrap.shnew file mode 100755index 0000000000000000000000000000000000000000..487ef09633d19e6da9ce118fbdcfd8e447668323--- /dev/null+++ b/solution/bootstrap.sh@@ -0,0 +1,35 @@+#!/usr/bin/env bash+# Offline bootstrap. Everything the trainer needs is either already provided by+# the runtime image (torch, torch_npu, numpy, CANN) or vendored in this bundle,+# so there is nothing to fetch and nothing to install. The base Python+# environment is left untouched; this step only verifies that the runtime can+# satisfy the imports and that the assigned devices are reachable, which turns a+# broken environment into an immediate, legible failure rather than a failure+# midway through a measured training run.+set -euo pipefail++here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+python_bin="$(command -v python3 || command -v python)"++PYTHONPATH="${here}${PYTHONPATH:+:${PYTHONPATH}}" "${python_bin}" -B - <<'PY'+import os+import sys++import torch+import torch_npu++from obtrain import contract++visible = os.environ.get("ASCEND_RT_VISIBLE_DEVICES", "")+requested = [p for p in os.environ.get("OPENBUILD_DEVICE_IDS", "0,1").split(",") if p]+count = torch.npu.device_count()+if count < len(requested):+    raise SystemExit(f"need {len(requested)} devices, runtime exposes {count}")++print(+    f"[obtrain] bootstrap ok: torch {torch.__version__}, "+    f"torch_npu {torch_npu.__version__}, devices={count}, visible={visible!r}, "+    f"parameters={contract.TOTAL_NUMEL}",+    flush=True,+)+PYdiff --git a/solution/manifest.json b/solution/manifest.jsonnew file mode 100644index 0000000000000000000000000000000000000000..0d5ba8f2123fd9125d23e7cdbf3624b37c1ee658--- /dev/null+++ b/solution/manifest.json@@ -0,0 +1,10 @@+{+  "schema_version": 1,+  "kind": "openbuild_training_solution",+  "task_id": "openbuild_training_qwen3_4b_2dev_v1",+  "entrypoints": {+    "bootstrap": "bootstrap.sh",+    "train": "train.sh"+  },+  "offline_bootstrap": true+}diff --git a/solution/obtrain/__init__.py b/solution/obtrain/__init__.pynew file mode 100644index 0000000000000000000000000000000000000000..33948317bfb18f838b7ccc1a1750fa4089b700f0--- /dev/null+++ b/solution/obtrain/__init__.py@@ -0,0 +1 @@+"""Two-device Qwen3-4B-Base training system for offline replay."""diff --git a/solution/obtrain/checkpoint.py b/solution/obtrain/checkpoint.pynew file mode 100644index 0000000000000000000000000000000000000000..46fe582cfaab6995884e59f5a6104460cb50d266--- /dev/null+++ b/solution/obtrain/checkpoint.py@@ -0,0 +1,191 @@+"""Complete, restartable checkpoint of the committed training state.++Each rank writes its own ZeRO-1 shard files, so the eight required state+components are captured in full with no cross-rank copies:++* ``model``            -- bf16 flat weights, one file per rank shard+* ``master_parameters``/``first_moments``/``second_moments`` -- fp32 shards+* ``parameter_steps``/``scheduler``/``data_cursor``/``committed_update``+  -- scalar state in ``state.json``++Files are written to a temporary name and renamed into place, then the manifest+is written last, so a manifest on disk always implies a complete checkpoint.+"""++from __future__ import annotations++import json+import os++import torch++from . import contract++SHARD_FIELDS = ("model", "master_parameters", "first_moments", "second_moments")+++def shard_name(field: str, rank: int) -> str:+    return f"{field}.rank{rank}.bin"+++def _write_tensor(path: str, tensor: torch.Tensor) -> None:+    """Write a device tensor to disk, staged then renamed.++    numpy has no bf16 dtype, so bf16 shards are reinterpreted as uint16; the+    stored bytes are the raw bf16 bit patterns either way, so the round trip is+    exact. Copies are staged in windows to keep a full-width host mirror of a+    7.49 GiB shard off the peak.+    """+    staging = f"{path}.partial"+    source = tensor.detach()+    if source.dtype == torch.bfloat16:+        source = source.view(torch.uint16)+    window = 1 << 26+    with open(staging, "wb") as handle:+        for position in range(0, source.numel(), window):+            chunk = source[position : position + window].contiguous().cpu()+            handle.write(chunk.numpy().tobytes())+            del chunk+    os.replace(staging, path)+++def _read_tensor(path: str, tensor: torch.Tensor) -> None:+    """Restore a shard from disk into an existing device tensor, in windows."""+    import numpy as np++    element = 4 if tensor.dtype == torch.float32 else 2+    expected = tensor.numel() * element+    actual = os.path.getsize(path)+    if actual != expected:+        raise RuntimeError(f"{path}: expected {expected} bytes, found {actual}")+    destination = tensor.view(torch.uint16) if tensor.dtype == torch.bfloat16 else tensor+    dtype = np.float32 if tensor.dtype == torch.float32 else np.uint16+    window = 1 << 26+    with open(path, "rb") as handle:+        position = 0+        while position < destination.numel():+            span = min(window, destination.numel() - position)+            block = np.frombuffer(handle.read(span * element), dtype=dtype)+            destination[position : position + span].copy_(torch.from_numpy(block))+            position += span+            del block+++def save(+    checkpoint_dir: str,+    output_dir: str,+    rank: int,+    world_size: int,+    profile_id: str,+    flat_model: torch.Tensor,+    optimizer,+    update_index: int,+) -> None:+    """Write this rank's shard files; rank 0 also writes scalars and manifest.++    The manifest is an *output* artifact whose ``files`` list is resolved against+    the checkpoint directory, and the checkpoint's observed file set must equal+    that list exactly -- so the manifest itself must not be written into the+    checkpoint directory.+    """+    os.makedirs(checkpoint_dir, exist_ok=True)+    start, stop = optimizer.start, optimizer.stop+    payload = {+        "model": flat_model[start:stop],+        "master_parameters": optimizer.master,+        "first_moments": optimizer.exp_avg,+        "second_moments": optimizer.exp_avg_sq,+    }+    for field, tensor in payload.items():+        _write_tensor(os.path.join(checkpoint_dir, shard_name(field, rank)), tensor)++    if rank != 0:+        return++    state = {+        "schema_version": 1,+        "task_id": contract.TASK_ID,+        "profile_id": profile_id,+        "initialization_spec": "canonical_tensor_counter_v1",+        "world_size": world_size,+        "total_numel": contract.TOTAL_NUMEL,+        "shard_bounds": [list(_bounds(index, world_size)) for index in range(world_size)],+        "committed_update": update_index,+        "parameter_steps": update_index,+        "data_cursor": {+            "next_update_index": update_index + 1,+            "consumed_updates": update_index,+            "consumed_tokens": update_index * contract.TOKENS_PER_UPDATE,+        },+        "scheduler": {+            "kind": "cosine_with_min_lr",+            "completed_updates": update_index,+            "decay_updates": contract.DECAY_UPDATES,+            "base_learning_rate": contract.LEARNING_RATE,+            "min_learning_rate": contract.MIN_LEARNING_RATE,+            "next_learning_rate": contract.learning_rate_for(update_index + 1),+        },+    }+    with open(os.path.join(checkpoint_dir, "state.json"), "w", encoding="utf-8") as handle:+        json.dump(state, handle, sort_keys=True, indent=1)+        handle.write("\n")++    files = ["state.json"]+    for field in SHARD_FIELDS:+        files.extend(shard_name(field, index) for index in range(world_size))+    manifest = {+        "schema_version": 1,+        "kind": "openbuild_training_checkpoint",+        "task_id": contract.TASK_ID,+        "profile_id": profile_id,+        "initialization_spec": "canonical_tensor_counter_v1",+        "optimizer_update": 30,+        "next_update_index": 31,+        "state_components": list(contract.STATE_COMPONENTS),+        "files": sorted(files),+        "fresh_load_entrypoint": "train.sh",+        "fresh_next_step_mode": "fresh_next_step_probe",+    }+    with open(+        os.path.join(output_dir, "checkpoint-manifest.json"), "w", encoding="utf-8"+    ) as handle:+        json.dump(manifest, handle, sort_keys=True, indent=1)+        handle.write("\n")+++def _bounds(rank: int, world_size: int) -> tuple[int, int]:+    from .zero import shard_bounds++    return shard_bounds(rank, world_size)+++def load(+    checkpoint_dir: str,+    rank: int,+    flat_model: torch.Tensor,+    optimizer,+) -> dict:+    """Restore the committed state into an already-allocated set of buffers."""+    with open(os.path.join(checkpoint_dir, "state.json"), "rb") as handle:+        state = json.load(handle)+    if state["total_numel"] != contract.TOTAL_NUMEL:+        raise RuntimeError("checkpoint parameter count does not match the contract")+    world_size = int(state["world_size"])+    for index in range(world_size):+        start, stop = _bounds(index, world_size)+        _read_tensor(+            os.path.join(checkpoint_dir, shard_name("model", index)),+            flat_model[start:stop],+        )+    _read_tensor(+        os.path.join(checkpoint_dir, shard_name("master_parameters", rank)),+        optimizer.master,+    )+    _read_tensor(+        os.path.join(checkpoint_dir, shard_name("first_moments", rank)), optimizer.exp_avg+    )+    _read_tensor(+        os.path.join(checkpoint_dir, shard_name("second_moments", rank)),+        optimizer.exp_avg_sq,+    )+    return statediff --git a/solution/obtrain/contract.py b/solution/obtrain/contract.pynew file mode 100644index 0000000000000000000000000000000000000000..1718358d49290cd5474439fb6cad84ed69fb7c48--- /dev/null+++ b/solution/obtrain/contract.py@@ -0,0 +1,164 @@+"""Public workload constants and the canonical parameter layout.++Everything here is a transcription of ``workloads/openbuild_contract.v1.json``.+The canonical layout defines one flat logical parameter vector; every rank+derives identical offsets from it so that sharding never changes the logical+tensor.+"""++from __future__ import annotations++from dataclasses import dataclass++TASK_ID = "openbuild_training_qwen3_4b_2dev_v1"++# --- model -----------------------------------------------------------------+NUM_LAYERS = 36+MODEL_WIDTH = 2560+FFN_WIDTH = 9728+NUM_HEADS = 32+NUM_KV_GROUPS = 8+KV_CHANNELS = 128+VOCAB_SIZE = 151936+NORM_EPS = 1e-6+ROTARY_BASE = 1000000+Q_WIDTH = NUM_HEADS * KV_CHANNELS  # 4096+KV_WIDTH = NUM_KV_GROUPS * KV_CHANNELS  # 1024++# --- optimizer -------------------------------------------------------------+LEARNING_RATE = 0.00000125+MIN_LEARNING_RATE = 0.000000125+WEIGHT_DECAY = 0.1+BETA1 = 0.9+BETA2 = 0.95+ADAM_EPS = 0.00000001+CLIP_GRAD = 1.0+CLIP_EPSILON = 0.000001+DECAY_UPDATES = 30+TRAINING_UPDATES = 30+FRESH_PROBE_UPDATE = 31++# --- profiles --------------------------------------------------------------+TOKENS_PER_UPDATE = 32768+TOTAL_TOKENS = 983040++PROFILES = {+    "long_sequence": {"global_batch_size": 16, "sequence_length": 2048},+    "update_heavy": {"global_batch_size": 64, "sequence_length": 512},+}++SELECTOR_CATEGORIES = (+    "logits",+    "gradients",+    "model_parameters",+    "master_parameters",+    "first_moments",+    "second_moments",+)++STATE_COMPONENTS = [+    "model",+    "master_parameters",+    "first_moments",+    "second_moments",+    "parameter_steps",+    "scheduler",+    "data_cursor",+    "committed_update",+]++ALIASES = {"lm_head.weight": "model.embed_tokens.weight"}+++@dataclass(frozen=True, slots=True)+class ParamSpec:+    """One canonical logical parameter."""++    name: str+    shape: tuple[int, ...]+    offset: int+    decay: bool+    constant_one: bool++    @property+    def numel(self) -> int:+        total = 1+        for dim in self.shape:+            total *= dim+        return total+++def _build_layout() -> tuple[tuple[ParamSpec, ...], int, int]:+    """Build the canonical flat layout.++    Weight-decay parameters (logical rank >= 2) come first, then the+    rank-1 constant-one norm parameters. Grouping by the decay rule keeps+    each rank's optimizer shard describable by at most two contiguous+    segments, which lets the AdamW step run as a couple of fused fp32+    tensor operations instead of per-parameter kernels.+    """+    decay_specs: list[tuple[str, tuple[int, ...]]] = [+        ("model.embed_tokens.weight", (VOCAB_SIZE, MODEL_WIDTH)),+    ]+    nodecay_specs: list[tuple[str, tuple[int, ...]]] = []+    for layer in range(NUM_LAYERS):+        prefix = f"model.layers.{layer}"+        decay_specs.extend(+            [+                (f"{prefix}.self_attn.q_proj.weight", (Q_WIDTH, MODEL_WIDTH)),+                (f"{prefix}.self_attn.k_proj.weight", (KV_WIDTH, MODEL_WIDTH)),+                (f"{prefix}.self_attn.v_proj.weight", (KV_WIDTH, MODEL_WIDTH)),+                (f"{prefix}.self_attn.o_proj.weight", (MODEL_WIDTH, Q_WIDTH)),+                (f"{prefix}.mlp.gate_proj.weight", (FFN_WIDTH, MODEL_WIDTH)),+                (f"{prefix}.mlp.up_proj.weight", (FFN_WIDTH, MODEL_WIDTH)),+                (f"{prefix}.mlp.down_proj.weight", (MODEL_WIDTH, FFN_WIDTH)),+            ]+        )+        nodecay_specs.extend(+            [+                (f"{prefix}.input_layernorm.weight", (MODEL_WIDTH,)),+                (f"{prefix}.self_attn.q_norm.weight", (KV_CHANNELS,)),+                (f"{prefix}.self_attn.k_norm.weight", (KV_CHANNELS,)),+                (f"{prefix}.post_attention_layernorm.weight", (MODEL_WIDTH,)),+            ]+        )+    nodecay_specs.append(("model.norm.weight", (MODEL_WIDTH,)))++    specs: list[ParamSpec] = []+    offset = 0+    for name, shape in decay_specs:+        spec = ParamSpec(name, shape, offset, True, False)+        specs.append(spec)+        offset += spec.numel+    decay_numel = offset+    for name, shape in nodecay_specs:+        spec = ParamSpec(name, shape, offset, False, True)+        specs.append(spec)+        offset += spec.numel+    return tuple(specs), offset, decay_numel+++PARAM_SPECS, TOTAL_NUMEL, DECAY_NUMEL = _build_layout()+SPEC_BY_NAME = {spec.name: spec for spec in PARAM_SPECS}+++def flat_index(canonical_name: str, element_index: int) -> int:+    """Map a canonical (name, flat element index) pair to the flat offset."""+    resolved = ALIASES.get(canonical_name, canonical_name)+    spec = SPEC_BY_NAME[resolved]+    if not 0 <= element_index < spec.numel:+        raise ValueError(f"flat index out of range for {canonical_name}")+    return spec.offset + element_index+++def is_decay(canonical_name: str) -> bool:+    return SPEC_BY_NAME[ALIASES.get(canonical_name, canonical_name)].decay+++def learning_rate_for(update_index: int) -> float:+    """Cosine schedule with no warmup, exactly as the public workload states."""+    import math++    progress = min(update_index - 1, DECAY_UPDATES - 1)+    cosine = 1.0 + math.cos(math.pi * progress / (DECAY_UPDATES - 1))+    return MIN_LEARNING_RATE + 0.5 * (LEARNING_RATE - MIN_LEARNING_RATE) * cosinediff --git a/solution/obtrain/data.py b/solution/obtrain/data.pynew file mode 100644index 0000000000000000000000000000000000000000..de698ea5404d9d3c8b86ef5f105e4b75a3375569--- /dev/null+++ b/solution/obtrain/data.py@@ -0,0 +1,134 @@+"""Deterministic data pipeline over the raw dense controller input bundle.++The bundle stores each field as a headerless little-endian dense array of shape+``[31, global_batch_size, sequence_length]``; slice ``update_index - 1`` is the+global batch for that update. Rows are split across ranks by a contiguous cut+that preserves the published order -- rank 0 takes the low rows, rank 1 the high+rows -- and each rank walks its rows in ascending order. No row is reordered,+substituted, dropped, or replayed, so the data cursor is fully described by the+next update index.+"""++from __future__ import annotations++import json+import os+from dataclasses import dataclass++import numpy as np+import torch++NUMPY_DTYPES = {"int32": np.int32, "int64": np.int64, "uint8": np.uint8}++# Tokens per micro-step. Chosen to keep the activation working set inside the+# HBM left over after the ZeRO-1 fixed residency (model + fp32 gradients ++# fp32 master/moment shards); both public profiles divide evenly.+MICRO_TOKENS = 2048+++@dataclass(slots=True)+class MicroBatch:+    """One micro-step of local rows, already resident on the device."""++    input_ids: torch.Tensor+    labels: torch.Tensor+    loss_mask: torch.Tensor+    position_ids: torch.Tensor+    row_start: int+    """Global batch row corresponding to local row 0."""++    @property+    def rows(self) -> int:+        return int(self.input_ids.shape[0])+++class ProfileInput:+    """Read-only view of one profile's global records for this rank."""++    def __init__(+        self,+        input_root: str,+        profile_id: str,+        rank: int,+        world_size: int,+        device: torch.device,+    ) -> None:+        with open(os.path.join(input_root, "input-manifest.json"), "rb") as handle:+            manifest = json.load(handle)+        profile = next(+            entry for entry in manifest["profiles"] if entry["profile_id"] == profile_id+        )+        self.profile_id = profile_id+        self.selector_set = profile["selector_set"]+        self.selector_set_id = self.selector_set["selector_set_id"]+        self.global_batch_size = int(profile["global_batch_size"])+        self.sequence_length = int(profile["sequence_length"])+        axis = profile["update_axis"]+        self.first_update_index = int(axis["first_update_index"])+        self.training_update_count = int(axis["training_update_count"])+        self.fresh_probe_update_index = int(axis["fresh_probe_update_index"])+        self.rank = rank+        self.world_size = world_size+        self.device = device++        self._arrays: dict[str, np.memmap] = {}+        for field, descriptor in profile["tensors"].items():+            path = os.path.join(input_root, descriptor["path"])+            self._arrays[field] = np.memmap(+                path,+                dtype=NUMPY_DTYPES[descriptor["dtype"]],+                mode="r",+                shape=tuple(int(value) for value in descriptor["shape"]),+            )++        if self.global_batch_size % world_size:+            raise ValueError("global batch size must divide across the assigned devices")+        self.rows_per_rank = self.global_batch_size // world_size+        self.row_start = rank * self.rows_per_rank+        self.micro_rows = max(1, min(self.rows_per_rank, MICRO_TOKENS // self.sequence_length))+        if self.rows_per_rank % self.micro_rows:+            raise ValueError("micro-batch rows must divide the per-rank rows")+        self.micro_steps = self.rows_per_rank // self.micro_rows++    @property+    def tokens_per_update(self) -> int:+        return self.global_batch_size * self.sequence_length++    def owner_of_row(self, global_batch_row: int) -> int:+        return global_batch_row // self.rows_per_rank++    def locate_row(self, global_batch_row: int) -> tuple[int, int]:+        """Map a global batch row to ``(micro_step, local_row_within_micro)``."""+        local = global_batch_row - self.row_start+        return local // self.micro_rows, local % self.micro_rows++    def _slice(self, field: str, update_index: int, start: int, stop: int) -> np.ndarray:+        return np.ascontiguousarray(+            self._arrays[field][update_index - 1, start:stop]+        )++    def micro_batches(self, update_index: int):+        """Yield this rank's micro-steps for ``update_index`` in published order."""+        for step in range(self.micro_steps):+            start = self.row_start + step * self.micro_rows+            stop = start + self.micro_rows+            yield MicroBatch(+                input_ids=torch.from_numpy(self._slice("input_ids", update_index, start, stop))+                .to(self.device, non_blocking=True)+                .long(),+                labels=torch.from_numpy(self._slice("labels", update_index, start, stop))+                .to(self.device, non_blocking=True)+                .long(),+                loss_mask=torch.from_numpy(+                    self._slice("loss_mask", update_index, start, stop)+                ).to(self.device, non_blocking=True),+                position_ids=torch.from_numpy(+                    self._slice("position_ids", update_index, start, stop)+                )+                .to(self.device, non_blocking=True)+                .long(),+                row_start=start,+            )++    def sample_ids(self, update_index: int) -> list[int]:+        return [int(value) for value in self._arrays["sample_ids"][update_index - 1]]diff --git a/solution/obtrain/initrng.py b/solution/obtrain/initrng.pynew file mode 100644index 0000000000000000000000000000000000000000..cdf78ff4ddd24c81d1c9756be6bf9d0e93c3981e--- /dev/null+++ b/solution/obtrain/initrng.py@@ -0,0 +1,136 @@+"""Deterministic update-zero initialization (``canonical_tensor_counter_v1``).++Every element is a stateless function of its canonical tensor name and its+global row-major element index, so the result is independent of shard order,+parameter traversal order, and process layout. The counter arithmetic runs+on-device in int64: torch's int64 wraps modulo 2^64 exactly like the public+specification requires, and shifts are masked to emulate logical shifts on the+two's-complement representation.+"""++from __future__ import annotations++import torch++from . import contract++MASK64 = (1 << 64) - 1+GLOBAL_SEED = 0x51454E334F50454E+FNV_OFFSET = 0xCBF29CE484222325+FNV_PRIME = 0x00000100000001B3+GOLDEN = 0x9E3779B97F4A7C15+SPLIT_C1 = 0xBF58476D1CE4E5B9+SPLIT_C2 = 0x94D049BB133111EB+++def _as_signed(value: int) -> int:+    """Reinterpret an unsigned 64-bit value as torch's signed int64."""+    value &= MASK64+    return value - (1 << 64) if value >= (1 << 63) else value+++def name_hash(canonical_name: str) -> int:+    """FNV-1a 64 over the UTF-8 canonical tensor name."""+    digest = FNV_OFFSET+    for byte in canonical_name.encode("utf-8"):+        digest ^= byte+        digest = (digest * FNV_PRIME) & MASK64+    return digest+++def _logical_shift(value: torch.Tensor, bits: int) -> torch.Tensor:+    """Logical right shift on int64 (torch's ``>>`` is arithmetic).++    ``bitwise_right_shift`` has no NPU kernel and silently falls back to the+    host, which dominates the cost of reconstructing 4.02e9 initial values. For+    two's-complement integers an arithmetic right shift by ``k`` is exactly+    ``floor(value / 2**k)``, which does run on device; masking off the sign+    extension then yields the logical shift.+    """+    shifted = torch.div(value, 1 << bits, rounding_mode="floor")+    return shifted & ((1 << (64 - bits)) - 1)+++def counter_values(+    canonical_name: str,+    start: int,+    count: int,+    device: torch.device | str,+) -> torch.Tensor:+    """Return ``count`` fp32 initial values starting at global element ``start``.++    Implements ``counter -> splitmix64_once -> signed_uniform_12_bit`` exactly:+        counter = seed xor name_hash xor (index * GOLDEN mod 2^64)+        q = ((random_u64 >> 52) & 0xfff) - 2048+        value = q * 2^-16+    """+    xor_constant = _as_signed(GLOBAL_SEED ^ name_hash(canonical_name))+    golden = _as_signed(GOLDEN)+    index = torch.arange(start, start + count, dtype=torch.int64, device=device)+    value = index * golden+    value = torch.bitwise_xor(value, xor_constant)+    # splitmix64, one round+    value = value + golden+    value = (torch.bitwise_xor(value, _logical_shift(value, 30))) * _as_signed(SPLIT_C1)+    value = (torch.bitwise_xor(value, _logical_shift(value, 27))) * _as_signed(SPLIT_C2)+    value = torch.bitwise_xor(value, _logical_shift(value, 31))+    quantized = torch.div(value, 1 << 52, rounding_mode="floor") & 0xFFF+    quantized = quantized - 2048+    del index, value+    return quantized.to(torch.float32) * (2.0**-16)+++def scalar_initial_master(canonical_name: str, element_index: int) -> float:+    """Host-side single-element initial master value (bf16 widened to fp32)."""+    spec = contract.SPEC_BY_NAME[+        contract.ALIASES.get(canonical_name, canonical_name)+    ]+    if spec.constant_one:+        return 1.0+    counter = (+        GLOBAL_SEED+        ^ name_hash(canonical_name)+        ^ ((element_index * GOLDEN) & MASK64)+    ) & MASK64+    value = (counter + GOLDEN) & MASK64+    value = ((value ^ (value >> 30)) * SPLIT_C1) & MASK64+    value = ((value ^ (value >> 27)) * SPLIT_C2) & MASK64+    value ^= value >> 31+    quantized = ((value >> 52) & 0xFFF) - 2048+    single = torch.tensor(quantized * (2.0**-16), dtype=torch.float32)+    return float(single.to(torch.bfloat16).to(torch.float32))+++def fill_model_range(+    flat_model: torch.Tensor,+    start: int,+    end: int,+    *,+    chunk_elements: int = 1 << 26,+) -> None:+    """Initialize ``flat_model[start:end]`` (a bf16 view of the flat vector).++    ``start``/``end`` are global flat offsets and may fall inside a parameter,+    which lets each rank initialize an arbitrary contiguous slice of the model+    while producing bit-identical values to any other partitioning.+    """+    device = flat_model.device+    for spec in contract.PARAM_SPECS:+        spec_end = spec.offset + spec.numel+        lower = max(start, spec.offset)+        upper = min(end, spec_end)+        if lower >= upper:+            continue+        destination = flat_model[lower - start : upper - start]+        if spec.constant_one:+            destination.fill_(1.0)+            continue+        position = lower+        while position < upper:+            span = min(chunk_elements, upper - position)+            values = counter_values(+                spec.name, position - spec.offset, span, device+            )+            destination[position - lower : position - lower + span].copy_(values)+            del values+            position += spandiff --git a/solution/obtrain/model.py b/solution/obtrain/model.pynew file mode 100644index 0000000000000000000000000000000000000000..22758d6fd0d46be1de0ddee6e73f2ee28cf5f62f--- /dev/null+++ b/solution/obtrain/model.py@@ -0,0 +1,299 @@+"""Qwen3-4B-Base forward/backward on Ascend NPU with fp32 gradient accumulation.++Design notes+------------+The whole model lives in one flat bf16 buffer and all gradients live in one+flat fp32 buffer. Weights are plain views into the model buffer, so they are+not autograd leaves; each custom ``autograd.Function`` routes its weight+gradient straight into the matching fp32 view. That reproduces Megatron's+``main_grad`` semantics (bf16 weight-gradient GEMM accumulated into an fp32+accumulator) while avoiding a second 8 GiB bf16 ``.grad`` mirror, and it makes+ZeRO-1 sharding a pure slicing operation on the flat vectors.++The tied output projection shares the embedding's flat region, so both the+embedding lookup and the LM head accumulate into the same canonical gradient.+"""++from __future__ import annotations++import math++import torch+import torch_npu++from . import contract++_ATTENTION_MASK: dict[torch.device, torch.Tensor] = {}+++def causal_mask(device: torch.device) -> torch.Tensor:+    """The 2048x2048 compressed causal mask used by ``sparse_mode=3``."""+    cached = _ATTENTION_MASK.get(device)+    if cached is None:+        cached = torch.triu(+            torch.ones(2048, 2048, dtype=torch.bool, device=device), diagonal=1+        )+        _ATTENTION_MASK[device] = cached+    return cached+++class FlatLinear(torch.autograd.Function):+    """``y = x @ w.T`` with the weight gradient accumulated in fp32."""++    @staticmethod+    def forward(ctx, x, weight, grad_view):  # type: ignore[override]+        ctx.save_for_backward(x, weight)+        ctx.grad_view = grad_view+        return torch.mm(x, weight.t())++    @staticmethod+    def backward(ctx, dy):  # type: ignore[override]+        x, weight = ctx.saved_tensors+        dy = dy.contiguous()+        dx = torch.mm(dy, weight)+        if ctx.grad_view is not None:+            ctx.grad_view.add_(torch.mm(dy.t(), x))+        return dx, None, None+++class FlatRMSNorm(torch.autograd.Function):+    """RMSNorm over the last dimension; ``dw`` arrives already in fp32."""++    @staticmethod+    def forward(ctx, x, weight, grad_view):  # type: ignore[override]+        y, rstd = torch_npu.npu_rms_norm(x, weight, epsilon=contract.NORM_EPS)+        ctx.save_for_backward(x, weight, rstd)+        ctx.grad_view = grad_view+        return y++    @staticmethod+    def backward(ctx, dy):  # type: ignore[override]+        x, weight, rstd = ctx.saved_tensors+        dx, dw = torch_npu.npu_rms_norm_backward(dy.contiguous(), x, weight, rstd)+        if ctx.grad_view is not None:+            ctx.grad_view.add_(dw.reshape(-1))+        return dx, None, None+++class FlatEmbedding(torch.autograd.Function):+    """Token lookup whose gradient scatters into the tied canonical region.++    ``graph_root`` is an unused scalar leaf. Because every weight is a plain+    view into the flat buffer rather than an autograd leaf, nothing in the+    network would otherwise require grad and the backward graph would never be+    built; threading one leaf through the first op anchors the whole chain.+    """++    @staticmethod+    def forward(ctx, weight, token_ids, grad_view, graph_root):  # type: ignore[override]+        ctx.save_for_backward(token_ids)+        ctx.grad_view = grad_view+        return weight.index_select(0, token_ids)++    @staticmethod+    def backward(ctx, dy):  # type: ignore[override]+        (token_ids,) = ctx.saved_tensors+        if ctx.grad_view is not None:+            ctx.grad_view.index_add_(0, token_ids, dy.reshape(-1, dy.shape[-1]).float())+        return None, None, None, None+++class FusedCrossEntropy(torch.autograd.Function):+    """Chunked LM head + fp32 softmax cross entropy.++    Returns the *sum* of masked token NLL for the local micro-batch; the caller+    divides by the global masked-token count so the reported loss and every+    gradient use the public global normalization. Logits are recomputed in+    backward instead of being cached, which keeps a [T, 151936] bf16 buffer out+    of the forward-pass memory peak.+    """++    CHUNK = 512+    VOCAB_CHUNK = 16384++    @staticmethod+    def forward(ctx, hidden, weight, grad_view, labels, mask, probe):  # type: ignore[override]+        tokens = hidden.shape[0]+        log_sum_exp = torch.empty(tokens, dtype=torch.float32, device=hidden.device)+        label_logit = torch.empty(tokens, dtype=torch.float32, device=hidden.device)+        chunk = FusedCrossEntropy.CHUNK+        for start in range(0, tokens, chunk):+            stop = min(start + chunk, tokens)+            logits = torch.mm(hidden[start:stop], weight.t()).float()+            log_sum_exp[start:stop] = torch.logsumexp(logits, dim=-1)+            label_logit[start:stop] = logits.gather(+                1, labels[start:stop].unsqueeze(1).long()+            ).squeeze(1)+            if probe is not None:+                for token_index, vocab_index, sink in probe:+                    if start <= token_index < stop:+                        sink.copy_(logits[token_index - start, vocab_index])+            del logits+        negative_log_likelihood = (log_sum_exp - label_logit) * mask+        ctx.save_for_backward(hidden, weight, labels, mask, log_sum_exp)+        ctx.grad_view = grad_view+        return negative_log_likelihood.sum()++    @staticmethod+    def backward(ctx, dloss):  # type: ignore[override]+        hidden, weight, labels, mask, log_sum_exp = ctx.saved_tensors+        tokens, width = hidden.shape+        scale = (dloss * mask).float()+        dlogits = torch.empty(+            tokens, weight.shape[0], dtype=torch.bfloat16, device=hidden.device+        )+        chunk = FusedCrossEntropy.CHUNK+        for start in range(0, tokens, chunk):+            stop = min(start + chunk, tokens)+            logits = torch.mm(hidden[start:stop], weight.t()).float()+            logits = torch.exp(logits - log_sum_exp[start:stop].unsqueeze(1))+            logits.scatter_add_(+                1,+                labels[start:stop].unsqueeze(1).long(),+                torch.full(+                    (stop - start, 1), -1.0, dtype=torch.float32, device=hidden.device+                ),+            )+            logits *= scale[start:stop].unsqueeze(1)+            dlogits[start:stop].copy_(logits)+            del logits+        dhidden = torch.mm(dlogits, weight)+        if ctx.grad_view is not None:+            vocab_chunk = FusedCrossEntropy.VOCAB_CHUNK+            for start in range(0, weight.shape[0], vocab_chunk):+                stop = min(start + vocab_chunk, weight.shape[0])+                ctx.grad_view[start:stop].add_(+                    torch.mm(dlogits[:, start:stop].t().contiguous(), hidden)+                )+        del dlogits+        return dhidden, None, None, None, None, None+++class RotaryCache:+    """fp32-derived cos/sin tables cast to bf16, matching Megatron's ordering."""++    def __init__(self, device: torch.device, max_positions: int = 32768) -> None:+        half = contract.KV_CHANNELS // 2+        exponent = torch.arange(0, half, dtype=torch.float32, device=device) / half+        inverse_frequency = 1.0 / (contract.ROTARY_BASE**exponent)+        positions = torch.arange(max_positions, dtype=torch.float32, device=device)+        angles = torch.outer(positions, inverse_frequency)+        self.cos = torch.cat([angles.cos(), angles.cos()], dim=-1).bfloat16()+        self.sin = torch.cat([angles.sin(), angles.sin()], dim=-1).bfloat16()++    def lookup(self, position_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+        flat = position_ids.reshape(-1).long()+        shape = (*position_ids.shape, 1, contract.KV_CHANNELS)+        return (+            self.cos.index_select(0, flat).view(shape),+            self.sin.index_select(0, flat).view(shape),+        )+++class Qwen3Flat:+    """Views over the flat model/gradient buffers plus the forward pass."""++    def __init__(+        self,+        flat_model: torch.Tensor,+        flat_grad: torch.Tensor | None,+        device: torch.device,+    ) -> None:+        self.flat_model = flat_model+        self.flat_grad = flat_grad+        self.device = device+        self.rotary = RotaryCache(device)+        self.graph_root = torch.zeros(+            (), dtype=torch.bfloat16, device=device, requires_grad=flat_grad is not None+        )+        self.weights: dict[str, torch.Tensor] = {}+        self.grads: dict[str, torch.Tensor] = {}+        for spec in contract.PARAM_SPECS:+            window = slice(spec.offset, spec.offset + spec.numel)+            self.weights[spec.name] = flat_model[window].view(spec.shape)+            self.grads[spec.name] = (+                None if flat_grad is None else flat_grad[window].view(spec.shape)+            )++    def _linear(self, x: torch.Tensor, name: str) -> torch.Tensor:+        return FlatLinear.apply(x, self.weights[name], self.grads[name])++    def _norm(self, x: torch.Tensor, name: str) -> torch.Tensor:+        return FlatRMSNorm.apply(x, self.weights[name], self.grads[name])++    def forward_loss(+        self,+        input_ids: torch.Tensor,+        labels: torch.Tensor,+        loss_mask: torch.Tensor,+        position_ids: torch.Tensor,+        *,+        logit_probe: list | None = None,+    ) -> torch.Tensor:+        """Return the summed masked NLL for this micro-batch (fp32 scalar)."""+        batch, sequence = input_ids.shape+        tokens = batch * sequence+        embed = "model.embed_tokens.weight"+        hidden = FlatEmbedding.apply(+            self.weights[embed],+            input_ids.reshape(-1),+            self.grads[embed],+            self.graph_root,+        ).view(batch, sequence, contract.MODEL_WIDTH)+        cos, sin = self.rotary.lookup(position_ids)+        mask = causal_mask(self.device)+        scale = 1.0 / math.sqrt(contract.KV_CHANNELS)++        for layer in range(contract.NUM_LAYERS):+            prefix = f"model.layers.{layer}"+            normed = self._norm(hidden, f"{prefix}.input_layernorm.weight")+            flat_normed = normed.reshape(tokens, contract.MODEL_WIDTH)+            query = self._linear(flat_normed, f"{prefix}.self_attn.q_proj.weight")+            key = self._linear(flat_normed, f"{prefix}.self_attn.k_proj.weight")+            value = self._linear(flat_normed, f"{prefix}.self_attn.v_proj.weight")+            query = self._norm(+                query.view(batch, sequence, contract.NUM_HEADS, contract.KV_CHANNELS),+                f"{prefix}.self_attn.q_norm.weight",+            )+            key = self._norm(+                key.view(batch, sequence, contract.NUM_KV_GROUPS, contract.KV_CHANNELS),+                f"{prefix}.self_attn.k_norm.weight",+            )+            query = torch_npu.npu_rotary_mul(query, cos, sin)+            key = torch_npu.npu_rotary_mul(key, cos, sin)+            attention = torch_npu.npu_fusion_attention(+                query.reshape(batch, sequence, contract.Q_WIDTH),+                key.reshape(batch, sequence, contract.KV_WIDTH),+                value.view(batch, sequence, contract.KV_WIDTH),+                contract.NUM_HEADS,+                "BSH",+                scale=scale,+                keep_prob=1.0,+                atten_mask=mask,+                sparse_mode=3,+                pre_tockens=2048,+                next_tockens=0,+            )[0]+            projected = self._linear(+                attention.reshape(tokens, contract.Q_WIDTH),+                f"{prefix}.self_attn.o_proj.weight",+            )+            hidden = hidden + projected.view(batch, sequence, contract.MODEL_WIDTH)++            normed = self._norm(hidden, f"{prefix}.post_attention_layernorm.weight")+            flat_normed = normed.reshape(tokens, contract.MODEL_WIDTH)+            gate = self._linear(flat_normed, f"{prefix}.mlp.gate_proj.weight")+            up = self._linear(flat_normed, f"{prefix}.mlp.up_proj.weight")+            activated = torch_npu.npu_swiglu(torch.cat([gate, up], dim=-1), dim=-1)+            down = self._linear(activated, f"{prefix}.mlp.down_proj.weight")+            hidden = hidden + down.view(batch, sequence, contract.MODEL_WIDTH)++        hidden = self._norm(hidden, "model.norm.weight")+        return FusedCrossEntropy.apply(+            hidden.reshape(tokens, contract.MODEL_WIDTH),+            self.weights[embed],+            self.grads[embed],+            labels.reshape(-1),+            loss_mask.reshape(-1).float(),+            logit_probe,+        )diff --git a/solution/obtrain/observe.py b/solution/obtrain/observe.pynew file mode 100644index 0000000000000000000000000000000000000000..c54451b9df87204de2a4967aff4b8c1e917de2b1--- /dev/null+++ b/solution/obtrain/observe.py@@ -0,0 +1,269 @@+"""Selector projection capture and observation record emission.++Every projection is read from the tensor that actually carries the value, on the+rank that owns it, and merged through a gloo side channel so the scalars stay+exact fp64 Python floats (an HCCL float reduction would round them). Rank 0 is+the only writer.++Capture points follow the public contract's update order:++* ``logits``            -- fp32 logit produced by the forward pass+* ``gradients``         -- reduced global gradient, before clipping is applied+* ``master_parameters`` -- fp32 master weight after the update commits+* ``model_parameters``  -- bf16 model weight after the update commits+* ``first_moments`` / ``second_moments`` -- AdamW moments after the update+"""++from __future__ import annotations++import json+import struct+from typing import Any++import torch+import torch.distributed as dist++from . import contract++CATEGORIES = (+    "logits",+    "gradients",+    "model_parameters",+    "master_parameters",+    "first_moments",+    "second_moments",+)+FLAT_CATEGORIES = (+    "gradients",+    "model_parameters",+    "master_parameters",+    "first_moments",+    "second_moments",+)+++class SelectorPlan:+    """Selectors for one profile, indexed by update and category."""++    def __init__(self, selector_set: dict[str, Any]) -> None:+        self.selector_set_id = selector_set["selector_set_id"]+        self.by_update: dict[int, dict[str, list[dict[str, Any]]]] = {}+        for category in CATEGORIES:+            for entry in selector_set.get(category, []):+                update = int(entry["update_index"])+                self.by_update.setdefault(update, {name: [] for name in CATEGORIES})+                self.by_update[update][category].append(entry)++    def for_update(self, update_index: int) -> dict[str, list[dict[str, Any]]]:+        return self.by_update.get(update_index, {name: [] for name in CATEGORIES})++    def updates(self) -> list[int]:+        return sorted(self.by_update)+++class ProjectionCollector:+    """Accumulates ``selector_id -> value`` for the update being processed."""++    def __init__(self, plan: SelectorPlan, device: torch.device, world_size: int) -> None:+        self.plan = plan+        self.device = device+        self.world_size = world_size+        self.values: dict[str, float] = {}++    def ordered_ids(self, update_index: int) -> list[str]:+        """Selector ids for one update, in manifest declaration order."""+        wanted = self.plan.for_update(update_index)+        return [+            entry["selector_id"] for category in CATEGORIES for entry in wanted[category]+        ]++    def reset(self) -> None:+        self.values.clear()++    def logit_probe(+        self, update_index: int, profile: Any, micro_step: int, device: torch.device+    ) -> list[tuple[int, int, torch.Tensor]] | None:+        """Probe descriptors for logits landing in this rank's micro-step."""+        wanted = self.plan.for_update(update_index)["logits"]+        if not wanted:+            return None+        probe: list[tuple[int, int, torch.Tensor]] = []+        self._logit_sinks: list[tuple[str, torch.Tensor]] = getattr(self, "_logit_sinks", [])+        for entry in wanted:+            row = int(entry["global_batch_row"])+            if profile.owner_of_row(row) != profile.rank:+                continue+            step, local_row = profile.locate_row(row)+            if step != micro_step:+                continue+            token_index = local_row * profile.sequence_length + int(entry["sequence_index"])+            sink = torch.zeros((), dtype=torch.float32, device=device)+            probe.append((token_index, int(entry["vocab_index"]), sink))+            self._logit_sinks.append((entry["selector_id"], sink))+        return probe or None++    def drain_logit_sinks(self) -> None:+        for selector_id, sink in getattr(self, "_logit_sinks", []):+            self.values[selector_id] = float(sink.item())+        self._logit_sinks = []++    def capture_flat(+        self,+        update_index: int,+        category: str,+        source: torch.Tensor,+        base_offset: int,+    ) -> None:+        """Read selectors for ``category`` out of a flat shard tensor.++        ``source`` covers flat elements ``[base_offset, base_offset + numel)``;+        indices outside that window belong to another rank and are skipped.+        """+        for entry in self.plan.for_update(update_index)[category]:+            index = contract.flat_index(+                entry["canonical_parameter_name"], int(entry["flat_index"])+            )+            local = index - base_offset+            if 0 <= local < source.numel():+                self.values[entry["selector_id"]] = float(source[local].item())++    def merge(self, update_index: int) -> dict[str, float]:+        """Union every rank's captured scalars without perturbing a single bit.++        The scalars are exchanged as raw fp32 bit patterns carried in an int32+        tensor, because an HCCL floating-point reduction would round them and+        the checker compares master/model projections at ulp granularity. Row 0+        of the exchange holds the bits, row 1 a presence flag; duplicated+        coordinates resolve to the lowest-numbered rank that captured them.+        """+        ordered = self.ordered_ids(update_index)+        if not ordered or self.world_size == 1:+            return dict(self.values)+        payload = torch.zeros(2, len(ordered), dtype=torch.int32, device=self.device)+        host = payload.cpu()+        for position, selector_id in enumerate(ordered):+            if selector_id in self.values:+                (bits,) = struct.unpack("<i", struct.pack("<f", self.values[selector_id]))+                host[0, position] = bits+                host[1, position] = 1+        payload.copy_(host)+        gathered = [torch.empty_like(payload) for _ in range(self.world_size)]+        dist.all_gather(gathered, payload)+        merged: dict[str, float] = {}+        for shard in (tensor.cpu() for tensor in gathered):+            for position, selector_id in enumerate(ordered):+                if selector_id in merged or not int(shard[1, position]):+                    continue+                (value,) = struct.unpack("<f", struct.pack("<i", int(shard[0, position])))+                merged[selector_id] = float(value)+        return merged++    def projections(self, update_index: int) -> dict[str, list[dict[str, Any]]]:+        """Projection payload in manifest declaration order."""+        merged = self.merge(update_index)+        payload: dict[str, list[dict[str, Any]]] = {}+        wanted = self.plan.for_update(update_index)+        for category in CATEGORIES:+            rows = []+            for entry in wanted[category]:+                selector_id = entry["selector_id"]+                if selector_id not in merged:+                    raise RuntimeError(f"projection {selector_id} was never captured")+                rows.append({"selector_id": selector_id, "value": merged[selector_id]})+            payload[category] = rows+        return payload+++class TrajectoryWriter:+    """Append-only JSONL writer for committed-update observations."""++    def __init__(self, path: str, profile_id: str, selector_set_id: str) -> None:+        self.path = path+        self.profile_id = profile_id+        self.selector_set_id = selector_set_id+        self._handle = open(path, "w", encoding="utf-8")++    def write(+        self,+        update_index: int,+        loss: float,+        global_grad_norm: float,+        projections: dict[str, list[dict[str, Any]]],+    ) -> None:+        record = {+            "schema_version": 1,+            "kind": "openbuild_training_step_observation",+            "profile_id": self.profile_id,+            "selector_set_id": self.selector_set_id,+            "update_index": update_index,+            "committed": True,+            "loss": loss,+            "global_grad_norm": global_grad_norm,+            "projections": projections,+        }+        self._handle.write(json.dumps(record, sort_keys=True) + "\n")+        self._handle.flush()++    def close(self) -> None:+        self._handle.close()+++def write_check_observation(+    path: str,+    profile_id: str,+    selector_set_id: str,+    loss: float,+    global_grad_norm: float,+    projections: dict[str, list[dict[str, Any]]],+) -> None:+    """Emit the single uncommitted update-31 observation from a fresh process."""+    record = {+        "schema_version": 1,+        "kind": "openbuild_training_fresh_process_observation",+        "profile_id": profile_id,+        "selector_set_id": selector_set_id,+        "source_optimizer_update": 30,+        "update_index": 31,+        "committed": False,+        "loss": loss,+        "global_grad_norm": global_grad_norm,+        "projections": projections,+    }+    with open(path, "w", encoding="utf-8") as handle:+        handle.write(json.dumps(record, sort_keys=True) + "\n")+++def write_result(path: str, profile_id: str) -> None:+    """Emit the candidate result record for a completed profile run."""+    record = {+        "schema_version": 1,+        "kind": "openbuild_training_result",+        "task_id": contract.TASK_ID,+        "profile_id": profile_id,+        "status": "completed",+        "optimizer_updates": 30,+        "consumed_tokens": 983040,+        "logical_device_ids": [0, 1],+        "trajectory_path": "trajectory.jsonl",+        "trajectory_rows": 30,+        "checkpoint_manifest_path": "checkpoint-manifest.json",+        "checkpoint_committed": True,+        "all_ranks_exited": True,+        "delivery_summary": {+            "parallelism": "zero1_data_parallel",+            "world_size": 2,+            "parameters": contract.TOTAL_NUMEL,+            "parameter_dtype": "bfloat16",+            "gradient_accumulation_dtype": "float32",+            "optimizer_state_dtype": "float32",+            "optimizer_state_sharded": True,+            "initialization_spec": "canonical_tensor_counter_v1",+            "attention": "npu_fusion_attention_bsh_causal",+            "activation_recompute": "cross_entropy_logits",+            "gradient_exchange": "chunked_inplace_all_reduce",+            "weight_publication": "all_gather_into_model_buffer",+        },+    }+    with open(path, "w", encoding="utf-8") as handle:+        json.dump(record, handle, sort_keys=True, indent=1)+        handle.write("\n")diff --git a/solution/obtrain/train.py b/solution/obtrain/train.pynew file mode 100644index 0000000000000000000000000000000000000000..6444eba0c2263acfb4396ddf315719c6926ace10--- /dev/null+++ b/solution/obtrain/train.py@@ -0,0 +1,295 @@+"""Two-device Qwen3-4B trainer: launcher, training loop, and fresh probe.++Invoked by ``train.sh``. Without ``OBTRAIN_RANK`` in the environment this module+is the launcher: it starts one child process per assigned logical device and+waits on all of them, so every rank stays attached to the foreground entrypoint+and the entrypoint cannot return before the last rank has exited. With+``OBTRAIN_RANK`` set it is the rank worker.++Both public actions share one code path; ``fresh_next_step_probe`` differs only+in that it restores the committed update-30 state from the checkpoint, consumes+the single update-31 slice, and never writes a checkpoint back.+"""++from __future__ import annotations++import json+import os+import socket+import subprocess+import sys+import time++import torch+import torch.distributed as dist+import torch_npu  # noqa: F401  (registers the NPU backend and fused ops)++from . import checkpoint as ckpt+from . import contract, data, initrng, observe+from .model import Qwen3Flat+from .zero import ShardedAdamW, all_gather_weights, reduce_gradients+++def log(message: str) -> None:+    print(f"[obtrain] {message}", flush=True)+++def device_ids() -> list[int]:+    raw = os.environ.get("OPENBUILD_DEVICE_IDS", "0,1")+    return [int(piece) for piece in raw.split(",") if piece.strip() != ""]+++def free_port() -> int:+    with socket.socket() as probe:+        probe.bind(("127.0.0.1", 0))+        return int(probe.getsockname()[1])+++def launch() -> int:+    """Start one worker per assigned device and wait for every one of them."""+    ranks = device_ids()+    port = free_port()+    started = time.time()+    children: list[subprocess.Popen] = []+    for rank, _ in enumerate(ranks):+        environment = dict(os.environ)+        environment["OBTRAIN_RANK"] = str(rank)+        environment["OBTRAIN_WORLD_SIZE"] = str(len(ranks))+        environment["OBTRAIN_PORT"] = str(port)+        children.append(+            subprocess.Popen([sys.executable, "-B", "-m", "obtrain.train"], env=environment)+        )+    failures = 0+    for rank, child in enumerate(children):+        code = child.wait()+        if code != 0:+            failures += 1+            log(f"rank {rank} exited with status {code}")+    log(f"all ranks exited after {time.time() - started:.1f}s")+    return 1 if failures else 0+++def setup(rank: int, world_size: int) -> torch.device:+    torch.npu.set_device(rank)+    os.environ.setdefault("MASTER_ADDR", "127.0.0.1")+    os.environ["MASTER_PORT"] = os.environ["OBTRAIN_PORT"]+    dist.init_process_group(+        backend="hccl", rank=rank, world_size=world_size, init_method="env://"+    )+    return torch.device(f"npu:{rank}")+++def initialize_state(+    flat_model: torch.Tensor,+    optimizer: ShardedAdamW,+    rank: int,+    world_size: int,+) -> None:+    """Reconstruct the deterministic update-zero state.++    Each rank materializes the canonical fp32 initial value for its own shard+    and derives the bf16 model shard from it, then the shards are gathered so+    every rank holds the whole bf16 model. Because the counter is a pure+    function of (name, element index), this is bit-identical to any other+    partitioning, including a single-device run.+    """+    initrng.fill_model_range(optimizer.master, optimizer.start, optimizer.stop)+    # The canonical update-zero master is the bf16 initial value widened back to+    # fp32, not the exact fp32 quantum, so round-trip through bf16 before the+    # first update. Chunked to keep the transient cast off the memory peak.+    chunk = 1 << 28+    for position in range(0, optimizer.master.numel(), chunk):+        window = optimizer.master[position : position + chunk]+        window.copy_(window.to(torch.bfloat16))+    optimizer.model_shard.copy_(optimizer.master)+    all_gather_weights(flat_model, rank, world_size)+++def global_mask_total(profile: data.ProfileInput, update_index: int, device) -> float:+    local = 0.0+    for batch in profile.micro_batches(update_index):+        local += float(batch.loss_mask.sum().item())+    total = torch.tensor([local], dtype=torch.float32, device=device)+    dist.all_reduce(total, op=dist.ReduceOp.SUM)+    return float(total.item())+++def run_update(+    update_index: int,+    model: Qwen3Flat,+    optimizer: ShardedAdamW,+    profile: data.ProfileInput,+    collector: observe.ProjectionCollector,+    flat_grad: torch.Tensor,+    flat_model: torch.Tensor,+    rank: int,+    world_size: int,+    device: torch.device,+) -> tuple[float, float]:+    """Run one full update and return ``(loss, global_grad_norm)``.++    The masked-mean normalization is global: every micro-step divides its summed+    NLL by the global masked-token count before backward, so summing gradients+    across micro-steps and then across ranks yields exactly the gradient of the+    global masked mean, with no per-rank rescaling.+    """+    flat_grad.zero_()+    collector.reset()+    mask_total = global_mask_total(profile, update_index, device)+    loss_accumulator = torch.zeros((), dtype=torch.float32, device=device)++    for micro_step, batch in enumerate(profile.micro_batches(update_index)):+        probe = collector.logit_probe(update_index, profile, micro_step, device)+        loss_sum = model.forward_loss(+            batch.input_ids,+            batch.labels,+            batch.loss_mask,+            batch.position_ids,+            logit_probe=probe,+        )+        loss_accumulator += loss_sum.detach()+        (loss_sum / mask_total).backward()+        del loss_sum, batch+    collector.drain_logit_sinks()++    dist.all_reduce(loss_accumulator, op=dist.ReduceOp.SUM)+    loss = float(loss_accumulator.item()) / mask_total++    reduce_gradients(flat_grad, rank, world_size)+    sum_of_squares = optimizer.local_sum_of_squares().reshape(1)+    dist.all_reduce(sum_of_squares, op=dist.ReduceOp.SUM)+    global_grad_norm = float(sum_of_squares.sqrt().item())++    # Gradient projections are read from the reduced global gradient before the+    # clipping coefficient is applied, matching the public update order.+    collector.capture_flat(update_index, "gradients", optimizer.grad_shard, optimizer.start)++    clip_scale = min(1.0, contract.CLIP_GRAD / (global_grad_norm + contract.CLIP_EPSILON))+    optimizer.step(update_index, clip_scale)+    all_gather_weights(flat_model, rank, world_size)++    collector.capture_flat(+        update_index, "master_parameters", optimizer.master, optimizer.start+    )+    collector.capture_flat(+        update_index, "model_parameters", optimizer.model_shard, optimizer.start+    )+    collector.capture_flat(update_index, "first_moments", optimizer.exp_avg, optimizer.start)+    collector.capture_flat(+        update_index, "second_moments", optimizer.exp_avg_sq, optimizer.start+    )+    return loss, global_grad_norm+++def worker() -> int:+    rank = int(os.environ["OBTRAIN_RANK"])+    world_size = int(os.environ["OBTRAIN_WORLD_SIZE"])+    action = os.environ.get("OPENBUILD_ACTION", "train")+    profile_id = os.environ["OPENBUILD_PROFILE_ID"]+    input_dir = os.environ["OPENBUILD_INPUT_DIR"]+    output_dir = os.environ["OPENBUILD_OUTPUT_DIR"]+    checkpoint_dir = os.environ["OPENBUILD_CHECKPOINT_DIR"]++    device = setup(rank, world_size)+    started = time.time()++    flat_model = torch.empty(contract.TOTAL_NUMEL, dtype=torch.bfloat16, device=device)+    flat_grad = torch.zeros(contract.TOTAL_NUMEL, dtype=torch.float32, device=device)+    optimizer = ShardedAdamW(flat_model, flat_grad, rank, world_size, device)+    model = Qwen3Flat(flat_model, flat_grad, device)+    profile = data.ProfileInput(input_dir, profile_id, rank, world_size, device)+    plan = observe.SelectorPlan(profile.selector_set)+    collector = observe.ProjectionCollector(plan, device, world_size)++    if action == "fresh_next_step_probe":+        ckpt.load(checkpoint_dir, rank, flat_model, optimizer)+        log(f"rank {rank} restored committed update 30 in {time.time() - started:.1f}s")+        update_index = contract.FRESH_PROBE_UPDATE+        loss, norm = run_update(+            update_index,+            model,+            optimizer,+            profile,+            collector,+            flat_grad,+            flat_model,+            rank,+            world_size,+            device,+        )+        projections = collector.projections(update_index)+        if rank == 0:+            observe.write_check_observation(+                os.path.join(output_dir, "check-observations.jsonl"),+                profile_id,+                profile.selector_set_id,+                loss,+                norm,+                projections,+            )+            log(f"probe update 31 loss={loss:.12f} norm={norm:.12f} (not committed)")+        dist.barrier()+        dist.destroy_process_group()+        return 0++    initialize_state(flat_model, optimizer, rank, world_size)+    log(f"rank {rank} reconstructed update-zero state in {time.time() - started:.1f}s")++    writer = None+    if rank == 0:+        writer = observe.TrajectoryWriter(+            os.path.join(output_dir, "trajectory.jsonl"), profile_id, profile.selector_set_id+        )+    for update_index in range(1, contract.TRAINING_UPDATES + 1):+        mark = time.time()+        loss, norm = run_update(+            update_index,+            model,+            optimizer,+            profile,+            collector,+            flat_grad,+            flat_model,+            rank,+            world_size,+            device,+        )+        projections = collector.projections(update_index)+        if writer is not None:+            writer.write(update_index, loss, norm, projections)+            log(+                f"update {update_index:2d} loss={loss:.10f} norm={norm:.10f} "+                f"lr={contract.learning_rate_for(update_index):.6e} "+                f"{time.time() - mark:.2f}s"+            )+    if writer is not None:+        writer.close()++    ckpt.save(+        checkpoint_dir,+        output_dir,+        rank,+        world_size,+        profile_id,+        flat_model,+        optimizer,+        contract.TRAINING_UPDATES,+    )+    dist.barrier()+    if rank == 0:+        observe.write_result(os.path.join(output_dir, "result.json"), profile_id)+        log(f"committed checkpoint and result after {time.time() - started:.1f}s")+    dist.destroy_process_group()+    return 0+++def main() -> int:+    if os.environ.get("OPENBUILD_ACTION") == "bootstrap":+        return 0+    if "OBTRAIN_RANK" in os.environ:+        return worker()+    return launch()+++if __name__ == "__main__":+    raise SystemExit(main())diff --git a/solution/obtrain/zero.py b/solution/obtrain/zero.pynew file mode 100644index 0000000000000000000000000000000000000000..04b27688657e2ca4443c8aef5e8b36b042342bc9--- /dev/null+++ b/solution/obtrain/zero.py@@ -0,0 +1,159 @@+"""ZeRO-1 sharded AdamW over the flat parameter vector.++Rank ``r`` owns ``[shard_start, shard_end)`` of the canonical flat vector and+holds fp32 master weights plus the two AdamW moments for exactly that window.+Because :mod:`contract` orders every weight-decay parameter before every+no-decay parameter, each shard intersects the decay region in at most one+contiguous run, so the whole update is a handful of fused fp32 tensor ops.++Gradients are exchanged with an in-place chunked halves swap rather than+``reduce_scatter``, which would need an 8 GiB output temporary; the updated+bf16 weights are gathered directly into a view of the live model buffer.+"""++from __future__ import annotations++import torch+import torch.distributed as dist++from . import contract++# Elements per in-place all_reduce call; bounds HCCL's internal workspace.+REDUCE_CHUNK = 1 << 28+# Elements per AdamW window. Two fp32 scratch buffers of this width are the+# only allocations the optimizer step makes (268 MiB each).+ADAM_CHUNK = 1 << 26+++def shard_bounds(rank: int, world_size: int) -> tuple[int, int]:+    """Element-aligned even split of the flat vector (last shard absorbs slack)."""+    per_rank = (contract.TOTAL_NUMEL + world_size - 1) // world_size+    start = rank * per_rank+    stop = min(start + per_rank, contract.TOTAL_NUMEL)+    return start, max(start, stop)+++def reduce_gradients(flat_grad: torch.Tensor, rank: int, world_size: int) -> None:+    """Sum-reduce ``flat_grad`` in place so every shard holds the global sum.++    ZeRO-1 strictly only needs each rank's own shard reduced, which a+    ``reduce_scatter`` would deliver at half the traffic -- but it would also+    need an 8 GiB fp32 output tensor, and that does not fit beside the model,+    the gradient buffer, and the three fp32 optimizer shards. An in-place+    ``all_reduce`` needs no output buffer at all, so the extra bandwidth buys+    back roughly 8 GiB of HBM that goes to activations instead.++    The reduction is issued in chunks to bound HCCL's internal workspace; the+    result is identical to a single call because summation is applied+    elementwise.+    """+    if world_size == 1:+        return+    total = flat_grad.numel()+    for position in range(0, total, REDUCE_CHUNK):+        window = flat_grad[position : min(position + REDUCE_CHUNK, total)]+        dist.all_reduce(window, op=dist.ReduceOp.SUM)+++def all_gather_weights(flat_model: torch.Tensor, rank: int, world_size: int) -> None:+    """Publish every rank's freshly updated bf16 shard into ``flat_model``."""+    if world_size == 1:+        return+    shards = [+        flat_model[start:stop]+        for start, stop in (shard_bounds(index, world_size) for index in range(world_size))+    ]+    width = max(shard.numel() for shard in shards)+    if all(shard.numel() == width for shard in shards):+        dist.all_gather(list(shards), shards[rank])+        return+    for index, shard in enumerate(shards):+        dist.broadcast(shard, src=index)+++class ShardedAdamW:+    """Decoupled-weight-decay AdamW on one fp32 shard of the flat vector."""++    def __init__(+        self,+        flat_model: torch.Tensor,+        flat_grad: torch.Tensor,+        rank: int,+        world_size: int,+        device: torch.device,+    ) -> None:+        self.flat_model = flat_model+        self.flat_grad = flat_grad+        self.rank = rank+        self.world_size = world_size+        self.device = device+        self.start, self.stop = shard_bounds(rank, world_size)+        width = self.stop - self.start+        self.master = torch.empty(width, dtype=torch.float32, device=device)+        self.exp_avg = torch.zeros(width, dtype=torch.float32, device=device)+        self.exp_avg_sq = torch.zeros(width, dtype=torch.float32, device=device)+        # Weight-decay parameters occupy [0, DECAY_NUMEL); intersect once.+        self.decay_split = min(max(contract.DECAY_NUMEL - self.start, 0), width)+        scratch = min(ADAM_CHUNK, width)+        self.scratch_a = torch.empty(scratch, dtype=torch.float32, device=device)+        self.scratch_b = torch.empty(scratch, dtype=torch.float32, device=device)++    @property+    def grad_shard(self) -> torch.Tensor:+        return self.flat_grad[self.start : self.stop]++    @property+    def model_shard(self) -> torch.Tensor:+        return self.flat_model[self.start : self.stop]++    def local_sum_of_squares(self) -> torch.Tensor:+        shard = self.grad_shard+        return torch.linalg.vector_norm(shard, ord=2, dtype=torch.float32).pow(2)++    def step(self, update_index: int, clip_scale: float) -> None:+        """Apply one committed AdamW update to the local shard, in place.++        Every fp32 shard here is 7.49 GiB, so a single full-width temporary+        would not fit beside the model and the gradient buffer. The moment+        recurrences are therefore run as in-place fused ops with the clipping+        coefficient folded into their scalar coefficients -- clipping the+        gradient elementwise first would need a full-width copy -- and the+        parameter update walks the shard in windows through two small reusable+        scratch buffers.++        ``clip_scale`` is the public global clipping coefficient. Folding it in+        is exact for the first moment and, because it is squared alongside the+        gradient, exact for the second moment too, so this matches the public+        order: clip, first moment, second moment, then decoupled weight decay+        applied to the pre-update master value.+        """+        learning_rate = contract.learning_rate_for(update_index)+        beta1, beta2 = contract.BETA1, contract.BETA2+        bias1 = 1.0 - beta1**update_index+        bias2 = 1.0 - beta2**update_index+        gradient = self.grad_shard++        self.exp_avg.mul_(beta1).add_(gradient, alpha=(1.0 - beta1) * clip_scale)+        self.exp_avg_sq.mul_(beta2).addcmul_(+            gradient, gradient, value=(1.0 - beta2) * clip_scale * clip_scale+        )++        width = self.master.numel()+        for position in range(0, width, ADAM_CHUNK):+            span = min(ADAM_CHUNK, width - position)+            stop = position + span+            direction = self.scratch_a[:span]+            denominator = self.scratch_b[:span]+            master = self.master[position:stop]++            direction.copy_(self.exp_avg[position:stop]).div_(bias1)+            denominator.copy_(self.exp_avg_sq[position:stop]).div_(bias2)+            denominator.sqrt_().add_(contract.ADAM_EPS)+            direction.div_(denominator)++            decayed = min(max(self.decay_split - position, 0), span)+            if decayed:+                direction[:decayed].add_(master[:decayed], alpha=contract.WEIGHT_DECAY)+            master.add_(direction, alpha=-learning_rate)++        self.model_shard.copy_(self.master)diff --git a/solution/train.sh b/solution/train.shnew file mode 100755index 0000000000000000000000000000000000000000..e9df673749dd3326dc13847cf89896c8a9aeb524--- /dev/null+++ b/solution/train.sh@@ -0,0 +1,16 @@+#!/usr/bin/env bash+# Foreground entrypoint for both public actions. The launcher process stays in+# the foreground and waits on every rank, so this script cannot return before+# all ranks have exited.+set -euo pipefail++here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+python_bin="$(command -v python3 || command -v python)"++export PYTHONPATH="${here}${PYTHONPATH:+:${PYTHONPATH}}"+export PYTHONUNBUFFERED=1+# Keep allocator growth predictable across the long-lived flat buffers.+export PYTORCH_NPU_ALLOC_CONF="${PYTORCH_NPU_ALLOC_CONF:-expandable_segments:True}"+export HCCL_CONNECT_TIMEOUT="${HCCL_CONNECT_TIMEOUT:-1800}"++exec "${python_bin}" -B -m obtrain.train