Kimi K3 · Training

T06 · Training build

Valid

OpenBuild Qwen3-4B training 2dev · Open Build

2.02×PERFORMANCE RATIO
70TOOL 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 agentKimi K3 · 70 visible calls

InspectEditValidateExecuteBuildProfileRollbackOther
39Inspect
18Edit
7Validate
4Execute
2Other

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 timeline52 groups · 70 calls

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

Main agent

  1. Inspect · Source & workspace

    Requested workspace inspection related to source & workspace.

    1 call · #0001–#0001

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

    Requested file and log inspection related to task requirements.

    2 calls · #0002–#0003

    Read <path>
  3. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0004–#0004

    Read <path>
  4. Inspect · Task requirements

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

    2 calls · #0005–#0006

    ls -l -a <path> <path> <path> <path> <path>Read <path>
  5. Inspect · Source & workspace

    Requested file and log inspection related to source & workspace.

    1 call · #0007–#0007

    Read <path>
  6. Validate · Benchmark & validation setup

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

    1 call · #0008–#0008

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

    Requested file and log inspection related to source & workspace.

    1 call · #0009–#0009

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

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

    1 call · #0010–#0010

    which <val> <val>python3 --versionpython3 -c <script> <n> >& <path>tail -n <n>npu-smi info <n> >& <path>head -n <n>
  9. Inspect · Source & workspace

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

    7 calls · #0011–#0017

    wc -l <path>head -n <n> <path>python3 -c <script>echo <flag>python3 -c <script> <n> >& <path>tail -n <n>
    3 more command sketches
    Read <path>cat <path>Update task list <tasks>
  10. Other · Precision & numerical checks

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

    1 call · #0018–#0018

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

    Requested file and log inspection related to source & workspace.

    1 call · #0019–#0019

    Read <path>
  12. Inspect · Parallelism & communication

    Requested script or workload execution, file and log inspection and dependency and build commands related to parallelism & communication.

    1 call · #0020–#0020

    python3 -c <script> <n> > <path>tail -n <n>pip list <n> > <path>grep -E -i <val>echo <flag>env
    4 more command sketches
    head -n <n>free -g<command> <args>df -h <path>
  13. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0021–#0021

    Write <path>
  14. Inspect · Source & workspace

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

    1 call · #0022–#0022

    cd <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  15. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0023–#0023

    Write <path>
  16. Inspect · Source & workspace

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

    1 call · #0024–#0024

    cd <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  17. Edit · Parallelism & communication

    Requested code edits related to parallelism & communication.

    1 call · #0025–#0025

    Write <path>
  18. Inspect · Parallelism & communication

    Requested workspace file updates, environment setup or inspection and source searches related to parallelism & communication.

    1 call · #0026–#0026

    cd <path>rm -f <val><command> <args>env <vars> timeout <n> <val> <path> > <path> <n> >& <path>echo <val>grep -v <val> <val>
    1 more command sketches
    tail -n <n>
  19. Inspect · Source & workspace

    1 tool error

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

    3 calls · #0027–#0029

    diff <path> <path>head -n <n>grep -n <val> <path>headdiff < <path> -n <val> <path> < <path> -n <val> <path>Update task list <tasks>
  20. Edit · Task requirements

    Requested code edits related to task requirements.

    1 call · #0030–#0030

    Write <path>
  21. Edit · Source & workspace

    Requested code edits related to source & workspace.

    4 calls · #0031–#0034

    Write <path>
  22. Inspect · Source & workspace

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

    1 call · #0035–#0035

    cd <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  23. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0036–#0036

    Edit <path>
  24. Inspect · Source & workspace

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

    2 calls · #0037–#0038

    cd <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>envgrep -E <val>
    4 more command sketches
    echo <flag>ls <path>cat <path> <n> > <path>head -n <n>
  25. Validate · Benchmark & validation setup

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

    1 call · #0039–#0039

    chmod <val> <path> <path>ls -l -a <path>bash <script> > <path> <n> >& <path>echo <val>tail -c <n> <path>echo
  26. Inspect · Source & workspace

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

    2 calls · #0040–#0041

    cd <path>timeout <n> <val> <path> --output <path> <n> >& <path>tail -n <n>Update task list <tasks>
  27. Execute · Checkpoints & weight state

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

    1 call · #0042–#0042

    mkdir -p <path> <path> <path>cd <path>env <vars> timeout <n> <path> > <path> <n> >& <path>echo <val>grep -v <val> <path>tail -n <n>
  28. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0043–#0043

    Write <path>
  29. Inspect · Source & workspace

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

    1 call · #0044–#0044

    cd <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  30. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0045–#0045

    Edit <path>
  31. Inspect · Source & workspace

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

    1 call · #0046–#0046

    cd <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  32. Edit · Source & workspace

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

    2 calls · #0047–#0048

    Edit <path>cd <path>sed -i <path> <path>python3 - <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>
    1 more command sketches
    tail -n <n>
  33. Execute · Checkpoints & weight state

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

    1 call · #0049–#0049

    rm -rf <path> <path> <path>mkdir -p <path> <path> <path>cd <path>env <vars> timeout <n> <path> > <path> <n> >& <path>echo <val>grep -E <val> <path>
    2 more command sketches
    head -n <n>cut <flag>
  34. Inspect · Precision & numerical checks

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

    1 call · #0050–#0050

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

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

    1 call · #0051–#0051

    rm -rf <path> <path> <path>cd <path>bash <script> > <path> <n> >& <path>echo <val>
  36. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0052–#0052

    Write <path>
  37. Inspect · Source & workspace

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

    1 call · #0053–#0053

    ls -l -a <path> <n> > <path>grep -i <val>find <path> -maxdepth <n> -name <val> <flag> <args>headecho <flag><command> <args>
    2 more command sketches
    grep -E <val> <val>tail -n <n>
  38. Validate · Benchmark & validation setup

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

    1 call · #0054–#0054

    sleep <n>env <vars>grep -E <val> <val>tail -n <n>ls <path> <n> > <path>
  39. Validate · Checkpoints & weight state

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

    1 call · #0055–#0055

    sleep <n>env <vars><command> <args>grep -E <val> <val>tail -n <n>ls <val> <n> > <path>
    4 more command sketches
    echo <flag>find <val> -name <val>xargs <flag> <args>grep -v <val>
  40. Inspect · Checkpoints & weight state

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

    1 call · #0056–#0056

    cat <path>echo <val>python3 - <script>
  41. Validate · Benchmark & validation setup

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

    1 call · #0057–#0057

    env <vars>grep -v <val> <path>grep -v -E <val>tail -n <n>
  42. Edit · Source & workspace

    Requested code edits related to source & workspace.

    2 calls · #0058–#0059

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

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

    1 call · #0060–#0060

    cd <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  44. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0061–#0061

    Edit <path>
  45. Inspect · Source & workspace

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

    1 call · #0062–#0062

    cd <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>
  46. Other · Source & workspace

    Requested tool activity related to source & workspace.

    1 call · #0063–#0063

    date -udate -u <val>echo <val>
  47. Edit · Source & workspace

    Requested code edits related to source & workspace.

    1 call · #0064–#0064

    Write <path>
  48. Inspect · Source & workspace

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

    1 call · #0065–#0065

    rm -rf <path> <path> <path>mkdir -p <path> <path> <path>cd <path>timeout <n> <val> <path> <path> <val> <n> >& <path>grep -v -E <val>tail -n <n>
    2 more command sketches
    ls -l -a <path>head -n <n>
  49. Execute · Checkpoints & weight state

    Requested environment setup or inspection, workspace inspection and script or workload execution related to checkpoints & weight state.

    2 calls · #0066–#0067

    cd <path>env <vars> timeout <n> <path> > <path> <n> >& <path>echo <val>ls -l -a <path> <n> > <path>python3 -c <script> <n> >& <path>tail -n <n>
    4 more command sketches
    rm -rf <path> <path> <path>mkdir -p <path> <path> <path>grep -E <val> <path>python3 - <script>
  50. Validate · Device memory

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

    1 call · #0068–#0068

    ls -l -a <path>echo <flag>bash <script> <n> > <path>python3 -c <script>ps <val>grep -E <path>
    5 more command sketches
    grep -v <val>wc -lnpu-smi infogrep -E <val>head -n <n>
  51. Inspect · Task requirements

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

    1 call · #0069–#0069

    cd <path>git status --shortheadecho <flag>du <flag> <args>head -c <n> <path>
  52. Inspect · Source & workspace

    Requested task coordination related to source & workspace.

    1 call · #0070–#0070

    Update task list <tasks>

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

Base commit: d1281fd46aa0575309be1eb6e0fcdc79e4be9670

diff --git a/solution/bootstrap.sh b/solution/bootstrap.shnew file mode 100755index 0000000000000000000000000000000000000000..d3f939199757ab99974668b6e0bd0fa2fdffa4c0--- /dev/null+++ b/solution/bootstrap.sh@@ -0,0 +1,7 @@+#!/usr/bin/env bash+# OpenBuild offline bootstrap. The base runtime already provides Python,+# PyTorch and torch_npu; this solution is pure Python and needs no additional+# packages, so bootstrap is intentionally a no-op. It is idempotent and never+# modifies the base environment.+set -euo pipefail+exit 0diff --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/train.sh b/solution/train.shnew file mode 100755index 0000000000000000000000000000000000000000..7e81790cff90f575360f627555488d1a11e96cd2--- /dev/null+++ b/solution/train.sh@@ -0,0 +1,34 @@+#!/usr/bin/env bash+# OpenBuild training entrypoint. Launches two foreground pipeline ranks+# (one per Ascend 910B logical device) and waits for both to exit.+set -uo pipefail++HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"++export PYTORCH_NPU_ALLOC_CONF="${PYTORCH_NPU_ALLOC_CONF:-expandable_segments:True}"+export PYTHONDONTWRITEBYTECODE=1++STORE_DIR="${TMPDIR:-/tmp}"+STORE="${STORE_DIR%/}/openbuild-hccl-store-$$"+rm -f "${STORE}" 2>/dev/null || true+export OPENBUILD_HCCL_STORE="${STORE}"++RANK=0 python3 -B "${HERE}/trainer.py" &+P0=$!+RANK=1 python3 -B "${HERE}/trainer.py" &+P1=$!++rc=0+wait "${P0}" || rc=$?+wait "${P1}" || rc=$?++if [ "${rc}" -ne 0 ]; then+  kill -TERM "${P0}" "${P1}" 2>/dev/null || true+  sleep 2+  kill -KILL "${P0}" "${P1}" 2>/dev/null || true+  wait "${P0}" 2>/dev/null || true+  wait "${P1}" 2>/dev/null || true+fi++rm -f "${STORE}" 2>/dev/null || true+exit "${rc}"diff --git a/solution/trainer.py b/solution/trainer.pynew file mode 100644index 0000000000000000000000000000000000000000..a4d5aaeabf9398832206ccc249e1afb609b352e5--- /dev/null+++ b/solution/trainer.py@@ -0,0 +1,887 @@+#!/usr/bin/env python3+"""OpenBuild Qwen3-4B-Base two-device training system (Ascend 910B, HCCL).++Two-stage pipeline parallelism over logical devices 0 and 1:+  rank 0: embedding + layers 0..19+  rank 1: layers 20..35 + final norm + fused chunked cross-entropy head+The output projection is tied to the input embedding; its gradient is the+sum of both ranks' contributions (one fp32 all-reduce per update).++Numerical contract (frozen): bf16 model storage, fp32 master parameters and+AdamW moments, fp32 gradient accumulation, fp32 softmax/loss, global L2+gradient clipping at 1.0, decoupled weight decay on rank>=2 parameters,+cosine LR 1.25e-6 -> 1.25e-7 over 30 updates.+"""+from __future__ import annotations++import json+import math+import os+import sys+import time+import traceback+from concurrent.futures import ThreadPoolExecutor+from datetime import timedelta+from pathlib import Path++import numpy as np+import torch+import torch.distributed as dist+import torch.nn.functional as F++try:+    import torch_npu  # noqa: F401  (registers the NPU backend)+except Exception:  # pragma: no cover - reported later when NPU is touched+    pass++from torch.utils.checkpoint import checkpoint++# ---------------- frozen model contract ----------------+NUM_LAYERS = 36+HIDDEN = 2560+FFN = 9728+NUM_HEADS = 32+NUM_KV = 8+HEAD_DIM = 128+VOCAB = 151936+ROPE_BASE = 1000000.0+NORM_EPS = 1e-6+ATTN_OUT = NUM_HEADS * HEAD_DIM  # 4096+KV_OUT = NUM_KV * HEAD_DIM  # 1024+STAGE_LAYERS = {0: range(0, 20), 1: range(20, 36)}+ROT_HALF = HEAD_DIM // 2++# ---------------- frozen optimizer contract ----------------+LR = 0.00000125+MIN_LR = 0.000000125+DECAY_UPDATES = 30+BETA1 = 0.9+BETA2 = 0.95+ADAM_EPS = 0.00000001+WEIGHT_DECAY = 0.1+CLIP_NORM = 1.0+CLIP_EPS = 0.000001+TOTAL_UPDATES = 30+FRESH_UPDATE = 31++# ---------------- deterministic init contract ----------------+MASK64 = (1 << 64) - 1+INIT_SEED = 0x51454E334F50454E+INIT_C = 0x9E3779B97F4A7C15+INIT_K1 = 0xBF58476D1CE4E5B9+INIT_K2 = 0x94D049BB133111EB++CATEGORIES = (+    "logits",+    "gradients",+    "model_parameters",+    "master_parameters",+    "first_moments",+    "second_moments",+)+EMBED_NAME = "model.embed_tokens.weight"+FINAL_NORM = "model.norm.weight"++TASK_ID = "openbuild_training_qwen3_4b_2dev_v1"+++def s64(u: int) -> int:+    u &= MASK64+    return u - (1 << 64) if u >= (1 << 63) else u+++def fnv1a64(name: str) -> int:+    h = 0xCBF29CE484222325+    for b in name.encode("utf-8"):+        h ^= b+        h = (h * 0x100000001B3) & MASK64+    return h+++def log0(rank: int, msg: str) -> None:+    if rank == 0:+        print(f"[rank0 {time.strftime('%H:%M:%S')}] {msg}", flush=True)+++# ---------------- parameter layout ----------------+def stage_param_specs(rank: int):+    """Ordered (name, shape, decay) list of this rank's canonical tensors."""+    specs = []+    if rank == 0:+        specs.append((EMBED_NAME, (VOCAB, HIDDEN), True))+    for layer in STAGE_LAYERS[rank]:+        p = f"model.layers.{layer}."+        specs.append((p + "input_layernorm.weight", (HIDDEN,), False))+        specs.append((p + "self_attn.q_proj.weight", (ATTN_OUT, HIDDEN), True))+        specs.append((p + "self_attn.k_proj.weight", (KV_OUT, HIDDEN), True))+        specs.append((p + "self_attn.v_proj.weight", (KV_OUT, HIDDEN), True))+        specs.append((p + "self_attn.q_norm.weight", (HEAD_DIM,), False))+        specs.append((p + "self_attn.k_norm.weight", (HEAD_DIM,), False))+        specs.append((p + "self_attn.o_proj.weight", (HIDDEN, ATTN_OUT), True))+        specs.append((p + "post_attention_layernorm.weight", (HIDDEN,), False))+        specs.append((p + "mlp.gate_proj.weight", (FFN, HIDDEN), True))+        specs.append((p + "mlp.up_proj.weight", (FFN, HIDDEN), True))+        specs.append((p + "mlp.down_proj.weight", (HIDDEN, FFN), True))+    if rank == 1:+        specs.append((FINAL_NORM, (HIDDEN,), False))+    return specs+++def owner_rank(name: str) -> int:+    if name == EMBED_NAME:+        return 0+    if name == FINAL_NORM:+        return 1+    # model.layers.N....+    layer = int(name.split(".")[2])+    return 0 if layer < 20 else 1+++# ---------------- deterministic parameter initialization ----------------+def generate_param_flat(name: str, numel: int, device, chunk: int = 1 << 24):+    """canonical_tensor_counter_v1: stateless per-element values, bf16 out."""+    base = torch.tensor(s64(INIT_SEED ^ fnv1a64(name)), dtype=torch.int64, device=device)+    c_s = s64(INIT_C)+    k1_s = s64(INIT_K1)+    k2_s = s64(INIT_K2)+    m30 = (1 << 34) - 1+    m27 = (1 << 37) - 1+    m31 = (1 << 33) - 1+    out = torch.empty(numel, dtype=torch.bfloat16, device=device)+    for off in range(0, numel, chunk):+        n = min(chunk, numel - off)+        z = torch.arange(off, off + n, dtype=torch.int64, device=device)+        z = z * c_s+        z = z ^ base+        z = z + c_s+        z = (z ^ ((z >> 30) & m30)) * k1_s+        z = (z ^ ((z >> 27) & m27)) * k2_s+        u = z ^ ((z >> 31) & m31)+        q = ((u >> 52) & 0xFFF) - 2048+        x = q.to(torch.float32) * (2.0 ** -16)+        out[off:off + n] = x.to(torch.bfloat16)+    return out+++# ---------------- model forward ----------------+def rmsnorm(x, w):+    xf = x.float()+    var = xf.pow(2).mean(-1, keepdim=True)+    xf = xf * torch.rsqrt(var + NORM_EPS)+    return xf.to(torch.bfloat16) * w+++def rotate_half(x):+    x1 = x[..., :ROT_HALF]+    x2 = x[..., ROT_HALF:]+    return torch.cat((-x2, x1), dim=-1)+++def rope_tables(position_ids, inv_freq):+    # position_ids [B,S] int64 -> cos,sin [B,1,S,HEAD_DIM] bf16+    freqs = position_ids.float().unsqueeze(-1) * inv_freq  # [B,S,64] fp32+    emb = torch.cat((freqs, freqs), dim=-1)+    return emb.cos().to(torch.bfloat16).unsqueeze(1), emb.sin().to(torch.bfloat16).unsqueeze(1)+++def attention(x, prm, layer_prefix, cos, sin):+    B, S, _ = x.shape+    q = F.linear(x, prm[layer_prefix + "self_attn.q_proj.weight"]).view(B, S, NUM_HEADS, HEAD_DIM)+    k = F.linear(x, prm[layer_prefix + "self_attn.k_proj.weight"]).view(B, S, NUM_KV, HEAD_DIM)+    v = F.linear(x, prm[layer_prefix + "self_attn.v_proj.weight"]).view(B, S, NUM_KV, HEAD_DIM)+    q = rmsnorm(q, prm[layer_prefix + "self_attn.q_norm.weight"])+    k = rmsnorm(k, prm[layer_prefix + "self_attn.k_norm.weight"])+    q = q.transpose(1, 2)+    k = k.transpose(1, 2)+    v = v.transpose(1, 2)+    q = q * cos + rotate_half(q) * sin+    k = k * cos + rotate_half(k) * sin+    o = F.scaled_dot_product_attention(q, k, v, is_causal=True, enable_gqa=True)+    o = o.transpose(1, 2).reshape(B, S, ATTN_OUT)+    return F.linear(o, prm[layer_prefix + "self_attn.o_proj.weight"])+++def layer_forward(x, prm, layer_prefix, cos, sin):+    h = rmsnorm(x, prm[layer_prefix + "input_layernorm.weight"])+    x = x + attention(h, prm, layer_prefix, cos, sin)+    h = rmsnorm(x, prm[layer_prefix + "post_attention_layernorm.weight"])+    gate = F.linear(h, prm[layer_prefix + "mlp.gate_proj.weight"])+    up = F.linear(h, prm[layer_prefix + "mlp.up_proj.weight"])+    x = x + F.linear(F.silu(gate) * up, prm[layer_prefix + "mlp.down_proj.weight"])+    return x+++class FusedCrossEntropy(torch.autograd.Function):+    """Chunked linear+softmax cross entropy over the tied embedding.++    forward returns the masked NLL sum (fp32 scalar); backward computes+    gradients wrt hidden states and the embedding weight without+    materializing full-vocabulary fp32 logits for the whole microbatch.+    """++    CHUNK = 2048++    @staticmethod+    def forward(ctx, h, w, labels, mask, taps, tap_out):+        # h [N,D] bf16, w [V,D] bf16, labels [N] int64, mask [N] fp32+        N = h.shape[0]+        C = min(FusedCrossEntropy.CHUNK, N)+        total = torch.zeros((), dtype=torch.float32, device=h.device)+        for i in range(0, N, C):+            hc = h[i:i + C]+            lg = F.linear(hc, w).float()  # [C,V] fp32+            if taps:+                n = lg.shape[0]+                for (pos, vocab, slot) in taps:+                    if i <= pos < i + n:+                        tap_out[slot] = float(lg[pos - i, vocab].item())+            lse = torch.logsumexp(lg, dim=-1)+            nll = lse - lg.gather(1, labels[i:i + C].unsqueeze(1)).squeeze(1)+            total += (nll * mask[i:i + C]).sum()+        ctx.save_for_backward(h, w, labels, mask)+        return total++    @staticmethod+    def backward(ctx, gout):+        h, w, labels, mask = ctx.saved_tensors+        N = h.shape[0]+        C = min(FusedCrossEntropy.CHUNK, N)+        go = float(gout)+        dh = torch.empty_like(h)+        dw = torch.zeros_like(w, dtype=torch.float32)+        for i in range(0, N, C):+            hc = h[i:i + C]+            lg = F.linear(hc, w).float()+            p = torch.softmax(lg, dim=-1)+            n = p.shape[0]+            p.scatter_add_(1, labels[i:i + C].unsqueeze(1),+                           torch.full((n, 1), -1.0, dtype=torch.float32, device=p.device))+            p *= mask[i:i + C].unsqueeze(1)+            p *= go+            d = p.to(torch.bfloat16)+            dh[i:i + C] = torch.mm(d, w)+            dw += torch.mm(d.t(), hc).float()+        return dh, dw.to(torch.bfloat16), None, None, None, None+++# ---------------- trainer ----------------+class Trainer:+    def __init__(self, rank: int, profile: dict, input_dir: Path, device):+        self.rank = rank+        self.profile = profile+        self.device = device+        self.profile_id = profile["profile_id"]+        self.G = int(profile["global_batch_size"])+        self.S = int(profile["sequence_length"])+        self.selector_set = profile["selector_set"]+        self.selector_set_id = self.selector_set["selector_set_id"]++        # data (kept on host; tiny)+        tensors = profile["tensors"]+        base = input_dir+        def load_tensor(key, np_dtype, shape):+            descriptor = tensors[key]+            arr = np.fromfile(base / descriptor["path"], dtype=np_dtype)+            if arr.size != int(np.prod(shape)):+                raise ValueError(f"input tensor {key} has wrong size")+            return arr.reshape(shape)+        dense = [31, self.G, self.S]+        self.input_ids = load_tensor("input_ids", "<i4", dense)+        self.labels = load_tensor("labels", "<i4", dense)+        self.loss_mask = load_tensor("loss_mask", np.uint8, dense)+        self.position_ids = load_tensor("position_ids", "<i4", dense)++        # microbatching+        self.num_micro = min(16, self.G)+        self.rows_per_micro = self.G // self.num_micro+        if self.rows_per_micro * self.num_micro != self.G:+            raise ValueError("global batch not divisible into microbatches")+        self.micro_shape = (self.rows_per_micro, self.S)++        # rope inv_freq (fp32, device)+        self.inv_freq = 1.0 / (ROPE_BASE ** (+            torch.arange(0, HEAD_DIM, 2, dtype=torch.float32, device=device) / HEAD_DIM))++        # selector bookkeeping+        self._build_selectors()++        # parameters+        self.specs = stage_param_specs(rank)+        self.params: dict[str, torch.Tensor] = {}       # bf16, autograd leaves+        self.masters: dict[str, torch.Tensor] = {}      # fp32+        self.mom1: dict[str, torch.Tensor] = {}+        self.mom2: dict[str, torch.Tensor] = {}+        self.grads: dict[str, torch.Tensor] = {}        # fp32 accumulation+        self.decay_flags: dict[str, bool] = {}+        self.embed_replica = None  # rank1's tied lm_head weight (bf16 leaf)+        if rank == 1:+            # tied output projection replica (canonical owner: rank 0)+            self.embed_replica = torch.empty((VOCAB, HIDDEN), dtype=torch.bfloat16,+                                             device=device, requires_grad=True)+        for (name, shape, decay) in self.specs:+            t = torch.empty(shape, dtype=torch.bfloat16, device=device)+            t.requires_grad_(True)+            self.params[name] = t+            self.masters[name] = torch.empty(shape, dtype=torch.float32, device=device)+            self.mom1[name] = torch.zeros(shape, dtype=torch.float32, device=device)+            self.mom2[name] = torch.zeros(shape, dtype=torch.float32, device=device)+            self.grads[name] = torch.zeros(shape, dtype=torch.float32, device=device)+            self.decay_flags[name] = decay++        self.owned_param_list = [self.params[n] for (n, _, _) in self.specs]+        self.owned_acc_list = [self.grads[n] for (n, _, _) in self.specs]++    # ---------------- selector planning ----------------+    def _build_selectors(self):+        ss = self.selector_set+        self.by_update: dict[int, dict[str, list]] = {}+        for cat in CATEGORIES:+            for sel in ss[cat]:+                self.by_update.setdefault(int(sel["update_index"]), {c: [] for c in CATEGORIES})+        for cat in CATEGORIES:+            for sel in ss[cat]:+                self.by_update[int(sel["update_index"])][cat].append(sel)+        # per update: ordered slots = [("loss",)] + per category entries+        self.update_slots: dict[int, list] = {}+        self.logit_taps: dict[int, dict[int, list]] = {}  # update -> microbatch -> [(pos,vocab,slot)]+        for u, cats in self.by_update.items():+            slots = [{"kind": "loss"}]+            for cat in CATEGORIES:+                for sel in cats[cat]:+                    entry = {"kind": "proj", "category": cat, "selector_id": sel["selector_id"]}+                    if cat == "logits":+                        entry["row"] = int(sel["global_batch_row"])+                        entry["seq"] = int(sel["sequence_index"])+                        entry["vocab"] = int(sel["vocab_index"])+                    else:+                        entry["name"] = sel["canonical_parameter_name"]+                        entry["flat_index"] = int(sel["flat_index"])+                        entry["owner"] = owner_rank(entry["name"])+                    slots.append(entry)+            self.update_slots[u] = slots+            # logit taps per microbatch+            taps: dict[int, list] = {}+            for slot, entry in enumerate(slots):+                if entry.get("kind") == "proj" and entry["category"] == "logits":+                    row, seq, vocab = entry["row"], entry["seq"], entry["vocab"]+                    mb = row // self.rows_per_micro+                    pos = (row % self.rows_per_micro) * self.S + seq+                    taps.setdefault(mb, []).append((pos, vocab, slot))+            self.logit_taps[u] = taps++    # ---------------- initialization ----------------+    def init_deterministic(self):+        for (name, shape, _) in self.specs:+            numel = int(np.prod(shape))+            if len(shape) < 2:+                # constant_one_tensor_patterns: exact bf16 one+                flat = torch.ones(numel, dtype=torch.bfloat16, device=self.device)+            else:+                flat = generate_param_flat(name, numel, self.device)+            self.params[name].data = flat.view(shape)+            self.masters[name].copy_(flat.view(shape).float())+        if self.embed_replica is not None:+            flat = generate_param_flat(EMBED_NAME, VOCAB * HIDDEN, self.device)+            self.embed_replica.data = flat.view(VOCAB, HIDDEN)+            self.replica_master = flat.view(VOCAB, HIDDEN).float().clone()+            self.replica_m1 = torch.zeros((VOCAB, HIDDEN), dtype=torch.float32, device=self.device)+            self.replica_m2 = torch.zeros((VOCAB, HIDDEN), dtype=torch.float32, device=self.device)+            self.replica_grad = torch.zeros((VOCAB, HIDDEN), dtype=torch.float32, device=self.device)+        else:+            self.replica_master = None+        torch.npu.synchronize()++    # ---------------- microbatch data ----------------+    def microbatch(self, update_index: int, mb: int):+        sl = update_index - 1+        r0 = mb * self.rows_per_micro+        r1 = r0 + self.rows_per_micro+        ids = torch.from_numpy(np.ascontiguousarray(self.input_ids[sl, r0:r1])).to(self.device).long()+        lab = torch.from_numpy(np.ascontiguousarray(self.labels[sl, r0:r1])).to(self.device).long()+        msk = torch.from_numpy(np.ascontiguousarray(self.loss_mask[sl, r0:r1])).to(self.device).float()+        pos = torch.from_numpy(np.ascontiguousarray(self.position_ids[sl, r0:r1])).to(self.device).long()+        return ids, lab, msk, pos++    def mask_count(self, update_index: int) -> int:+        return int(self.loss_mask[update_index - 1].sum())++    # ---------------- forward stages ----------------+    def stage0_forward(self, ids, pos):+        h = F.embedding(ids, self.params[EMBED_NAME])+        cos, sin = rope_tables(pos, self.inv_freq)+        for layer in STAGE_LAYERS[0]:+            prefix = f"model.layers.{layer}."+            h = checkpoint(layer_forward, h, self.params, prefix, cos, sin,+                           use_reentrant=False)+        return h++    def stage1_forward(self, h, lab, msk, pos, taps, tap_out):+        cos, sin = rope_tables(pos, self.inv_freq)+        for layer in STAGE_LAYERS[1]:+            prefix = f"model.layers.{layer}."+            h = checkpoint(layer_forward, h, self.params, prefix, cos, sin,+                           use_reentrant=False)+        h = rmsnorm(h, self.params[FINAL_NORM])+        total = FusedCrossEntropy.apply(+            h.reshape(-1, HIDDEN), self.embed_replica,+            lab.reshape(-1), msk.reshape(-1), taps, tap_out)+        return total++    # ---------------- gradient accumulation ----------------+    def accumulate_grads(self):+        gs = []+        as_ = []+        for name, _, _ in self.specs:+            p = self.params[name]+            if p.grad is not None:+                gs.append(p.grad)+                as_.append(self.grads[name])+                p.grad = None+        if self.rank == 1 and self.embed_replica.grad is not None:+            gs.append(self.embed_replica.grad)+            as_.append(self.replica_grad)+            self.embed_replica.grad = None+        if not gs:+            return+        try:+            torch._foreach_add_(as_, gs)+        except (RuntimeError, TypeError):+            for a, g in zip(as_, gs):+                a.add_(g.float())++    # ---------------- one optimizer update ----------------+    def run_update(self, update_index: int, commit: bool):+        rank = self.rank+        dev = self.device+        count = self.mask_count(update_index)+        inv_count = float(count)+        slots = self.update_slots.get(update_index, [{"kind": "loss"}])+        nslots = len(slots)+        report = [0.0] * nslots+        taps_by_mb = self.logit_taps.get(update_index, {})+        tap_out: dict[int, float] = {}++        # zero fp32 gradient accumulation+        for g in self.grads.values():+            g.zero_()+        if rank == 1:+            self.replica_grad.zero_()++        losses = []+        if rank == 0:+            saved = []+            for mb in range(self.num_micro):+                ids, lab, msk, pos = self.microbatch(update_index, mb)+                x = self.stage0_forward(ids, pos)+                out = x.contiguous()+                dist.send(out, 1)+                saved.append(x)+            for mb in range(self.num_micro):+                gbuf = torch.empty(self.micro_shape + (HIDDEN,), dtype=torch.bfloat16, device=dev)+                dist.recv(gbuf, 1)+                saved[mb].backward(gbuf)+                self.accumulate_grads()+            saved = None+        else:+            saved = []+            for mb in range(self.num_micro):+                ids, lab, msk, pos = self.microbatch(update_index, mb)+                buf = torch.empty(self.micro_shape + (HIDDEN,), dtype=torch.bfloat16, device=dev)+                dist.recv(buf, 0)+                buf.requires_grad_(True)+                total = self.stage1_forward(buf, lab, msk, pos,+                                            taps_by_mb.get(mb), tap_out)+                losses.append(total)+                saved.append((buf, total))+            for mb in range(self.num_micro):+                buf, total = saved[mb]+                (total / inv_count).backward()+                self.accumulate_grads()+                dist.send(buf.grad.contiguous(), 0)+            saved = None++        # tied-embedding gradient: sum both ranks' contributions+        if rank == 0:+            dist.all_reduce(self.grads[EMBED_NAME])+        else:+            dist.all_reduce(self.replica_grad)++        # loss (rank1 knows it; pipeline sees every record)+        if rank == 1:+            loss_val = float(torch.stack([t.detach() for t in losses]).sum().item()) / inv_count+            report[0] = loss_val+            for slot, val in tap_out.items():+                report[slot] = val++        # pre-clip gradient projections+        for slot, entry in enumerate(slots):+            if entry.get("kind") == "proj" and entry["category"] == "gradients" \+                    and entry["owner"] == rank:+                name = entry["name"]+                src = self.grads[name] if name in self.grads else None+                if src is None and rank == 1 and name == EMBED_NAME:+                    src = self.replica_grad+                if src is not None:+                    report[slot] = float(src.view(-1)[entry["flat_index"]].item())++        # global gradient norm over unique canonical parameters+        ssq = torch.zeros((), dtype=torch.float32, device=dev)+        for name, _, _ in self.specs:+            g = self.grads[name]+            ssq += torch.sum(g * g)+        # rank1's replica_grad duplicates the canonical embedding gradient:+        # it is summed through rank 0's buffer after the all-reduce, so it is+        # intentionally not added here.+        dist.all_reduce(ssq)+        grad_norm_t = torch.sqrt(ssq)+        grad_norm = float(grad_norm_t.item())+        coefficient = min(1.0, CLIP_NORM / (grad_norm + CLIP_EPS))+        coefficient = float(np.float32(coefficient))++        # clip in place+        all_accs = list(self.grads.values()) + ([self.replica_grad] if rank == 1 else [])+        torch._foreach_mul_(all_accs, coefficient)++        # AdamW+        t = update_index+        progress = min(t - 1, DECAY_UPDATES - 1)+        lr = MIN_LR + 0.5 * (LR - MIN_LR) * (1.0 + math.cos(math.pi * progress / (DECAY_UPDATES - 1)))+        lr = float(np.float32(lr))+        bc1 = 1.0 - BETA1 ** t+        bc2 = 1.0 - BETA2 ** t++        def adamw_step(name, master, m1, m2, g, decay, model_out):+            m1.mul_(BETA1)+            m1.add_(g, alpha=1.0 - BETA1)+            m2.mul_(BETA2)+            m2.addcmul_(g, g, value=1.0 - BETA2)+            mhat = m1.div(bc1)+            vhat = m2.div(bc2)+            direction = mhat.div_(vhat.sqrt_().add_(ADAM_EPS))+            if decay:+                direction.add_(master, alpha=WEIGHT_DECAY)+            master.add_(direction, alpha=-lr)+            model_out.copy_(master.to(torch.bfloat16))++        for name, _, decay in self.specs:+            adamw_step(name, self.masters[name], self.mom1[name], self.mom2[name],+                       self.grads[name], decay, self.params[name].data)+        if rank == 1:+            adamw_step(EMBED_NAME, self.replica_master, self.replica_m1, self.replica_m2,+                       self.replica_grad, True, self.embed_replica.data)++        # post-step projections+        for slot, entry in enumerate(slots):+            if entry.get("kind") != "proj" or entry["category"] in ("logits", "gradients"):+                continue+            if entry["owner"] != rank:+                continue+            name = entry["name"]+            idx = entry["flat_index"]+            cat = entry["category"]+            if name in self.params:+                if cat == "model_parameters":+                    report[slot] = float(self.params[name].view(-1)[idx].float().item())+                elif cat == "master_parameters":+                    report[slot] = float(self.masters[name].view(-1)[idx].item())+                elif cat == "first_moments":+                    report[slot] = float(self.mom1[name].view(-1)[idx].item())+                elif cat == "second_moments":+                    report[slot] = float(self.mom2[name].view(-1)[idx].item())+            elif rank == 1 and name == EMBED_NAME:+                # unreachable: embed owner is rank 0+                pass++        # gather the report vector+        vec = torch.tensor(report, dtype=torch.float32, device=dev)+        dist.all_reduce(vec)+        values = vec.cpu().tolist()++        projections = {cat: [] for cat in CATEGORIES}+        loss_value = values[0]+        for slot, entry in enumerate(slots):+            if entry.get("kind") == "proj":+                projections[entry["category"]].append(+                    {"selector_id": entry["selector_id"], "value": float(values[slot])})++        row = {+            "schema_version": 1,+            "kind": ("openbuild_training_step_observation" if commit+                     else "openbuild_training_fresh_process_observation"),+            "profile_id": self.profile_id,+            "selector_set_id": self.selector_set_id,+            "update_index": update_index,+            "committed": bool(commit),+            "loss": float(loss_value),+            "global_grad_norm": grad_norm,+            "projections": projections,+        }+        if not commit:+            row["source_optimizer_update"] = TOTAL_UPDATES+            # reorder to keep stable structure; schema is order-insensitive+        return row++    # ---------------- checkpoint ----------------+    def checkpoint_layout(self, rank: int):+        layout = []+        off = 0+        for (name, shape, decay) in stage_param_specs(rank):+            numel = int(np.prod(shape))+            layout.append({"name": name, "offset": off, "numel": numel,+                           "shape": list(shape), "decay": decay})+            off += numel+        return layout, off++    def _write_component(self, path: Path, tensors_by_name, layout, dtype):+        total = layout[1]+        layout_entries = layout[0]+        cpu = torch.empty(total, dtype=dtype)+        for entry in layout_entries:+            src = tensors_by_name[entry["name"]].detach()+            cpu[entry["offset"]:entry["offset"] + entry["numel"]].copy_(src.view(-1))+        if dtype == torch.bfloat16:+            arr = cpu.view(torch.uint16).numpy()+        else:+            arr = cpu.numpy()+        write_file_fast(path, arr)++    def write_checkpoint(self, ckpt_dir: Path):+        layout = self.checkpoint_layout(self.rank)+        suffix = f"rank{self.rank}"+        self._write_component(ckpt_dir / f"model.{suffix}.bf16.bin",+                              self.params, layout, torch.bfloat16)+        self._write_component(ckpt_dir / f"master.{suffix}.fp32.bin",+                              self.masters, layout, torch.float32)+        self._write_component(ckpt_dir / f"m.{suffix}.fp32.bin",+                              self.mom1, layout, torch.float32)+        self._write_component(ckpt_dir / f"v.{suffix}.fp32.bin",+                              self.mom2, layout, torch.float32)+        if self.rank == 0:+            state = {+                "kind": "openbuild_training_checkpoint_state",+                "task_id": TASK_ID,+                "profile_id": self.profile_id,+                "parameter_steps": TOTAL_UPDATES,+                "committed_update": TOTAL_UPDATES,+                "next_update_index": FRESH_UPDATE,+                "scheduler": {+                    "kind": "cosine",+                    "learning_rate": LR,+                    "minimum_learning_rate": MIN_LR,+                    "warmup_updates": 0,+                    "decay_updates": DECAY_UPDATES,+                    "next_update_index": FRESH_UPDATE,+                },+                "data_cursor": {+                    "next_update_index": FRESH_UPDATE,+                    "next_global_sample_ordinal": TOTAL_UPDATES * self.G,+                },+                "layout": {"rank0": self.checkpoint_layout(0)[0],+                           "rank1": self.checkpoint_layout(1)[0]},+                "embed_replica_source": "rank0",+            }+            (ckpt_dir / "state.json").write_text(+                json.dumps(state, indent=2, sort_keys=True) + "\n", encoding="utf-8")++    def load_checkpoint(self, ckpt_dir: Path):+        state = json.loads((ckpt_dir / "state.json").read_text(encoding="utf-8"))+        layout = state["layout"][f"rank{self.rank}"]+        for entry in layout:+            name, numel, shape = entry["name"], entry["numel"], entry["shape"]+            off = entry["offset"]+            for comp, store, dtype, np_dtype in (+                ("model", self.params, torch.bfloat16, np.uint16),+                ("master", self.masters, torch.float32, np.float32),+                ("m", self.mom1, torch.float32, np.float32),+                ("v", self.mom2, torch.float32, np.float32),+            ):+                suffix = "bf16" if dtype == torch.bfloat16 else "fp32"+                path = ckpt_dir / f"{comp}.rank{self.rank}.{suffix}.bin"+                arr = np.fromfile(path, dtype=np_dtype, count=numel,+                                  offset=off * (2 if dtype == torch.bfloat16 else 4))+                t = torch.from_numpy(np.ascontiguousarray(arr))+                if dtype == torch.bfloat16:+                    t = t.view(torch.bfloat16)+                store[name].data = t.view(shape).to(self.device)+        # rank1 reconstructs its tied-embedding replica from rank0's state+        if self.rank == 1:+            embed_numel = VOCAB * HIDDEN+            for comp, attr in (("master", "replica_master"),+                               ("m", "replica_m1"), ("v", "replica_m2")):+                path = ckpt_dir / f"{comp}.rank0.fp32.bin"+                arr = np.fromfile(path, dtype=np.float32, count=embed_numel, offset=0)+                setattr(self, attr, torch.from_numpy(np.ascontiguousarray(arr))+                        .view(VOCAB, HIDDEN).to(self.device))+            self.embed_replica.data = self.replica_master.to(torch.bfloat16)+            self.replica_grad = torch.zeros((VOCAB, HIDDEN), dtype=torch.float32,+                                            device=self.device)+        self.parameter_steps = int(state["parameter_steps"])+        torch.npu.synchronize()+++def write_file_fast(path: Path, arr: np.ndarray) -> None:+    mv = memoryview(arr).cast("B")+    total = mv.nbytes+    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o644)+    try:+        nthreads = min(8, max(1, (total + (1 << 28) - 1) // (1 << 28)))+        bounds = []+        step = (total + nthreads - 1) // nthreads+        for i in range(nthreads):+            start = i * step+            end = min(total, start + step)+            if start < end:+                bounds.append((start, end))++        def worker(be):+            start, end = be+            buf = mv[start:end]+            off = start+            while len(buf) > 0:+                n = os.pwrite(fd, buf, off)+                off += n+                buf = buf[n:]++        with ThreadPoolExecutor(max_workers=len(bounds)) as pool:+            list(pool.map(worker, bounds))+    finally:+        os.close(fd)+++# ---------------- result / manifest writers ----------------+def write_train_outputs(trainer: Trainer, output_dir: Path, rows: list) -> None:+    ckpt_files = [+        f"model.rank{r}.bf16.bin" for r in (0, 1)+    ] + [+        f"{comp}.rank{r}.fp32.bin" for comp in ("master", "m", "v") for r in (0, 1)+    ] + ["state.json"]+    if trainer.rank == 0:+        with open(output_dir / "trajectory.jsonl", "w", encoding="utf-8") as fh:+            for row in rows:+                fh.write(json.dumps(row, allow_nan=False) + "\n")+        manifest = {+            "schema_version": 1,+            "kind": "openbuild_training_checkpoint",+            "task_id": TASK_ID,+            "profile_id": trainer.profile_id,+            "initialization_spec": "canonical_tensor_counter_v1",+            "optimizer_update": TOTAL_UPDATES,+            "next_update_index": FRESH_UPDATE,+            "state_components": [+                "model", "master_parameters", "first_moments", "second_moments",+                "parameter_steps", "scheduler", "data_cursor", "committed_update",+            ],+            "files": ckpt_files,+            "fresh_load_entrypoint": "train.sh",+            "fresh_next_step_mode": "fresh_next_step_probe",+        }+        (output_dir / "checkpoint-manifest.json").write_text(+            json.dumps(manifest, indent=2) + "\n", encoding="utf-8")+        result = {+            "schema_version": 1,+            "kind": "openbuild_training_result",+            "task_id": TASK_ID,+            "profile_id": trainer.profile_id,+            "status": "completed",+            "optimizer_updates": TOTAL_UPDATES,+            "consumed_tokens": 983040,+            "logical_device_ids": [0, 1],+            "trajectory_path": "trajectory.jsonl",+            "trajectory_rows": TOTAL_UPDATES,+            "checkpoint_manifest_path": "checkpoint-manifest.json",+            "checkpoint_committed": True,+            "all_ranks_exited": True,+            "delivery_summary": {+                "architecture": "two-stage pipeline over logical devices 0,1 "+                                "(HCCL), bf16 model, fp32 master/moments, "+                                "fused chunked cross-entropy, per-layer "+                                "activation checkpointing",+            },+        }+        (output_dir / "result.json").write_text(+            json.dumps(result, indent=2) + "\n", encoding="utf-8")+++# ---------------- main ----------------+def run() -> None:+    rank = int(os.environ["RANK"])+    action = os.environ["OPENBUILD_ACTION"]+    profile_id = os.environ["OPENBUILD_PROFILE_ID"]+    input_dir = Path(os.environ["OPENBUILD_INPUT_DIR"])+    output_dir = Path(os.environ["OPENBUILD_OUTPUT_DIR"])+    ckpt_dir = Path(os.environ["OPENBUILD_CHECKPOINT_DIR"])+    store = os.environ["OPENBUILD_HCCL_STORE"]++    torch.npu.set_device(rank)+    device = torch.device("npu", rank)+    dist.init_process_group(backend="hccl", init_method=f"file://{store}",+                            rank=rank, world_size=2,+                            timeout=timedelta(seconds=600))++    manifest = json.loads((input_dir / "input-manifest.json").read_text(encoding="utf-8"))+    profile = next(p for p in manifest["profiles"] if p["profile_id"] == profile_id)+    trainer = Trainer(rank, profile, input_dir, device)++    debug_updates = os.environ.get("OPENBUILD_DEBUG_MAX_UPDATES")+    debug_updates = int(debug_updates) if debug_updates else None++    if action == "train":+        log0(rank, f"[{profile_id}] init: generating deterministic parameters")+        t0 = time.monotonic()+        trainer.init_deterministic()+        log0(rank, f"[{profile_id}] init done in {time.monotonic()-t0:.1f}s")+        rows = []+        updates = range(1, TOTAL_UPDATES + 1)+        if debug_updates:+            updates = range(1, debug_updates + 1)+        for u in updates:+            t1 = time.monotonic()+            row = trainer.run_update(u, commit=True)+            rows.append(row)+            if rank == 0:+                print(f"[{profile_id}] update {u}: loss={row['loss']:.6f} "+                      f"norm={row['global_grad_norm']:.6f} "+                      f"({time.monotonic()-t1:.2f}s)", flush=True)+        if debug_updates:+            if rank == 0:+                print(json.dumps({"debug_rows": rows}, allow_nan=False), flush=True)+            dist.barrier()+            dist.destroy_process_group()+            return+        log0(rank, f"[{profile_id}] writing checkpoint")+        t2 = time.monotonic()+        # release gradient accumulation buffers before checkpoint staging+        trainer.grads = {k: None for k in trainer.grads}+        if rank == 1:+            trainer.replica_grad = None+        torch.npu.empty_cache()+        trainer.write_checkpoint(ckpt_dir)+        log0(rank, f"[{profile_id}] checkpoint written in {time.monotonic()-t2:.1f}s")+        write_train_outputs(trainer, output_dir, rows)+        dist.barrier()+        dist.destroy_process_group()+    elif action == "fresh_next_step_probe":+        log0(rank, f"[{profile_id}] probe: loading checkpoint")+        trainer.load_checkpoint(ckpt_dir)+        row = trainer.run_update(FRESH_UPDATE, commit=False)+        if rank == 0:+            with open(output_dir / "check-observations.jsonl", "w", encoding="utf-8") as fh:+                fh.write(json.dumps(row, allow_nan=False) + "\n")+        dist.barrier()+        dist.destroy_process_group()+    else:+        raise ValueError(f"unknown action {action}")+++def main() -> None:+    try:+        run()+    except Exception:+        traceback.print_exc()+        sys.stdout.flush()+        sys.stderr.flush()+        os._exit(1)+++if __name__ == "__main__":+    main()