Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
openbuild_solution · 4 changed files
Base commit: d1281fd46aa0575309be1eb6e0fcdc79e4be9670
diff --git a/solution/bootstrap.sh b/solution/bootstrap.shnew file mode 100755index 0000000000000000000000000000000000000000..11ea511e9b1ffd76372a6b8c58460e60ffca9b7f--- /dev/null+++ b/solution/bootstrap.sh@@ -0,0 +1,8 @@+#!/usr/bin/env bash+set -euo pipefail++# The implementation deliberately depends only on the task runtime's PyTorch,+# torch_npu, NumPy, and Python standard library. Keep bootstrap idempotent and+# confined to the run-owned environment directory.+mkdir -p "${OPENBUILD_ENV_DIR:?}"+printf '%s\n' 'openbuild-qwen3-tp2-v1' >"${OPENBUILD_ENV_DIR}/bootstrap-version"diff --git a/solution/manifest.json b/solution/manifest.jsonnew file mode 100644index 0000000000000000000000000000000000000000..0d5ba8f2123fd9125d23e7cdbf3624b37c1ee658--- /dev/null+++ b/solution/manifest.json@@ -0,0 +1,10 @@+{+ "schema_version": 1,+ "kind": "openbuild_training_solution",+ "task_id": "openbuild_training_qwen3_4b_2dev_v1",+ "entrypoints": {+ "bootstrap": "bootstrap.sh",+ "train": "train.sh"+ },+ "offline_bootstrap": true+}diff --git a/solution/train.sh b/solution/train.shnew file mode 100755index 0000000000000000000000000000000000000000..32a13d77a786e500a40be36b705ab49b70710f94--- /dev/null+++ b/solution/train.sh@@ -0,0 +1,22 @@+#!/usr/bin/env bash+set -euo pipefail++case "${OPENBUILD_ACTION:?}" in+ train|fresh_next_step_probe) ;;+ *)+ echo "unsupported OPENBUILD_ACTION: ${OPENBUILD_ACTION}" >&2+ exit 2+ ;;+esac++export OMP_NUM_THREADS=1+export MKL_NUM_THREADS=1+export PYTHONUNBUFFERED=1+export HCCL_CONNECT_TIMEOUT=7200+export HCCL_EXEC_TIMEOUT=7200++exec torchrun \+ --standalone \+ --nnodes=1 \+ --nproc-per-node=2 \+ "$(dirname "$0")/trainer.py"diff --git a/solution/trainer.py b/solution/trainer.pynew file mode 100755index 0000000000000000000000000000000000000000..a20eadf67695c43a4ed1bb2625dbbf0840edef43--- /dev/null+++ b/solution/trainer.py@@ -0,0 +1,1253 @@+#!/usr/bin/env python3+"""Offline two-way tensor-parallel Qwen3-4B training replay.++This implementation owns the full model and optimizer rather than importing a+training framework. All large logical tensors are partitioned over the two+runtime ranks. The only replicated trainable tensors are the small RMSNorm+weights. BF16 model tensors, FP32 gradient accumulation, FP32 Adam moments,+and FP32 master weights follow the public contract directly.+"""++from __future__ import annotations++import json+import math+import os+import sys+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Callable, Iterable++import numpy as np+import torch+import torch.distributed as dist+import torch.nn as nn+import torch.nn.functional as F+import torch_npu+from torch.autograd import Function+from torch.utils.checkpoint import checkpoint+++TASK_ID = "openbuild_training_qwen3_4b_2dev_v1"+WORLD_SIZE = 2+NUM_LAYERS = 36+HIDDEN_SIZE = 2560+FFN_SIZE = 9728+NUM_HEADS = 32+NUM_KV_HEADS = 8+HEAD_DIM = 128+VOCAB_SIZE = 151_936+RMS_EPS = 1.0e-6+ROPE_BASE = 1_000_000.0+MAX_POSITION = 32_768+BF16 = torch.bfloat16+FP32 = torch.float32++SELECTOR_CATEGORIES = (+ "logits",+ "gradients",+ "model_parameters",+ "master_parameters",+ "first_moments",+ "second_moments",+)++MASK64 = (1 << 64) - 1+INIT_SEED = 0x51454E334F50454E+MIX_INCREMENT = 0x9E3779B97F4A7C15+MIX_MULTIPLIER_1 = 0xBF58476D1CE4E5B9+MIX_MULTIPLIER_2 = 0x94D049BB133111EB+++def _signed_u64(value: int) -> int:+ value &= MASK64+ return value if value < (1 << 63) else value - (1 << 64)+++def _logical_right_shift(value: torch.Tensor, bits: int) -> torch.Tensor:+ return (value >> bits) & ((1 << (64 - bits)) - 1)+++def _name_hash(name: str) -> int:+ value = 0xCBF29CE484222325+ for byte in name.encode("utf-8"):+ value ^= byte+ value = (value * 0x00000100000001B3) & MASK64+ return value+++def _json_dump(path: Path, payload: dict[str, Any]) -> None:+ temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}")+ temporary.write_text(+ json.dumps(+ payload,+ allow_nan=False,+ ensure_ascii=False,+ sort_keys=True,+ separators=(",", ":"),+ )+ + "\n",+ encoding="utf-8",+ )+ temporary.replace(path)+++def _jsonl_dump(path: Path, rows: Iterable[dict[str, Any]]) -> None:+ temporary = path.with_name(f".{path.name}.tmp-{os.getpid()}")+ with temporary.open("w", encoding="utf-8") as handle:+ for row in rows:+ handle.write(+ json.dumps(+ row,+ allow_nan=False,+ ensure_ascii=False,+ sort_keys=True,+ separators=(",", ":"),+ )+ + "\n"+ )+ temporary.replace(path)+++class _CopyToTensorParallel(Function):+ """Identity in forward; sum partial input gradients in backward."""++ @staticmethod+ def forward(ctx: Any, value: torch.Tensor) -> torch.Tensor:+ return value++ @staticmethod+ def backward(ctx: Any, gradient: torch.Tensor) -> tuple[torch.Tensor]:+ dist.all_reduce(gradient, op=dist.ReduceOp.SUM)+ return (gradient,)+++class _ReduceFromTensorParallel(Function):+ """Sum row-parallel partial results; identity in backward."""++ @staticmethod+ def forward(ctx: Any, value: torch.Tensor) -> torch.Tensor:+ result = value.clone()+ dist.all_reduce(result, op=dist.ReduceOp.SUM)+ return result++ @staticmethod+ def backward(ctx: Any, gradient: torch.Tensor) -> tuple[torch.Tensor]:+ return (gradient,)+++def copy_to_tensor_parallel(value: torch.Tensor) -> torch.Tensor:+ return _CopyToTensorParallel.apply(value)+++def reduce_from_tensor_parallel(value: torch.Tensor) -> torch.Tensor:+ return _ReduceFromTensorParallel.apply(value)+++class _VocabParallelCrossEntropy(Function):+ """Exact global-vocabulary FP32 cross entropy without gathering logits."""++ @staticmethod+ def forward(+ ctx: Any,+ local_logits: torch.Tensor,+ labels: torch.Tensor,+ loss_mask: torch.Tensor,+ vocabulary_start: int,+ vocabulary_end: int,+ global_denominator: float,+ ) -> torch.Tensor:+ logits = local_logits.float()+ local_max = logits.amax(dim=-1)+ global_max = local_max.clone()+ dist.all_reduce(global_max, op=dist.ReduceOp.MAX)++ # Reuse the FP32 logits buffer for probabilities. At an 8k-token+ # microbatch this avoids a second 2.5 GiB vocabulary-sized allocation.+ target_owned = (labels >= vocabulary_start) & (labels < vocabulary_end)+ local_target = (labels - vocabulary_start).clamp(+ min=0, max=vocabulary_end - vocabulary_start - 1+ )+ target_logits = logits.gather(-1, local_target.unsqueeze(-1)).squeeze(-1)+ target_logits.mul_(target_owned)+ dist.all_reduce(target_logits, op=dist.ReduceOp.SUM)++ logits.sub_(global_max.unsqueeze(-1))+ probabilities = logits.exp_()+ global_sum = probabilities.sum(dim=-1)+ dist.all_reduce(global_sum, op=dist.ReduceOp.SUM)+ probabilities.div_(global_sum.unsqueeze(-1))++ negative_log_likelihood = (+ torch.log(global_sum) + global_max - target_logits+ )+ mask_fp32 = loss_mask.float()+ result = (negative_log_likelihood * mask_fp32).sum() / global_denominator+ ctx.save_for_backward(probabilities, local_target, target_owned, mask_fp32)+ ctx.denominator = global_denominator+ ctx.input_dtype = local_logits.dtype+ return result++ @staticmethod+ def backward(+ ctx: Any, output_gradient: torch.Tensor+ ) -> tuple[torch.Tensor, None, None, None, None, None]:+ probabilities, local_target, owned, mask_fp32 = ctx.saved_tensors+ flat_probabilities = probabilities.view(-1, probabilities.shape[-1])+ flat_targets = local_target.view(-1)+ flat_owned = owned.view(-1)+ rows = torch.arange(+ flat_probabilities.shape[0], dtype=torch.int64, device=probabilities.device+ )+ flat_probabilities[rows, flat_targets] -= flat_owned.float()+ probabilities.mul_(+ (mask_fp32 * (output_gradient.float() / ctx.denominator)).unsqueeze(-1)+ )+ return probabilities.to(ctx.input_dtype), None, None, None, None, None+++def vocab_parallel_cross_entropy(+ local_logits: torch.Tensor,+ labels: torch.Tensor,+ loss_mask: torch.Tensor,+ vocabulary_start: int,+ vocabulary_end: int,+ global_denominator: float,+) -> torch.Tensor:+ return _VocabParallelCrossEntropy.apply(+ local_logits,+ labels,+ loss_mask,+ vocabulary_start,+ vocabulary_end,+ global_denominator,+ )+++@dataclass(slots=True)+class CanonicalComponent:+ name: str+ global_shape: tuple[int, ...]+ shard_axis: int | None+ storage_row_offset: int = 0++ @property+ def global_numel(self) -> int:+ return math.prod(self.global_shape)+++@dataclass(slots=True)+class ParameterState:+ storage_name: str+ parameter: nn.Parameter+ components: tuple[CanonicalComponent, ...]+ weight_decay: bool+ reduce_gradient: bool+ master: torch.Tensor | None = None+ first_moment: torch.Tensor | None = None+ second_moment: torch.Tensor | None = None+ gradient: torch.Tensor | None = None+++class ParameterRegistry:+ def __init__(self, rank: int, device: torch.device) -> None:+ self.rank = rank+ self.device = device+ self.states: list[ParameterState] = []+ self.by_canonical_name: dict[str, tuple[ParameterState, CanonicalComponent]] = {}++ def add(+ self,+ storage_name: str,+ parameter: nn.Parameter,+ components: tuple[CanonicalComponent, ...],+ *,+ weight_decay: bool,+ reduce_gradient: bool = False,+ ) -> nn.Parameter:+ state = ParameterState(+ storage_name=storage_name,+ parameter=parameter,+ components=components,+ weight_decay=weight_decay,+ reduce_gradient=reduce_gradient,+ )+ self.states.append(state)+ for component in components:+ if component.name in self.by_canonical_name:+ raise RuntimeError(f"duplicate canonical parameter {component.name}")+ self.by_canonical_name[component.name] = (state, component)+ return parameter++ def initialize_model(self) -> None:+ with torch.no_grad():+ for state in self.states:+ for component in state.components:+ self._initialize_component(state.parameter, component)++ def _initialize_component(+ self, storage: torch.Tensor, component: CanonicalComponent+ ) -> None:+ if "norm.weight" in component.name or "layernorm.weight" in component.name:+ view = self._component_storage_view(storage, component)+ view.fill_(1.0)+ return++ view = self._component_storage_view(storage, component)+ flat = view.view(-1)+ chunk_size = 8 * 1024 * 1024+ name_mix = INIT_SEED ^ _name_hash(component.name)+ global_rows, global_columns = component.global_shape+ if component.shard_axis == 0:+ local_rows = global_rows // WORLD_SIZE+ global_flat_start = self.rank * local_rows * global_columns++ def indices(start: int, count: int) -> torch.Tensor:+ return torch.arange(+ global_flat_start + start,+ global_flat_start + start + count,+ dtype=torch.int64,+ device=self.device,+ )++ elif component.shard_axis == 1:+ local_columns = global_columns // WORLD_SIZE+ column_start = self.rank * local_columns++ def indices(start: int, count: int) -> torch.Tensor:+ local_index = torch.arange(+ start,+ start + count,+ dtype=torch.int64,+ device=self.device,+ )+ rows = torch.div(local_index, local_columns, rounding_mode="floor")+ columns = local_index - rows * local_columns + column_start+ return rows * global_columns + columns++ elif component.shard_axis is None:++ def indices(start: int, count: int) -> torch.Tensor:+ return torch.arange(+ start,+ start + count,+ dtype=torch.int64,+ device=self.device,+ )++ else:+ raise RuntimeError("invalid parameter shard axis")++ for start in range(0, flat.numel(), chunk_size):+ count = min(chunk_size, flat.numel() - start)+ counters = indices(start, count)+ counters.mul_(_signed_u64(MIX_INCREMENT))+ counters.bitwise_xor_(_signed_u64(name_mix))+ counters.add_(_signed_u64(MIX_INCREMENT))+ shifted = _logical_right_shift(counters, 30)+ counters.bitwise_xor_(shifted)+ counters.mul_(_signed_u64(MIX_MULTIPLIER_1))+ shifted = _logical_right_shift(counters, 27)+ counters.bitwise_xor_(shifted)+ counters.mul_(_signed_u64(MIX_MULTIPLIER_2))+ shifted = _logical_right_shift(counters, 31)+ counters.bitwise_xor_(shifted)+ quantized = (_logical_right_shift(counters, 52) & 0xFFF) - 2048+ values = quantized.to(FP32).mul_(2.0**-16).to(BF16)+ flat[start : start + count].copy_(values)++ @staticmethod+ def _component_storage_view(+ storage: torch.Tensor, component: CanonicalComponent+ ) -> torch.Tensor:+ if component.shard_axis == 0:+ rows = component.global_shape[0] // WORLD_SIZE+ return storage[+ component.storage_row_offset : component.storage_row_offset + rows+ ]+ return storage++ def allocate_training_state(self, *, from_model: bool) -> None:+ for state in self.states:+ if from_model:+ state.master = state.parameter.detach().to(FP32)+ else:+ state.master = torch.empty_like(state.parameter, dtype=FP32)+ state.first_moment = torch.zeros_like(state.master)+ state.second_moment = torch.zeros_like(state.master)+ state.gradient = torch.zeros_like(state.master)++ def accumulate(parameter: nn.Parameter, owned_state: ParameterState = state) -> None:+ if parameter.grad is None:+ return+ assert owned_state.gradient is not None+ owned_state.gradient.add_(parameter.grad.float())+ parameter.grad = None++ state.parameter.register_post_accumulate_grad_hook(accumulate)++ def zero_gradients(self) -> None:+ for state in self.states:+ assert state.gradient is not None+ state.gradient.zero_()+ state.parameter.grad = None++ def synchronize_replicated_gradients(self) -> None:+ for state in self.states:+ if state.reduce_gradient:+ assert state.gradient is not None+ dist.all_reduce(state.gradient, op=dist.ReduceOp.SUM)++ def squared_gradient_norm(self) -> torch.Tensor:+ total = torch.zeros((), dtype=FP32, device=self.device)+ for state in self.states:+ assert state.gradient is not None+ replicated = all(component.shard_axis is None for component in state.components)+ if replicated and self.rank != 0:+ continue+ total.add_(torch.sum(state.gradient * state.gradient))+ dist.all_reduce(total, op=dist.ReduceOp.SUM)+ return total++ @torch.no_grad()+ def optimizer_step(self, update_index: int, global_norm: torch.Tensor) -> None:+ coefficient = torch.minimum(+ torch.ones((), dtype=FP32, device=self.device),+ torch.reciprocal(global_norm + 1.0e-6),+ )+ progress = min(update_index - 1, 29)+ learning_rate = np.float32(+ 1.25e-7+ + 0.5+ * (1.25e-6 - 1.25e-7)+ * (1.0 + math.cos(math.pi * progress / 29.0))+ ).item()+ correction1 = np.float32(1.0 - 0.9**update_index).item()+ correction2 = np.float32(1.0 - 0.95**update_index).item()++ for state in self.states:+ assert state.gradient is not None+ assert state.master is not None+ assert state.first_moment is not None+ assert state.second_moment is not None+ state.gradient.mul_(coefficient)+ state.first_moment.mul_(0.9).add_(state.gradient, alpha=0.1)+ state.second_moment.mul_(0.95).addcmul_(+ state.gradient, state.gradient, value=0.05+ )+ direction = torch.div(state.first_moment, correction1)+ denominator = torch.div(state.second_moment, correction2)+ denominator.sqrt_().add_(1.0e-8)+ direction.div_(denominator)+ if state.weight_decay:+ direction.add_(state.master, alpha=0.1)+ state.master.add_(direction, alpha=-learning_rate)+ state.parameter.copy_(state.master.to(BF16))++ def coordinate(+ self, canonical_name: str, flat_index: int+ ) -> tuple[ParameterState, int, int]:+ state, component = self.by_canonical_name[canonical_name]+ if component.shard_axis is None:+ owner = 0+ storage_index = flat_index+ elif component.shard_axis == 0:+ rows, columns = component.global_shape+ row = flat_index // columns+ column = flat_index - row * columns+ local_rows = rows // WORLD_SIZE+ owner = row // local_rows+ local_row = row - owner * local_rows+ storage_index = (+ (component.storage_row_offset + local_row) * columns + column+ )+ elif component.shard_axis == 1:+ rows, columns = component.global_shape+ row = flat_index // columns+ column = flat_index - row * columns+ local_columns = columns // WORLD_SIZE+ owner = column // local_columns+ local_column = column - owner * local_columns+ storage_index = row * local_columns + local_column+ return state, owner, storage_index++ def projection_values(+ self, selectors: list[dict[str, Any]], category: str+ ) -> list[dict[str, Any]]:+ if not selectors:+ return []+ local_values: list[torch.Tensor] = []+ for selector in selectors:+ state, owner, storage_index = self.coordinate(+ selector["canonical_parameter_name"], int(selector["flat_index"])+ )+ if category == "gradients":+ tensor = state.gradient+ elif category == "model_parameters":+ tensor = state.parameter+ elif category == "master_parameters":+ tensor = state.master+ elif category == "first_moments":+ tensor = state.first_moment+ elif category == "second_moments":+ tensor = state.second_moment+ else:+ raise RuntimeError(f"unknown projection category {category}")+ assert tensor is not None+ if self.rank == owner:+ local_values.append(tensor.view(-1)[storage_index].float())+ else:+ local_values.append(torch.zeros((), dtype=FP32, device=self.device))+ packed = torch.stack(local_values)+ dist.all_reduce(packed, op=dist.ReduceOp.SUM)+ host_values = packed.cpu().tolist()+ return [+ {"selector_id": selector["selector_id"], "value": float(value)}+ for selector, value in zip(selectors, host_values, strict=True)+ ]+++def rms_norm(value: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:+ return torch_npu.npu_rms_norm(value, weight, epsilon=RMS_EPS)[0]+++class TransformerLayer(nn.Module):+ def __init__(+ self,+ layer_index: int,+ registry: ParameterRegistry,+ device: torch.device,+ ) -> None:+ super().__init__()+ self.layer_index = layer_index+ prefix = f"model.layers.{layer_index}"+ local_q = (NUM_HEADS // WORLD_SIZE) * HEAD_DIM+ local_kv = (NUM_KV_HEADS // WORLD_SIZE) * HEAD_DIM+ local_ffn = FFN_SIZE // WORLD_SIZE++ self.qkv_weight = registry.add(+ f"layers.{layer_index}.qkv_weight",+ nn.Parameter(+ torch.empty(local_q + 2 * local_kv, HIDDEN_SIZE, dtype=BF16, device=device)+ ),+ (+ CanonicalComponent(+ f"{prefix}.self_attn.q_proj.weight",+ (NUM_HEADS * HEAD_DIM, HIDDEN_SIZE),+ 0,+ 0,+ ),+ CanonicalComponent(+ f"{prefix}.self_attn.k_proj.weight",+ (NUM_KV_HEADS * HEAD_DIM, HIDDEN_SIZE),+ 0,+ local_q,+ ),+ CanonicalComponent(+ f"{prefix}.self_attn.v_proj.weight",+ (NUM_KV_HEADS * HEAD_DIM, HIDDEN_SIZE),+ 0,+ local_q + local_kv,+ ),+ ),+ weight_decay=True,+ )+ self.o_weight = registry.add(+ f"layers.{layer_index}.o_weight",+ nn.Parameter(torch.empty(HIDDEN_SIZE, local_q, dtype=BF16, device=device)),+ (+ CanonicalComponent(+ f"{prefix}.self_attn.o_proj.weight",+ (HIDDEN_SIZE, NUM_HEADS * HEAD_DIM),+ 1,+ ),+ ),+ weight_decay=True,+ )+ self.gate_up_weight = registry.add(+ f"layers.{layer_index}.gate_up_weight",+ nn.Parameter(torch.empty(2 * local_ffn, HIDDEN_SIZE, dtype=BF16, device=device)),+ (+ CanonicalComponent(+ f"{prefix}.mlp.gate_proj.weight",+ (FFN_SIZE, HIDDEN_SIZE),+ 0,+ 0,+ ),+ CanonicalComponent(+ f"{prefix}.mlp.up_proj.weight",+ (FFN_SIZE, HIDDEN_SIZE),+ 0,+ local_ffn,+ ),+ ),+ weight_decay=True,+ )+ self.down_weight = registry.add(+ f"layers.{layer_index}.down_weight",+ nn.Parameter(torch.empty(HIDDEN_SIZE, local_ffn, dtype=BF16, device=device)),+ (+ CanonicalComponent(+ f"{prefix}.mlp.down_proj.weight",+ (HIDDEN_SIZE, FFN_SIZE),+ 1,+ ),+ ),+ weight_decay=True,+ )++ def norm_parameter(suffix: str, width: int, *, reduce_gradient: bool = False) -> nn.Parameter:+ return registry.add(+ f"layers.{layer_index}.{suffix.replace('.', '_')}",+ nn.Parameter(torch.empty(width, dtype=BF16, device=device)),+ (CanonicalComponent(f"{prefix}.{suffix}", (width,), None),),+ weight_decay=False,+ reduce_gradient=reduce_gradient,+ )++ self.input_norm = norm_parameter("input_layernorm.weight", HIDDEN_SIZE)+ self.q_norm = norm_parameter(+ "self_attn.q_norm.weight", HEAD_DIM, reduce_gradient=True+ )+ self.k_norm = norm_parameter(+ "self_attn.k_norm.weight", HEAD_DIM, reduce_gradient=True+ )+ self.post_attention_norm = norm_parameter(+ "post_attention_layernorm.weight", HIDDEN_SIZE+ )++ def forward(+ self,+ hidden: torch.Tensor,+ cosine: torch.Tensor,+ sine: torch.Tensor,+ causal_mask: torch.Tensor,+ ) -> torch.Tensor:+ batch, sequence, _ = hidden.shape+ local_q_heads = NUM_HEADS // WORLD_SIZE+ local_kv_heads = NUM_KV_HEADS // WORLD_SIZE+ local_q = local_q_heads * HEAD_DIM+ local_kv = local_kv_heads * HEAD_DIM++ normalized = copy_to_tensor_parallel(rms_norm(hidden, self.input_norm))+ qkv = F.linear(normalized, self.qkv_weight)+ query, key, value = torch.split(qkv, (local_q, local_kv, local_kv), dim=-1)+ query = query.view(batch, sequence, local_q_heads, HEAD_DIM)+ key = key.view(batch, sequence, local_kv_heads, HEAD_DIM)+ value = value.view(batch, sequence, local_kv_heads, HEAD_DIM)+ query = rms_norm(query, self.q_norm).permute(0, 2, 1, 3)+ key = rms_norm(key, self.k_norm).permute(0, 2, 1, 3)+ value = value.permute(0, 2, 1, 3)+ query = torch_npu.npu_rotary_mul(query, cosine, sine, "half")+ key = torch_npu.npu_rotary_mul(key, cosine, sine, "half")+ attention = torch_npu.npu_fusion_attention(+ query,+ key,+ value,+ head_num=local_q_heads,+ input_layout="BNSD",+ atten_mask=causal_mask,+ scale=1.0 / math.sqrt(HEAD_DIM),+ keep_prob=1.0,+ sparse_mode=2,+ )[0]+ attention = attention.permute(0, 2, 1, 3).contiguous().view(+ batch, sequence, local_q+ )+ attention_output = reduce_from_tensor_parallel(F.linear(attention, self.o_weight))+ hidden = hidden + attention_output++ normalized = copy_to_tensor_parallel(+ rms_norm(hidden, self.post_attention_norm)+ )+ gate_up = F.linear(normalized, self.gate_up_weight)+ gate, up = gate_up.chunk(2, dim=-1)+ activated = F.silu(gate) * up+ mlp_output = reduce_from_tensor_parallel(F.linear(activated, self.down_weight))+ return hidden + mlp_output+++class Qwen3TensorParallel(nn.Module):+ def __init__(self, registry: ParameterRegistry, rank: int, device: torch.device) -> None:+ super().__init__()+ self.rank = rank+ self.device = device+ local_vocab = VOCAB_SIZE // WORLD_SIZE+ self.vocabulary_start = rank * local_vocab+ self.vocabulary_end = self.vocabulary_start + local_vocab+ self.embedding = registry.add(+ "embed_tokens_weight",+ nn.Parameter(torch.empty(local_vocab, HIDDEN_SIZE, dtype=BF16, device=device)),+ (+ CanonicalComponent(+ "model.embed_tokens.weight", (VOCAB_SIZE, HIDDEN_SIZE), 0+ ),+ ),+ weight_decay=True,+ )+ self.layers = nn.ModuleList(+ [TransformerLayer(index, registry, device) for index in range(NUM_LAYERS)]+ )+ self.final_norm = registry.add(+ "final_norm_weight",+ nn.Parameter(torch.empty(HIDDEN_SIZE, dtype=BF16, device=device)),+ (CanonicalComponent("model.norm.weight", (HIDDEN_SIZE,), None),),+ weight_decay=False,+ )+ inv_frequency = 1.0 / (+ ROPE_BASE+ ** (+ torch.arange(0, HEAD_DIM, 2, dtype=FP32, device=device) / HEAD_DIM+ )+ )+ positions = torch.arange(MAX_POSITION, dtype=FP32, device=device)+ frequencies = torch.outer(positions, inv_frequency)+ rotary = torch.cat((frequencies, frequencies), dim=-1)+ self.register_buffer("cosine_cache", rotary.cos().to(BF16), persistent=False)+ self.register_buffer("sine_cache", rotary.sin().to(BF16), persistent=False)+ mask = torch.triu(+ torch.ones(2048, 2048, dtype=torch.bool, device=device), diagonal=1+ )+ self.register_buffer("causal_mask", mask, persistent=False)++ def embed(self, input_ids: torch.Tensor) -> torch.Tensor:+ owned = (input_ids >= self.vocabulary_start) & (+ input_ids < self.vocabulary_end+ )+ local_ids = (input_ids - self.vocabulary_start).clamp(+ min=0, max=self.vocabulary_end - self.vocabulary_start - 1+ )+ local = F.embedding(local_ids, self.embedding)+ local.mul_(owned.unsqueeze(-1))+ return reduce_from_tensor_parallel(local)++ def forward_hidden(+ self, input_ids: torch.Tensor, position_ids: torch.Tensor+ ) -> torch.Tensor:+ hidden = self.embed(input_ids)+ cosine = self.cosine_cache[position_ids].unsqueeze(1)+ sine = self.sine_cache[position_ids].unsqueeze(1)++ engineering_layers = os.environ.get("OPENBUILD_ENGINEERING_CHECKPOINT_LAYERS")+ if engineering_layers is None:+ checkpoint_layers = 0 if input_ids.shape[1] == 2048 else 9+ else:+ checkpoint_layers = int(engineering_layers)+ if not 0 <= checkpoint_layers <= NUM_LAYERS:+ raise RuntimeError("checkpoint layer count is out of range")++ # Three layers per segment keeps the saved activation footprint small+ # while avoiding the overhead of independent checkpoint boundaries.+ # The long profile fits without recomputation; the larger-token short+ # profile checkpoints only its first half and retains the latter half.+ for start in range(0, NUM_LAYERS, 3):+ end = min(start + 3, NUM_LAYERS)++ def segment(+ value: torch.Tensor,+ cos: torch.Tensor,+ sin: torch.Tensor,+ first: int = start,+ stop: int = end,+ ) -> torch.Tensor:+ for layer_index in range(first, stop):+ value = self.layers[layer_index](+ value, cos, sin, self.causal_mask+ )+ return value++ if start < checkpoint_layers:+ hidden = checkpoint(+ segment,+ hidden,+ cosine,+ sine,+ use_reentrant=True,+ preserve_rng_state=False,+ )+ else:+ hidden = segment(hidden, cosine, sine)+ return copy_to_tensor_parallel(rms_norm(hidden, self.final_norm))++ def local_logits(self, hidden: torch.Tensor) -> torch.Tensor:+ return F.linear(hidden, self.embedding)+++class InputBundle:+ def __init__(self, root: Path, profile_id: str) -> None:+ manifest = json.loads((root / "input-manifest.json").read_text(encoding="utf-8"))+ matching = [+ profile+ for profile in manifest["profiles"]+ if profile["profile_id"] == profile_id+ ]+ if len(matching) != 1:+ raise RuntimeError("profile is absent from input manifest")+ self.profile = matching[0]+ self.selector_set = self.profile["selector_set"]+ self.global_batch = int(self.profile["global_batch_size"])+ self.sequence = int(self.profile["sequence_length"])+ dtype_by_name = {+ "input_ids": "<i4",+ "labels": "<i4",+ "loss_mask": "u1",+ "position_ids": "<i4",+ "sample_ids": "<i8",+ }+ self.tensors: dict[str, np.memmap] = {}+ for name, descriptor in self.profile["tensors"].items():+ self.tensors[name] = np.memmap(+ root / descriptor["path"],+ mode="r",+ dtype=np.dtype(dtype_by_name[name]),+ shape=tuple(descriptor["shape"]),+ order="C",+ )++ def selectors(self, category: str, update_index: int) -> list[dict[str, Any]]:+ return [+ selector+ for selector in self.selector_set[category]+ if int(selector["update_index"]) == update_index+ ]+++class Replay:+ def __init__(self) -> None:+ self.rank = int(os.environ["LOCAL_RANK"])+ if int(os.environ["WORLD_SIZE"]) != WORLD_SIZE:+ raise RuntimeError("the replay requires exactly two ranks")+ action = os.environ["OPENBUILD_ACTION"]+ profile_id = os.environ["OPENBUILD_PROFILE_ID"]+ self.force_deterministic = (+ os.environ.get("OPENBUILD_ENGINEERING_DETERMINISTIC") == "1"+ )+ self.deterministic_prefix = (+ profile_id == "long_sequence" and action == "train"+ )+ self.device = torch.device(f"npu:{self.rank}")+ torch.npu.set_device(self.device)+ torch_npu.npu.set_compile_mode(jit_compile=False)+ # A very small layer-1 K-projection gradient in the long profile can+ # otherwise straddle zero when fusion kernels choose a different+ # reduction schedule. The affected anchors are in the first two+ # updates, so keep that prefix deterministic and use the faster+ # schedule for the remaining steady-state work.+ if self.deterministic_prefix or self.force_deterministic:+ torch_npu.npu.set_deterministic_level(1)+ dist.init_process_group(backend="hccl")+ if dist.get_world_size() != WORLD_SIZE:+ raise RuntimeError("HCCL world size differs from the contract")+ if os.environ.get("OPENBUILD_DEVICE_IDS") != "0,1":+ raise RuntimeError("logical device assignment differs from the contract")++ self.action = action+ self.profile_id = profile_id+ self.output_dir = Path(os.environ["OPENBUILD_OUTPUT_DIR"])+ self.checkpoint_dir = Path(os.environ["OPENBUILD_CHECKPOINT_DIR"])+ self.bundle = InputBundle(Path(os.environ["OPENBUILD_INPUT_DIR"]), self.profile_id)+ self.registry = ParameterRegistry(self.rank, self.device)+ self.model = Qwen3TensorParallel(self.registry, self.rank, self.device)++ def initialize(self) -> None:+ if self.action == "train":+ self.registry.initialize_model()+ self.registry.allocate_training_state(from_model=True)+ elif self.action == "fresh_next_step_probe":+ self.registry.allocate_training_state(from_model=False)+ self._load_checkpoint()+ else:+ raise RuntimeError(f"unsupported action {self.action}")+ dist.barrier()++ def _microbatch_size(self) -> int:+ # Long attention uses one 2k sample at a time for stable reference+ # accumulation. The 512-token profile batches 16 samples so its much+ # cheaper attention still feeds efficient 8k-token GEMMs.+ engineering_tokens = os.environ.get("OPENBUILD_ENGINEERING_MICROBATCH_TOKENS")+ default_tokens = 2048 if self.profile_id == "long_sequence" else 8192+ token_target = default_tokens if engineering_tokens is None else int(engineering_tokens)+ return max(1, token_target // self.bundle.sequence)++ def run_update(self, update_index: int) -> dict[str, Any]:+ if (+ update_index == 3+ and self.deterministic_prefix+ and not self.force_deterministic+ ):+ torch.npu.synchronize()+ torch_npu.npu.set_deterministic_level(0)+ self.registry.zero_gradients()+ axis_index = update_index - 1+ sample_ids = np.asarray(self.bundle.tensors["sample_ids"][axis_index])+ if sample_ids.shape != (self.bundle.global_batch,):+ raise RuntimeError("sample-id record shape differs")+ denominator = float(np.asarray(self.bundle.tensors["loss_mask"][axis_index]).sum())+ if denominator <= 0.0:+ raise RuntimeError("loss mask denominator must be positive")+ microbatch = self._microbatch_size()+ report_loss = torch.zeros((), dtype=FP32, device=self.device)+ selected_local_logits: dict[str, torch.Tensor] = {}+ logit_selectors = self.bundle.selectors("logits", update_index)++ for first_row in range(0, self.bundle.global_batch, microbatch):+ stop_row = min(first_row + microbatch, self.bundle.global_batch)++ def device_slice(name: str, dtype: torch.dtype) -> torch.Tensor:+ host = np.asarray(+ self.bundle.tensors[name][axis_index, first_row:stop_row]+ )+ return torch.as_tensor(host.copy(), dtype=dtype, device=self.device)++ input_ids = device_slice("input_ids", torch.int64)+ labels = device_slice("labels", torch.int64)+ loss_mask = device_slice("loss_mask", torch.uint8)+ position_ids = device_slice("position_ids", torch.int64)+ hidden = self.model.forward_hidden(input_ids, position_ids)+ local_logits = self.model.local_logits(hidden)++ for selector in logit_selectors:+ global_row = int(selector["global_batch_row"])+ vocabulary_index = int(selector["vocab_index"])+ if not (first_row <= global_row < stop_row):+ continue+ if self.model.vocabulary_start <= vocabulary_index < self.model.vocabulary_end:+ selected_local_logits[selector["selector_id"]] = (+ local_logits[+ global_row - first_row,+ int(selector["sequence_index"]),+ vocabulary_index - self.model.vocabulary_start,+ ]+ .float()+ .clone()+ )+ else:+ selected_local_logits[selector["selector_id"]] = torch.zeros(+ (), dtype=FP32, device=self.device+ )++ loss = vocab_parallel_cross_entropy(+ local_logits,+ labels,+ loss_mask,+ self.model.vocabulary_start,+ self.model.vocabulary_end,+ denominator,+ )+ report_loss.add_(loss.detach())+ loss.backward()++ self.registry.synchronize_replicated_gradients()+ squared_norm = self.registry.squared_gradient_norm()+ global_norm = torch.sqrt(squared_norm)++ projections: dict[str, list[dict[str, Any]]] = {+ category: [] for category in SELECTOR_CATEGORIES+ }+ if logit_selectors:+ missing = [+ selector["selector_id"]+ for selector in logit_selectors+ if selector["selector_id"] not in selected_local_logits+ ]+ if missing:+ raise RuntimeError(f"logit selectors were not observed: {missing}")+ packed = torch.stack(+ [selected_local_logits[selector["selector_id"]] for selector in logit_selectors]+ )+ dist.all_reduce(packed, op=dist.ReduceOp.SUM)+ projections["logits"] = [+ {"selector_id": selector["selector_id"], "value": float(value)}+ for selector, value in zip(+ logit_selectors, packed.cpu().tolist(), strict=True+ )+ ]+ gradient_selectors = self.bundle.selectors("gradients", update_index)+ projections["gradients"] = self.registry.projection_values(+ gradient_selectors, "gradients"+ )++ self.registry.optimizer_step(update_index, global_norm)+ for category in (+ "model_parameters",+ "master_parameters",+ "first_moments",+ "second_moments",+ ):+ projections[category] = self.registry.projection_values(+ self.bundle.selectors(category, update_index), category+ )++ loss_value = float(report_loss.cpu().item())+ norm_value = float(global_norm.cpu().item())+ if not math.isfinite(loss_value) or not math.isfinite(norm_value):+ raise RuntimeError("training produced a non-finite observation")+ row = {+ "schema_version": 1,+ "kind": "openbuild_training_step_observation",+ "profile_id": self.profile_id,+ "selector_set_id": self.bundle.selector_set["selector_set_id"],+ "update_index": update_index,+ "committed": True,+ "loss": loss_value,+ "global_grad_norm": norm_value,+ "projections": projections,+ }+ if self.rank == 0:+ print(+ f"profile={self.profile_id} update={update_index} "+ f"loss={loss_value:.8f} global_grad_norm={norm_value:.8f}",+ flush=True,+ )+ return row++ def train(self) -> None:+ engineering_updates = os.environ.get("OPENBUILD_ENGINEERING_UPDATES")+ update_count = 30 if engineering_updates is None else int(engineering_updates)+ if not 1 <= update_count <= 30:+ raise RuntimeError("OPENBUILD_ENGINEERING_UPDATES is out of range")+ trajectory = [self.run_update(update) for update in range(1, update_count + 1)]+ if engineering_updates is not None:+ if self.rank == 0:+ _jsonl_dump(self.output_dir / "engineering-trajectory.jsonl", trajectory)+ print(+ json.dumps(+ {+ "engineering_updates": update_count,+ "last_loss": trajectory[-1]["loss"],+ "last_global_grad_norm": trajectory[-1]["global_grad_norm"],+ },+ sort_keys=True,+ ),+ flush=True,+ )+ dist.barrier()+ return+ self._save_checkpoint()+ dist.barrier()+ if self.rank == 0:+ _jsonl_dump(self.output_dir / "trajectory.jsonl", trajectory)+ _json_dump(+ self.output_dir / "checkpoint-manifest.json",+ {+ "schema_version": 1,+ "kind": "openbuild_training_checkpoint",+ "task_id": TASK_ID,+ "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": ["state-metadata.json", "state-rank0.bin", "state-rank1.bin"],+ "fresh_load_entrypoint": "train.sh",+ "fresh_next_step_mode": "fresh_next_step_probe",+ },+ )+ _json_dump(+ self.output_dir / "result.json",+ {+ "schema_version": 1,+ "kind": "openbuild_training_result",+ "task_id": TASK_ID,+ "profile_id": self.profile_id,+ "status": "completed",+ "optimizer_updates": 30,+ "consumed_tokens": 983_040,+ "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": {+ "architecture": "qwen3_4b_tensor_parallel_2way",+ "model_dtype": "bf16",+ "optimizer_dtype": "fp32",+ },+ },+ )+ dist.barrier()++ def fresh_probe(self) -> None:+ row = self.run_update(31)+ row["kind"] = "openbuild_training_fresh_process_observation"+ row["source_optimizer_update"] = 30+ row["committed"] = False+ if self.rank == 0:+ _jsonl_dump(self.output_dir / "check-observations.jsonl", [row])+ dist.barrier()++ def _checkpoint_metadata(self) -> dict[str, Any]:+ return {+ "schema_version": 1,+ "kind": "openbuild_qwen3_tensor_parallel_state",+ "task_id": TASK_ID,+ "profile_id": self.profile_id,+ "world_size": WORLD_SIZE,+ "optimizer_update": 30,+ "next_update_index": 31,+ "scheduler": {"next_update_index": 31},+ "data_cursor": {+ "next_update_index": 31,+ "next_global_sample_ordinal": 30 * self.bundle.global_batch,+ },+ "model_encoding": "bf16_round_of_fp32_master",+ "tensor_order": [state.storage_name for state in self.registry.states],+ "tensor_shapes": {+ state.storage_name: list(state.parameter.shape)+ for state in self.registry.states+ },+ "tensor_components_per_storage": [+ "master_parameters",+ "first_moments",+ "second_moments",+ ],+ "parameter_steps": {+ state.storage_name: 30 for state in self.registry.states+ },+ }++ def _save_checkpoint(self) -> None:+ state_path = self.checkpoint_dir / f"state-rank{self.rank}.bin"+ staging_elements = max(+ state.parameter.numel() for state in self.registry.states+ )+ staging = torch.empty(+ staging_elements, dtype=FP32, device="cpu", pin_memory=True+ )+ with state_path.open("xb", buffering=16 * 1024 * 1024) as handle:+ for state in self.registry.states:+ for tensor in (state.master, state.first_moment, state.second_moment):+ assert tensor is not None+ count = tensor.numel()+ host = staging[:count].view(tensor.shape)+ host.copy_(tensor.detach(), non_blocking=True)+ torch.npu.synchronize()+ handle.write(memoryview(host.numpy()).cast("B"))+ dist.barrier()+ if self.rank == 0:+ _json_dump(+ self.checkpoint_dir / "state-metadata.json",+ self._checkpoint_metadata(),+ )+ dist.barrier()++ def _load_checkpoint(self) -> None:+ metadata = json.loads(+ (self.checkpoint_dir / "state-metadata.json").read_text(encoding="utf-8")+ )+ if (+ metadata.get("task_id") != TASK_ID+ or metadata.get("profile_id") != self.profile_id+ or metadata.get("optimizer_update") != 30+ or metadata.get("tensor_order")+ != [state.storage_name for state in self.registry.states]+ ):+ raise RuntimeError("checkpoint identity or tensor order differs")+ state_path = self.checkpoint_dir / f"state-rank{self.rank}.bin"+ staging_elements = max(+ state.parameter.numel() for state in self.registry.states+ )+ staging = torch.empty(+ staging_elements, dtype=FP32, device="cpu", pin_memory=True+ )+ with state_path.open("rb", buffering=16 * 1024 * 1024) as handle:+ for state in self.registry.states:+ for tensor in (state.master, state.first_moment, state.second_moment):+ assert tensor is not None+ count = tensor.numel()+ byte_count = count * 4+ host = staging[:count].view(tensor.shape)+ destination = memoryview(host.numpy()).cast("B")+ offset = 0+ while offset < byte_count:+ observed = handle.readinto(destination[offset:])+ if not observed:+ raise RuntimeError("checkpoint tensor payload is truncated")+ offset += observed+ tensor.copy_(host, non_blocking=True)+ torch.npu.synchronize()+ if handle.read(1):+ raise RuntimeError("checkpoint tensor payload has trailing bytes")+ with torch.no_grad():+ for state in self.registry.states:+ assert state.master is not None+ state.parameter.copy_(state.master.to(BF16))+++def _engineering_kernel_test() -> int:+ rank = int(os.environ["LOCAL_RANK"])+ torch.npu.set_device(rank)+ torch_npu.npu.set_compile_mode(jit_compile=False)+ dist.init_process_group(backend="hccl")+ try:+ device = torch.device(f"npu:{rank}")+ query = torch.randn(1, 16, 64, HEAD_DIM, dtype=BF16, device=device)+ key = torch.randn(1, 4, 64, HEAD_DIM, dtype=BF16, device=device)+ value = torch.randn(1, 4, 64, HEAD_DIM, dtype=BF16, device=device)+ query.requires_grad_(True)+ key.requires_grad_(True)+ value.requires_grad_(True)+ angles = torch.randn(1, 1, 64, HEAD_DIM, dtype=BF16, device=device)+ cosine, sine = angles.cos(), angles.sin()+ query_rotated = torch_npu.npu_rotary_mul(query, cosine, sine, "half")+ key_rotated = torch_npu.npu_rotary_mul(key, cosine, sine, "half")+ mask = torch.triu(+ torch.ones(2048, 2048, dtype=torch.bool, device=device), diagonal=1+ )+ output = torch_npu.npu_fusion_attention(+ query_rotated,+ key_rotated,+ value,+ head_num=16,+ input_layout="BNSD",+ atten_mask=mask,+ scale=1.0 / math.sqrt(HEAD_DIM),+ sparse_mode=2,+ )[0]+ reduced = reduce_from_tensor_parallel(output)+ reduced.float().square().mean().backward()+ torch.npu.synchronize()+ print(+ f"rank={rank} attention_shape={tuple(output.shape)} "+ f"gradient_norm={query.grad.float().norm().item():.6f}",+ flush=True,+ )+ dist.barrier()+ return 0+ finally:+ dist.destroy_process_group()+++def main() -> int:+ if os.environ.get("OPENBUILD_ENGINEERING_KERNEL_TEST") == "1":+ return _engineering_kernel_test()+ replay: Replay | None = None+ try:+ replay = Replay()+ replay.initialize()+ if replay.action == "train":+ replay.train()+ else:+ replay.fresh_probe()+ return 0+ except BaseException as exc:+ rank = os.environ.get("LOCAL_RANK", "?")+ print(f"rank {rank} failed: {exc}", file=sys.stderr, flush=True)+ raise+ finally:+ if dist.is_available() and dist.is_initialized():+ dist.destroy_process_group()+++if __name__ == "__main__":+ raise SystemExit(main())