Inspect · Source & workspace
Requested workspace inspection and file and log inspection related to source & workspace.
1 call · #0001–#0001
echo <val>ls -l -a <path> <n> > <path>head -n <n>Claude Fable 5.1 · Training
OpenBuild Qwen3-4B training 2dev · Open Build
01 / PROCESS MAP
Each row shows one agent’s tool events in its own recorded order. Colors show broad activities; bar widths do not represent duration.
Main agentClaude Fable 5.1 · 94 visible calls
02 / EVENT SEQUENCE
Requests are grouped by agent, activity and topic. Delegations open into child branches. Summaries describe visible requests; tool errors and missing responses are flagged. A recorded response does not establish command success or a performance improvement.
Scroll within this panel to view all events. Command sketches retain familiar programs and options. Values become <val> or <n>; paths, addresses and script bodies are hidden as <path>, <url> and <script>.
Requested workspace inspection and file and log inspection related to source & workspace.
1 call · #0001–#0001
echo <val>ls -l -a <path> <n> > <path>head -n <n>Requested environment setup or inspection, workspace inspection and file and log inspection related to task requirements.
3 calls · #0002–#0004
env <vars>echo <val>ls -l -a <val>echowc -lc <path> <n> > <path>cat <path> <n> > <path>cd <path>cat <val>find <val> <val> -maxdepth <n> <flag> <args>sort <flag>find <val> <val> -type <val>wc -lRequested environment setup or inspection, workspace inspection and file and log inspection related to source & workspace.
2 calls · #0005–#0006
env <vars>echo <val>find <val> -type <val> <flag> <args>sort <flag>awk <val>echoecho <path>cat <path>wc -lc <val>head -c <n> <val>Requested environment setup or inspection and file and log inspection related to benchmark & validation setup.
2 calls · #0007–#0008
env <vars><command> <args>cat <path>echoRequested environment setup or inspection and file and log inspection related to source & workspace.
3 calls · #0009–#0011
env <vars><command> <args>head -c <n> <val>echoecho <val>cat <path>Requested environment setup or inspection and file and log inspection related to task requirements.
1 call · #0012–#0012
env <vars><command> <args>head -c <n> <path>echoecho <flag>Requested file and log inspection, script or workload execution and runtime inspection related to parallelism & communication.
1 call · #0013–#0013
echo <val><command> <args>head <flag>echopython3 -Vwhich <val>echo <path>python3 -c <script> <n> >& <path>head -n <n>free -gdf -h <path> <path> <n> > <path>envgrep -i -E <val>sortRequested file and log inspection related to task requirements.
1 call · #0014–#0014
cat <path>Requested environment setup or inspection and file and log inspection related to source & workspace.
4 calls · #0015–#0018
env <vars>echo <val>sed -n <val> <val>sed -n <val> <path>Requested file and log inspection related to checkpoints & weight state.
1 call · #0019–#0019
cd <path><command> <args>cat <val>echoRequested script or workload execution related to task requirements.
1 call · #0020–#0020
python3 - <script>Requested script or workload execution, file and log inspection and workspace inspection related to attention kernels.
2 calls · #0021–#0022
echo <val>python3 -m <module> <val> <n> > <path>tail -n <val>echo<command> <args>echo <path>ls -l -a <path> <n> > <path>python3 - <script>Requested file and log inspection related to source & workspace.
2 calls · #0023–#0024
sed -n <val> <path>Requested script or workload execution related to optimizer & gradients.
1 call · #0025–#0025
python3 - <script>Requested file and log inspection, script or workload execution and source searches related to attention kernels.
1 call · #0026–#0026
cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>Requested file and log inspection and environment setup or inspection related to parallelism & communication.
1 call · #0027–#0027
cat > <path> <script>cd <path>env <vars> timeout <n> <val> -c <path>tail -n <n>Requested file and log inspection, workspace file updates and environment setup or inspection related to source & workspace.
2 calls · #0028–#0029
<command> <args>echo <val>df -h <val>tail -n <n>rm -f <path>echoenv <vars>wait <val>rm -f <path> <path>cd <path>nohup <val> -B <path> --output <path> > <path> <n> >& <path>sleep <n>echo <flag>cat <path>find <path> -type <val> <flag> <args>sort <flag>Requested environment setup or inspection, source searches and script or workload execution related to benchmark & validation setup.
1 call · #0030–#0030
env <vars>echo <val>envgrep -E <val>sortechobash <script> <n> >& <path>head -c <n>tail -c <n>Requested file and log inspection, script or workload execution and source searches related to attention kernels.
2 calls · #0031–#0032
cat > <path> <script>python3 <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>Requested file and log inspection, script or workload execution and source searches related to device memory.
1 call · #0033–#0033
cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>Requested file and log inspection, script or workload execution and source searches related to attention kernels.
1 call · #0034–#0034
cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>Requested environment setup or inspection, workspace file updates and file and log inspection related to checkpoints & weight state.
1 call · #0035–#0035
env <vars>mkdir -p <path>echo <val><command> <args>tail -n <n>rm -f <path>wait <val>rm -f <path> <path>python3 - <script>df -h <path>echofree -ghead -n <n>Requested file and log inspection, script or workload execution and source searches related to source & workspace.
1 call · #0036–#0036
cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>grep -v -i -E <val>tail -n <n>Requested environment setup or inspection, workspace file updates and file and log inspection related to checkpoints & weight state.
1 call · #0037–#0037
env <vars>mkdir -p <val>echo <val><command> <args>tail -n <n>rm -f <path>wait <val>echopython3 - <script>Requested file and log inspection, environment setup or inspection and script or workload execution related to attention kernels.
1 call · #0038–#0038
cat > <path> <script>export <vars>echo <val>timeout <n> <val> <path> <val> <n> >& <path>grep -v <val>grep -v -i -E <val>tail -n <n>Requested file and log inspection, script or workload execution and source searches related to device memory.
1 call · #0039–#0039
cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>grep -v -i -E <val>tail -n <n>Requested file and log inspection, script or workload execution and source searches related to precision & numerical checks.
1 call · #0040–#0040
cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>grep -v -i -E <val>tail -n <n>Requested file and log inspection, environment setup or inspection and script or workload execution related to attention kernels.
1 call · #0041–#0041
cat > <path> <script>export <vars>echo <val>timeout <n> <val> <path> <val> <n> >& <path>grep -v <val>grep -v -i -E <val>tail -n <n>Requested file and log inspection, script or workload execution and source searches related to checkpoints & weight state.
1 call · #0042–#0042
cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>grep -v -i -E <val>tail -n <n>rm -rf <path>Requested file and log inspection, environment setup or inspection and script or workload execution related to attention kernels.
2 calls · #0043–#0044
cat > <path> <script>export <vars>timeout <n> <val> <path> <val> <n> >& <path>grep -v <val>grep -v -i -E <val>tail -n <n>echo <val>timeout <n> <val> <path> <n> >& <path>Requested file and log inspection, script or workload execution and source searches related to device memory.
1 call · #0045–#0045
cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>grep -v -i -E <val>tail -n <n>Requested file and log inspection, script or workload execution and workspace file updates related to checkpoints & weight state.
1 call · #0046–#0046
cat > <path> <script>timeout <n> <val> <path> <n> >& <path>tail -n <n>rm -rf <path>Requested script or workload execution, workspace inspection and workspace file updates related to source & workspace.
1 call · #0047–#0047
echo <val>date -u <val>python3 - <script>echols -l -a <path>mkdir -p <path>cd <path>git status --shortgit log --oneline <flag>du <flag> <args>Requested file and log inspection, workspace file updates and workspace inspection related to parallelism & communication.
1 call · #0048–#0048
cd <path>cat > <path> <script>chmod <val> <path> <path>ls -lechopython3 -c <script>Requested workspace file updates, file and log inspection and script or workload execution related to attention kernels.
1 call · #0049–#0049
mkdir -p <val>cd <val>cat > <path> <script>python3 -c <script>Requested file and log inspection and script or workload execution related to checkpoints & weight state.
1 call · #0050–#0050
cd <path>cat > <path> <script>python3 -c <script>du <flag> <args>Requested script or workload execution, source searches and file and log inspection related to checkpoints & weight state.
1 call · #0051–#0051
cd <path>python3 - <script>python3 -c <script>grep -n <val> <path>headechoecho <val>Requested file and log inspection and workspace file updates related to checkpoints & weight state.
1 call · #0052–#0052
cat > <path> <script>chmod <val> <path>echo <val>Requested script or workload execution, execution waits and source searches related to runtime processes.
1 call · #0053–#0053
nohup <path> <val> <n> > <path> <n> >& <path>echo <val>sleep <n>grep -v <val> <path>grep -v -i -E <val>tail -n <n>Requested file and log inspection and script or workload execution related to optimizer & gradients.
1 call · #0054–#0054
cat > <path> <script>echo <val>echopython3 - <script>Requested source searches and file and log inspection related to source & workspace.
1 call · #0055–#0055
echo <val>grep -v <val> <path> <n> > <path>grep -v -i -E <val>tail -n <n>Requested script or workload execution, workspace inspection and file and log inspection related to device memory.
1 call · #0056–#0056
python3 -c <script>echoecho <val>ls <flag> <args>head -n <n>ls -l <path> <n> > <path>headdu <flag> <args>ps <flag> <args>grep -E <path>grep -v <val>npu-smi info <n> > <path>grep -E <val>Requested script or workload execution, source searches and workspace file updates related to checkpoints & weight state.
1 call · #0057–#0057
cd <path>python3 - <script>python3 -c <script>grep -n <val> <path>rm -rf <path>nohup <path> <val> <n> > <path> <n> >& <path>echo <val>Requested file and log inspection, workspace file updates and script or workload execution related to benchmark & validation setup.
1 call · #0058–#0058
cat > <path> <script>chmod <val> <path>echo <val>python3 -c <script>Requested execution waits, source searches and file and log inspection related to device memory.
1 call · #0059–#0059
sleep <n>echo <val>grep -v <val> <path> <n> > <path>grep -v -i -E <val>tail -n <n>echops <flag> <args>grep -E <val>grep -v <val>head -n <n>npu-smi info <n> > <path>grep -E <val> <flag>grep <flag> <args>Requested environment setup or inspection, workspace inspection and file and log inspection related to source & workspace.
1 call · #0060–#0060
env <vars><command> <args>echodu <flag> <args>find <val> -type <val>wc -lRequested script or workload execution, source searches and workspace file updates related to device memory.
1 call · #0061–#0061
cd <path>python3 - <script>python3 -c <script>grep -n <val> <path>rm -rf <path>nohup <path> <val> <n> > <path> <n> >& <path>echo <val>sleep <n>grep -v <val> <path>grep -v -i -E <val>tail -n <n>Requested script or workload execution related to precision & numerical checks.
1 call · #0062–#0062
python3 -c <script>echoecho <val>Requested script or workload execution, file and log inspection and workspace file updates related to parallelism & communication.
1 call · #0063–#0063
cd <path>python3 - <script>python3 -c <script>sed -n <path> <path>head -n <n>rm -rf <path>nohup <path> <val> <n> > <path> <n> >& <path>echo <val>sleep <n>grep -v <val> <path>grep -v -i -E <val>tail -n <n>Requested script or workload execution related to checkpoints & weight state.
1 call · #0064–#0064
python3 -c <script>echoecho <val>Requested script or workload execution, file and log inspection and workspace file updates related to parallelism & communication.
1 call · #0065–#0065
cd <path>python3 - <script>python3 -c <script>sed -n <path> <path>rm -rf <path>nohup <path> <val> <n> > <path> <n> >& <path>echo <val>sleep <n>grep -v <val> <path>grep -v -i -E <val>tail -n <n>Requested execution waits, source searches and file and log inspection related to source & workspace.
2 calls · #0066–#0067
sleep <n>echo <val>grep -v <val> <path>grep -v -i -E <val>tail -n <n>python3 -c <script>echols -l <path> <n> > <path>du <flag> <args>ps <flag> <args>grep <val>grep -v <val>head -n <n>Requested execution waits, source searches and workspace inspection related to optimizer & gradients.
1 call · #0068–#0068
<command> <args>sleep <n>echo <val>grep -E <val> <path>echols -l <path> <n> > <path>python3 - <script>grep -v <val> <path>grep -v -i -E <val>tail -n <n>Requested script or workload execution related to checkpoints & weight state.
1 call · #0069–#0069
cd <path> <n> > <path><command> <args>python3 - <script>Requested script or workload execution related to optimizer & gradients.
1 call · #0070–#0070
python3 - <script>Requested script or workload execution and workspace file updates related to benchmark & validation setup.
2 calls · #0071–#0072
python3 -c <script>cd <path>rm -rf <path>nohup <path> > <path> <n> >& <path>echo <val>Requested environment setup or inspection, source searches and file and log inspection related to source & workspace.
2 calls · #0073–#0074
env <vars>grep -v <val> <val> <n> > <path>grep -v -i -E <val>tail -n <n>python3 -c <script>echoecho <val>du <flag> <args>find <path> -type <val>sortls -l <path>Requested execution waits, source searches and file and log inspection related to benchmark & validation setup.
1 call · #0075–#0075
<command> <args>sleep <n>grep -v <val> <path>grep -v -i -E <val>tail -n <n>Requested script or workload execution related to source & workspace.
2 calls · #0076–#0077
cd <path>python3 - <script>python3 -c <script>Requested file and log inspection, source searches and runtime inspection related to benchmark & validation setup.
1 call · #0078–#0078
echo <val>tail -n <n> <path> <n> > <path>echogrep -c <val> <path> <n> > <path>ps <flag> <args>grep -E <val>grep -v <val>head -n <n>ls <flag> <args><command> <args>head <flag>find <val> -maxdepth <n> -name <val> -o -maxdepth <n> -name <val>du <flag> <args>Requested environment setup or inspection, file and log inspection and script or workload execution related to benchmark & validation setup.
1 call · #0079–#0079
env <vars>echo <val>cat <path> <n> > <path>python3 -m <module> <n> > <path>head -n <n>echo<command> <args>python3 -c <script>python3 - <script>echo <path>wc -l < <path>Requested source searches, execution waits and file and log inspection related to benchmark & validation setup.
1 call · #0080–#0080
<command> <args>grep -q <val> <path> <n> > <path>sleep <n>echo <val>grep -v <val> <path> <n> > <path>grep -v -i -E <val>tail -n <n>echopgrep -f <path> > <path>Requested script or workload execution related to source & workspace.
1 call · #0081–#0081
python3 -c <script>Requested script or workload execution related to benchmark & validation setup.
1 call · #0082–#0082
cd <path>nohup <path> <val> <val> <val> <val> <val> > <path> <n> >& <path>echo <val>Requested script or workload execution, runtime inspection and workspace inspection related to device memory.
1 call · #0083–#0083
python3 -c <script>echoecho <val>pgrep <flag> <args>ls -l <path> <n> > <path>df -h <path>tail -n <n>du <flag> <args>npu-smi info <n> > <path>grep <flag> <args>Requested execution waits, source searches and file and log inspection related to runtime processes.
1 call · #0084–#0084
<command> <args>sleep <n>echo <val>grep -v <val> <path> <n> > <path>grep -v -i -E <val>tail -n <n>echopgrep -f <path> > <path>Requested script or workload execution, workspace inspection and file and log inspection related to source & workspace.
1 call · #0085–#0085
python3 -c <script>cd <path>echoecho <val>find <val> -type <val> <flag> <args>sort <flag>cat -A <path>git status --shortpython3 -m <module> <script>bash -n <script>Requested environment setup or inspection, workspace inspection and file and log inspection related to device memory.
1 call · #0086–#0086
env <vars>ls <val> <n> > <path>echo <flag>cat <path> <n> > <path>cat > <path> <script><command> <args>grep -q <val> <path>echo <flag> <args>echocat <path>Requested workspace inspection and script or workload execution related to source & workspace.
1 call · #0087–#0087
cd <path>echo <val>find <val> -name <val> -o -name <val>sortfind <val> -name <val> -type <val> <flag> <args>find <val> -name <val> <flag> <args>trueechofind <val> -type <val> <flag> <args>sort <flag>python3 -c <script>Requested execution waits, source searches and file and log inspection related to checkpoints & weight state.
1 call · #0088–#0088
<command> <args>sleep <n>echo <val>grep -v <val> <path> <n> > <path>grep -v -i -E <val>tail -n <n>echopgrep -f <path> > <path>python3 - <script>Requested execution waits, source searches and file and log inspection related to checkpoints & weight state.
1 call · #0089–#0089
<command> <args>sleep <n>echo <val>grep -v <val> <path> <n> > <path>grep -v -i -E <val>tail -n <n>echopgrep -f <path> > <path>python3 - <script>cat <path> <n> > <path>python3 -m <module> <n> > <path>head -n <n>echo <path>ls -l <path> <n> > <path>pgrep -f <val> > <path>Requested environment setup or inspection, script or workload execution and file and log inspection related to checkpoints & weight state.
2 calls · #0090–#0091
env <vars>echo <val><command> <args>echo <flag>python3 -c <script> <n> > <path>echopython3 -c <script>cat > <path> <script>grep -q <val> <path>echo <flag> <args>cat <path>ls -l <val>Requested runtime inspection, source searches and file and log inspection related to device memory.
1 call · #0092–#0092
echo <val>ps <flag> <args>grep <val>echonpu-smi info <n> > <path>sed -n <path>echo <path>grep -E <val>grep <flag> <args>Requested workspace inspection, script or workload execution and file and log inspection related to source & workspace.
1 call · #0093–#0093
cd <path>echo <val>find <val> <val> -name <val> -o -name <val> -o -name <val> <val> <args>sorttrue<command> <args>echofind <val> -type <val> <flag> <args>sort <flag>python3 -c <script>sha256sum <path>cat -A <path>echo <path>git status --shortRequested script or workload execution related to source & workspace.
1 call · #0094–#0094
date -u <val>echo <val>python3 -c <script>03 / CANDIDATE ARTIFACT
Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
Base commit: d1281fd46aa0575309be1eb6e0fcdc79e4be9670
@@ -0,0 +1,9 @@+#!/usr/bin/env bash+# Offline, idempotent bootstrap. Every dependency the trainer needs is either+# supplied by the base runtime (torch, torch_npu, numpy) or vendored below+# solution/. Nothing is installed and the base environment is untouched.+set -euo pipefail+cd "$(dirname "$0")"+python3 -c 'import torch, torch_npu, numpy' >/dev/null+mkdir -p "${OPENBUILD_ENV_DIR:-.}" 2>/dev/null || true+echo "bootstrap ok"@@ -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+}@@ -0,0 +1 @@+"""Qwen3-4B two-device OpenBuild training system."""@@ -0,0 +1,155 @@+"""Canonical parameter layout and the public deterministic initializer.++Every value is a stateless function of the canonical tensor name and the+zero-based dense-C global element index, so shard boundaries and traversal+order cannot change the logical tensor.+"""+from __future__ import annotations++import torch++H = 2560+FFN = 9728+N_Q = 32+N_KV = 8+D_HEAD = 128+VOCAB = 151936+N_LAYERS = 36+EPS = 1e-6+ROPE_BASE = 1000000.0++MASK64 = (1 << 64) - 1+_SEED = 0x51454E334F50454E+_FNV_OFFSET = 0xCBF29CE484222325+_FNV_PRIME = 0x00000100000001B3+++def _signed(value: int) -> int:+ value &= MASK64+ return value - (1 << 64) if value >= (1 << 63) else value+++_K = _signed(0x9E3779B97F4A7C15)+_C1 = _signed(0xBF58476D1CE4E5B9)+_C2 = _signed(0x94D049BB133111EB)++# name -> (shape, is_constant_one)+_SUFFIXES = (+ ("self_attn.q_proj.weight", (N_Q * D_HEAD, H), False),+ ("self_attn.k_proj.weight", (N_KV * D_HEAD, H), False),+ ("self_attn.v_proj.weight", (N_KV * D_HEAD, H), False),+ ("self_attn.q_norm.weight", (D_HEAD,), True),+ ("self_attn.k_norm.weight", (D_HEAD,), True),+ ("self_attn.o_proj.weight", (H, N_Q * D_HEAD), False),+ ("mlp.gate_proj.weight", (FFN, H), False),+ ("mlp.up_proj.weight", (FFN, H), False),+ ("mlp.down_proj.weight", (H, FFN), False),+ ("input_layernorm.weight", (H,), True),+ ("post_attention_layernorm.weight", (H,), True),+)+++def build_spec() -> list[tuple[str, tuple[int, ...], bool]]:+ spec: list[tuple[str, tuple[int, ...], bool]] = [+ ("model.embed_tokens.weight", (VOCAB, H), False)+ ]+ for layer in range(N_LAYERS):+ prefix = f"model.layers.{layer}."+ for suffix, shape, const in _SUFFIXES:+ spec.append((prefix + suffix, shape, const))+ spec.append(("model.norm.weight", (H,), True))+ return spec+++SPEC = build_spec()+++def numel(shape: tuple[int, ...]) -> int:+ total = 1+ for dim in shape:+ total *= dim+ return total+++def build_offsets() -> tuple[dict[str, int], dict[str, tuple[int, ...]], int]:+ offsets: dict[str, int] = {}+ shapes: dict[str, tuple[int, ...]] = {}+ cursor = 0+ for name, shape, _ in SPEC:+ offsets[name] = cursor+ shapes[name] = shape+ cursor += numel(shape)+ return offsets, shapes, cursor+++OFFSETS, SHAPES, TOTAL_ELEMENTS = build_offsets()+# Parameters of rank >= 2 receive decoupled weight decay.+DECAY = {name: len(shape) >= 2 for name, shape, _ in SPEC}+CONSTANT = {name: const for name, _, const in SPEC}+++def fnv1a_64(name: str) -> int:+ digest = _FNV_OFFSET+ for byte in name.encode("utf-8"):+ digest ^= byte+ digest = (digest * _FNV_PRIME) & MASK64+ return digest+++def _logical_shift_right(value: torch.Tensor, bits: int) -> torch.Tensor:+ return (value >> bits) & ((1 << (64 - bits)) - 1)+++def fill_random(out: torch.Tensor, name: str, first_index: int) -> None:+ """Write the canonical random values for [first_index, first_index+len)."""+ seed = _signed(_SEED ^ fnv1a_64(name))+ count = out.numel()+ index = torch.arange(+ first_index, first_index + count, device=out.device, dtype=torch.int64+ )+ state = (index * _K) ^ seed+ state = state + _K+ state = (state ^ _logical_shift_right(state, 30)) * _C1+ state = (state ^ _logical_shift_right(state, 27)) * _C2+ state = state ^ _logical_shift_right(state, 31)+ quantized = (_logical_shift_right(state, 52) & 0xFFF) - 2048+ out.copy_(quantized.to(torch.float32).mul_(2.0 ** -16))+++def initialize_range(+ flat: torch.Tensor, start: int, stop: int, chunk: int = 1 << 25+) -> None:+ """Initialize flat[start:stop] of the global parameter vector in place."""+ for name, shape, const in SPEC:+ offset = OFFSETS[name]+ size = numel(shape)+ lo = max(start, offset)+ hi = min(stop, offset + size)+ if lo >= hi:+ continue+ target = flat[lo - start : hi - start]+ if const:+ target.fill_(1.0)+ continue+ for base in range(lo, hi, chunk):+ end = min(base + chunk, hi)+ view = target[base - lo : end - lo]+ scratch = torch.empty(+ end - base, device=flat.device, dtype=torch.float32+ )+ fill_random(scratch, name, base - offset)+ view.copy_(scratch)+ del scratch+++def segments(start: int, stop: int) -> list[tuple[str, int, int]]:+ """Parameter segments (name, local_start, local_stop) covering [start,stop)."""+ result: list[tuple[str, int, int]] = []+ for name, shape, _ in SPEC:+ offset = OFFSETS[name]+ size = numel(shape)+ lo = max(start, offset)+ hi = min(stop, offset + size)+ if lo < hi:+ result.append((name, lo - start, hi - start))+ return result@@ -0,0 +1,654 @@+"""Two-device Qwen3-4B training driver.++Data parallel over the two assigned logical devices: each rank consumes half of+every global batch in input order, gradients are reduced in FP32, optimizer+state is sharded in halves, and updated bf16 parameters are gathered back onto+both ranks. Per-layer recompute keeps activation memory small enough that the+full FP32 optimizer shard stays resident on device.+"""+from __future__ import annotations++import json+import math+import os+import time+from pathlib import Path++import numpy as np+import torch+import torch.distributed as dist+import torch_npu++from .layout import (+ CONSTANT,+ DECAY,+ H,+ OFFSETS,+ SHAPES,+ TOTAL_ELEMENTS,+ VOCAB,+ initialize_range,+ numel,+ segments,+)+from .model import (+ build_views,+ decoder_layer,+ layer_parameter_names,+ rms_norm,+ rope_tables,+ view,+)++N_LAYERS = 36+TRAIN_UPDATES = 30+FRESH_UPDATE = 31+CE_CHUNK = 1024++LR_MAX = 0.00000125+LR_MIN = 0.000000125+DECAY_UPDATES = 30+BETA1 = 0.9+BETA2 = 0.95+ADAM_EPS = 0.00000001+WEIGHT_DECAY = 0.1+CLIP = 1.0+CLIP_EPS = 0.000001++CATEGORIES = (+ "logits",+ "gradients",+ "model_parameters",+ "master_parameters",+ "first_moments",+ "second_moments",+)+++def learning_rate(update_index: int) -> float:+ progress = min(update_index - 1, DECAY_UPDATES - 1)+ return LR_MIN + 0.5 * (LR_MAX - LR_MIN) * (+ 1.0 + math.cos(math.pi * progress / (DECAY_UPDATES - 1))+ )+++class Inputs:+ """Reader for the read-only controller input bundle."""++ def __init__(self, root: Path, profile: dict) -> None:+ self.dir = root / "profiles" / profile["profile_id"]+ self.batch = int(profile["global_batch_size"])+ self.seq = int(profile["sequence_length"])++ def _read(self, name: str, dtype, count: int, offset: int) -> np.ndarray:+ return np.fromfile(self.dir / name, dtype=dtype, count=count, offset=offset)++ def slice(self, update_index: int, row_lo: int, row_hi: int, device):+ rows = row_hi - row_lo+ per_update = self.batch * self.seq+ base = (update_index - 1) * per_update + row_lo * self.seq+ count = rows * self.seq+ ids = self._read("input_ids.i32le.bin", np.int32, count, base * 4)+ labels = self._read("labels.i32le.bin", np.int32, count, base * 4)+ mask = self._read("loss_mask.u8.bin", np.uint8, count, base)+ positions = self._read("position_ids.i32le.bin", np.int32, count, base * 4)+ to = lambda a, dt: torch.from_numpy(np.ascontiguousarray(a)).to(+ device=device, dtype=dt, non_blocking=True+ )+ return (+ to(ids, torch.int64).view(rows, self.seq),+ to(labels, torch.int64).view(rows, self.seq),+ to(mask, torch.float32).view(rows, self.seq),+ to(positions, torch.int64).view(rows, self.seq),+ )+++class Trainer:+ def __init__(self) -> None:+ self.rank = int(os.environ["RANK"])+ self.world = int(os.environ["WORLD_SIZE"])+ self.action = os.environ["OPENBUILD_ACTION"]+ self.profile_id = os.environ["OPENBUILD_PROFILE_ID"]+ self.input_root = Path(os.environ["OPENBUILD_INPUT_DIR"])+ self.output_dir = Path(os.environ["OPENBUILD_OUTPUT_DIR"])+ self.checkpoint_dir = Path(os.environ["OPENBUILD_CHECKPOINT_DIR"])+ torch.npu.set_device(self.rank)+ self.device = torch.device(f"npu:{self.rank}")+ dist.init_process_group("hccl", rank=self.rank, world_size=self.world)++ manifest = json.loads(+ (self.input_root / "input-manifest.json").read_text(encoding="utf-8")+ )+ self.profile = next(+ item for item in manifest["profiles"] if item["profile_id"] == self.profile_id+ )+ self.selector_set = self.profile["selector_set"]+ self.inputs = Inputs(self.input_root, self.profile)+ self.batch = self.inputs.batch+ self.seq = self.inputs.seq+ per_rank = self.batch // self.world+ self.row_lo = self.rank * per_rank+ self.row_hi = self.row_lo + per_rank++ self.shard = TOTAL_ELEMENTS // self.world+ self.shard_lo = self.rank * self.shard+ self.shard_hi = self.shard_lo + self.shard+ self.segments = segments(self.shard_lo, self.shard_hi)++ self.flat = torch.empty(TOTAL_ELEMENTS, device=self.device, dtype=torch.bfloat16)+ self.grad = torch.zeros(TOTAL_ELEMENTS, device=self.device, dtype=torch.float32)+ self.master = torch.empty(self.shard, device=self.device, dtype=torch.float32)+ self.moment1 = torch.zeros(self.shard, device=self.device, dtype=torch.float32)+ self.moment2 = torch.zeros(self.shard, device=self.device, dtype=torch.float32)+ self.reduced = self.grad[self.shard_lo : self.shard_hi]+ self.steps = 0+ self.committed = 0+ self.cursor_update = 1+ self.cursor_sample = 0++ self.cos, self.sin = rope_tables(self.seq, self.device)+ self.mask = torch.triu(+ torch.ones(2048, 2048, device=self.device, dtype=torch.bool), diagonal=1+ )++ # ---------------- state -----------------+ def initialize_state(self) -> None:+ # The initializer is a pure function of name and global index, so each+ # rank builds the whole bf16 vector in place: no collective, and no+ # full-size temporary competing with the resident optimizer shards.+ storage = self.flat.detach()+ initialize_range(storage, 0, TOTAL_ELEMENTS)+ self.master.copy_(storage[self.shard_lo : self.shard_hi])+ self.flat.requires_grad_(True)+ build_views(self.flat)+ torch.npu.empty_cache()++ def shard_paths(self) -> dict[str, str]:+ return {+ "model": f"model.shard{self.rank}.bf16.bin",+ "master": f"master.shard{self.rank}.fp32.bin",+ "moment1": f"first_moment.shard{self.rank}.fp32.bin",+ "moment2": f"second_moment.shard{self.rank}.fp32.bin",+ }++ def _write_raw(self, path: Path, tensor: torch.Tensor) -> None:+ host = tensor.detach().to("cpu", copy=True).contiguous().view(torch.uint8).numpy()+ buffer = memoryview(host).cast("B")+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)+ try:+ block = 64 << 20+ for start in range(0, len(buffer), block):+ chunk = buffer[start : start + block]+ written = 0+ while written < len(chunk):+ written += os.write(fd, chunk[written:])+ finally:+ os.close(fd)++ def _read_raw(self, path: Path, out: torch.Tensor) -> None:+ raw = np.fromfile(path, dtype=np.uint8)+ host = torch.from_numpy(raw).view(out.dtype)+ out.copy_(host.to(self.device, non_blocking=True))++ def save_checkpoint(self) -> list[str]:+ names = self.shard_paths()+ tensors = {+ "model": self.flat.detach()[self.shard_lo : self.shard_hi],+ "master": self.master,+ "moment1": self.moment1,+ "moment2": self.moment2,+ }+ # Serialize the two ranks so each write gets the full device bandwidth.+ for turn in range(self.world):+ if turn == self.rank:+ for key, relative in names.items():+ self._write_raw(self.checkpoint_dir / relative, tensors[key])+ dist.barrier()+ files = []+ for turn in range(self.world):+ files.extend(+ [+ f"model.shard{turn}.bf16.bin",+ f"master.shard{turn}.fp32.bin",+ f"first_moment.shard{turn}.fp32.bin",+ f"second_moment.shard{turn}.fp32.bin",+ ]+ )+ if self.rank == 0:+ state = {+ "schema_version": 1,+ "kind": "openbuild_training_checkpoint_state",+ "profile_id": self.profile_id,+ "initialization_spec": "canonical_tensor_counter_v1",+ "committed_update": self.committed,+ "next_update_index": self.committed + 1,+ "parameter_steps": self.steps,+ "scheduler": {+ "kind": "cosine",+ "next_update_index": self.committed + 1,+ "warmup_updates": 0,+ "decay_updates": DECAY_UPDATES,+ "learning_rate": LR_MAX,+ "minimum_learning_rate": LR_MIN,+ },+ "data_cursor": {+ "next_update_index": self.cursor_update,+ "next_global_sample_ordinal": self.cursor_sample,+ },+ "world_size": self.world,+ "total_elements": TOTAL_ELEMENTS,+ "shard_elements": self.shard,+ }+ (self.checkpoint_dir / "state.json").write_text(+ json.dumps(state, sort_keys=True, indent=2) + "\n", encoding="utf-8"+ )+ dist.barrier()+ files.append("state.json")+ return sorted(files)++ def load_checkpoint(self) -> None:+ names = self.shard_paths()+ storage = self.flat.detach()+ self._read_raw(+ self.checkpoint_dir / names["model"],+ storage[self.shard_lo : self.shard_hi],+ )+ for source in range(self.world):+ lo = source * self.shard+ dist.broadcast(storage[lo : lo + self.shard], src=source)+ self._read_raw(self.checkpoint_dir / names["master"], self.master)+ self._read_raw(self.checkpoint_dir / names["moment1"], self.moment1)+ self._read_raw(self.checkpoint_dir / names["moment2"], self.moment2)+ state = json.loads((self.checkpoint_dir / "state.json").read_text(encoding="utf-8"))+ self.committed = int(state["committed_update"])+ self.steps = int(state["parameter_steps"])+ self.cursor_update = int(state["data_cursor"]["next_update_index"])+ self.cursor_sample = int(state["data_cursor"]["next_global_sample_ordinal"])+ self.flat.requires_grad_(True)+ build_views(self.flat)++ # ---------------- one update -----------------+ def forward_backward(self, update_index: int) -> tuple[float, dict]:+ ids, labels, mask, _positions = self.inputs.slice(+ update_index, self.row_lo, self.row_hi, self.device+ )+ rows = ids.shape[0]+ self.grad.zero_()+ embed = view(self.flat, "model.embed_tokens.weight")+ activations: list[torch.Tensor] = []+ with torch.no_grad():+ x = torch.nn.functional.embedding(ids, embed)+ for layer in range(N_LAYERS):+ activations.append(x)+ x = decoder_layer(+ self.flat, x, layer, self.cos, self.sin, self.mask, rows, self.seq+ )+ final = x.detach().requires_grad_(True)+ del x++ local_tokens = mask.sum()+ denom = local_tokens.clone()+ dist.all_reduce(denom)+ denom_value = denom.item()++ norm_weight = view(self.flat, "model.norm.weight")+ labels_flat = labels.view(-1)+ mask_flat = mask.view(-1)++ with torch.no_grad():+ flat_hidden = rms_norm(final, norm_weight).view(-1, H)+ loss_sum = torch.zeros((), device=self.device, dtype=torch.float32)+ grad_hidden = torch.empty_like(flat_hidden, dtype=torch.bfloat16)+ embed_grad = self.grad[+ OFFSETS["model.embed_tokens.weight"] :+ OFFSETS["model.embed_tokens.weight"] + VOCAB * H+ ].view(VOCAB, H)+ logit_requests = self._logit_requests(update_index)+ logit_values: dict[str, float] = {}++ total_tokens = flat_hidden.shape[0]+ with torch.no_grad():+ for start in range(0, total_tokens, CE_CHUNK):+ stop = min(start + CE_CHUNK, total_tokens)+ chunk = flat_hidden[start:stop]+ logits = (chunk @ embed.t()).float()+ log_probs = logits.log_softmax(-1)+ del logits+ targets = labels_flat[start:stop, None]+ weights = mask_flat[start:stop]+ loss_sum -= (log_probs.gather(1, targets).squeeze(1) * weights).sum()+ # exp in place: one [chunk, vocab] fp32 buffer instead of two.+ probs = log_probs.exp_()+ del log_probs+ probs.scatter_add_(+ 1, targets, -torch.ones(stop - start, 1, device=self.device)+ )+ probs *= (weights / denom_value)[:, None]+ grad_chunk = probs.to(torch.bfloat16)+ del probs+ grad_hidden[start:stop] = grad_chunk @ embed+ # add_ promotes the bf16 product into the fp32 accumulator without+ # materializing a full-size fp32 copy of the embedding gradient.+ embed_grad.add_(grad_chunk.t() @ chunk)+ del grad_chunk+ with torch.no_grad():+ for selector_id, row, position, vocab_index in logit_requests:+ token = (row - self.row_lo) * self.seq + position+ logit_values[selector_id] = float(+ torch.dot(+ flat_hidden[token].float(), embed[vocab_index].float()+ ).item()+ )+ dist.all_reduce(loss_sum)+ loss = loss_sum.item() / denom_value++ # Recompute the final norm with grad enabled purely to differentiate it.+ with torch.enable_grad():+ hidden = rms_norm(final, norm_weight)+ grad_norm_weight, grad_final = torch.autograd.grad(+ hidden, [norm_weight, final], grad_outputs=grad_hidden.view(rows, self.seq, H)+ )+ self._accumulate("model.norm.weight", grad_norm_weight)+ del grad_norm_weight, hidden, grad_hidden, flat_hidden+ current = grad_final+ del grad_final, final++ for layer in reversed(range(N_LAYERS)):+ inbound = activations[layer].detach().requires_grad_(True)+ activations[layer] = None+ with torch.enable_grad():+ out = decoder_layer(+ self.flat, inbound, layer, self.cos, self.sin, self.mask, rows, self.seq+ )+ names = layer_parameter_names(layer)+ wanted = [inbound] + [view(self.flat, name) for name in names]+ grads = torch.autograd.grad(out, wanted, grad_outputs=current)+ del out+ current = grads[0]+ for name, value in zip(names, grads[1:]):+ self._accumulate(name, value)+ del grads, inbound+ embed_grad.index_add_(0, ids.view(-1), current.view(-1, H).float())+ del current, activations+ return loss, logit_values++ def _accumulate(self, name: str, value: torch.Tensor) -> None:+ offset = OFFSETS[name]+ size = numel(SHAPES[name])+ self.grad[offset : offset + size].add_(value.reshape(-1).float())++ def _logit_requests(self, update_index: int):+ out = []+ for selector in self.selector_set["logits"]:+ if selector["update_index"] != update_index:+ continue+ row = int(selector["global_batch_row"])+ if self.row_lo <= row < self.row_hi:+ out.append(+ (+ selector["selector_id"],+ row,+ int(selector["sequence_index"]),+ int(selector["vocab_index"]),+ )+ )+ return out++ def reduce_gradients(self) -> float:+ block = 1 << 28+ for base in range(0, TOTAL_ELEMENTS, block):+ dist.all_reduce(self.grad[base : base + block])+ pieces = 256+ step = (self.shard + pieces - 1) // pieces+ partials = torch.stack(+ [+ torch.linalg.vector_norm(+ self.reduced[start : start + step], dtype=torch.float32+ )+ for start in range(0, self.shard, step)+ ]+ )+ partials.pow_(2)+ dist.all_reduce(partials)+ return math.sqrt(sum(partials.tolist()))++ def optimizer_step(self, update_index: int, grad_norm: float) -> None:+ coefficient = min(1.0, CLIP / (grad_norm + CLIP_EPS))+ lr = learning_rate(update_index)+ self.steps += 1+ bias1 = 1.0 - BETA1 ** self.steps+ bias2 = 1.0 - BETA2 ** self.steps+ for name, lo, hi in self.segments:+ g = self.reduced[lo:hi] * coefficient+ m = self.moment1[lo:hi]+ v = self.moment2[lo:hi]+ m.mul_(BETA1).add_(g, alpha=1.0 - BETA1)+ v.mul_(BETA2).addcmul_(g, g, value=1.0 - BETA2)+ direction = (m / bias1) / ((v / bias2).sqrt() + ADAM_EPS)+ p = self.master[lo:hi]+ if DECAY[name]:+ direction = direction + p * WEIGHT_DECAY+ p.add_(direction, alpha=-lr)+ del g, direction+ with torch.no_grad():+ storage = self.flat.detach()+ storage[self.shard_lo : self.shard_hi].copy_(self.master)+ for source in range(self.world):+ lo = source * self.shard+ dist.broadcast(storage[lo : lo + self.shard], src=source)+ self.committed = update_index+ self.cursor_update = update_index + 1+ self.cursor_sample = update_index * self.batch++ # ---------------- projections -----------------+ def gather_projections(self, update_index: int, phase: str) -> dict:+ requests: list[tuple[str, str, int]] = []+ for category in CATEGORIES:+ if category == "logits":+ continue+ for selector in self.selector_set[category]:+ if selector["update_index"] != update_index:+ continue+ offset = OFFSETS[selector["canonical_parameter_name"]] + int(+ selector["flat_index"]+ )+ requests.append((category, selector["selector_id"], offset))+ if not requests:+ return {}+ values = torch.zeros(len(requests), device=self.device, dtype=torch.float32)+ for index, (category, _selector_id, offset) in enumerate(requests):+ if not (self.shard_lo <= offset < self.shard_hi):+ continue+ local = offset - self.shard_lo+ if category == "gradients":+ values[index] = self.reduced[local]+ elif category == "model_parameters":+ values[index] = self.flat.detach()[offset].float()+ elif category == "master_parameters":+ values[index] = self.master[local]+ elif category == "first_moments":+ values[index] = self.moment1[local]+ elif category == "second_moments":+ values[index] = self.moment2[local]+ dist.all_reduce(values)+ listed = values.tolist()+ result: dict[str, float] = {}+ for (category, selector_id, _offset), value in zip(requests, listed):+ result[f"{category}/{selector_id}"] = value+ return result++ def projection_block(+ self, update_index: int, scalars: dict, logits: dict+ ) -> dict:+ block: dict[str, list] = {}+ for category in CATEGORIES:+ entries = []+ for selector in self.selector_set[category]:+ if selector["update_index"] != update_index:+ continue+ selector_id = selector["selector_id"]+ if category == "logits":+ value = logits.get(selector_id, 0.0)+ else:+ value = scalars[f"{category}/{selector_id}"]+ entries.append({"selector_id": selector_id, "value": value})+ block[category] = entries+ return block++ def collect_logits(self, local: dict[str, float], update_index: int) -> dict:+ ids = [+ selector["selector_id"]+ for selector in self.selector_set["logits"]+ if selector["update_index"] == update_index+ ]+ if not ids:+ return {}+ values = torch.zeros(len(ids), device=self.device, dtype=torch.float32)+ for index, selector_id in enumerate(ids):+ if selector_id in local:+ values[index] = local[selector_id]+ dist.all_reduce(values)+ return dict(zip(ids, values.tolist()))++ # ---------------- actions -----------------+ def run_train(self) -> None:+ self.initialize_state()+ rows = []+ limit = int(os.environ.get("OPENBUILD_MAX_UPDATES", TRAIN_UPDATES))+ for update_index in range(1, limit + 1):+ loss, local_logits = self.forward_backward(update_index)+ grad_norm = self.reduce_gradients()+ logits = self.collect_logits(local_logits, update_index)+ pre_step = self.gather_projections(update_index, "pre")+ self.optimizer_step(update_index, grad_norm)+ post = self.gather_projections(update_index, "post")+ merged = dict(post)+ for key, value in pre_step.items():+ if key.startswith("gradients/"):+ merged[key] = value+ if self.rank == 0:+ rows.append(+ {+ "schema_version": 1,+ "kind": "openbuild_training_step_observation",+ "profile_id": self.profile_id,+ "selector_set_id": self.selector_set["selector_set_id"],+ "update_index": update_index,+ "committed": True,+ "loss": loss,+ "global_grad_norm": grad_norm,+ "projections": self.projection_block(+ update_index, merged, logits+ ),+ }+ )+ files = self.save_checkpoint()+ if self.rank == 0:+ with (self.output_dir / "trajectory.jsonl").open("w", encoding="utf-8") as handle:+ for row in rows:+ handle.write(json.dumps(row, allow_nan=False) + "\n")+ manifest = {+ "schema_version": 1,+ "kind": "openbuild_training_checkpoint",+ "task_id": "openbuild_training_qwen3_4b_2dev_v1",+ "profile_id": self.profile_id,+ "initialization_spec": "canonical_tensor_counter_v1",+ "optimizer_update": 30,+ "next_update_index": 31,+ "state_components": [+ "model",+ "master_parameters",+ "first_moments",+ "second_moments",+ "parameter_steps",+ "scheduler",+ "data_cursor",+ "committed_update",+ ],+ "files": files,+ "fresh_load_entrypoint": "train.sh",+ "fresh_next_step_mode": "fresh_next_step_probe",+ }+ (self.output_dir / "checkpoint-manifest.json").write_text(+ json.dumps(manifest, sort_keys=True, indent=2) + "\n", encoding="utf-8"+ )+ result = {+ "schema_version": 1,+ "kind": "openbuild_training_result",+ "task_id": "openbuild_training_qwen3_4b_2dev_v1",+ "profile_id": self.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": "data_parallel_two_device_sharded_optimizer",+ "devices": 2,+ "recompute": "per_layer",+ "loss_precision": "fp32",+ "master_precision": "fp32",+ "model_precision": "bf16",+ },+ }+ (self.output_dir / "result.json").write_text(+ json.dumps(result, sort_keys=True, indent=2) + "\n", encoding="utf-8"+ )+ dist.barrier()++ def run_fresh_probe(self) -> None:+ self.load_checkpoint()+ loss, local_logits = self.forward_backward(FRESH_UPDATE)+ grad_norm = self.reduce_gradients()+ logits = self.collect_logits(local_logits, FRESH_UPDATE)+ pre_step = self.gather_projections(FRESH_UPDATE, "pre")+ self.optimizer_step(FRESH_UPDATE, grad_norm)+ post = self.gather_projections(FRESH_UPDATE, "post")+ merged = dict(post)+ for key, value in pre_step.items():+ if key.startswith("gradients/"):+ merged[key] = value+ if self.rank == 0:+ row = {+ "schema_version": 1,+ "kind": "openbuild_training_fresh_process_observation",+ "profile_id": self.profile_id,+ "selector_set_id": self.selector_set["selector_set_id"],+ "source_optimizer_update": 30,+ "update_index": FRESH_UPDATE,+ "committed": False,+ "loss": loss,+ "global_grad_norm": grad_norm,+ "projections": self.projection_block(FRESH_UPDATE, merged, logits),+ }+ with (self.output_dir / "check-observations.jsonl").open(+ "w", encoding="utf-8"+ ) as handle:+ handle.write(json.dumps(row, allow_nan=False) + "\n")+ dist.barrier()+++def main() -> int:+ trainer = Trainer()+ try:+ if trainer.action == "train":+ trainer.run_train()+ elif trainer.action == "fresh_next_step_probe":+ trainer.run_fresh_probe()+ else:+ raise SystemExit(f"unsupported action {trainer.action}")+ finally:+ try:+ dist.barrier()+ except Exception:+ pass+ dist.destroy_process_group()+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())@@ -0,0 +1,137 @@+"""Qwen3-4B forward math over a single flat bf16 parameter vector."""+from __future__ import annotations++import torch+import torch_npu++from .layout import (+ D_HEAD,+ EPS,+ FFN,+ H,+ N_KV,+ N_Q,+ N_LAYERS,+ OFFSETS,+ ROPE_BASE,+ SHAPES,+)+++_VIEW_CACHE: dict[int, dict[str, torch.Tensor]] = {}+++def view(flat: torch.Tensor, name: str) -> torch.Tensor:+ """Return the one shared view of `name`.++ autograd identifies inputs by tensor object, so every consumer must see the+ same view instance that the forward graph recorded.+ """+ cache = _VIEW_CACHE.setdefault(id(flat), {})+ cached = cache.get(name)+ if cached is not None:+ return cached+ offset = OFFSETS[name]+ shape = SHAPES[name]+ size = 1+ for dim in shape:+ size *= dim+ created = flat[offset : offset + size].view(*shape)+ cache[name] = created+ return created+++def build_views(flat: torch.Tensor) -> None:+ """Materialize every view while grad recording is enabled."""+ _VIEW_CACHE.pop(id(flat), None)+ with torch.enable_grad():+ for name in SHAPES:+ view(flat, name)+++def rms_norm(x: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:+ return torch_npu.npu_rms_norm(x, weight, EPS)[0]+++def rope_tables(seq_len: int, device: torch.device) -> tuple[torch.Tensor, torch.Tensor]:+ inverse = 1.0 / (+ ROPE_BASE+ ** (torch.arange(0, D_HEAD, 2, device=device, dtype=torch.float32) / D_HEAD)+ )+ angles = torch.arange(seq_len, device=device, dtype=torch.float32)[:, None] * inverse[None, :]+ return angles.cos().to(torch.bfloat16), angles.sin().to(torch.bfloat16)+++def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:+ half = D_HEAD // 2+ left, right = x[..., :half], x[..., half:]+ cos = cos[None, :, None, :]+ sin = sin[None, :, None, :]+ return torch.cat((left * cos - right * sin, right * cos + left * sin), -1)+++LAYER_SUFFIXES = (+ "self_attn.q_proj.weight",+ "self_attn.k_proj.weight",+ "self_attn.v_proj.weight",+ "self_attn.q_norm.weight",+ "self_attn.k_norm.weight",+ "self_attn.o_proj.weight",+ "mlp.gate_proj.weight",+ "mlp.up_proj.weight",+ "mlp.down_proj.weight",+ "input_layernorm.weight",+ "post_attention_layernorm.weight",+)+++def layer_parameter_names(layer: int) -> list[str]:+ prefix = f"model.layers.{layer}."+ return [prefix + suffix for suffix in LAYER_SUFFIXES]+++def decoder_layer(+ flat: torch.Tensor,+ x: torch.Tensor,+ layer: int,+ cos: torch.Tensor,+ sin: torch.Tensor,+ mask: torch.Tensor,+ batch: int,+ seq: int,+) -> torch.Tensor:+ prefix = f"model.layers.{layer}."++ def w(suffix: str) -> torch.Tensor:+ return view(flat, prefix + suffix)++ hidden = rms_norm(x, w("input_layernorm.weight"))+ q = rms_norm(+ (hidden @ w("self_attn.q_proj.weight").t()).view(batch, seq, N_Q, D_HEAD),+ w("self_attn.q_norm.weight"),+ )+ k = rms_norm(+ (hidden @ w("self_attn.k_proj.weight").t()).view(batch, seq, N_KV, D_HEAD),+ w("self_attn.k_norm.weight"),+ )+ v = (hidden @ w("self_attn.v_proj.weight").t()).view(batch, seq, N_KV, D_HEAD)+ q = apply_rope(q, cos, sin)+ k = apply_rope(k, cos, sin)+ attended = torch_npu.npu_fusion_attention(+ q.reshape(batch, seq, N_Q * D_HEAD),+ k.reshape(batch, seq, N_KV * D_HEAD),+ v.reshape(batch, seq, N_KV * D_HEAD),+ N_Q,+ "BSH",+ atten_mask=mask,+ scale=D_HEAD ** -0.5,+ keep_prob=1.0,+ sparse_mode=2,+ )[0]+ x = x + (attended @ w("self_attn.o_proj.weight").t())+ hidden = rms_norm(x, w("post_attention_layernorm.weight"))+ gate = torch.cat(+ (hidden @ w("mlp.gate_proj.weight").t(), hidden @ w("mlp.up_proj.weight").t()),+ -1,+ )+ return x + (torch_npu.npu_swiglu(gate, dim=-1) @ w("mlp.down_proj.weight").t())@@ -0,0 +1,26 @@+#!/usr/bin/env bash+# Foreground launcher: starts exactly one rank per assigned logical device,+# keeps both attached to this process, and exits only after both ranks exit.+set -uo pipefail+cd "$(dirname "$0")"+export PYTHONPATH="$PWD${PYTHONPATH:+:$PYTHONPATH}"+export MASTER_ADDR=127.0.0.1+export MASTER_PORT="$(python3 - <<'PY'+import socket+s=socket.socket(); s.bind(("127.0.0.1",0)); print(s.getsockname()[1]); s.close()+PY+)"+export WORLD_SIZE=2+export HCCL_CONNECT_TIMEOUT="${HCCL_CONNECT_TIMEOUT:-600}"+export TOKENIZERS_PARALLELISM=false+export PYTORCH_NPU_ALLOC_CONF="${PYTORCH_NPU_ALLOC_CONF:-expandable_segments:True}"+pids=()+for rank in 0 1; do+ RANK="$rank" LOCAL_RANK="$rank" python3 -B -m openbuild_train.main &+ pids+=("$!")+done+status=0+for pid in "${pids[@]}"; do+ if ! wait "$pid"; then status=1; fi+done+exit "$status"