Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
openbuild_solution · 21 changed files
Base commit: d1281fd46aa0575309be1eb6e0fcdc79e4be9670
diff --git a/solution/LICENSE.zstd b/solution/LICENSE.zstdnew file mode 100644index 0000000000000000000000000000000000000000..75800288cc243f164b9d130f125e2ffae28f8e39--- /dev/null+++ b/solution/LICENSE.zstd@@ -0,0 +1,30 @@+BSD License++For Zstandard software++Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.++Redistribution and use in source and binary forms, with or without modification,+are permitted provided that the following conditions are met:++ * Redistributions of source code must retain the above copyright notice, this+ list of conditions and the following disclaimer.++ * Redistributions in binary form must reproduce the above copyright notice,+ this list of conditions and the following disclaimer in the documentation+ and/or other materials provided with the distribution.++ * Neither the name Facebook, nor Meta, nor the names of its contributors may+ be used to endorse or promote products derived from this software without+ specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.diff --git a/solution/README.md b/solution/README.mdnew file mode 100644index 0000000000000000000000000000000000000000..3ab4251878cba1c224cf504f50d7a7d4c28d370c--- /dev/null+++ b/solution/README.md@@ -0,0 +1,109 @@+# Two-device Qwen3-4B training++This delivery implements the public Qwen3-4B-Base architecture directly in+PyTorch and `torch_npu`. It requires only the declared base runtime and NumPy.+There are no downloaded weights, model frameworks, runtime downloads, or stored+training observations.++## Replay++Run `bootstrap.sh` and then `train.sh` with the `OPENBUILD_*` environment from+the delivery contract. `train.sh` supports `train` and+`fresh_next_step_probe`. Its foreground Python supervisor starts exactly two+HCCL ranks on logical devices 0 and 1, joins both, and publishes `result.json`+only after both have exited successfully. Failure or termination stops and+joins the remaining rank.++## Architecture and numerical state++* Both devices store the complete BF16 model. Each processes a contiguous half+ of the supplied global records, in order, using the supplied positions,+ pre-shifted labels, and loss masks.+* `initialization.py` implements unsigned 64-bit FNV-1a and SplitMix64 counter+ initialization at canonical global indices. Each rank initializes only the+ model interval it owns. A bounded host thread pool generates independent+ counter blocks, and HCCL exchanges the completed model intervals. BF16 rounding+ is round to nearest, ties to even. The embedding and output projection share+ one parameter and one gradient buffer.+ A small, source-included native counter implementation (`counter.cpp` /+ `counter.so`) accelerates host initialization. An equivalent NumPy path is+ available if the native library cannot be loaded.+* Backward accumulates into a persistent FP32 gradient buffer. Loss uses the+ global mask count. HCCL reduce-scatter sums each gradient onto the rank that+ owns its optimizer state, without averaging it again. The pre-clip norm counts+ each canonical coordinate exactly once. A full all-reduce path is available+ through `OPENBUILD_GRADIENT_REDUCTION=all_reduce`.+* FP32 masters and both Adam moments are split into two contiguous disjoint+ intervals. Updates use the public clipping, bias correction, cosine learning+ rate, rank-based weight decay, and BF16 conversion formulas. All-gathers+ distribute the updated model intervals through a bounded staging buffer.+ `OPENBUILD_MODEL_EXCHANGE=broadcast` selects the alternate broadcast path.+ The default source-included AscendC vector implementation of AdamW fuses+ clipping, moment updates, bias correction, weight decay, the master update,+ and BF16 conversion. `native_optimizer.py`+ registers and launches the packaged device binary through the CANN runtime;+ it requires no compiler or extra Python package during replay.+ `OPENBUILD_OPTIMIZER=torch` selects the equivalent PyTorch implementation.+* Attention uses CANN fused causal grouped-query attention with FP32 softmax+ statistics. Q and K have per-head RMS normalization and noninterleaved RoPE.+ The default retains transformer activations. Optional block or MLP activation+ recomputation is available through `OPENBUILD_RECOMPUTE`. The vocabulary loss+ uses FP32 softmax and caches its BF16 derivative, releasing FP32 logits before+ transformer backward.++The principal costs are the transformer matrix multiplications,+FP32 gradient communication, and writing the complete optimizer+checkpoint. The state layout avoids replicating the three FP32 optimizer+arrays and avoids an extra full-model all-gather allocation.++## Observations and checkpoints++Selectors come exclusively from `input-manifest.json`. Their counts, IDs,+indices, and category order are honored at runtime. Every committed row reports+its actual forward loss, selected logits, pre-clip global gradients and norm,+and post-update parameter and optimizer values.++The checkpoint has four raw little-endian tensor files and one JSON state file+per rank. Each tensor file covers the rank's canonical flat interval. The JSON+records the full canonical layout, alias, parameter steps, scheduler, committed+update, and global data cursor, including the most recent sample IDs. Files are+streamed through reusable pinned host buffers, flushed, and atomically renamed+before the checkpoint manifest is published. All model, master, first-moment, and+second-moment elements are included.++Raw tensor files are the default. The optional+`OPENBUILD_CHECKPOINT_ENCODING=zstd-byte-shuffle-v1` format applies a lossless+byte-plane transform and independent Zstandard frames. A bounded pool encodes+and decodes frames in parallel while preserving their order. The matching+Zstandard library, license, and dependency metadata are included in the delivery.++A fresh process loads all four state arrays, computes only input slice 30+(would-be update 31), and writes a single observation. Its updated state stays+in memory; committed state and the supplied checkpoint remain at update 30.++## Development++The task's public scripts exercise complete model shapes and both profiles:++```sh+bash "$TASK_DIR/run/describe.sh"+bash "$TASK_DIR/run/smoke.sh"+bash "$TASK_DIR/run/development_correctness.sh"+bash "$TASK_DIR/run/development_measurement.sh"+```++Formal correctness and measurement use the explicitly supplied formal bundle.+The task's `cleanup.sh` completes the public lifecycle. Runtime inputs, logs,+checkpoints, and compilation caches belong outside this source delivery.++The small native host library and native optimizer binary are already packaged.+`build_native.sh` and `build_optimizer.sh` are optional development rebuilds;+the latter uses CANN's Ascend 910B compiler. Both replace artifacts atomically.+From the source root, unit checks cover canonical initialization, lossless+checkpoint frames, and real-device optimizer rounding and transitions:++```sh+python3 -B -m unittest discover -s solution -p 'test_*.py' -v+```++See [VALIDATION.md](VALIDATION.md) for measured throughput and completed checks.diff --git a/solution/VALIDATION.md b/solution/VALIDATION.mdnew file mode 100644index 0000000000000000000000000000000000000000..6ee102496f2f446d7d045e617398a17fd3c9210d--- /dev/null+++ b/solution/VALIDATION.md@@ -0,0 +1,71 @@+# Validation record++Validated on REDACTED_DATE with the supplied two logical Ascend 910B devices and+base runtime. The final defaults use native AdamW, FP32 reduce-scatter, bounded+BF16 all-gather, retained activations, and raw checkpoints.++## Full public-development replay++```sh+OPENBUILD_TIMING=1 bash "$TASK_DIR/run/development_measurement.sh"+```++The final configuration passed all 172 numeric checks (148 hard checks and+24 diagnostics), all 32 optimizer-transition checks, and every public gate.+Both profiles completed 30 updates and 983,040 tokens, wrote complete+checkpoints, loaded them in fresh processes for update 31, and exited all ranks.+The controller verified unchanged restart checkpoints and completed cleanup.++| Profile | Host-observed seconds | Tokens/second |+| --- | ---: | ---: |+| long_sequence | 178.381 | 5,510.915 |+| update_heavy | 183.500 | 5,357.180 |++Geometric mean: **5,433.504 tokens/second**. These timings include bootstrap,+training, checkpoint writing, and rank shutdown; they exclude the fresh probe.+Peak allocated NPU memory was **56.49 GiB per rank**.++A representative long-sequence update spent 2.544 seconds in forward/backward,+0.505 seconds in gradient reduction and norm calculation, and 0.288 seconds in+the optimizer, model exchange, and remaining observations. Matrix operations+and FP32 gradient communication dominate the training step; checkpoint I/O is+also material to the end-to-end result.++## Focused checks++All seven unit checks passed: three for canonical initialization and partition+invariance, three for exact checkpoint-codec round trips and invalid frames,+and one real-NPU test covering 31 optimizer transitions, aligned tails, and+exact BF16 conversion. Shell syntax, Python syntax, and JSON checks also passed.++## Formal correctness++The final source passed `run/correctness.sh` with the separate formal input+bundle supplied through `TASK_EXTERNAL_INPUT_ROOT`. Every public gate passed,+including all 32 transition checks, both complete checkpoints, fresh-process+restart, observed work on both devices, all-rank exit, and cleanup. Each+checkpoint contained 10 files and approximately 56.315 GB of complete state.++## Formal measurement and lifecycle++The unchanged final implementation also passed `run/measurement.sh` with the+formal input bundle. `measurement_valid` was true, every public gate passed,+and all 32 optimizer-transition checks passed again.++| Profile | Host-observed seconds | Tokens/second |+| --- | ---: | ---: |+| long_sequence | 182.461 | 5,387.686 |+| update_heavy | 174.265 | 5,641.058 |++Formal geometric mean: **5,512.916 tokens/second**. Both profiles completed+exactly 30 committed updates and 983,040 input tokens, with full checkpoints,+fresh-process probes, observed execution on both NPUs, and all ranks exited.++The required lifecycle `describe -> smoke -> correctness -> measurement ->+cleanup` completed successfully. The final standalone cleanup reported+`status=passed`, `complete=true`, no controller process state, and an intact+protected marker. A final `npu-smi` inspection found no running processes on+either assigned NPU.++The public tools do not provide the final same-hardware baseline normalization.+These measurements therefore do not establish the baseline-relative speedup.diff --git a/solution/adam_ascendc.cpp b/solution/adam_ascendc.cppnew file mode 100644index 0000000000000000000000000000000000000000..42618e43e772788f2701c7417354618ef83b7f22--- /dev/null+++ b/solution/adam_ascendc.cpp@@ -0,0 +1,74 @@+// Ahead-of-time Ascend 910B vector kernel for the public FP32 AdamW update.+#define __ASCENDC_INCLUDE_INTERNAL_HEADERS__+#include "kernel_tpipe.h"+#include "kernel_tensor.h"+#include "kernel_type.h"+#include "kernel_operator_common_intf.h"+#include "kernel_operator_data_copy_intf.h"+#include "kernel_operator_vec_binary_intf.h"+#include "kernel_operator_vec_binary_scalar_intf.h"+#include "kernel_operator_vec_unary_intf.h"+#include "kernel_operator_vec_vconv_intf.h"+using namespace AscendC;++extern "C" __global__ __aicore__ void openbuild_adam(+ GM_ADDR pp, GM_ADDR mm, GM_ADDR vv, GM_ADDR gg, GM_ADDR ww,+ uint32_t n, float clip, float lr, float bc1, float bc2, float wd) {+ constexpr uint32_t TILE = 2048;+ TPipe pipe;+ TBuf<TPosition::VECCALC> pb, mb, vb, gb, ab, bb, wb;+ pipe.InitBuffer(pb, TILE * 4);+ pipe.InitBuffer(mb, TILE * 4);+ pipe.InitBuffer(vb, TILE * 4);+ pipe.InitBuffer(gb, TILE * 4);+ pipe.InitBuffer(ab, TILE * 4);+ pipe.InitBuffer(bb, TILE * 4);+ pipe.InitBuffer(wb, TILE * 2);+ auto p = pb.Get<float>(); auto m = mb.Get<float>();+ auto v = vb.Get<float>(); auto g = gb.Get<float>();+ auto a = ab.Get<float>(); auto b = bb.Get<float>();+ auto w = wb.Get<bfloat16_t>();+ GlobalTensor<float> pg, mg, vg, gglobal;+ GlobalTensor<bfloat16_t> wg;+ pg.SetGlobalBuffer((__gm__ float*)pp, n);+ mg.SetGlobalBuffer((__gm__ float*)mm, n);+ vg.SetGlobalBuffer((__gm__ float*)vv, n);+ gglobal.SetGlobalBuffer((__gm__ float*)gg, n);+ wg.SetGlobalBuffer((__gm__ bfloat16_t*)ww, n);+ for (uint32_t at = GetBlockIdx() * TILE; at < n; at += GetBlockNum() * TILE) {+ uint32_t count = n - at < TILE ? n - at : TILE;+ DataCopy(p, pg[at], count); DataCopy(m, mg[at], count);+ DataCopy(v, vg[at], count); DataCopy(g, gglobal[at], count);+ PipeBarrier<PIPE_ALL>();+ Muls(g, g, clip, count);+ Muls(m, m, 0.9f, count); Muls(a, g, 0.1f, count);+ PipeBarrier<PIPE_V>();+ Add(m, m, a, count); Mul(a, g, g, count);+ Muls(v, v, 0.95f, count);+ PipeBarrier<PIPE_V>();+ Muls(a, a, 0.05f, count);+ PipeBarrier<PIPE_V>();+ Add(v, v, a, count);+ Muls(a, m, 1.0f / bc1, count);+ PipeBarrier<PIPE_V>();+ Muls(b, v, 1.0f / bc2, count);+ PipeBarrier<PIPE_V>();+ Sqrt(b, b, count);+ PipeBarrier<PIPE_V>();+ Adds(b, b, 1.0e-8f, count);+ PipeBarrier<PIPE_V>();+ Div(a, a, b, count); Muls(b, p, wd, count);+ PipeBarrier<PIPE_V>();+ Add(a, a, b, count);+ PipeBarrier<PIPE_V>();+ Muls(a, a, lr, count);+ PipeBarrier<PIPE_V>();+ Sub(p, p, a, count);+ PipeBarrier<PIPE_V>();+ Cast(w, p, RoundMode::CAST_RINT, count);+ PipeBarrier<PIPE_ALL>();+ DataCopy(pg[at], p, count); DataCopy(mg[at], m, count);+ DataCopy(vg[at], v, count); DataCopy(wg[at], w, count);+ PipeBarrier<PIPE_ALL>();+ }+}diff --git a/solution/bootstrap.sh b/solution/bootstrap.shnew file mode 100755index 0000000000000000000000000000000000000000..89b5df4f7849bfc14b5c8defe03825058f9b03f2--- /dev/null+++ b/solution/bootstrap.sh@@ -0,0 +1,13 @@+#!/usr/bin/env bash+set -euo pipefail+cd -- "$(dirname -- "${BASH_SOURCE[0]}")"+: "${OPENBUILD_ENV_DIR:?}"+mkdir -p -- "$OPENBUILD_ENV_DIR"+# The entire implementation uses the declared base Python/PyTorch/NPU runtime.+# No package installation, network access, or base-environment mutation is needed.+python3 -B - <<'PY'+import importlib.util+for name in ("numpy", "torch", "torch_npu"):+ if importlib.util.find_spec(name) is None:+ raise RuntimeError(f"Required base-runtime dependency is missing: {name}")+PYdiff --git a/solution/build_native.sh b/solution/build_native.shnew file mode 100755index 0000000000000000000000000000000000000000..ef5afc4721a42819ae46686fe35cf897d210609e--- /dev/null+++ b/solution/build_native.sh@@ -0,0 +1,10 @@+#!/usr/bin/env bash+# Optional development rebuild. Replay uses the packaged library and needs no compiler.+set -euo pipefail+cd -- "$(dirname -- "${BASH_SOURCE[0]}")"+counter_build_dir="$(mktemp -d "${TMPDIR:-/tmp}/openbuild-counter.XXXXXXXX")"+trap 'rm -rf -- "$counter_build_dir"' EXIT+c++ -O3 -std=c++17 -fPIC -shared counter.cpp -o "$counter_build_dir/counter.so"+# Copy to a new inode, then replace atomically. Existing ranks retain their library.+cp -- "$counter_build_dir/counter.so" counter.so.new+mv -f -- counter.so.new counter.sodiff --git a/solution/build_optimizer.sh b/solution/build_optimizer.shnew file mode 100755index 0000000000000000000000000000000000000000..9371d01fc8428ab7906422cf7d201660b5704437--- /dev/null+++ b/solution/build_optimizer.sh@@ -0,0 +1,18 @@+#!/usr/bin/env bash+# Optional development rebuild; replay uses the packaged Ascend 910B binary.+set -euo pipefail+cd -- "$(dirname -- "${BASH_SOURCE[0]}")"+: "${ASCEND_HOME_PATH:?CANN development installation is required for rebuilding}"+optimizer_build_dir="$(mktemp -d "${TMPDIR:-/tmp}/openbuild-adam.XXXXXXXX")"+trap 'rm -rf -- "$optimizer_build_dir"' EXIT+"$ASCEND_HOME_PATH/bin/bisheng" -x cce -O2 \+ --cce-aicore-only --cce-aicore-arch=dav-c220-vec --cce-auto-sync \+ -std=c++17 \+ -I"$ASCEND_HOME_PATH/asc" \+ -I"$ASCEND_HOME_PATH/asc/include" \+ -I"$ASCEND_HOME_PATH/asc/include/basic_api" \+ -I"$ASCEND_HOME_PATH/asc/impl" \+ -I"$ASCEND_HOME_PATH/asc/impl/basic_api" \+ -c adam_ascendc.cpp -o "$optimizer_build_dir/adam_ascendc.o"+cp -- "$optimizer_build_dir/adam_ascendc.o" adam_ascendc.o.new+mv -f -- adam_ascendc.o.new adam_ascendc.odiff --git a/solution/checkpoint_codec.py b/solution/checkpoint_codec.pynew file mode 100644index 0000000000000000000000000000000000000000..e629d628d28d19b24e73a53ecb61a13b39fbac02--- /dev/null+++ b/solution/checkpoint_codec.py@@ -0,0 +1,78 @@+"""Lossless, bounded-memory byte-shuffled Zstandard checkpoint frames."""+import ctypes+from pathlib import Path+import struct++import numpy as np+++_root = Path(__file__).parent+_zstd = ctypes.CDLL(str(_root / "libzstd.so.1"))+_zstd.ZSTD_compressBound.argtypes = [ctypes.c_size_t]+_zstd.ZSTD_compressBound.restype = ctypes.c_size_t+_zstd.ZSTD_compress.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int]+_zstd.ZSTD_compress.restype = ctypes.c_size_t+_zstd.ZSTD_decompress.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p, ctypes.c_size_t]+_zstd.ZSTD_decompress.restype = ctypes.c_size_t+_zstd.ZSTD_isError.argtypes = [ctypes.c_size_t]+_zstd.ZSTD_isError.restype = ctypes.c_uint+_zstd.ZSTD_getErrorName.argtypes = [ctypes.c_size_t]+_zstd.ZSTD_getErrorName.restype = ctypes.c_char_p++try:+ _native = ctypes.CDLL(str(_root / "counter.so"))+ for _name in ("shuffle_bytes", "unshuffle_bytes"):+ _fn = getattr(_native, _name)+ _fn.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint64, ctypes.c_uint]+ _fn.restype = None+except (OSError, AttributeError):+ _native = None+++MAGIC = b"OBCKZ001"+HEADER = struct.Struct("<8sIQ")+FRAME = struct.Struct("<II")+++def _check(value):+ if _zstd.ZSTD_isError(value):+ raise ValueError(_zstd.ZSTD_getErrorName(value).decode())+ return value+++def encode(array):+ width = array.dtype.itemsize+ assert width in (2, 4) and array.flags.c_contiguous+ src = array.view(np.uint8).reshape(-1)+ shuffled = np.empty_like(src)+ if _native is not None:+ _native.shuffle_bytes(src.ctypes.data, shuffled.ctypes.data, array.size, width)+ else:+ shuffled[:] = src.reshape(-1, width).T.reshape(-1)+ dst = np.empty(_zstd.ZSTD_compressBound(src.size), dtype=np.uint8)+ size = _check(_zstd.ZSTD_compress(dst.ctypes.data, dst.size, shuffled.ctypes.data, shuffled.size, 1))+ return FRAME.pack(src.size, size) + dst[:size].tobytes()+++def decode(payload, raw_size, width, output=None):+ if width not in (2, 4) or raw_size % width:+ raise ValueError("invalid checkpoint frame dimensions")+ shuffled = np.empty(raw_size, dtype=np.uint8)+ size = _check(_zstd.ZSTD_decompress(shuffled.ctypes.data, raw_size, payload, len(payload)))+ if size != raw_size:+ raise ValueError("checkpoint frame length differs")+ dst = np.empty_like(shuffled) if output is None else output.view(np.uint8).reshape(-1)+ if dst.size != raw_size or not dst.flags.c_contiguous:+ raise ValueError("checkpoint destination size differs")+ if _native is not None:+ _native.unshuffle_bytes(shuffled.ctypes.data, dst.ctypes.data, raw_size // width, width)+ else:+ dst[:] = shuffled.reshape(width, -1).T.reshape(-1)+ return dst.view(np.dtype("<u2") if width == 2 else np.dtype("<f4"))+++def read_exact(f, size):+ value = f.read(size)+ if len(value) != size:+ raise ValueError("truncated checkpoint")+ return valuediff --git a/solution/counter.cpp b/solution/counter.cppnew file mode 100644index 0000000000000000000000000000000000000000..5836f483377791245d07d3c918f6d68a8f86b83b--- /dev/null+++ b/solution/counter.cpp@@ -0,0 +1,57 @@+// Stateless canonical initialization. No floating-point arithmetic except an+// exactly representable binary scaling; explicit round-to-nearest-even BF16.+#include <cstdint>+#include <cstring>++extern "C" void canonical_bf16(uint16_t* out, uint64_t seed_and_name,+ uint64_t start, uint64_t count) {+ for (uint64_t j = 0; j < count; ++j) {+ uint64_t z = seed_and_name ^ ((start + j) * UINT64_C(0x9e3779b97f4a7c15));+ z += UINT64_C(0x9e3779b97f4a7c15);+ z = (z ^ (z >> 30)) * UINT64_C(0xbf58476d1ce4e5b9);+ z = (z ^ (z >> 27)) * UINT64_C(0x94d049bb133111eb);+ z ^= z >> 31;+ int32_t q = static_cast<int32_t>(z >> 52) - 2048;+ float value = static_cast<float>(q) * (1.0f / 65536.0f);+ uint32_t bits;+ std::memcpy(&bits, &value, sizeof(bits));+ bits += 0x7fff + ((bits >> 16) & 1);+ out[j] = static_cast<uint16_t>(bits >> 16);+ }+}++// Lossless byte-plane transforms improve compression of floating-point state.+// The independent planes let the compiler use interleaved SIMD loads/stores.+extern "C" void shuffle_bytes(const uint8_t* __restrict__ in,+ uint8_t* __restrict__ out,+ uint64_t n, unsigned width) {+ if (width == 4) {+ auto b = out + n; auto c = b + n; auto d = c + n;+ for (uint64_t j = 0; j < n; ++j) {+ out[j] = in[4*j]; b[j] = in[4*j+1];+ c[j] = in[4*j+2]; d[j] = in[4*j+3];+ }+ } else if (width == 2) {+ auto b = out + n;+ for (uint64_t j = 0; j < n; ++j) {+ out[j] = in[2*j]; b[j] = in[2*j+1];+ }+ }+}++extern "C" void unshuffle_bytes(const uint8_t* __restrict__ in,+ uint8_t* __restrict__ out,+ uint64_t n, unsigned width) {+ if (width == 4) {+ auto b = in + n; auto c = b + n; auto d = c + n;+ for (uint64_t j = 0; j < n; ++j) {+ out[4*j] = in[j]; out[4*j+1] = b[j];+ out[4*j+2] = c[j]; out[4*j+3] = d[j];+ }+ } else if (width == 2) {+ auto b = in + n;+ for (uint64_t j = 0; j < n; ++j) {+ out[2*j] = in[j]; out[2*j+1] = b[j];+ }+ }+}diff --git a/solution/dependencies.json b/solution/dependencies.jsonnew file mode 100644index 0000000000000000000000000000000000000000..8bf288a484475eb5293013492509b89d39cd2583--- /dev/null+++ b/solution/dependencies.json@@ -0,0 +1,39 @@+{+ "schema_version": 1,+ "base_runtime": [+ "Python 3.11",+ "NumPy",+ "PyTorch",+ "torch_npu",+ "CANN/HCCL"+ ],+ "bundled": [+ {+ "name": "zstd",+ "version": "1.5.7",+ "file": "libzstd.so.1",+ "upstream": "https://github.com/facebook/zstd",+ "source_package": "zstd-1.5.7-hc8aa508_0 (linux-aarch64)",+ "sha256": "3e97d1dd1e9d7bb745caef88cf48b81187435aea20aeaae07946953f056382ab",+ "license": "LICENSE.zstd"+ },+ {+ "name": "canonical counter and byte shuffle",+ "file": "counter.so",+ "source": "counter.cpp",+ "build": "build_native.sh",+ "architecture": "aarch64",+ "sha256": "3c6d0dc33593b6315b5b5199ce40cf062f79688635a674722c8e72969f25fc37"+ },+ {+ "name": "AscendC AdamW vector kernel",+ "file": "adam_ascendc.o",+ "source": "adam_ascendc.cpp",+ "build": "build_optimizer.sh",+ "target": "Ascend 910B (dav-c220-vec)",+ "build_runtime": "CANN 9.0.0",+ "replay_runtime": "CANN libruntime.so",+ "sha256": "f6d1653737ee17a6b922463108d81b9bcb7b61251f02bd42af4bebad342ca662"+ }+ ]+}diff --git a/solution/initialization.py b/solution/initialization.pynew file mode 100644index 0000000000000000000000000000000000000000..c4b54b670b52cb7ca8f8b92997a8e4aeecdd45c3--- /dev/null+++ b/solution/initialization.py@@ -0,0 +1,64 @@+"""Partition-independent public counter initialization; no model weights on disk."""+import ctypes+from pathlib import Path++import numpy as np++MASK64 = (1 << 64) - 1++try:+ _library = ctypes.CDLL(str(Path(__file__).with_name("counter.so")))+ _counter = _library.canonical_bf16+ _counter.argtypes = (ctypes.c_void_p, ctypes.c_uint64, ctypes.c_uint64, ctypes.c_uint64)+ _counter.restype = None+except OSError:+ _counter = None+++def name_hash(name):+ value = 0xCBF29CE484222325+ for byte in name.encode("utf8"):+ value = ((value ^ byte) * 0x100000001B3) & MASK64+ return value+++def initial_bf16_bits(name, start, count):+ """Return exact BF16 bits for a contiguous interval of the canonical tensor."""+ if "norm.weight" in name or "layernorm.weight" in name:+ return np.full(count, 0x3F80, dtype=np.uint16)+ if _counter is not None:+ bits = np.empty(count, dtype=np.uint16)+ _counter(bits.ctypes.data, 0x51454E334F50454E ^ name_hash(name), start, count)+ return bits+ index = np.arange(start, start + count, dtype=np.uint64)+ with np.errstate(over="ignore"):+ z = index * np.uint64(0x9E3779B97F4A7C15)+ z ^= np.uint64(0x51454E334F50454E ^ name_hash(name))+ z += np.uint64(0x9E3779B97F4A7C15)+ z = (z ^ (z >> 30)) * np.uint64(0xBF58476D1CE4E5B9)+ z = (z ^ (z >> 27)) * np.uint64(0x94D049BB133111EB)+ z ^= z >> 31+ q = (z >> 52).astype(np.int32) - 2048+ bits = (q.astype(np.float32) * np.float32(2.0 ** -16)).view(np.uint32)+ return ((bits + np.uint32(0x7FFF) + ((bits >> 16) & 1)) >> 16).astype(np.uint16)+++def canonical_specs():+ yield "model.embed_tokens.weight", (151936, 2560)+ for layer in range(36):+ base = f"model.layers.{layer}."+ for suffix, shape in (+ ("input_layernorm.weight", (2560,)),+ ("self_attn.q_proj.weight", (4096, 2560)),+ ("self_attn.k_proj.weight", (1024, 2560)),+ ("self_attn.v_proj.weight", (1024, 2560)),+ ("self_attn.q_norm.weight", (128,)),+ ("self_attn.k_norm.weight", (128,)),+ ("self_attn.o_proj.weight", (2560, 4096)),+ ("post_attention_layernorm.weight", (2560,)),+ ("mlp.gate_proj.weight", (9728, 2560)),+ ("mlp.up_proj.weight", (9728, 2560)),+ ("mlp.down_proj.weight", (2560, 9728)),+ ):+ yield base + suffix, shape+ yield "model.norm.weight", (2560,)diff --git a/solution/launch.py b/solution/launch.pynew file mode 100644index 0000000000000000000000000000000000000000..3e50d985860fac1ba8660c9438f4a58911e96b8f--- /dev/null+++ b/solution/launch.py@@ -0,0 +1,69 @@+"""Own and join both ranks. Publish success only after their successful exit."""+import json+import os+from pathlib import Path+import signal+import socket+import subprocess+import sys+import time+++def main():+ assert os.environ["OPENBUILD_DEVICE_IDS"] == "0,1"+ assert os.environ["ASCEND_RT_VISIBLE_DEVICES"] == "0,1"+ action = os.environ["OPENBUILD_ACTION"]+ assert action in ("train", "fresh_next_step_probe")+ with socket.socket() as sock:+ sock.bind(("127.0.0.1", 0))+ port = sock.getsockname()[1]+ children = []++ def stop(signum, frame):+ for child in children:+ if child.poll() is None:+ child.terminate()+ raise KeyboardInterrupt++ signal.signal(signal.SIGTERM, stop)+ signal.signal(signal.SIGINT, stop)+ success = False+ try:+ for rank in range(2):+ env = dict(os.environ, RANK=str(rank), LOCAL_RANK=str(rank), WORLD_SIZE="2", MASTER_ADDR="127.0.0.1", MASTER_PORT=str(port))+ children.append(subprocess.Popen([sys.executable, "-B", str(Path(__file__).with_name("worker.py"))], env=env))+ while True:+ statuses = [child.poll() for child in children]+ if any(code is not None and code != 0 for code in statuses):+ raise RuntimeError(f"training rank failed: {statuses}")+ if all(code == 0 for code in statuses):+ success = True+ break+ time.sleep(0.1)+ finally:+ for child in children:+ if child.poll() is None:+ child.terminate()+ deadline = time.monotonic() + 10+ for child in children:+ try:+ child.wait(timeout=max(0.1, deadline-time.monotonic()))+ except subprocess.TimeoutExpired:+ child.kill()+ child.wait()+ if success and action == "train":+ output = Path(os.environ["OPENBUILD_OUTPUT_DIR"])+ result = dict(schema_version=1, kind="openbuild_training_result", task_id="openbuild_training_qwen3_4b_2dev_v1",+ profile_id=os.environ["OPENBUILD_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=dict(architecture="Qwen3-4B-Base", parallelism="two data-parallel ranks with sharded FP32 AdamW state",+ model_storage="bf16", gradient_accumulation="fp32", attention="CANN fused causal GQA",+ dependencies="base Python, NumPy, PyTorch, torch_npu"))+ temporary = output / "result.json.tmp"+ temporary.write_text(json.dumps(result, indent=2) + "\n")+ os.replace(temporary, output / "result.json")+++if __name__ == "__main__":+ main()diff --git a/solution/manifest.json b/solution/manifest.jsonnew file mode 100644index 0000000000000000000000000000000000000000..9d805f12f62917c876d7d1a1f944ce691c78b8e0--- /dev/null+++ b/solution/manifest.json@@ -0,0 +1,7 @@+{+ "schema_version": 1,+ "kind": "openbuild_training_solution",+ "task_id": "openbuild_training_qwen3_4b_2dev_v1",+ "entrypoints": {"bootstrap": "bootstrap.sh", "train": "train.sh"},+ "offline_bootstrap": true+}diff --git a/solution/model.py b/solution/model.pynew file mode 100644index 0000000000000000000000000000000000000000..975ec37f2682117e3326e750303a157026733d3d--- /dev/null+++ b/solution/model.py@@ -0,0 +1,157 @@+"""Qwen3-4B with BF16 storage and persistent FP32 gradient accumulation."""+import math+import os++import torch+import torch.nn.functional as F+import torch_npu+from torch.utils.checkpoint import checkpoint+++class Linear(torch.autograd.Function):+ @staticmethod+ def forward(ctx, x, weight):+ ctx.save_for_backward(x, weight)+ return F.linear(x, weight)++ @staticmethod+ def backward(ctx, dy):+ x, weight = ctx.saved_tensors+ dy = dy.reshape(-1, dy.shape[-1])+ dx = torch.matmul(dy, weight).view_as(x)+ # Each microbatch's weight derivative is widened before accumulation.+ dw = torch.matmul(dy.t(), x.reshape(-1, x.shape[-1]))+ weight.main_grad.add_(dw)+ return dx, None+++class Embedding(torch.autograd.Function):+ @staticmethod+ def forward(ctx, ids, weight):+ ctx.save_for_backward(ids)+ ctx.weight = weight+ return F.embedding(ids, weight)++ @staticmethod+ def backward(ctx, dy):+ (ids,) = ctx.saved_tensors+ ctx.weight.main_grad.index_add_(0, ids.reshape(-1), dy.reshape(-1, dy.shape[-1]).float())+ return None, None+++def linear(x, weight):+ return Linear.apply(x, weight)+++def rmsnorm(x, weight):+ return torch_npu.npu_rms_norm(x, weight, 1.0e-6)[0]+++def rotate_half(x):+ a, b = x.chunk(2, dim=-1)+ return torch.cat((-b, a), dim=-1)+++class Qwen:+ def __init__(self, parameters, device):+ self.p = parameters+ self.checkpoint_mode = os.environ.get("OPENBUILD_RECOMPUTE", "none")+ if self.checkpoint_mode not in ("none", "block", "mlp"):+ raise ValueError("OPENBUILD_RECOMPUTE must be none, block, or mlp")+ self.mask = torch.triu(torch.ones((2048, 2048), device=device, dtype=torch.bool), diagonal=1)+ self.inv_freq = 1.0 / (1000000.0 ** (torch.arange(0, 128, 2, device=device, dtype=torch.float32) / 128))++ def mlp(self, x, layer):+ p = self.p+ base = f"model.layers.{layer}."+ x = rmsnorm(x, p[base + "post_attention_layernorm.weight"])+ gate = linear(x, p[base + "mlp.gate_proj.weight"])+ up = linear(x, p[base + "mlp.up_proj.weight"])+ return linear(F.silu(gate) * up, p[base + "mlp.down_proj.weight"])++ def block(self, x, cos, sin, layer):+ p = self.p+ base = f"model.layers.{layer}."+ attn = base + "self_attn."+ residual = x+ x = rmsnorm(x, p[base + "input_layernorm.weight"])+ batch, seq, _ = x.shape+ q = linear(x, p[attn + "q_proj.weight"]).view(batch, seq, 32, 128)+ k = linear(x, p[attn + "k_proj.weight"]).view(batch, seq, 8, 128)+ v = linear(x, p[attn + "v_proj.weight"]).view(batch, seq, 8, 128)+ q = rmsnorm(q, p[attn + "q_norm.weight"])+ k = rmsnorm(k, p[attn + "k_norm.weight"])+ q = q * cos + rotate_half(q) * sin+ k = k * cos + rotate_half(k) * sin+ out = torch_npu.npu_fusion_attention(+ q, k, v, 32, "BSND", atten_mask=self.mask,+ scale=1.0 / math.sqrt(128), keep_prob=1.0, sparse_mode=3,+ )[0]+ x = residual + linear(out.reshape(batch, seq, 4096), p[attn + "o_proj.weight"])+ if self.checkpoint_mode == "mlp":+ y = checkpoint(self.mlp, x, layer, use_reentrant=True, preserve_rng_state=False)+ else:+ y = self.mlp(x, layer)+ return x + y++ def __call__(self, ids, positions):+ phase = positions.float().unsqueeze(-1) * self.inv_freq+ phase = torch.cat((phase, phase), dim=-1)+ cos, sin = phase.cos().bfloat16().unsqueeze(2), phase.sin().bfloat16().unsqueeze(2)+ x = Embedding.apply(ids, self.p["model.embed_tokens.weight"])+ for layer in range(36):+ if self.checkpoint_mode == "block":+ x = checkpoint(self.block, x, cos, sin, layer, use_reentrant=True, preserve_rng_state=False)+ else:+ x = self.block(x, cos, sin, layer)+ return rmsnorm(x, self.p["model.norm.weight"])+++class LanguageModelLoss(torch.autograd.Function):+ """Chunked full-vocabulary FP32 cross entropy with exact pre-shifted labels.++ Cache the BF16 logit derivative after the FP32 softmax. This avoids a second+ vocabulary projection and releases FP32 logits before transformer backward.+ The tied output and input derivatives use the same FP32 accumulation buffer.+ """+ @staticmethod+ def forward(ctx, hidden, weight, labels, mask, denominator, coordinates):+ h = hidden.reshape(-1, hidden.shape[-1])+ labels, mask = labels.reshape(-1), mask.reshape(-1)+ labels = torch.where(mask != 0, labels, 0)+ ctx.hidden_shape = hidden.shape+ ctx.chunk = 2048+ loss = torch.zeros((), device=h.device, dtype=torch.float32)+ selected = torch.zeros(len(coordinates), device=h.device, dtype=torch.float32)+ derivatives = []+ for start in range(0, h.shape[0], ctx.chunk):+ end = min(start + ctx.chunk, h.shape[0])+ logits = F.linear(h[start:end], weight)+ for i, (row, vocab) in enumerate(coordinates):+ if start <= row < end:+ selected[i] = logits[row - start, vocab].float()+ values = logits.float()+ del logits+ nll = torch.logsumexp(values, dim=-1) - values.gather(1, labels[start:end, None]).squeeze(1)+ loss.add_((nll * mask[start:end]).sum() / denominator)+ prob = values.softmax(dim=-1)+ del values+ prob.scatter_add_(1, labels[start:end, None], -torch.ones((end-start, 1), device=h.device))+ prob.mul_((mask[start:end].float() / denominator)[:, None])+ derivatives.append(prob.bfloat16())+ del prob+ ctx.save_for_backward(h, weight, *derivatives)+ ctx.mark_non_differentiable(selected)+ return loss, selected++ @staticmethod+ def backward(ctx, dloss, unused):+ h, weight, *derivatives = ctx.saved_tensors+ dh = torch.empty_like(h)+ for start, saved in zip(range(0, h.shape[0], ctx.chunk), derivatives):+ end = min(start + ctx.chunk, h.shape[0])+ dy = saved * dloss+ dh[start:end] = torch.matmul(dy, weight)+ # Keep the vocabulary projection's accumulation in FP32 as well.+ weight.main_grad.add_(torch.matmul(dy.t(), h[start:end]))+ return dh.view(ctx.hidden_shape), None, None, None, None, Nonediff --git a/solution/native_optimizer.py b/solution/native_optimizer.pynew file mode 100644index 0000000000000000000000000000000000000000..794057085a996bd4c07b0a2e36c716c7f77f45c7--- /dev/null+++ b/solution/native_optimizer.py@@ -0,0 +1,76 @@+"""Thin CANN runtime launcher for the source-included AscendC AdamW kernel."""+import ctypes+from pathlib import Path++import torch+import torch_npu+++class Arguments(ctypes.Structure):+ _fields_ = [(name, ctypes.c_void_p) for name in ("p", "m", "v", "g", "w")] + [+ ("n", ctypes.c_uint32), ("clip", ctypes.c_float), ("lr", ctypes.c_float),+ ("bc1", ctypes.c_float), ("bc2", ctypes.c_float), ("wd", ctypes.c_float),+ ]+++class DeviceBinary(ctypes.Structure):+ # CANN runtime/runtime/kernel.h: rtDevBinary_t (native AArch64 alignment).+ _fields_ = [("magic", ctypes.c_uint32), ("version", ctypes.c_uint32),+ ("data", ctypes.c_void_p), ("length", ctypes.c_uint64)]+++class NativeAdam:+ def __init__(self, device):+ root = Path(__file__).parent+ self.device = device+ self.runtime = ctypes.CDLL("libruntime.so")+ self.image = ctypes.create_string_buffer((root / "adam_ascendc.o").read_bytes())+ self.binary = DeviceBinary(0x41415246, 0, ctypes.addressof(self.image), len(self.image)-1)+ self.module = ctypes.c_void_p()+ register = self.runtime.rtDevBinaryRegister+ register.argtypes = [ctypes.POINTER(DeviceBinary), ctypes.POINTER(ctypes.c_void_p)]+ register.restype = ctypes.c_int+ self._check(register(ctypes.byref(self.binary), ctypes.byref(self.module)), "binary registration")+ # CANN identifies the host stub by its stable address; it never executes+ # the stub. Keep both its storage and the device image alive for the run.+ self.stub = ctypes.c_uint64()+ self.function = ctypes.addressof(self.stub)+ self.name = ctypes.create_string_buffer(b"openbuild_adam")+ register_function = self.runtime.rtFunctionRegister+ register_function.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_char_p, ctypes.c_void_p, ctypes.c_uint32]+ register_function.restype = ctypes.c_int+ self._check(register_function(self.module, self.function, self.name, ctypes.addressof(self.name), 0), "function registration")+ self.launch = self.runtime.rtKernelLaunch+ self.launch.argtypes = [ctypes.c_void_p, ctypes.c_uint32, ctypes.c_void_p, ctypes.c_uint32, ctypes.c_void_p, ctypes.c_void_p]+ self.launch.restype = ctypes.c_int++ @staticmethod+ def _check(result, operation):+ if result:+ raise RuntimeError(f"CANN optimizer {operation} failed: {result}")++ def __call__(self, p, m, v, g, w, coefficient, lr, update, decay):+ n = p.numel()+ if n % 16 or not (0 < n < 2**31):+ raise ValueError("native optimizer requires a positive, aligned canonical interval")+ args = Arguments(p.data_ptr(), m.data_ptr(), v.data_ptr(), g.data_ptr(), w.data_ptr(),+ n, coefficient, lr, 1.0-0.9**update, 1.0-0.95**update, decay)+ stream = torch_npu._C._npu_getCurrentRawStream(self.device)+ result = self.launch(self.function, min(48, (n+2047)//2048), ctypes.byref(args), ctypes.sizeof(args), None, stream)+ self._check(result, "launch")+++if __name__ == "__main__":+ torch.npu.set_device(0)+ torch.npu.set_compile_mode(jit_compile=False)+ n = 65536+ p = torch.ones(n, dtype=torch.float32, device="npu")+ m = torch.zeros_like(p); v = torch.zeros_like(p)+ g = torch.full_like(p, 0.000123)+ w = torch.zeros_like(p, dtype=torch.bfloat16)+ optimizer = NativeAdam(0)+ torch.npu.synchronize()+ optimizer(p, m, v, g, w, 0.31, 1.25e-6, 1, 0.1)+ torch.npu.synchronize()+ print("native scalars", p[0].item(), m[0].item(), v[0].item(), w[0].item(), flush=True)+ assert m[0].item() != 0 and w[0].item() == 1diff --git a/solution/state.py b/solution/state.pynew file mode 100644index 0000000000000000000000000000000000000000..11f092405ee0736be59a23b10e90bcd71a277ca9--- /dev/null+++ b/solution/state.py@@ -0,0 +1,332 @@+"""Flat canonical state, sharded AdamW, and complete streaming checkpoints."""+import json+import math+import os+from pathlib import Path+from collections import deque+from concurrent.futures import ThreadPoolExecutor++import numpy as np+import torch+import torch.distributed as dist++from initialization import canonical_specs, initial_bf16_bits+++CHUNK = 16 * 1024 * 1024+++def write_json(path, value):+ path = Path(path)+ temporary = path.with_name(path.name + ".tmp")+ with temporary.open("w") as f:+ json.dump(value, f, indent=2, allow_nan=False)+ f.write("\n")+ f.flush()+ os.fsync(f.fileno())+ os.replace(temporary, path)+++class State:+ def __init__(self, rank, device, checkpoint=None):+ self.rank, self.device = rank, device+ self.checkpoint_encoding = os.environ.get("OPENBUILD_CHECKPOINT_ENCODING", "raw")+ assert self.checkpoint_encoding in ("raw", "zstd-byte-shuffle-v1")+ self.specs = []+ offset = 0+ for name, shape in canonical_specs():+ count = math.prod(shape)+ self.specs.append(dict(name=name, shape=shape, offset=offset, count=count))+ offset += count+ self.total = offset+ assert self.total % 2 == 0+ self.shard_size = self.total // 2+ self.begin = rank * self.shard_size+ self.end = self.begin + self.shard_size+ self.model = torch.empty(self.total, dtype=torch.bfloat16, device=device)+ self.master = torch.empty(self.shard_size, dtype=torch.float32, device=device)+ self.first = torch.zeros_like(self.master)+ self.second = torch.zeros_like(self.master)+ self.gradient = torch.zeros(self.total, dtype=torch.float32, device=device)+ self.parameters = {}+ self.by_name = {}+ for spec in self.specs:+ name, start, count = spec["name"], spec["offset"], spec["count"]+ p = torch.nn.Parameter(self.model[start:start+count].view(spec["shape"]), requires_grad=True)+ p.main_grad = self.gradient[start:start+count].view(spec["shape"])+ if len(spec["shape"]) == 1:+ p.register_post_accumulate_grad_hook(self._accumulate_norm)+ self.parameters[name] = p+ self.by_name[name] = spec+ self.committed = 0+ self.next_update = 1+ self.next_sample = 0+ self.last_sample_ids = []+ if checkpoint is None:+ self.initialize()+ else:+ self.load(checkpoint)+ self.synchronize_model()++ @staticmethod+ def _accumulate_norm(p):+ p.main_grad.add_(p.grad)+ p.grad = None++ def initialize(self):+ # Counter blocks are independent. A bounded host pool computes future+ # blocks while the rank copies completed blocks to its canonical range.+ # Consume futures in order, so scheduling never changes model placement.+ pending = deque()+ def copy_block(at, count, future):+ source = torch.from_numpy(future.result()).view(torch.bfloat16)+ self.model[at:at+count].copy_(source)+ with ThreadPoolExecutor(max_workers=4) as pool:+ for spec in self.specs:+ start = max(spec["offset"], self.begin)+ end = min(spec["offset"] + spec["count"], self.end)+ for at in range(start, end, 4 * 1024 * 1024):+ count = min(4 * 1024 * 1024, end - at)+ pending.append((at, count, pool.submit(initial_bf16_bits, spec["name"], at-spec["offset"], count)))+ if len(pending) == 8:+ copy_block(*pending.popleft())+ while pending:+ copy_block(*pending.popleft())+ self.master.copy_(self.model[self.begin:self.end])++ def synchronize_model(self):+ mode = os.environ.get("OPENBUILD_MODEL_EXCHANGE", "all_gather")+ if mode == "all_gather":+ # Exchange both owners concurrently. Bounded staging avoids a second+ # complete model allocation while retaining canonical storage order.+ bucket = 64 * 1024 * 1024+ staging = torch.empty(2*bucket, dtype=torch.bfloat16, device=self.device)+ for at in range(0, self.shard_size, bucket):+ count = min(bucket, self.shard_size-at)+ dist.all_gather_into_tensor(staging[:2*count], self.model[self.begin+at:self.begin+at+count])+ self.model[at:at+count].copy_(staging[:count])+ self.model[self.shard_size+at:self.shard_size+at+count].copy_(staging[count:2*count])+ return+ if mode != "broadcast":+ raise ValueError("unsupported model exchange")+ for owner in range(2):+ begin = owner * self.shard_size+ end = begin + self.shard_size+ for at in range(begin, end, CHUNK):+ dist.broadcast(self.model[at:min(at+CHUNK, end)], src=owner)++ def reduce_gradient(self):+ # Each local backward uses the GLOBAL masked-token denominator. SUM+ # therefore gives the global mean derivative without a second division.+ mode = os.environ.get("OPENBUILD_GRADIENT_REDUCTION", "reduce_scatter")+ if mode == "reduce_scatter":+ # Only the owning rank needs each reduced gradient. Pair matching+ # intervals of the two shards into bounded collective buckets.+ bucket = 64 * 1024 * 1024+ staging = torch.empty(2 * bucket, dtype=torch.float32, device=self.device)+ reduced = torch.empty(bucket, dtype=torch.float32, device=self.device)+ for at in range(0, self.shard_size, bucket):+ count = min(bucket, self.shard_size-at)+ staging[:count].copy_(self.gradient[at:at+count])+ staging[count:2*count].copy_(self.gradient[self.shard_size+at:self.shard_size+at+count])+ dist.reduce_scatter_tensor(reduced[:count], staging[:2*count], op=dist.ReduceOp.SUM)+ self.gradient[self.begin+at:self.begin+at+count].copy_(reduced[:count])+ elif mode == "all_reduce":+ for at in range(0, self.total, CHUNK):+ dist.all_reduce(self.gradient[at:at+CHUNK], op=dist.ReduceOp.SUM)+ else:+ raise ValueError("unsupported gradient reduction")+ squares = torch.zeros((), device=self.device, dtype=torch.float32)+ for at in range(self.begin, self.end, CHUNK):+ g = self.gradient[at:min(at+CHUNK, self.end)]+ squares.add_(torch.sum(g * g))+ dist.all_reduce(squares)+ return float(squares.sqrt().item())++ @torch.no_grad()+ def step(self, update, norm):+ coefficient = min(1.0, 1.0 / (norm + 1e-6))+ lr = 0.000000125 + 0.5 * (0.00000125 - 0.000000125) * (1 + math.cos(math.pi * min(update-1, 29) / 29))+ optimizer = os.environ.get("OPENBUILD_OPTIMIZER", "native")+ if optimizer == "native":+ from native_optimizer import NativeAdam+ if not hasattr(self, "native_adam"):+ self.native_adam = NativeAdam(self.rank)+ # The raw CANN launcher shares the current PyTorch stream. Drain the+ # host task queue before submitting kernels directly, and finish the+ # native interval before enqueueing collective model broadcasts.+ torch.npu.synchronize()+ for spec in self.specs:+ start = max(spec["offset"], self.begin)+ end = min(spec["offset"]+spec["count"], self.end)+ if start < end:+ lo, hi = start-self.begin, end-self.begin+ self.native_adam(self.master[lo:hi], self.first[lo:hi], self.second[lo:hi],+ self.gradient[start:end], self.model[start:end],+ coefficient, lr, update, 0.1 if len(spec["shape"]) >= 2 else 0.0)+ torch.npu.synchronize()+ self.synchronize_model()+ return+ if optimizer != "torch":+ raise ValueError("unsupported optimizer implementation")+ for spec in self.specs:+ start, end = max(spec["offset"], self.begin), min(spec["offset"]+spec["count"], self.end)+ for at in range(start, end, CHUNK):+ stop = min(at + CHUNK, end)+ lo, hi = at - self.begin, stop - self.begin+ g = self.gradient[at:stop]+ g.mul_(coefficient)+ p, m, v = self.master[lo:hi], self.first[lo:hi], self.second[lo:hi]+ m.mul_(0.9).add_(g, alpha=0.1)+ v.mul_(0.95).addcmul_(g, g, value=0.05)+ direction = m / (1.0 - 0.9 ** update)+ denominator = (v / (1.0 - 0.95 ** update)).sqrt_().add_(1e-8)+ direction.div_(denominator)+ if len(spec["shape"]) >= 2:+ direction.add_(p, alpha=0.1)+ p.add_(direction, alpha=-lr)+ self.model[at:stop].copy_(p)+ self.synchronize_model()++ def projection(self, category, selector):+ spec = self.by_name[selector["canonical_parameter_name"]]+ index = int(selector["flat_index"])+ if not 0 <= index < spec["count"]:+ raise ValueError("parameter selector outside canonical tensor")+ index += spec["offset"]+ # Exactly one rank contributes each canonical scalar, including replicas.+ if not self.begin <= index < self.end:+ return torch.zeros((), device=self.device, dtype=torch.float32)+ if category == "gradients":+ return self.gradient[index]+ if category == "model_parameters":+ return self.model[index].float()+ values = {"master_parameters": self.master, "first_moments": self.first, "second_moments": self.second}[category]+ return values[index-self.begin]++ def commit(self, update, global_batch, sample_ids):+ assert update == self.next_update+ self.committed = update+ self.next_update = update + 1+ self.next_sample += global_batch+ self.last_sample_ids = [int(x) for x in sample_ids]++ def metadata(self, profile):+ return dict(+ schema_version=1, profile_id=profile, rank=self.rank, world_size=2,+ canonical_specs=self.specs, aliases={"lm_head.weight":"model.embed_tokens.weight"},+ shard_begin=self.begin, shard_end=self.end, total_elements=self.total,+ committed_update=self.committed,+ parameter_steps={spec["name"]:self.committed for spec in self.specs},+ scheduler={"next_update_index":self.next_update, "decay_updates":30},+ data_cursor={"next_update_index":self.next_update, "next_global_sample_ordinal":self.next_sample,+ "last_global_sample_ids":self.last_sample_ids},+ tensor_dtypes={"model":"bfloat16", "master_parameters":"float32", "first_moments":"float32", "second_moments":"float32"},+ tensor_encoding=self.checkpoint_encoding,+ )++ def save(self, root, profile):+ root = Path(root)+ names = []+ for name, tensor in (("model", self.model[self.begin:self.end]), ("master_parameters",self.master), ("first_moments", self.first), ("second_moments",self.second)):+ filename = f"rank{self.rank}.{name}.bin"+ temporary = root / (filename + ".tmp")+ with temporary.open("wb") as f:+ if self.checkpoint_encoding == "zstd-byte-shuffle-v1":+ import checkpoint_codec as codec+ width = tensor.element_size()+ f.write(codec.HEADER.pack(codec.MAGIC, width, tensor.numel()))+ pending = deque()+ buffers = [torch.empty(CHUNK, dtype=tensor.dtype, device="cpu", pin_memory=True) for _ in range(8)]+ available = deque(range(len(buffers)))+ with ThreadPoolExecutor(max_workers=4) as pool:+ for at in range(0, tensor.numel(), CHUNK):+ if not available:+ buffer_id, future = pending.popleft()+ f.write(future.result())+ available.append(buffer_id)+ buffer_id = available.popleft()+ cpu = buffers[buffer_id][:min(CHUNK, tensor.numel()-at)]+ cpu.copy_(tensor[at:at+CHUNK].detach())+ array = cpu.view(torch.uint16).numpy() if tensor.dtype == torch.bfloat16 else cpu.numpy()+ pending.append((buffer_id, pool.submit(codec.encode, array)))+ while pending:+ _, future = pending.popleft()+ f.write(future.result())+ else:+ buffer = torch.empty(CHUNK, dtype=tensor.dtype, device="cpu", pin_memory=True)+ for at in range(0, tensor.numel(), CHUNK):+ cpu = buffer[:min(CHUNK, tensor.numel()-at)]+ cpu.copy_(tensor[at:at+CHUNK].detach())+ array = cpu.view(torch.uint16).numpy() if tensor.dtype == torch.bfloat16 else cpu.numpy()+ array.tofile(f)+ f.flush()+ os.fsync(f.fileno())+ os.replace(temporary, root / filename)+ names.append(filename)+ filename = f"rank{self.rank}.state.json"+ write_json(root / filename, self.metadata(profile))+ names.append(filename)+ return names++ def load(self, root):+ root = Path(root)+ meta = json.loads((root / f"rank{self.rank}.state.json").read_text())+ expected_specs = json.loads(json.dumps(self.specs))+ assert meta["canonical_specs"] == expected_specs+ assert meta["shard_begin"] == self.begin and meta["shard_end"] == self.end+ assert meta["committed_update"] == 30+ assert meta["profile_id"] == os.environ["OPENBUILD_PROFILE_ID"]+ assert meta["scheduler"]["next_update_index"] == 31+ assert meta["data_cursor"]["next_update_index"] == 31+ assert all(x == 30 for x in meta["parameter_steps"].values())+ self.checkpoint_encoding = meta.get("tensor_encoding", "raw")+ assert self.checkpoint_encoding in ("raw", "zstd-byte-shuffle-v1")+ for name, tensor in (("model", self.model[self.begin:self.end]), ("master_parameters",self.master), ("first_moments", self.first), ("second_moments",self.second)):+ path = root / f"rank{self.rank}.{name}.bin"+ dtype = np.dtype("<u2") if name == "model" else np.dtype("<f4")+ if self.checkpoint_encoding == "zstd-byte-shuffle-v1":+ import checkpoint_codec as codec+ pending = deque()+ buffers = [torch.empty(CHUNK, dtype=tensor.dtype, device="cpu", pin_memory=True) for _ in range(8)]+ available = deque(range(len(buffers)))+ def copy_frame(at, count, buffer_id, future):+ future.result()+ cpu = buffers[buffer_id][:count]+ tensor[at:at+count].copy_(cpu)+ available.append(buffer_id)+ with path.open("rb") as f, ThreadPoolExecutor(max_workers=4) as pool:+ magic, width, size = codec.HEADER.unpack(codec.read_exact(f, codec.HEADER.size))+ assert (magic, width, size) == (codec.MAGIC, dtype.itemsize, self.shard_size)+ at = 0+ while at < self.shard_size:+ if not available:+ copy_frame(*pending.popleft())+ raw_size, compressed_size = codec.FRAME.unpack(codec.read_exact(f, codec.FRAME.size))+ count = min(CHUNK, self.shard_size-at)+ assert raw_size == count * width+ assert 0 < compressed_size <= codec._zstd.ZSTD_compressBound(raw_size)+ payload = codec.read_exact(f, compressed_size)+ buffer_id = available.popleft()+ cpu = buffers[buffer_id][:count]+ array = cpu.view(torch.uint16).numpy() if tensor.dtype == torch.bfloat16 else cpu.numpy()+ pending.append((at, count, buffer_id, pool.submit(codec.decode, payload, raw_size, width, array)))+ at += count+ while pending:+ copy_frame(*pending.popleft())+ assert not f.read(1)+ else:+ assert path.stat().st_size == self.shard_size * dtype.itemsize+ buffer = torch.empty(CHUNK, dtype=tensor.dtype, device="cpu", pin_memory=True)+ with path.open("rb") as f:+ for at in range(0, self.shard_size, CHUNK):+ count = min(CHUNK, self.shard_size-at)+ cpu = buffer[:count]+ array = cpu.view(torch.uint16).numpy() if tensor.dtype == torch.bfloat16 else cpu.numpy()+ size = f.readinto(array.view(np.uint8))+ assert size == count * dtype.itemsize+ tensor[at:at+count].copy_(cpu)+ self.committed = 30+ self.next_update = 31+ self.next_sample = meta["data_cursor"]["next_global_sample_ordinal"]+ self.last_sample_ids = meta["data_cursor"]["last_global_sample_ids"]diff --git a/solution/test_checkpoint_codec.py b/solution/test_checkpoint_codec.pynew file mode 100644index 0000000000000000000000000000000000000000..a42fc64a277095b2518142230e947bcf030ed61b--- /dev/null+++ b/solution/test_checkpoint_codec.py@@ -0,0 +1,43 @@+"""Round-trip raw IEEE bits, including NaNs, and reject damaged frames."""+import unittest+from concurrent.futures import ThreadPoolExecutor++import numpy as np++import checkpoint_codec as codec+++class CodecTests(unittest.TestCase):+ def test_roundtrip_arbitrary_bits_and_tails(self):+ rng = np.random.default_rng(719)+ for width in (2, 4):+ for count in (1, 7, 128, 65537):+ raw = rng.integers(0, 256, count * width, dtype=np.uint8)+ a = raw.view(np.dtype("<u2") if width == 2 else np.dtype("<f4"))+ frame = codec.encode(a)+ size, compressed = codec.FRAME.unpack(frame[:codec.FRAME.size])+ self.assertEqual(compressed, len(frame) - codec.FRAME.size)+ out = codec.decode(frame[codec.FRAME.size:], size, width)+ self.assertEqual(out.tobytes(), a.tobytes())+ destination = np.empty_like(a)+ codec.decode(frame[codec.FRAME.size:], size, width, destination)+ self.assertEqual(destination.tobytes(), a.tobytes())++ def test_concurrent_independent_frames(self):+ a = np.arange(16387, dtype=np.float32)+ with ThreadPoolExecutor(max_workers=4) as pool:+ frames = list(pool.map(codec.encode, [a] * 16))+ self.assertTrue(all(x == frames[0] for x in frames))++ def test_corruption_and_wrong_lengths(self):+ a = np.arange(4096, dtype=np.float32)+ frame = codec.encode(a)+ size, _ = codec.FRAME.unpack(frame[:codec.FRAME.size])+ with self.assertRaises(ValueError):+ codec.decode(frame[codec.FRAME.size:-4], size, 4)+ with self.assertRaises(ValueError):+ codec.decode(frame[codec.FRAME.size:], size+4, 4)+++if __name__ == "__main__":+ unittest.main()diff --git a/solution/test_initialization.py b/solution/test_initialization.pynew file mode 100644index 0000000000000000000000000000000000000000..f0cef98ffa56a10de2416582fd49df3a7308730b--- /dev/null+++ b/solution/test_initialization.py@@ -0,0 +1,57 @@+"""CPU-only checks for the host-side deterministic initialization ABI."""+import math+import struct+import unittest++import numpy as np++import initialization+++def scalar_reference(name, index):+ if "norm.weight" in name or "layernorm.weight" in name:+ return 0x3F80+ mask = (1 << 64) - 1+ h = 0xCBF29CE484222325+ for byte in name.encode("utf8"):+ h = ((h ^ byte) * 0x100000001B3) & mask+ z = 0x51454E334F50454E ^ h ^ ((index * 0x9E3779B97F4A7C15) & mask)+ z = (z + 0x9E3779B97F4A7C15) & mask+ z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & mask+ z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & mask+ z ^= z >> 31+ value = (((z >> 52) & 4095) - 2048) * 2.0 ** -16+ bits = struct.unpack("<I", struct.pack("<f", value))[0]+ return (bits + 32767 + ((bits >> 16) & 1)) >> 16+++class InitializationTests(unittest.TestCase):+ def test_architecture_and_unique_alias(self):+ specs = dict(initialization.canonical_specs())+ self.assertEqual(sum(math.prod(s) for s in specs.values()), 4022468096)+ self.assertEqual(len(specs), 398)+ self.assertNotIn("lm_head.weight", specs)++ def test_canonical_scalar_vectors(self):+ for name, shape in initialization.canonical_specs():+ count = math.prod(shape)+ for at in (0, count // 2, count - 8):+ with self.subTest(name=name, at=at):+ actual = initialization.initial_bf16_bits(name, at, 8)+ self.assertEqual(actual.tolist(), [scalar_reference(name, i) for i in range(at, at+8)])++ def test_partition_and_implementation_invariance(self):+ name, start, count = "model.layers.31.mlp.down_proj.weight", 973135, 16384+ whole = initialization.initial_bf16_bits(name, start, count)+ pieces = np.concatenate([initialization.initial_bf16_bits(name, start+at, min(1031,count-at)) for at in range(0,count,1031)])+ np.testing.assert_array_equal(whole, pieces)+ native = initialization._counter+ try:+ initialization._counter = None+ np.testing.assert_array_equal(whole, initialization.initial_bf16_bits(name, start, count))+ finally:+ initialization._counter = native+++if __name__ == "__main__":+ unittest.main()diff --git a/solution/test_native_optimizer.py b/solution/test_native_optimizer.pynew file mode 100644index 0000000000000000000000000000000000000000..4ea03988d3f28e853785e14a37d5e3fc32fdf0d4--- /dev/null+++ b/solution/test_native_optimizer.py@@ -0,0 +1,74 @@+"""Exercise real native AdamW transitions, tails, and BF16 rounding on an NPU."""+import math+import unittest++import numpy as np+import torch+import torch_npu++from native_optimizer import NativeAdam+++def ordered(values):+ bits = np.asarray(values, dtype=np.float32).view(np.uint32).astype(np.int64)+ return np.where(bits & 0x80000000, 0xffffffff-bits, bits+0x80000000)+++class NativeOptimizerTest(unittest.TestCase):+ def test_public_transitions_and_bf16_rounding(self):+ torch.npu.set_device(0)+ torch.npu.set_compile_mode(jit_compile=False)+ optimizer = NativeAdam(0)+ rng = np.random.default_rng(72931)+ n = 65536 + 128 # Includes a partial tile, aligned like canonical tensors.+ initial = rng.integers(-2048, 2048, n).astype(np.float32) * 2**-16+ initial[::19] = 1+ initial[::23] = 0+ p = torch.from_numpy(initial).to(torch.bfloat16).float().npu()+ m, v = torch.zeros_like(p), torch.zeros_like(p)+ w = torch.empty_like(p, dtype=torch.bfloat16)+ worst = [0, 0, 0]+ for update in range(1, 32):+ previous = [x.cpu().numpy() for x in (p, m, v)]+ gradient = (rng.normal(size=n) * 10**rng.uniform(-7, -1, n)).astype(np.float32)+ g = torch.from_numpy(gradient).npu()+ clip = (1.0, 0.31, 0.013)[update % 3]+ decay = 0.0 if update % 2 else 0.1+ lr = 1.25e-7 + 0.5 * (1.25e-6-1.25e-7) * (1+math.cos(math.pi*min(update-1, 29)/29))+ torch.npu.synchronize()+ optimizer(p, m, v, g, w, clip, lr, update, decay)+ torch.npu.synchronize()+ actual = [x.cpu().numpy() for x in (p, m, v)]+ # Independent CPU evaluation follows the public operation rounding;+ # use the actual previous state to check every individual transition.+ old_p, old_m, old_v = previous+ clipped = gradient * np.float32(clip)+ em = (old_m.astype(np.float64)*0.9).astype(np.float32) + (clipped.astype(np.float64)*0.1).astype(np.float32)+ ev = (old_v.astype(np.float64)*0.95).astype(np.float32) + ((clipped*clipped).astype(np.float64)*0.05).astype(np.float32)+ mh = (em.astype(np.float64)/(1-0.9**update)).astype(np.float32)+ vh = (ev.astype(np.float64)/(1-0.95**update)).astype(np.float32)+ direction = mh / (np.sqrt(vh) + np.float32(1e-8))+ if decay:+ direction += (old_p.astype(np.float64)*decay).astype(np.float32)+ ep = old_p - np.float32(lr)*direction+ scales = [abs(old_p.astype(np.float64))+abs(np.float32(lr)*direction.astype(np.float64)),+ abs(old_m.astype(np.float64)*0.9)+abs(clipped.astype(np.float64)*0.1),+ abs(old_v.astype(np.float64)*0.95)+abs((clipped*clipped).astype(np.float64)*0.05)]+ for i, expected in enumerate((ep, em, ev)):+ ulps = abs(ordered(actual[i])-ordered(expected))+ worst[i] = max(worst[i], int(ulps.max()))+ valid = ulps <= (32 if i == 0 else 8)+ # A subtraction can produce a tiny master near zero. Bound its+ # forward rounding error against the operands as well as ULPs.+ # The task's selected transition checks separately enforce their+ # exact public limits during the full-model replay.+ valid |= abs(actual[i].astype(np.float64)-expected) <= 8*2**-24*scales[i]+ self.assertTrue(valid.all(), f"update={update}, state={i}, failures={np.count_nonzero(~valid)}, max_ulps={ulps.max()}")+ expected_bits = actual[0].view(np.uint32)+ expected_bits = ((expected_bits + 0x7fff + ((expected_bits >> 16) & 1)) >> 16).astype(np.uint16)+ np.testing.assert_array_equal(w.cpu().view(torch.uint16).numpy(), expected_bits)+ print("Native optimizer maximum ULP distances (master, first, second):", worst)+++if __name__ == "__main__":+ unittest.main()diff --git a/solution/train.sh b/solution/train.shnew file mode 100755index 0000000000000000000000000000000000000000..4f5dcabd2b763084025ad067970e37dfae58cf3e--- /dev/null+++ b/solution/train.sh@@ -0,0 +1,10 @@+#!/usr/bin/env bash+set -euo pipefail+cd -- "$(dirname -- "${BASH_SOURCE[0]}")"+export PYTHONDONTWRITEBYTECODE=1+export OMP_NUM_THREADS=4+export MKL_NUM_THREADS=4+export HCCL_CONNECT_TIMEOUT=180+export HCCL_EXEC_TIMEOUT=600+export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True+exec python3 -B launch.pydiff --git a/solution/worker.py b/solution/worker.pynew file mode 100644index 0000000000000000000000000000000000000000..b2c372b848fdea175a585efd6a740f3e77d41e79--- /dev/null+++ b/solution/worker.py@@ -0,0 +1,180 @@+"""Foreground HCCL rank: ordered input, actual training, and observations."""+import datetime+import json+import os+from pathlib import Path+import time++import numpy as np+import torch+import torch.distributed as dist+import torch_npu++from model import Qwen, LanguageModelLoss+from state import State, write_json+++CATEGORIES = ("logits", "gradients", "model_parameters", "master_parameters", "first_moments", "second_moments")+TASK_ID = "openbuild_training_qwen3_4b_2dev_v1"+++class Input:+ def __init__(self, root, profile_id):+ root = Path(root).resolve()+ manifest = json.loads((root / "input-manifest.json").read_text())+ assert manifest["task_id"] == TASK_ID+ self.profile = next(p for p in manifest["profiles"] if p["profile_id"] == profile_id)+ self.selectors = self.profile["selector_set"]+ self.batch = self.profile["global_batch_size"]+ self.sequence = self.profile["sequence_length"]+ assert (self.batch, self.sequence) == ({"long_sequence": (16,2048), "update_heavy":(64,512)}[profile_id])+ self.tensors = {}+ for name, spec in self.profile["tensors"].items():+ path = root / spec["path"]+ assert path.resolve().is_relative_to(root)+ assert path.stat().st_size == spec["byte_length"]+ dtype = {"int32":"<i4", "int64":"<i8", "uint8":"u1"}[spec["dtype"]]+ self.tensors[name] = np.memmap(path, mode="r", dtype=dtype, shape=tuple(spec["shape"]))++ def selectors_at(self, update):+ return {category: [s for s in self.selectors[category] if s["update_index"] == update] for category in CATEGORIES}+++def gather_values(values, device):+ if not values:+ return []+ tensor = torch.stack(values).to(device=device, dtype=torch.float32)+ dist.all_reduce(tensor)+ return tensor.cpu().tolist()+++def observe_parameters(state, selectors, categories):+ projections = {}+ for category in categories:+ entries = selectors[category]+ values = gather_values([state.projection(category, s) for s in entries], state.device)+ projections[category] = [dict(selector_id=s["selector_id"], value=value) for s,value in zip(entries,values)]+ return projections+++def update_step(state, model, data, update):+ timing = os.environ.get("OPENBUILD_TIMING") == "1" and update == 2+ state.gradient.zero_()+ selectors = data.selectors_at(update)+ idx = update-1+ denominator = int(np.sum(data.tensors["loss_mask"][idx], dtype=np.int64))+ assert denominator > 0+ first_row = state.rank * (data.batch // 2)+ last_row = first_row + data.batch // 2+ micro = int(os.environ.get("OPENBUILD_MICROBATCH", str(2048 // data.sequence)))+ assert micro > 0 and (data.batch // 2) % micro == 0+ loss_sum = torch.zeros((), device=state.device, dtype=torch.float32)+ logits_values = [torch.zeros((), device=state.device, dtype=torch.float32) for _ in selectors["logits"]]+ if timing:+ torch.npu.synchronize()+ phase_start = time.monotonic()+ for row in range(first_row, last_row, micro):+ def tensor(name, dtype):+ return torch.from_numpy(np.array(data.tensors[name][idx, row:row+micro], copy=True)).to(device=state.device, dtype=dtype)+ ids = tensor("input_ids", torch.int64)+ labels = tensor("labels", torch.int64)+ mask = tensor("loss_mask", torch.float32)+ positions = tensor("position_ids", torch.int64)+ hidden = model(ids, positions)+ coordinates, coordinate_ids = [], []+ for i, s in enumerate(selectors["logits"]):+ if row <= s["global_batch_row"] < row + micro:+ coordinates.append(((s["global_batch_row"]-row)*data.sequence+s["sequence_index"], s["vocab_index"]))+ coordinate_ids.append(i)+ loss, selected = LanguageModelLoss.apply(hidden, state.parameters["model.embed_tokens.weight"], labels, mask, denominator, coordinates)+ loss_sum.add_(loss.detach())+ for i, value in zip(coordinate_ids, selected.unbind()):+ logits_values[i] = value+ loss.backward()+ del hidden, loss, selected+ if timing:+ torch.npu.synchronize()+ compute_end = time.monotonic()+ dist.all_reduce(loss_sum)+ norm = state.reduce_gradient()+ if timing:+ reduction_end = time.monotonic()+ loss = float(loss_sum.item())+ if not np.isfinite(loss) or not np.isfinite(norm):+ raise FloatingPointError("non-finite training observation")+ logits = gather_values(logits_values, state.device)+ projections = {"logits": [dict(selector_id=s["selector_id"], value=v) for s,v in zip(selectors["logits"],logits)]}+ projections.update(observe_parameters(state, selectors, ("gradients",)))+ state.step(update, norm)+ projections.update(observe_parameters(state, selectors, CATEGORIES[2:]))+ if timing:+ torch.npu.synchronize()+ if state.rank == 0:+ print("phase_seconds=" + json.dumps(dict(forward_backward=compute_end-phase_start,+ reduction_and_norm=reduction_end-compute_end, optimizer_and_observations=time.monotonic()-reduction_end)), flush=True)+ return dict(schema_version=1, kind="openbuild_training_step_observation" if update <= 30 else "openbuild_training_fresh_process_observation",+ profile_id=data.profile["profile_id"], selector_set_id=data.selectors["selector_set_id"],+ update_index=update, committed=update<=30, loss=loss, global_grad_norm=norm, projections=projections)+++def main():+ rank = int(os.environ["RANK"])+ torch.set_num_threads(4)+ torch.npu.set_device(rank)+ torch.npu.set_compile_mode(jit_compile=False)+ torch.npu.config.allow_internal_format = False+ torch.npu.matmul.allow_hf32 = False+ device = torch.device(f"npu:{rank}")+ dist.init_process_group("hccl", rank=rank, world_size=2, timeout=datetime.timedelta(seconds=660))+ started = time.monotonic()+ action, profile = os.environ["OPENBUILD_ACTION"], os.environ["OPENBUILD_PROFILE_ID"]+ output, checkpoint_dir = Path(os.environ["OPENBUILD_OUTPUT_DIR"]), Path(os.environ["OPENBUILD_CHECKPOINT_DIR"])+ try:+ data = Input(os.environ["OPENBUILD_INPUT_DIR"], profile)+ assert torch.npu.device_count() == 2+ state = State(rank, device, checkpoint=checkpoint_dir if action == "fresh_next_step_probe" else None)+ model = Qwen(state.parameters, device)+ torch.npu.synchronize()+ print(f"rank={rank} initialized parameters={state.total} seconds={time.monotonic()-started:.2f}", flush=True)+ if action == "train":+ trajectory = (output / "trajectory.jsonl").open("w") if rank == 0 else None+ try:+ for update in range(1, 31):+ step_start = time.monotonic()+ row = update_step(state, model, data, update)+ state.commit(update, data.batch, data.tensors["sample_ids"][update-1])+ if trajectory is not None:+ trajectory.write(json.dumps(row, allow_nan=False) + "\n")+ trajectory.flush()+ print(f"update={update} loss={row['loss']:.9f} norm={row['global_grad_norm']:.9f} seconds={time.monotonic()-step_start:.2f} memory_gib={torch.npu.max_memory_allocated()/2**30:.2f}", flush=True)+ finally:+ if trajectory is not None:+ trajectory.close()+ torch.npu.synchronize()+ saved = state.save(checkpoint_dir, profile)+ all_files = [None, None]+ dist.all_gather_object(all_files, saved)+ if rank == 0:+ write_json(output / "checkpoint-manifest.json", dict(+ schema_version=1, kind="openbuild_training_checkpoint", task_id=TASK_ID, profile_id=profile,+ 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=[name for files in all_files for name in files], fresh_load_entrypoint="train.sh", fresh_next_step_mode="fresh_next_step_probe"))+ elif action == "fresh_next_step_probe":+ assert state.next_sample == 30 * data.batch+ row = update_step(state, model, data, 31)+ row["source_optimizer_update"] = 30+ assert state.committed == 30 and state.next_update == 31+ if rank == 0:+ with (output / "check-observations.jsonl").open("w") as f:+ f.write(json.dumps(row, allow_nan=False) + "\n")+ else:+ raise ValueError(f"unsupported action: {action}")+ torch.npu.synchronize()+ dist.barrier()+ finally:+ dist.destroy_process_group()+++if __name__ == "__main__":+ main()