Inspect · Task requirements
Requested workspace inspection and file and log inspection related to task requirements.
3 calls · #0001–#0003
echo <val>find <path> -name <val> <n> > <path>Read <path>Gemini 3.7 Flash · Training
OpenBuild Qwen3-4B training 2dev · Open Build
01 / PROCESS MAP
Each row shows one agent’s tool events in its own recorded order. Colors show broad activities; bar widths do not represent duration.
Main agentGemini 3.7 Flash · 72 visible calls
02 / EVENT SEQUENCE
Requests are grouped by agent, activity and topic. Delegations open into child branches. Summaries describe visible requests; tool errors and missing responses are flagged. A recorded response does not establish command success or a performance improvement.
Scroll within this panel to view all events. Command sketches retain familiar programs and options. Values become <val> or <n>; paths, addresses and script bodies are hidden as <path>, <url> and <script>.
Requested workspace inspection and file and log inspection related to task requirements.
3 calls · #0001–#0003
echo <val>find <path> -name <val> <n> > <path>Read <path>Requested workspace inspection and file and log inspection related to source & workspace.
2 calls · #0004–#0005
ls -l -a <path>ls -l -a <val>Read <path>Requested file and log inspection related to task requirements.
1 call · #0006–#0006
Read <path>Requested file and log inspection related to source & workspace.
4 calls · #0007–#0010
Read <path>Requested file and log inspection related to benchmark & validation setup.
1 call · #0011–#0011
Read <path>Requested file and log inspection related to source & workspace.
2 calls · #0012–#0013
Read <path>Requested file and log inspection related to task requirements.
1 call · #0014–#0014
Read <path>Requested script or workload execution and runtime inspection related to device memory.
1 call · #0015–#0015
python3 -c <script>npu-smi infoRequested task coordination related to source & workspace.
1 call · #0016–#0016
Manage task <task>Requested file and log inspection related to source & workspace.
1 call · #0017–#0017
Read <path>Requested file and log inspection related to benchmark & validation setup.
1 call · #0018–#0018
Read <path>Requested file and log inspection related to source & workspace.
1 call · #0019–#0019
Read <path>Requested environment setup or inspection and source searches related to source & workspace.
1 call · #0020–#0020
envgrep <val>Requested script or workload execution related to benchmark & validation setup.
1 call · #0021–#0021
bash <script>Requested file and log inspection related to source & workspace.
2 calls · #0022–#0023
Read <path>Requested file and log inspection related to checkpoints & weight state.
1 call · #0024–#0024
Read <path>Requested file and log inspection related to source & workspace.
1 call · #0025–#0025
Read <path>Requested file and log inspection related to task requirements.
1 call · #0026–#0026
Read <path>Requested file and log inspection related to benchmark & validation setup.
2 calls · #0027–#0028
Read <path>Requested file and log inspection related to source & workspace.
1 call · #0029–#0029
Read <path>Requested script or workload execution related to device memory.
1 call · #0030–#0030
python3 -m <module> <val>which <val> <val> <val> <val> <val>Requested tool activity related to source & workspace.
1 call · #0031–#0031
shell <script>Requested tool activity related to parallelism & communication.
1 call · #0032–#0032
shell <script>Requested tool activity related to source & workspace.
1 call · #0033–#0033
which <val>Requested tool activity related to parallelism & communication.
1 call · #0034–#0034
shell <script>Requested tool activity related to source & workspace.
1 call · #0035–#0035
shell <script>Requested tool activity related to data movement.
1 call · #0036–#0036
shell <script>Requested script or workload execution related to source & workspace.
2 calls · #0037–#0038
shell <script>python3 -c <script>Requested tool activity related to attention kernels.
3 calls · #0039–#0041
shell <script>Requested tool activity related to checkpoints & weight state.
10 calls · #0042–#0051
shell <script>Requested workspace inspection related to source & workspace.
1 call · #0052–#0052
ls -l -a <path>Requested code edits related to source & workspace.
1 call · #0053–#0053
Write <path>Requested workspace file updates related to source & workspace.
1 call · #0054–#0054
mkdir -p <path> <path>Requested file and log inspection related to task requirements.
1 call · #0055–#0055
cat <script>Requested file and log inspection related to data movement.
1 call · #0056–#0056
cat <script>Requested file and log inspection and workspace file updates related to source & workspace.
1 call · #0057–#0057
cat <script>chmod <val> <path>Requested file and log inspection related to checkpoints & weight state.
1 call · #0058–#0058
cat <script>Requested file and log inspection related to source & workspace.
1 call · #0059–#0059
cat <script>Requested file and log inspection related to task requirements.
1 call · #0060–#0060
cat <script>Requested file and log inspection related to source & workspace.
1 call · #0061–#0061
cat <script>Requested file and log inspection and workspace file updates related to source & workspace.
1 call · #0062–#0062
cat <script>chmod <val> <path>Requested workspace inspection related to source & workspace.
1 call · #0063–#0063
ls -l -a <path> <path> <path>Requested script or workload execution related to benchmark & validation setup.
1 call · #0064–#0064
bash <script>Requested file and log inspection related to source & workspace.
1 call · #0065–#0065
cat <script>Requested script or workload execution related to source & workspace.
1 call · #0066–#0066
python3 -m <module> <script>Requested script or workload execution related to benchmark & validation setup.
1 call · #0067–#0067
bash <script>Requested file and log inspection related to source & workspace.
1 call · #0068–#0068
cat <script>Requested script or workload execution related to benchmark & validation setup.
2 calls · #0069–#0070
bash <script>Requested script or workload execution related to benchmark & validation setup.
1 call · #0071–#0071
bash <script>Requested repository inspection related to source & workspace.
1 call · #0072–#0072
du <flag> <args>git status <path>03 / CANDIDATE ARTIFACT
Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
Base commit: d1281fd46aa0575309be1eb6e0fcdc79e4be9670
@@ -0,0 +1,10 @@+#!/usr/bin/env bash+set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"++if [[ ! -f "${SCRIPT_DIR}/c_src/libgen.so" ]]; then+ gcc -O3 -fopenmp -shared -fPIC "${SCRIPT_DIR}/c_src/generator.c" -o "${SCRIPT_DIR}/c_src/libgen.so"+fi++exit 0@@ -0,0 +1,43 @@+#include <stdint.h>+#include <omp.h>+#include <string.h>++static inline uint32_t f32_to_bits(float f) {+ uint32_t u;+ memcpy(&u, &f, sizeof(u));+ return u;+}++static inline float bits_to_f32(uint32_t u) {+ float f;+ memcpy(&f, &u, sizeof(f));+ return f;+}++void generate_tensor(uint64_t name_hash, uint64_t n, uint16_t* out_bf16, float* out_fp32) {+ const uint64_t seed = 0x51454E334F50454EULL;+ const uint64_t mult1 = 0x9E3779B97F4A7C15ULL;+ const uint64_t mult2 = 0xBF58476D1CE4E5B9ULL;+ const uint64_t mult3 = 0x94D049BB133111EBULL;+ const float scale = 1.0f / 65536.0f; // 2^-16++ #pragma omp parallel for schedule(static)+ for (uint64_t i = 0; i < n; i++) {+ uint64_t mixed = i * mult1;+ uint64_t value = seed ^ name_hash ^ mixed;+ value += mult1;+ value = (value ^ (value >> 30)) * mult2;+ value = (value ^ (value >> 27)) * mult3;+ value ^= (value >> 31);+ int32_t signed_val = (int32_t)((value >> 52) & 0xFFF) - 2048;+ float f = (float)signed_val * scale;+ uint32_t bits = f32_to_bits(f);+ uint32_t rounded = bits + 0x7FFF + ((bits >> 16) & 1);+ uint16_t bf16 = (uint16_t)(rounded >> 16);+ if (out_bf16) out_bf16[i] = bf16;+ if (out_fp32) {+ uint32_t widened = ((uint32_t)bf16) << 16;+ out_fp32[i] = bits_to_f32(widened);+ }+ }+}@@ -0,0 +1,10 @@+{+ "schema_version": 1,+ "kind": "openbuild_training_solution",+ "task_id": "openbuild_training_qwen3_4b_2dev_v1",+ "entrypoints": {+ "bootstrap": "bootstrap.sh",+ "train": "train.sh"+ },+ "offline_bootstrap": true+}@@ -0,0 +1,50 @@+import os+import json+import numpy as np+import torch++class BinaryDataset:+ def __init__(self, input_dir: str, profile_id: str):+ self.input_dir = input_dir+ self.profile_id = profile_id+ + manifest_path = os.path.join(input_dir, 'input-manifest.json')+ with open(manifest_path, 'r', encoding='utf-8') as f:+ manifest = json.load(f)+ + self.profile_manifest = None+ for p in manifest['profiles']:+ if p['profile_id'] == profile_id:+ self.profile_manifest = p+ break+ + if self.profile_manifest is None:+ raise ValueError(f"Profile {profile_id} not found in input manifest")+ + self.global_batch_size = self.profile_manifest['global_batch_size']+ self.sequence_length = self.profile_manifest['sequence_length']+ self.selector_set = self.profile_manifest['selector_set']+ + profile_root = os.path.join(input_dir, 'profiles', profile_id)+ shape_3d = (31, self.global_batch_size, self.sequence_length)+ shape_2d = (31, self.global_batch_size)+ + self.input_ids = np.fromfile(os.path.join(profile_root, 'input_ids.i32le.bin'), dtype=np.int32).reshape(shape_3d)+ self.labels = np.fromfile(os.path.join(profile_root, 'labels.i32le.bin'), dtype=np.int32).reshape(shape_3d)+ self.loss_mask = np.fromfile(os.path.join(profile_root, 'loss_mask.u8.bin'), dtype=np.uint8).reshape(shape_3d)+ self.position_ids = np.fromfile(os.path.join(profile_root, 'position_ids.i32le.bin'), dtype=np.int32).reshape(shape_3d)+ self.sample_ids = np.fromfile(os.path.join(profile_root, 'sample_ids.i64le.bin'), dtype=np.int64).reshape(shape_2d)++ def get_update_batch(self, update_index: int, rank: int, world_size: int, device: torch.device):+ axis_idx = update_index - 1+ local_bs = self.global_batch_size // world_size+ start = rank * local_bs+ end = start + local_bs+ + inp = torch.from_numpy(self.input_ids[axis_idx, start:end]).to(device=device, dtype=torch.long)+ lbl = torch.from_numpy(self.labels[axis_idx, start:end]).to(device=device, dtype=torch.long)+ mask = torch.from_numpy(self.loss_mask[axis_idx, start:end]).to(device=device, dtype=torch.float32)+ pos = torch.from_numpy(self.position_ids[axis_idx, start:end]).to(device=device, dtype=torch.long)+ + global_mask_sum = float(self.loss_mask[axis_idx].sum())+ return inp, lbl, mask, pos, global_mask_sum@@ -0,0 +1,58 @@+import os+import ctypes+import torch++def fnv1a_64(name: str) -> int:+ h = 0xCBF29CE484222325+ for b in name.encode('utf-8'):+ h ^= b+ h = (h * 0x00000100000001B3) & 0xFFFFFFFFFFFFFFFF+ return h++def load_generator_lib():+ script_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+ lib_path = os.path.join(script_dir, 'c_src', 'libgen.so')+ c_src_path = os.path.join(script_dir, 'c_src', 'generator.c')+ if not os.path.exists(lib_path):+ os.system('gcc -O3 -fopenmp -shared -fPIC ' + c_src_path + ' -o ' + lib_path)+ lib = ctypes.CDLL(lib_path)+ lib.generate_tensor.argtypes = [ctypes.c_uint64, ctypes.c_uint64, ctypes.c_void_p, ctypes.c_void_p]+ return lib++def initialize_model_weights(model, my_group_names, world_size, rank, device):+ lib = load_generator_lib()+ named_params = list(model.named_parameters())+ + def get_group(name):+ if name.startswith('layers.'):+ return "layers." + name.split('.')[1]+ elif name.startswith('embed_tokens'):+ return 'embed'+ return 'norm'++ my_params = []+ master_params = {}+ first_moments = {}+ second_moments = {}++ for name, p in named_params:+ grp = get_group(name)+ canonical_name = 'model.' + name+ is_decay = not ('norm.weight' in canonical_name or 'layernorm.weight' in canonical_name)+ + if not is_decay:+ p.data.fill_(1.0)+ else:+ h = fnv1a_64(canonical_name)+ n = p.numel()+ buf = torch.empty(n, dtype=torch.bfloat16)+ lib.generate_tensor(h, n, buf.data_ptr(), None)+ p.data.copy_(buf.view(p.shape))+ + if grp in my_group_names:+ my_params.append((name, p))+ master_params[name] = p.data.to(device=device, dtype=torch.float32)+ first_moments[name] = torch.zeros(p.shape, dtype=torch.float32, device=device)+ second_moments[name] = torch.zeros(p.shape, dtype=torch.float32, device=device)++ return my_params, master_params, first_moments, second_moments@@ -0,0 +1,107 @@+import math+import torch+import torch.nn as nn+import torch.nn.functional as F+import torch.utils.checkpoint as checkpoint++class RMSNorm(nn.Module):+ def __init__(self, dim, eps=1e-6):+ super().__init__()+ self.eps = eps+ self.weight = nn.Parameter(torch.ones(dim, dtype=torch.bfloat16))+ + def forward(self, x):+ var = x.float().pow(2).mean(-1, keepdim=True)+ return (x.float() * torch.rsqrt(var + self.eps)).to(x.dtype) * self.weight++class Qwen3SelfAttention(nn.Module):+ def __init__(self, layer_idx):+ super().__init__()+ self.layer_idx = layer_idx+ self.hidden_size = 2560+ self.num_heads = 32+ self.num_kv_heads = 8+ self.head_dim = 128+ + self.q_proj = nn.Linear(2560, 4096, bias=False, dtype=torch.bfloat16)+ self.k_proj = nn.Linear(2560, 1024, bias=False, dtype=torch.bfloat16)+ self.v_proj = nn.Linear(2560, 1024, bias=False, dtype=torch.bfloat16)+ self.o_proj = nn.Linear(4096, 2560, bias=False, dtype=torch.bfloat16)+ + self.q_norm = RMSNorm(128, eps=1e-6)+ self.k_norm = RMSNorm(128, eps=1e-6)++ def forward(self, x, cos, sin):+ B, S, _ = x.shape+ q = self.q_proj(x).view(B, S, self.num_heads, self.head_dim)+ k = self.k_proj(x).view(B, S, self.num_kv_heads, self.head_dim)+ v = self.v_proj(x).view(B, S, self.num_kv_heads, self.head_dim)+ + q = self.q_norm(q)+ k = self.k_norm(k)+ + # RoPE (half-split rotary: rotary_interleaved = False)+ q1, q2 = q[..., :64], q[..., 64:]+ k1, k2 = k[..., :64], k[..., 64:]+ q = torch.cat((q1 * cos - q2 * sin, q1 * sin + q2 * cos), dim=-1)+ k = torch.cat((k1 * cos - k2 * sin, k1 * sin + k2 * cos), dim=-1)+ + # GQA repeat+ k = k.repeat_interleave(4, dim=2)+ v = v.repeat_interleave(4, dim=2)+ + q = q.transpose(1, 2)+ k = k.transpose(1, 2)+ v = v.transpose(1, 2)+ + context = F.scaled_dot_product_attention(q, k, v, is_causal=True)+ context = context.transpose(1, 2).reshape(B, S, 4096)+ return self.o_proj(context)++class Qwen3MLP(nn.Module):+ def __init__(self, layer_idx):+ super().__init__()+ self.gate_proj = nn.Linear(2560, 9728, bias=False, dtype=torch.bfloat16)+ self.up_proj = nn.Linear(2560, 9728, bias=False, dtype=torch.bfloat16)+ self.down_proj = nn.Linear(9728, 2560, bias=False, dtype=torch.bfloat16)+ + def forward(self, x):+ return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))++class Qwen3DecoderLayer(nn.Module):+ def __init__(self, layer_idx):+ super().__init__()+ self.input_layernorm = RMSNorm(2560, eps=1e-6)+ self.self_attn = Qwen3SelfAttention(layer_idx)+ self.post_attention_layernorm = RMSNorm(2560, eps=1e-6)+ self.mlp = Qwen3MLP(layer_idx)+ + def forward(self, x, cos, sin):+ h = x + self.self_attn(self.input_layernorm(x), cos, sin)+ out = h + self.mlp(self.post_attention_layernorm(h))+ return out++class Qwen3Model(nn.Module):+ def __init__(self):+ super().__init__()+ self.embed_tokens = nn.Embedding(151936, 2560, dtype=torch.bfloat16)+ self.layers = nn.ModuleList([Qwen3DecoderLayer(i) for i in range(36)])+ self.norm = RMSNorm(2560, eps=1e-6)+ + def forward(self, input_ids, position_ids):+ B, S = input_ids.shape+ x = self.embed_tokens(input_ids)+ + dim = 128+ base = 1000000.0+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32, device=x.device) / dim))+ freqs = position_ids.float().unsqueeze(-1) * inv_freq.unsqueeze(0).unsqueeze(0)+ cos = freqs.cos().unsqueeze(2).to(torch.bfloat16)+ sin = freqs.sin().unsqueeze(2).to(torch.bfloat16)+ + for layer in self.layers:+ x = checkpoint.checkpoint(layer, x, cos, sin, use_reentrant=False)+ + x = self.norm(x)+ logits = F.linear(x, self.embed_tokens.weight)+ return logits@@ -0,0 +1,428 @@+import os+import sys+import math+import json+import time+import torch+import torch.nn as nn+import torch.nn.functional as F+import torch.distributed as dist+import torch_npu+import numpy as np++from model import Qwen3Model+from init_weights import initialize_model_weights+from dataset import BinaryDataset++def get_param_groups(named_params):+ param_groups = {}+ for name, p in named_params:+ if name.startswith('layers.'):+ grp_name = f"layers.{name.split('.')[1]}"+ elif name.startswith('embed_tokens'):+ grp_name = 'embed'+ else:+ grp_name = 'norm'+ param_groups.setdefault(grp_name, []).append((name, p))+ + all_group_names = sorted(+ param_groups.keys(),+ key=lambda g: -1 if g == 'embed' else (999 if g == 'norm' else int(g.split('.')[1]))+ )+ return param_groups, all_group_names++def main():+ action = os.environ.get('OPENBUILD_ACTION', 'train')+ input_dir = os.environ['OPENBUILD_INPUT_DIR']+ output_dir = os.environ['OPENBUILD_OUTPUT_DIR']+ checkpoint_dir = os.environ['OPENBUILD_CHECKPOINT_DIR']+ profile_id = os.environ['OPENBUILD_PROFILE_ID']++ local_rank = int(os.environ.get('LOCAL_RANK', 0))+ torch.npu.set_device(local_rank)+ dist.init_process_group(backend='hccl')+ rank = dist.get_rank()+ world_size = dist.get_world_size()+ device = torch.device(f'npu:{local_rank}')++ # Load dataset+ dataset = BinaryDataset(input_dir, profile_id)+ selector_set = dataset.selector_set+ selector_set_id = selector_set['selector_set_id']++ # Pre-index selectors by update_index+ selectors_by_update = {}+ for u in range(1, 32):+ selectors_by_update[u] = {+ 'logits': [s for s in selector_set['logits'] if s['update_index'] == u],+ 'gradients': [s for s in selector_set['gradients'] if s['update_index'] == u],+ 'model_parameters': [s for s in selector_set['model_parameters'] if s['update_index'] == u],+ 'master_parameters': [s for s in selector_set['master_parameters'] if s['update_index'] == u],+ 'first_moments': [s for s in selector_set['first_moments'] if s['update_index'] == u],+ 'second_moments': [s for s in selector_set['second_moments'] if s['update_index'] == u],+ }++ # Model definition+ model = Qwen3Model()+ named_params = list(model.named_parameters())+ named_params_dict = dict(named_params)+ param_groups, all_group_names = get_param_groups(named_params)++ my_group_names = set(grp for idx, grp in enumerate(all_group_names) if idx % world_size == rank)++ if action == 'train':+ my_params, master_params, first_moments, second_moments = initialize_model_weights(+ model, my_group_names, world_size, rank, device+ )+ elif action == 'fresh_next_step_probe':+ model_weights_path = os.path.join(checkpoint_dir, 'model.pt')+ state_dict = torch.load(model_weights_path, map_location='cpu')+ model.load_state_dict(state_dict)+ + my_params = []+ for name, p in named_params:+ grp = 'embed' if name.startswith('embed_tokens') else ('norm' if name.startswith('norm') else f"layers.{name.split('.')[1]}")+ if grp in my_group_names:+ my_params.append((name, p))++ opt_path = os.path.join(checkpoint_dir, f'optimizer_rank{rank}.pt')+ opt_state = torch.load(opt_path, map_location=device)+ master_params = opt_state['master_params']+ first_moments = opt_state['first_moments']+ second_moments = opt_state['second_moments']+ else:+ raise ValueError(f"Unknown OPENBUILD_ACTION: {action}")++ model.to(device)++ # Microbatching configuration+ if profile_id == 'long_sequence':+ micro_size = 1+ else:+ micro_size = 4++ local_batch_size = dataset.global_batch_size // world_size++ def run_step(u: int, is_probe: bool = False):+ input_ids, labels, loss_mask, position_ids, global_mask_sum = dataset.get_update_batch(+ u, rank, world_size, device+ )++ local_loss = 0.0+ model.zero_grad()+ local_observed_projections = {}++ active_logit_selectors = selectors_by_update[u]['logits']++ for i in range(0, local_batch_size, micro_size):+ mb_input_ids = input_ids[i:i+micro_size]+ mb_labels = labels[i:i+micro_size]+ mb_loss_mask = loss_mask[i:i+micro_size]+ mb_pos_ids = position_ids[i:i+micro_size]++ mb_logits = model(mb_input_ids, mb_pos_ids)++ for sel in active_logit_selectors:+ global_row = sel['global_batch_row']+ my_start_row = rank * local_batch_size+ if my_start_row <= global_row < my_start_row + local_batch_size:+ local_row = global_row - my_start_row+ if i <= local_row < i + micro_size:+ mb_row = local_row - i+ seq_idx = sel['sequence_index']+ vocab_idx = sel['vocab_index']+ val = mb_logits[mb_row, seq_idx, vocab_idx].item()+ local_observed_projections[sel['selector_id']] = float(val)++ mb_loss_all = F.cross_entropy(+ mb_logits.float().view(-1, 151936), mb_labels.view(-1), reduction='none'+ ).view(micro_size, dataset.sequence_length)+ + mb_loss = (mb_loss_all * mb_loss_mask).sum() / global_mask_sum+ local_loss += mb_loss.item()+ mb_loss.backward()++ loss_tensor = torch.tensor([local_loss], dtype=torch.float32, device=device)+ dist.all_reduce(loss_tensor, op=dist.ReduceOp.SUM)+ step_loss = float(loss_tensor.item())++ local_sq_norm = 0.0+ reduced_grads = {}++ for idx, grp_name in enumerate(all_group_names):+ owner = idx % world_size+ for name, p in param_groups[grp_name]:+ if p.grad is not None:+ dist.all_reduce(p.grad, op=dist.ReduceOp.SUM)+ if owner == rank:+ g_f32 = p.grad.float()+ reduced_grads[name] = g_f32+ local_sq_norm += g_f32.pow(2).sum().item()+ p.grad = None++ sq_norm_tensor = torch.tensor([local_sq_norm], dtype=torch.float32, device=device)+ dist.all_reduce(sq_norm_tensor, op=dist.ReduceOp.SUM)+ step_grad_norm = math.sqrt(float(sq_norm_tensor.item()))++ # Pre-clip gradient selectors+ for sel in selectors_by_update[u]['gradients']:+ short_name = sel['canonical_parameter_name'].replace('model.', '', 1)+ flat_idx = sel['flat_index']+ if short_name in reduced_grads:+ val = reduced_grads[short_name].flatten()[flat_idx].item()+ local_observed_projections[sel['selector_id']] = float(val)++ clip_coeff = min(1.0, 1.0 / (step_grad_norm + 1e-6))+ progress = min(u - 1, 29)+ lr_u = 1.25e-7 + 0.5 * (1.25e-6 - 1.25e-7) * (1.0 + math.cos(math.pi * progress / 29.0))++ bias_cor1 = 1.0 - 0.9**u+ bias_cor2 = 1.0 - 0.95**u++ if not is_probe:+ for name, p in my_params:+ g = reduced_grads[name] * clip_coeff+ m = first_moments[name]+ v = second_moments[name]+ master = master_params[name]++ m.mul_(0.9).add_(g, alpha=0.1)+ v.mul_(0.95).addcmul_(g, g, value=0.05)++ m_hat = m / bias_cor1+ v_hat = v / bias_cor2++ step = m_hat / (torch.sqrt(v_hat) + 1e-8)+ canonical_name = f'model.{name}'+ if not ('norm.weight' in canonical_name or 'layernorm.weight' in canonical_name):+ step.add_(master, alpha=0.1)++ master.add_(step, alpha=-lr_u)+ p.data.copy_(master.to(torch.bfloat16))++ del reduced_grads++ for sel in selectors_by_update[u]['model_parameters']:+ short_name = sel['canonical_parameter_name'].replace('model.', '', 1)+ if short_name in named_params_dict:+ val = named_params_dict[short_name].data.flatten()[sel['flat_index']].item()+ local_observed_projections[sel['selector_id']] = float(val)++ for sel in selectors_by_update[u]['master_parameters']:+ short_name = sel['canonical_parameter_name'].replace('model.', '', 1)+ if short_name in master_params:+ val = master_params[short_name].flatten()[sel['flat_index']].item()+ local_observed_projections[sel['selector_id']] = float(val)++ for sel in selectors_by_update[u]['first_moments']:+ short_name = sel['canonical_parameter_name'].replace('model.', '', 1)+ if short_name in first_moments:+ val = first_moments[short_name].flatten()[sel['flat_index']].item()+ local_observed_projections[sel['selector_id']] = float(val)++ for sel in selectors_by_update[u]['second_moments']:+ short_name = sel['canonical_parameter_name'].replace('model.', '', 1)+ if short_name in second_moments:+ val = second_moments[short_name].flatten()[sel['flat_index']].item()+ local_observed_projections[sel['selector_id']] = float(val)++ # Broadcast updated parameters to all ranks+ for idx, grp_name in enumerate(all_group_names):+ owner = idx % world_size+ for name, p in param_groups[grp_name]:+ dist.broadcast(p.data, src=owner)++ else:+ # Probe simulation: compute per-parameter without allocating global dicts+ needed_param_names = set()+ for cat in ['model_parameters', 'master_parameters', 'first_moments', 'second_moments']:+ for sel in selectors_by_update[u][cat]:+ needed_param_names.add(sel['canonical_parameter_name'].replace('model.', '', 1))++ for name, p in my_params:+ if name in needed_param_names:+ g = reduced_grads[name] * clip_coeff+ m = first_moments[name]+ v = second_moments[name]+ master = master_params[name]++ sim_m = 0.9 * m + 0.1 * g+ sim_v = 0.95 * v + 0.05 * (g * g)++ m_hat = sim_m / bias_cor1+ v_hat = sim_v / bias_cor2++ step = m_hat / (torch.sqrt(v_hat) + 1e-8)+ canonical_name = f'model.{name}'+ if not ('norm.weight' in canonical_name or 'layernorm.weight' in canonical_name):+ step = step + 0.1 * master++ sim_master = master - lr_u * step+ sim_bf16 = sim_master.to(torch.bfloat16)++ # Extract selectors+ for sel in selectors_by_update[u]['model_parameters']:+ if sel['canonical_parameter_name'].replace('model.', '', 1) == name:+ local_observed_projections[sel['selector_id']] = float(sim_bf16.flatten()[sel['flat_index']].item())++ for sel in selectors_by_update[u]['master_parameters']:+ if sel['canonical_parameter_name'].replace('model.', '', 1) == name:+ local_observed_projections[sel['selector_id']] = float(sim_master.flatten()[sel['flat_index']].item())++ for sel in selectors_by_update[u]['first_moments']:+ if sel['canonical_parameter_name'].replace('model.', '', 1) == name:+ local_observed_projections[sel['selector_id']] = float(sim_m.flatten()[sel['flat_index']].item())++ for sel in selectors_by_update[u]['second_moments']:+ if sel['canonical_parameter_name'].replace('model.', '', 1) == name:+ local_observed_projections[sel['selector_id']] = float(sim_v.flatten()[sel['flat_index']].item())++ del reduced_grads++ gathered_projections = [None for _ in range(world_size)]+ dist.all_gather_object(gathered_projections, local_observed_projections)+ + combined_projections = {}+ for d in gathered_projections:+ if d:+ combined_projections.update(d)++ projections_payload = {}+ for cat in ['logits', 'gradients', 'model_parameters', 'master_parameters', 'first_moments', 'second_moments']:+ projections_payload[cat] = [+ {'selector_id': sel['selector_id'], 'value': combined_projections[sel['selector_id']]}+ for sel in selectors_by_update[u][cat]+ ]++ return step_loss, step_grad_norm, projections_payload++ if action == 'train':+ trajectory_rows = []+ for u in range(1, 31):+ t0 = time.time()+ loss_val, grad_norm_val, proj_dict = run_step(u, is_probe=False)+ dt = time.time() - t0+ + if rank == 0:+ print(f"[{profile_id}] Update {u:2d}/30 | Loss: {loss_val:.6f} | GradNorm: {grad_norm_val:.6f} | Time: {dt:.2f}s", flush=True)+ row = {+ 'schema_version': 1,+ 'kind': 'openbuild_training_step_observation',+ 'profile_id': profile_id,+ 'selector_set_id': selector_set_id,+ 'update_index': u,+ 'committed': True,+ 'loss': loss_val,+ 'global_grad_norm': grad_norm_val,+ 'projections': proj_dict,+ }+ trajectory_rows.append(row)++ if rank == 0:+ traj_path = os.path.join(output_dir, 'trajectory.jsonl')+ with open(traj_path, 'w', encoding='utf-8') as f:+ for row in trajectory_rows:+ f.write(json.dumps(row, ensure_ascii=False) + '\n')++ result_payload = {+ 'schema_version': 1,+ 'kind': 'openbuild_training_result',+ 'task_id': 'openbuild_training_qwen3_4b_2dev_v1',+ 'profile_id': profile_id,+ 'status': 'completed',+ 'optimizer_updates': 30,+ 'consumed_tokens': 983040,+ 'logical_device_ids': [0, 1],+ 'trajectory_path': 'trajectory.jsonl',+ 'trajectory_rows': 30,+ 'checkpoint_manifest_path': 'checkpoint-manifest.json',+ 'checkpoint_committed': True,+ 'all_ranks_exited': True,+ 'delivery_summary': {+ 'framework': 'PyTorch + torch_npu',+ 'parallelism': 'DataParallel + ZeRO-1',+ 'precision': 'BF16 model, FP32 master',+ },+ }+ with open(os.path.join(output_dir, 'result.json'), 'w', encoding='utf-8') as f:+ json.dump(result_payload, f, indent=2)++ ckpt_manifest = {+ 'schema_version': 1,+ 'kind': 'openbuild_training_checkpoint',+ 'task_id': 'openbuild_training_qwen3_4b_2dev_v1',+ 'profile_id': 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': [+ 'model.pt',+ 'optimizer_rank0.pt',+ 'optimizer_rank1.pt',+ 'state.json',+ ],+ 'fresh_load_entrypoint': 'train.sh',+ 'fresh_next_step_mode': 'fresh_next_step_probe',+ }+ with open(os.path.join(output_dir, 'checkpoint-manifest.json'), 'w', encoding='utf-8') as f:+ json.dump(ckpt_manifest, f, indent=2)++ torch.save(model.state_dict(), os.path.join(checkpoint_dir, 'model.pt'))+ + state_data = {+ 'profile_id': profile_id,+ 'committed_update': 30,+ 'next_update_index': 31,+ 'parameter_steps': 30,+ }+ with open(os.path.join(checkpoint_dir, 'state.json'), 'w', encoding='utf-8') as f:+ json.dump(state_data, f, indent=2)++ opt_state = {+ 'master_params': master_params,+ 'first_moments': first_moments,+ 'second_moments': second_moments,+ }+ torch.save(opt_state, os.path.join(checkpoint_dir, f'optimizer_rank{rank}.pt'))++ dist.barrier()+ if rank == 0:+ print(f"[{profile_id}] Training and checkpoint commit complete!", flush=True)++ elif action == 'fresh_next_step_probe':+ loss_val, grad_norm_val, proj_dict = run_step(31, is_probe=True)+ if rank == 0:+ obs_row = {+ 'schema_version': 1,+ 'kind': 'openbuild_training_fresh_process_observation',+ 'profile_id': profile_id,+ 'selector_set_id': selector_set_id,+ 'source_optimizer_update': 30,+ 'update_index': 31,+ 'committed': False,+ 'loss': loss_val,+ 'global_grad_norm': grad_norm_val,+ 'projections': proj_dict,+ }+ obs_path = os.path.join(output_dir, 'check-observations.jsonl')+ with open(obs_path, 'w', encoding='utf-8') as f:+ f.write(json.dumps(obs_row, ensure_ascii=False) + '\n')+ print(f"[{profile_id}] Fresh probe observation written!", flush=True)++ dist.barrier()++ dist.destroy_process_group()+ sys.exit(0)++if __name__ == '__main__':+ main()@@ -0,0 +1,10 @@+#!/usr/bin/env bash+set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"++export OMP_NUM_THREADS=1+export PYTHONUNBUFFERED=1++# Run distributed engine on 2 NPUs+exec torchrun --nproc_per_node=2 --master_port=29522 "${SCRIPT_DIR}/src/train_engine.py"BINARY PLACEHOLDERS
These files are named for inspection. Their bytes are intentionally omitted.
openbuild_solution/solution/c_src/libgen.so