Read code changes as Git diffs. Identifying strings are masked; binary files are listed by their full relative names.
openbuild_solution · 22 changed files
Base commit: d1281fd46aa0575309be1eb6e0fcdc79e4be9670
diff --git a/solution/README.md b/solution/README.mdnew file mode 100644index 0000000000000000000000000000000000000000..5c3a2f8996d9d84759f7123f9b97519f5010fd78--- /dev/null+++ b/solution/README.md@@ -0,0 +1,152 @@+# Offline online GRPO for Qwen3 on Ascend 910B++This delivery implements the full eight-update, eight-group, four-response+workload. It uses the supplied model/tokenizer, PyTorch, torch_npu and CANN.+There is no installed RL framework, external download, adapter, reference model,+critic, or CPU model execution.++## Architecture++- **Actor on logical device 0:** all 2,031,739,904 checkpoint parameters, BF16+ forward/backward, FP32 master parameters and FP32 AdamW moments. The supplied+ checkpoint has separate embedding and output-head tensors; both are trained.+- **Rollout on logical device 1:** a BF16 copy of every actor tensor, batched+ prefill and autoregressive decoding with a KV cache. NPU fused attention,+ RMSNorm and rotary kernels implement Qwen3. A captured NPU graph uses dynamic+ tensor cache indices and masks to avoid repeated Python dispatch during decode.+- **Coordinator:** receives the task input only in execute, submits generated+ text to the task-owned verifier, normalizes each four-response group, accumulates+ gradients across all accepted response tokens, and overlaps the next rollout+ with the actor's AdamW update on the other device. Once both finish, it copies+ all model parameters to rollout and synchronizes both devices before commit.+- **Lifecycle:** one foreground Python process owns both NPU contexts. CPU+ actor/checkpoint threads are bounded and joined before completion. There are no+ persistent workers or listening ports. Cleanup is idempotent and can also stop+ an interrupted execution, checking its PID and process start time.++The measured task assignment uses both devices.++## Algorithm and sampling++Every request has its own seeded random stream:++```text+seed = base + update * 100000 + policy_version * 10000+ + prompt_ordinal * 4 + response_ordinal+```++The supplied Qwen3 tokenizer renders system/user messages with thinking disabled.+Preparation verifies the minimal runtime renderer against the supplied chat+template and checks tokenization/decoding equivalence. Sampling applies temperature+0.7, top-k 20 and top-p 0.8 on NPU. Responses end at EOS or 256 tokens. Finished+batch lanes become padding. Only accepted response tokens enter loss/accounting.++Old log probabilities describe the unwarped policy distribution. The actor+computes fresh token log probabilities, the minimum of unclipped and [0.8, 1.2]+clipped advantage-weighted ratios, and a mean over **all response tokens in the+update**. Group advantages use sample standard deviation plus 1e-6. There is one+PPO epoch, no KL penalty and no entropy term. AdamW uses lr 1e-6, betas (0.9, 0.999),+epsilon 1e-8, weight decay 0.01, and global gradient clipping at 1.0. Even groups+with zero advantages run forward/backward and participate in the full update.++The first batch has lag zero. On two devices, subsequent batches use the current+rollout snapshot while the actor updates, and are consumed with lag one. Every+update waits for that generation and the full weight refresh before reporting+completion; no rollout request observes partially copied weights. Restart starts+at lag zero. Selected old log probabilities, separate actor/rollout freshness+passes, losses, clipping statistics, gradient norms, parameter projections and+stage timings are recorded from actual computation.++## Checkpoint and restart++Update eight writes the full FP32 master model and both AdamW moment tensors,+plus optimizer step/hyperparameters, constant scheduler state, policy versions,+data cursor, seed and RNG state. The checkpoint tensor index describes every+tensor, shape and chunk. Compression is lossless Zstandard with a bundled native+library and its license. It changes storage only; optimizer state remains FP32.++Transfers into pinned host buffers overlap 32 bounded compression/write workers;+each worker waits for its NPU transfer event before reading a buffer. All workers+finish before the atomic checkpoint manifest and+result are committed. Fresh restart loads every state tensor, verifies the+restored parameter projection and optimizer/scheduler/cursor, rebuilds rollout+from the restored actor, and performs update nine with newly generated responses.++## Entrypoints and checks++The task runner supplies the `OPENBUILD_*` environment. Bootstrap installs nothing+and only creates run-owned directories. Prepare verifies tokenization, warms the+task-owned Python bytecode cache, and reads the declared checkpoint shards into+the OS file cache. Execute supports the published flags:++```bash+./execute.sh --input-manifest INPUT.json --output-dir OUTPUT+./probe.sh --input-manifest PROBE.json --output RESULT.json+```++Public lifecycle checks:++```bash+bash "$TASK_DIR/run/describe.sh"+bash "$TASK_DIR/run/smoke.sh"+bash "$TASK_DIR/run/development_correctness.sh"+bash "$TASK_DIR/run/correctness.sh"+bash "$TASK_DIR/run/measurement.sh"+bash "$TASK_DIR/run/cleanup.sh"+```++Additional numerical checks:++```bash+python3 solution/check_math.py+python3 solution/check_decode.py+python3 solution/checkpoint_io.py+python3 solution/checkpoint_io.py --npu+python3 solution/check_lifecycle.py+```++These check clipping gradients, FP32 AdamW against PyTorch, graph decoding against+eager KV decoding and dense teacher forcing, weight refresh, bitwise checkpoint+round trips, rejection of truncated checkpoint chunks, sampling at probability+boundaries, and cleanup process ownership/termination/idempotency.++`OPENBUILD_GRAPH_DECODE=0` selects the verified eager decode path for diagnosis.+`OPENBUILD_PIPELINE=0` selects synchronous rollout/training with lag zero.+`OPENBUILD_MICROBATCH` controls actor memory usage (default 4); it does not alter+the workload, epoch count, or global token-mean loss.++## Validation and performance++The final public development check passed every gate in a fresh run-owned+runtime directory, including all eight updates, 256 trajectories, full+checkpoint restore in a new process, update nine, and cleanup. It consumed+19,394 response tokens in **53.69 host-observed execute seconds: 361.2 tokens/s**.+Peak PyTorch-allocated NPU memory was 34.32 GiB for actor and optimizer, and+5.08 GiB for rollout. These are development figures; the task reports+`measurement_valid: false` for development checks.++| Complete development run | Consumed tokens | Execute seconds | Tokens/second |+| --- | ---: | ---: | ---: |+| Initial eager implementation | 19,490 | 174.45 | 111.7 |+| Parallel checkpoint I/O and startup caching | 19,490 | 103.58 | 188.2 |+| Captured NPU decoding | 19,490 | 72.77 | 267.8 |+| Final pipeline and pinned checkpoint transfers; fresh runtime | 19,394 | 53.69 | 361.2 |++The initial bottlenecks were checkpoint serialization (68.1 seconds) and eager+decoding (about 44 seconds). Graph decoding removes repeated Python dispatch;+lag-one pipelining overlaps actor work with rollout. Bounded compression workers+and pinned transfers reduced the final complete checkpoint to 8.00 seconds.+The eight online update intervals total 18.64 seconds, including their overlap;+process startup, model/state initialization, and teardown account for most of+the remaining execute time. The final throughput is 3.23 times the initial+implementation. The pipelined run has different policy versions and generated+token counts, with the same declared workload and sampling rules.++Describe, smoke, development correctness, numerical checks, and cleanup passed.+Both formal correctness and measurement were attempted and returned+`evaluation input bundle is unavailable`; their task-owned input bundle was not+provided in this session. No formal score is claimed. Cleanup also confirmed+that both assigned NPUs had no remaining candidate processes.++See [validation.json](validation.json) for the task-reported gates, timings,+fresh-restart evidence, source hashes, and the formal validation limitation.diff --git a/solution/algorithm.py b/solution/algorithm.pynew file mode 100644index 0000000000000000000000000000000000000000..d8e90da1364545e13e7faf7fb3f2d6a11f4e8241--- /dev/null+++ b/solution/algorithm.py@@ -0,0 +1,52 @@+"""Shared GRPO group normalization and the fixed-trajectory math interface."""+import argparse+import json+import math+import statistics+from pathlib import Path+++def advantages(rewards, epsilon=1e-6):+ mean = statistics.fmean(rewards)+ std = statistics.stdev(rewards)+ return [0.0 if std == 0 else (r - mean) / (std + epsilon) for r in rewards]+++def policy_terms(current, old, advantage, low=0.2, high=0.2):+ """Tensor implementation used by the real actor and the numerical tests."""+ delta = current - old+ ratio = delta.exp()+ loss = -(ratio * advantage).minimum(ratio.clamp(1.0 - low, 1.0 + high) * advantage)+ kl = (-delta).exp() + delta - 1.0+ clipped = (ratio < 1.0 - low) | (ratio > 1.0 + high)+ return loss, kl, clipped+++def probe(payload):+ grouped, losses, kls, clips = [], [], [], []+ low, high = payload['clip_ratio_low'], payload['clip_ratio_high']+ for group in payload['groups']:+ adv = advantages(group['rewards'], payload['group_normalization_epsilon'])+ grouped.append(adv)+ for a, old, current in zip(adv, group['old_logprobs'], group['current_logprobs'], strict=True):+ if not old or len(old) != len(current):+ raise ValueError('Invalid probe token rows')+ for o, c in zip(old, current, strict=True):+ delta = c - o+ ratio = math.exp(delta)+ losses.append(-min(ratio * a, min(max(ratio, 1 - low), 1 + high) * a))+ kls.append(math.expm1(-delta) + delta)+ clips.append(float(ratio < 1 - low or ratio > 1 + high))+ return dict(schema_version=1, kind='openbuild_rl_algorithm_probe_result',+ probe_id=payload['probe_id'], advantages=grouped,+ policy_loss=statistics.fmean(losses), approx_kl=statistics.fmean(kls),+ clip_fraction=statistics.fmean(clips))+++if __name__ == '__main__':+ parser = argparse.ArgumentParser()+ parser.add_argument('--input-manifest', required=True)+ parser.add_argument('--output', required=True)+ args = parser.parse_args()+ result = probe(json.loads(Path(args.input_manifest).read_text()))+ Path(args.output).write_text(json.dumps(result, allow_nan=False) + '\n')diff --git a/solution/bootstrap.sh b/solution/bootstrap.shnew file mode 100755index 0000000000000000000000000000000000000000..41a4047d9dfa5d279d321019873d568c58bf42dc--- /dev/null+++ b/solution/bootstrap.sh@@ -0,0 +1,14 @@+#!/usr/bin/env bash+set -euo pipefail+mkdir -p "${OPENBUILD_ENV_DIR}" "${OPENBUILD_STATE_DIR}"+# No installation or mutation of the base Python environment is needed.+python3 - <<'PY'+import ctypes+import importlib.util+import os+from pathlib import Path+assert all(importlib.util.find_spec(n) for n in ('torch', 'torch_npu', 'safetensors', 'transformers', 'tokenizers'))+codec = ctypes.CDLL(str(Path(os.environ['OPENBUILD_SOLUTION_DIR']) / 'vendor/libzstd.so.1'))+codec.ZSTD_versionNumber.restype = ctypes.c_uint+assert codec.ZSTD_versionNumber() == 10408+PYdiff --git a/solution/check_decode.py b/solution/check_decode.pynew file mode 100644index 0000000000000000000000000000000000000000..291c9c9ca02051f5951d90effc5384852a0074f1--- /dev/null+++ b/solution/check_decode.py@@ -0,0 +1,67 @@+"""Compare captured decoding, eager KV decoding, and dense teacher forcing."""+import torch+import torch_npu++from decode_graph import DecodeGraph, sample+from model import Qwen+++@torch.inference_mode()+def main():+ device = 'npu:1'+ torch.npu.set_device(device)+ torch.npu.set_compile_mode(jit_compile=False)+ torch.manual_seed(27)+ cfg = dict(hidden_size=256, intermediate_size=512, head_dim=64,+ num_attention_heads=4, num_key_value_heads=2, num_hidden_layers=2,+ vocab_size=512, rms_norm_eps=1e-6, rope_theta=1000000.)+ model = Qwen(cfg).to(device).eval().requires_grad_(False)+ # Qwen's checkpoint supplies norm weights; initialize the tiny test fixture.+ for name, p in model.named_parameters():+ if 'norm' in name:+ p.fill_(1.)+ model.init_rope()+ batch, plen, capacity = 4, 16, 48+ graph = DecodeGraph(model, batch, capacity)+ eager_cache = model.cache(batch, capacity)+ ids = torch.randint(0, 512, (batch, plen), device=device)+ pos = torch.arange(plen, device=device)[None].expand(batch, -1)+ mask = torch.ones((plen, plen), dtype=torch.bool, device=device).triu(1)+ a = model.hidden(ids, pos, mask, graph.caches)+ b = model.hidden(ids, pos, mask, eager_cache)+ torch.testing.assert_close(a, b, atol=0, rtol=0)+ prefix_mask = torch.zeros((batch, 1, 1, capacity), dtype=torch.bool, device=device)+ physical = torch.arange(capacity, device=device)[None, None, None]+ token = torch.randint(0, 512, (batch,), device=device)+ all_ids = ids+ for step in range(12):+ offset = plen + step+ positions = torch.full((batch, 1), offset, device=device, dtype=torch.long)+ uniform = torch.tensor([.13, .45, .69, .91], device=device)+ hidden = model.hidden(token[:, None], positions, prefix_mask, eager_cache, offset)+ expected_token, expected_lp = sample(model.lm_head(hidden[:, -1]).float(), uniform)+ got_token, got_lp = graph.run(token, positions, offset, prefix_mask | (physical > offset), uniform)+ torch.testing.assert_close(got_token, expected_token, atol=0, rtol=0)+ torch.testing.assert_close(got_lp, expected_lp, atol=.03, rtol=0)+ all_ids = torch.cat((all_ids, token[:, None]), dim=1)+ dense_pos = torch.arange(all_ids.shape[1], device=device)[None].expand(batch, -1)+ dense_mask = torch.ones((all_ids.shape[1], all_ids.shape[1]), device=device, dtype=torch.bool).triu(1)+ dense = model.lm_head(model.hidden(all_ids, dense_pos, dense_mask)[:, -1]).float()+ dense_lp = dense.gather(1, got_token[:, None]).squeeze(1) - dense.logsumexp(-1)+ torch.testing.assert_close(got_lp, dense_lp, atol=.05, rtol=0)+ token = got_token.clone()+ # An in-place policy refresh must affect captured computation too.+ model.lm_head.weight.mul_(.5)+ offset += 1+ positions.fill_(offset)+ hidden = model.hidden(token[:, None], positions, prefix_mask, eager_cache, offset)+ expected_token, expected_lp = sample(model.lm_head(hidden[:, -1]).float(), uniform)+ got_token, got_lp = graph.run(token, positions, offset, prefix_mask | (physical > offset), uniform)+ torch.testing.assert_close(got_token, expected_token, atol=0, rtol=0)+ torch.testing.assert_close(got_lp, expected_lp, atol=.03, rtol=0)+ torch.npu.synchronize()+ print('Graph decode matches eager cache, dense log probabilities, and refreshed weights', flush=True)+++if __name__ == '__main__':+ main()diff --git a/solution/check_lifecycle.py b/solution/check_lifecycle.pynew file mode 100644index 0000000000000000000000000000000000000000..7f0e6261b680ddb2609f21b116d9599ca920ada9--- /dev/null+++ b/solution/check_lifecycle.py@@ -0,0 +1,48 @@+"""Verify cleanup ownership checks, termination, and repeated cleanup."""+import json+import os+import subprocess+import sys+import tempfile+from pathlib import Path++from lifecycle import cleanup+++def main():+ with tempfile.TemporaryDirectory() as directory:+ state = Path(directory)+ env = dict(os.environ, OPENBUILD_STATE_DIR=str(state))+ code = ('import torch, time; from lifecycle import register_execution; '+ 'register_execution([]); print("READY", flush=True); time.sleep(60)')+ child = subprocess.Popen([sys.executable, '-u', '-c', code],+ cwd=Path(__file__).parent, env=env,+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)+ try:+ while True:+ line = child.stdout.readline()+ if not line:+ raise RuntimeError('Lifecycle fixture failed: ' + child.stderr.read())+ if 'READY' in line:+ break+ record = state / 'execution.json'+ identity = json.loads(record.read_text())+ record.write_text(json.dumps({**identity, 'start': 'stale-start-time'}))+ cleanup(state)+ assert child.poll() is None, 'Cleanup signaled a mismatched process identity'+ record.write_text(json.dumps(identity))+ cleanup(state)+ assert child.wait(timeout=5) == 143+ cleanup(state)+ assert not record.exists() and not (state / 'ready.json').exists()+ finally:+ if child.poll() is None:+ child.kill()+ child.wait(timeout=5)+ child.stdout.close()+ child.stderr.close()+ print('Cleanup identity, termination and idempotency checks passed', flush=True)+++if __name__ == '__main__':+ main()diff --git a/solution/check_math.py b/solution/check_math.pynew file mode 100644index 0000000000000000000000000000000000000000..7e0afc86f6fadf8a864f68798c512f442161ec27--- /dev/null+++ b/solution/check_math.py@@ -0,0 +1,72 @@+"""Meaningful numerical checks; run with python3 solution/check_math.py.++Tiny tensors test formulas and accelerator kernels, not benchmark trajectories.+"""+import math++import torch+import torch_npu++from algorithm import advantages, policy_terms, probe+from optimizer import MasterAdamW+from decode_graph import sample+++def test_group_and_clipping():+ assert advantages([1, 1, 1, 1]) == [0, 0, 0, 0]+ expected = [-1.5, -0.5, 0.5, 1.5]+ scale = math.sqrt(5 / 3) + 1e-6+ assert max(abs(a - b / scale) for a, b in zip(advantages([0, 1, 2, 3]), expected)) < 1e-12+ old = torch.tensor([-1., -2., -3., -4.], dtype=torch.float64)+ current = old + torch.tensor([math.log(1.5), math.log(0.5), 0., math.log(0.5)], dtype=torch.float64)+ adv = torch.tensor([1., -1., 1., 1.], dtype=torch.float64)+ current.requires_grad_()+ losses, kl, clipped = policy_terms(current, old, adv)+ torch.testing.assert_close(losses, torch.tensor([-1.2, .8, -1., -.5], dtype=torch.float64))+ losses.sum().backward()+ torch.testing.assert_close(current.grad, torch.tensor([0., 0., -1., -.5], dtype=torch.float64))+ assert clipped.tolist() == [True, True, False, True]+ assert bool((kl >= 0).all())+++def test_master_adamw():+ torch.npu.set_device(0)+ torch.npu.set_compile_mode(jit_compile=False)+ model = torch.nn.Linear(32, 16, bias=False, dtype=torch.bfloat16, device='npu:0')+ opt = MasterAdamW(model)+ reference = torch.nn.Parameter(model.weight.detach().cpu().float())+ expected = torch.optim.AdamW([reference], lr=1e-6, weight_decay=.01, betas=(.9, .999), eps=1e-8)+ for i in range(3):+ grad = torch.linspace(-2 + i, 1 + i, reference.numel()).reshape_as(reference).bfloat16()+ model.weight.grad = grad.to('npu:0')+ reference.grad = grad.float()+ norm = torch.nn.utils.clip_grad_norm_([reference], 1.0)+ got_norm = opt.step()+ expected.step()+ assert abs(got_norm - float(norm)) < 1e-5+ torch.testing.assert_close(opt.master['weight'].cpu(), reference.detach(), rtol=1e-6, atol=1e-8)+ torch.testing.assert_close(opt.first['weight'].cpu(), expected.state[reference]['exp_avg'], rtol=1e-5, atol=1e-8)+ torch.testing.assert_close(opt.second['weight'].cpu(), expected.state[reference]['exp_avg_sq'], rtol=1e-5, atol=1e-9)+ torch.npu.synchronize()+++def test_sampling_boundaries():+ # Equal logits make the expected nucleus easy to check independently.+ logits = torch.zeros((3, 32), dtype=torch.float32, device='npu:0')+ uniform = torch.tensor([0., .5, 1.], device='npu:0')+ tokens, lp = sample(logits, uniform)+ top = logits.topk(20, sorted=True).indices+ assert tokens[0].item() == top[0, 0].item()+ # A rounded upper-end draw must not select a zero-probability masked tail.+ assert tokens[2].item() in top[2, :17].cpu().tolist()+ assert tokens[2].item() not in top[2, 17:].cpu().tolist()+ torch.testing.assert_close(lp, torch.full_like(lp, -math.log(32)), atol=1e-6, rtol=0)+++if __name__ == '__main__':+ test_group_and_clipping()+ print('Group normalization and clipped-loss gradients passed', flush=True)+ test_master_adamw()+ print('NPU FP32 master AdamW matches PyTorch AdamW', flush=True)+ test_sampling_boundaries()+ print('Top-k/top-p sampling boundary checks passed', flush=True)diff --git a/solution/checkpoint_io.py b/solution/checkpoint_io.pynew file mode 100644index 0000000000000000000000000000000000000000..ee9b0063d526aa0296590f2cd054dfe001da2dd0--- /dev/null+++ b/solution/checkpoint_io.py@@ -0,0 +1,196 @@+"""Bounded, parallel, lossless FP32 tensor checkpoint I/O.++The bundled libzstd is an ordinary CPU compression library. All actor and+optimizer computation stays on NPU. Workers are joined before checkpoint commit.+"""+import ctypes+import json+import time+from collections import deque+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path++import torch+++class Zstd:+ def __init__(self):+ self.lib = ctypes.CDLL(str(Path(__file__).parent / 'vendor/libzstd.so.1'))+ size = ctypes.c_size_t+ ptr = ctypes.c_void_p+ for name, arguments, result in [+ ('ZSTD_compressBound', [size], size),+ ('ZSTD_compress', [ptr, size, ptr, size, ctypes.c_int], size),+ ('ZSTD_decompress', [ptr, size, ptr, size], size),+ ('ZSTD_isError', [size], ctypes.c_uint),+ ('ZSTD_getErrorName', [size], ctypes.c_char_p),+ ]:+ fn = getattr(self.lib, name)+ fn.argtypes, fn.restype = arguments, result++ def check(self, result):+ if self.lib.ZSTD_isError(result):+ raise ValueError(self.lib.ZSTD_getErrorName(result).decode())+ return result++ def write(self, tensor, path, ready=None):+ if ready is not None:+ ready.synchronize()+ started = time.monotonic()+ assert tensor.device.type == 'cpu' and tensor.dtype == torch.float32 and tensor.is_contiguous()+ count = tensor.numel() * tensor.element_size()+ capacity = self.lib.ZSTD_compressBound(count)+ # The compressor overwrites the output; avoid zero-filling a large+ # temporary buffer for every chunk.+ buffer = torch.empty(capacity, dtype=torch.uint8, device='cpu')+ length = self.check(self.lib.ZSTD_compress(buffer.data_ptr(), capacity, tensor.data_ptr(), count, 1))+ encoded = time.monotonic()+ temporary = path.with_suffix('.tmp')+ with temporary.open('wb') as f:+ f.write(memoryview(buffer.numpy())[:length])+ temporary.replace(path)+ return length, encoded - started, time.monotonic() - encoded++ def read(self, path, elements):+ data = path.read_bytes()+ target = torch.empty(elements, dtype=torch.float32)+ count = elements * 4+ length = self.check(self.lib.ZSTD_decompress(target.data_ptr(), count, data, len(data)))+ if length != count:+ raise ValueError(f'Checkpoint chunk length differs: {path.name}')+ return target+++def save_tensors(root, components, workers=32, chunk_elements=16 * 1024 * 1024):+ root = Path(root)+ (root / 'tensors').mkdir(parents=True, exist_ok=True)+ codec = Zstd()+ records, files, pending = [], [], deque()+ compressed = 0+ encoding_seconds, writing_seconds, copy_seconds, waiting_seconds = 0., 0., 0., 0.+ with ThreadPoolExecutor(max_workers=workers, thread_name_prefix='checkpoint-write') as pool:+ for component, tensors in components.items():+ for name, value in tensors.items():+ if value.dtype != torch.float32:+ raise TypeError('Checkpoint state must be FP32')+ record = dict(component=component, name=name, shape=list(value.shape), parts=[])+ flat = value.detach().reshape(-1)+ for offset in range(0, value.numel(), chunk_elements):+ end = min(offset + chunk_elements, value.numel())+ filename = f'tensors/{len(files):06d}.zst'+ copied = time.monotonic()+ ready = None+ if flat.device.type == 'npu':+ # Pinned storage and a per-chunk event allow the next+ # transfer to overlap host compression and disk writes.+ # A writer cannot read a buffer before its event finishes.+ with torch.npu.device(flat.device):+ cpu = torch.empty(end - offset, dtype=torch.float32, device='cpu', pin_memory=True)+ cpu.copy_(flat[offset:end], non_blocking=True)+ ready = torch.npu.Event()+ ready.record()+ else:+ cpu = flat[offset:end].cpu().contiguous()+ copy_seconds += time.monotonic() - copied+ pending.append(pool.submit(codec.write, cpu, root / filename, ready))+ record['parts'].append(dict(file=filename, elements=end - offset))+ files.append(filename)+ if len(pending) >= 2 * workers:+ waited = time.monotonic()+ nbytes, encoded, written = pending.popleft().result()+ waiting_seconds += time.monotonic() - waited+ compressed += nbytes+ encoding_seconds += encoded+ writing_seconds += written+ records.append(record)+ while pending:+ waited = time.monotonic()+ nbytes, encoded, written = pending.popleft().result()+ waiting_seconds += time.monotonic() - waited+ compressed += nbytes+ encoding_seconds += encoded+ writing_seconds += written+ index = dict(format='openbuild-fp32-zstd-v1', dtype='float32', tensors=records,+ uncompressed_bytes=sum(v.numel() * 4 for c in components.values() for v in c.values()),+ compressed_bytes=compressed,+ timing={'copy_host_seconds': copy_seconds, 'producer_wait_seconds': waiting_seconds,+ 'encoding_worker_seconds': encoding_seconds, 'writing_worker_seconds': writing_seconds})+ temporary = root / 'tensors.json.tmp'+ temporary.write_text(json.dumps(index, separators=(',', ':')) + '\n')+ temporary.replace(root / 'tensors.json')+ print(f'checkpoint bytes={index["uncompressed_bytes"]} compressed_bytes={compressed} chunks={len(files)}', flush=True)+ print(f'checkpoint timing={index["timing"]}', flush=True)+ return ['tensors.json', *files]+++def restore_tensors(root, components, workers=16):+ root = Path(root)+ index = json.loads((root / 'tensors.json').read_text())+ if index.get('format') != 'openbuild-fp32-zstd-v1' or index.get('dtype') != 'float32':+ raise ValueError('Unsupported checkpoint tensor format')+ if index.get('byte_shuffle', False):+ raise ValueError('Unsupported checkpoint byte transform')+ expected = {(c, n) for c, tensors in components.items() for n in tensors}+ found, chunks = set(), []+ for record in index['tensors']:+ key = (record['component'], record['name'])+ if key not in expected or key in found:+ raise ValueError('Checkpoint has unexpected or duplicate state tensors')+ found.add(key)+ target = components[key[0]][key[1]]+ if list(target.shape) != record['shape'] or target.dtype != torch.float32:+ raise ValueError('Checkpoint tensor metadata differs')+ flat = target.reshape(-1)+ offset = 0+ for part in record['parts']:+ relative = Path(part['file'])+ if relative.is_absolute() or '..' in relative.parts or (root / relative).is_symlink():+ raise ValueError('Unsafe checkpoint chunk path')+ elements = part['elements']+ if type(elements) is not int or elements <= 0 or offset + elements > flat.numel():+ raise ValueError('Checkpoint chunk size is invalid')+ chunks.append((root / relative, elements, flat[offset:offset + elements]))+ offset += elements+ if offset != target.numel():+ raise ValueError('Checkpoint tensor is truncated')+ if found != expected:+ raise ValueError('Checkpoint has missing state tensors')+ codec = Zstd()+ pending = deque()+ with ThreadPoolExecutor(max_workers=workers, thread_name_prefix='checkpoint-read') as pool:+ for path, count, target in chunks:+ pending.append((pool.submit(codec.read, path, count), target))+ if len(pending) >= 2 * workers:+ future, destination = pending.popleft()+ destination.copy_(future.result())+ while pending:+ future, destination = pending.popleft()+ destination.copy_(future.result())+++if __name__ == '__main__':+ import tempfile+ import sys+ if '--npu' in sys.argv:+ import torch_npu+ torch.npu.set_device(0)+ torch.npu.set_compile_mode(jit_compile=False)+ device = 'npu:0' if '--npu' in sys.argv else 'cpu'+ with tempfile.TemporaryDirectory() as directory:+ original = {'model': {'random': torch.randn(256, 256).to(device), 'zeros': torch.zeros(37).to(device),+ 'scalar': torch.tensor(-0.0).to(device)}}+ files = save_tensors(directory, original, chunk_elements=4096)+ restored = {'model': {name: torch.empty_like(t) for name, t in original['model'].items()}}+ restore_tensors(directory, restored)+ for name, tensor in original['model'].items():+ assert torch.equal(tensor.cpu().reshape(-1).view(torch.int32), restored['model'][name].cpu().reshape(-1).view(torch.int32))+ # A truncated compressed frame must fail, rather than restore silently.+ chunk = Path(directory) / files[1]+ chunk.write_bytes(chunk.read_bytes()[:10])+ try:+ restore_tensors(directory, restored)+ except ValueError:+ pass+ else:+ raise AssertionError('Corrupt checkpoint was accepted')+ print('Checkpoint bitwise round trip and truncation checks passed', flush=True)diff --git a/solution/cleanup.sh b/solution/cleanup.shnew file mode 100755index 0000000000000000000000000000000000000000..0de5389fc9e397ed3f88288c9d48bc867c1ab251--- /dev/null+++ b/solution/cleanup.sh@@ -0,0 +1,4 @@+#!/usr/bin/env bash+set -euo pipefail+cd "$(dirname "$0")"+exec python3 -u lifecycle.py cleanupdiff --git a/solution/decode_graph.py b/solution/decode_graph.pynew file mode 100644index 0000000000000000000000000000000000000000..b089cf528732c71916b84814d84d4cbfc3a8f6cf--- /dev/null+++ b/solution/decode_graph.py@@ -0,0 +1,66 @@+"""Static-shape NPU decode with tensor-valued cache positions and masks."""+import time++import torch+++def sample(logits, uniform, active=None):+ values, indices = logits.topk(20, dim=-1, sorted=True)+ probabilities = (values / 0.7).softmax(dim=-1)+ remove = probabilities.cumsum(-1) > .8+ remove = torch.cat((torch.zeros_like(remove[:, :1]), remove[:, :-1]), dim=-1)+ probabilities = probabilities.masked_fill(remove, 0.)+ cumulative = probabilities.cumsum(-1)+ # Sampling from unnormalized weights avoids a second normalization roundoff.+ # Using '<' also keeps a uniform rounded to 1 on the last nonzero token.+ threshold = uniform.clamp(0., 1.) * cumulative[:, -1]+ choice = (cumulative < threshold[:, None]).sum(-1).clamp_max(19)+ token = indices.gather(1, choice[:, None]).squeeze(1)+ logprob = logits.gather(1, token[:, None]).squeeze(1) - logits.logsumexp(-1)+ if active is not None:+ # Finished lanes are padding, not additional generated trajectories.+ token = token.masked_fill(~active, 151643)+ logprob = logprob.masked_fill(~active, 0.)+ return token, logprob+++class DecodeGraph:+ def __init__(self, model, batch, capacity):+ self.model, self.batch, self.capacity = model, batch, capacity+ device = next(model.parameters()).device+ self.caches = model.cache(batch, capacity)+ self.ids = torch.zeros((batch, 1), dtype=torch.long, device=device)+ self.positions = torch.zeros_like(self.ids)+ self.offset = torch.zeros(batch, dtype=torch.int32, device=device)+ self.mask = torch.zeros((batch, 1, 1, capacity), dtype=torch.bool, device=device)+ self.uniform = torch.zeros(batch, dtype=torch.float32, device=device)+ self.active = torch.ones(batch, dtype=torch.bool, device=device)+ self.graph = None+ self.capture_seconds = 0.0++ def forward(self):+ hidden = self.model.hidden(self.ids, self.positions, self.mask, self.caches, self.offset)+ logits = self.model.lm_head(hidden[:, -1]).float()+ return sample(logits, self.uniform, self.active)++ @torch.inference_mode()+ def run(self, token, positions, offset, mask, uniform, active=None):+ self.ids.copy_(token[:, None])+ self.positions.copy_(positions)+ self.offset.fill_(offset)+ self.mask.copy_(mask)+ self.uniform.copy_(uniform)+ if active is not None:+ self.active.copy_(active)+ if self.graph is None:+ started = time.monotonic()+ self.forward()+ torch.npu.synchronize(self.ids.device)+ self.graph = torch.npu.NPUGraph()+ with torch.npu.graph(self.graph):+ self.token, self.logprob = self.forward()+ torch.npu.synchronize(self.ids.device)+ self.capture_seconds = time.monotonic() - started+ print(f'decode_graph capture_seconds={self.capture_seconds:.3f} batch={self.batch} capacity={self.capacity}', flush=True)+ self.graph.replay()+ return self.token, self.logprobdiff --git a/solution/execute.sh b/solution/execute.shnew file mode 100755index 0000000000000000000000000000000000000000..e7fcf27430cc6ec5179f8421690b8abb84a0a3de--- /dev/null+++ b/solution/execute.sh@@ -0,0 +1,9 @@+#!/usr/bin/env bash+set -euo pipefail+cd "$(dirname "$0")"+export OMP_NUM_THREADS=8+export MKL_NUM_THREADS=8+export TOKENIZERS_PARALLELISM=false+unset PYTHONDONTWRITEBYTECODE+export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True+exec python3 -u train.py "$@"diff --git a/solution/lifecycle.py b/solution/lifecycle.pynew file mode 100644index 0000000000000000000000000000000000000000..46868ac7f3d0918461bd06e1e6ce46837443fc51--- /dev/null+++ b/solution/lifecycle.py@@ -0,0 +1,129 @@+"""Entrypoints own no detached workers, sockets, or deferred accelerator work."""+import json+import os+import sys+import signal+import time+import atexit+from pathlib import Path+++def process_start(pid):+ try:+ fields = Path(f'/proc/{pid}/stat').read_text().rsplit(')', 1)[1].split()+ return None if fields[0] == 'Z' else fields[19]+ except (OSError, IndexError):+ return None+++def register_execution(devices):+ state = Path(os.environ['OPENBUILD_STATE_DIR'])+ record = state / 'execution.json'+ identity = dict(pid=os.getpid(), start=process_start(os.getpid()))+ temporary = state / f'execution-{os.getpid()}.tmp'+ temporary.write_text(json.dumps(identity) + '\n')+ temporary.replace(record)++ def remove():+ try:+ if json.loads(record.read_text()) == identity:+ record.unlink(missing_ok=True)+ except (OSError, ValueError):+ pass++ def terminate(signum, _frame):+ import torch+ if torch.npu.is_initialized():+ for device in devices:+ try:+ torch.npu.synchronize(device)+ except RuntimeError:+ pass+ raise SystemExit(128 + signum)++ atexit.register(remove)+ signal.signal(signal.SIGTERM, terminate)+ signal.signal(signal.SIGINT, terminate)+++def cleanup(state):+ record = state / 'execution.json'+ try:+ identity = json.loads(record.read_text())+ except FileNotFoundError:+ identity = None+ if identity is not None:+ pid = identity['pid']+ def alive():+ return process_start(pid) == identity['start'] and identity['start'] is not None+ if type(pid) is not int or pid <= 1 or pid == os.getpid():+ raise ValueError('Invalid execution process identity')+ if alive():+ try:+ os.kill(pid, signal.SIGTERM)+ except ProcessLookupError:+ pass+ deadline = time.monotonic() + 30+ while alive() and time.monotonic() < deadline:+ time.sleep(.1)+ if alive():+ try:+ os.kill(pid, signal.SIGKILL)+ except ProcessLookupError:+ pass+ deadline = time.monotonic() + 10+ while alive() and time.monotonic() < deadline:+ time.sleep(.1)+ if alive():+ raise RuntimeError('Execution process did not stop')+ record.unlink(missing_ok=True)+ (state / 'ready.json').unlink(missing_ok=True)+++def main():+ state = Path(os.environ['OPENBUILD_STATE_DIR'])+ state.mkdir(parents=True, exist_ok=True)+ if sys.argv[1] == 'cleanup':+ cleanup(state)+ return+ model = Path(os.environ['OPENBUILD_MODEL_PATH'])+ tokenizer = Path(os.environ['OPENBUILD_TOKENIZER_PATH'])+ assert model.is_dir() and tokenizer.is_dir()+ devices = [int(d) for d in os.environ['OPENBUILD_DEVICE_IDS'].split(',')]+ assert devices and set(devices).issubset({0, 1})+ from transformers import AutoTokenizer+ from tokenizer import QwenTokenizer+ tok = AutoTokenizer.from_pretrained(str(tokenizer), local_files_only=True)+ fast = QwenTokenizer(tokenizer)+ for system, question in [('', 'Ready.'), ('Answer briefly.\nPreserve Unicode: café.', 'What is 2 + 3?')]:+ messages = [{'role': 'system', 'content': system}, {'role': 'user', 'content': question}]+ rendered = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True,+ enable_thinking=False)+ assert rendered == fast.render(system, question)+ ids = fast.prompt_ids(dict(system_prompt=system, question=question))+ assert ids == tok(rendered, add_special_tokens=False)['input_ids']+ assert fast.decode(ids) == tok.decode(ids, skip_special_tokens=True)+ # Warm only declared model file pages, outside the scored interval. This+ # makes cold offline replay independent of earlier Agent-session file reads.+ warmed = 0+ buffer = bytearray(16 * 1024 * 1024)+ shards = sorted(model.glob('*.safetensors'))+ if not shards:+ raise ValueError('Model checkpoint shards are unavailable')+ for shard in shards:+ with shard.open('rb', buffering=0) as handle:+ while True:+ count = handle.readinto(buffer)+ if not count:+ break+ warmed += count+ del buffer+ ready = dict(status='ready', process_group_ids=[], ports=[], devices=devices,+ checkpoint=os.environ.get('OPENBUILD_RESTART_CHECKPOINT'), model_bytes_warmed=warmed)+ tmp = state / 'ready.json.tmp'+ tmp.write_text(json.dumps(ready) + '\n')+ tmp.replace(state / 'ready.json')+++if __name__ == '__main__':+ main()diff --git a/solution/manifest.json b/solution/manifest.jsonnew file mode 100644index 0000000000000000000000000000000000000000..f03b063f10a308877b77b3886deefc737af62f27--- /dev/null+++ b/solution/manifest.json@@ -0,0 +1,13 @@+{+ "schema_version": 1,+ "kind": "openbuild_rl_solution",+ "task_id": "openbuild_rl_qwen3_1_7b_online_grpo_rlvr_2dev_v1",+ "model": "Qwen/Qwen3-1.7B",+ "offline_replay": true,+ "framework": "Local GRPO with PyTorch, CANN fused attention and FP32 master AdamW",+ "bootstrap": "bootstrap.sh",+ "prepare": "prepare.sh",+ "execute": "execute.sh",+ "probe": "probe.sh",+ "cleanup": "cleanup.sh"+}diff --git a/solution/model.py b/solution/model.pynew file mode 100644index 0000000000000000000000000000000000000000..6bd718da066ef1ea910c365b931fa882de469d06--- /dev/null+++ b/solution/model.py@@ -0,0 +1,188 @@+"""Qwen3 BF16 actor and cached NPU rollout kernels.++The supplied checkpoint contains an explicit, separate lm_head. All 311 tensors+are preserved and trained. No framework/model source is patched at runtime.+"""+import json+from pathlib import Path++import torch+import torch.nn.functional as F+import torch_npu+from safetensors import safe_open+from torch import nn+++class RMSNorm(nn.Module):+ def __init__(self, size, eps):+ super().__init__()+ self.weight = nn.Parameter(torch.empty(size, dtype=torch.bfloat16))+ self.eps = eps++ def forward(self, x):+ return torch_npu.npu_rms_norm(x, self.weight, epsilon=self.eps)[0]+++class Attention(nn.Module):+ def __init__(self, cfg):+ super().__init__()+ h, d = cfg['hidden_size'], cfg['head_dim']+ self.nh, self.nkv, self.d = cfg['num_attention_heads'], cfg['num_key_value_heads'], d+ self.scale = d ** -0.5+ self.q_proj = nn.Linear(h, self.nh * d, bias=False, dtype=torch.bfloat16)+ self.k_proj = nn.Linear(h, self.nkv * d, bias=False, dtype=torch.bfloat16)+ self.v_proj = nn.Linear(h, self.nkv * d, bias=False, dtype=torch.bfloat16)+ self.o_proj = nn.Linear(self.nh * d, h, bias=False, dtype=torch.bfloat16)+ self.q_norm = RMSNorm(d, cfg['rms_norm_eps'])+ self.k_norm = RMSNorm(d, cfg['rms_norm_eps'])++ def forward(self, x, cos, sin, mask, cache=None, offset=0):+ b, s, _ = x.shape+ q = self.q_norm(self.q_proj(x).view(b, s, self.nh, self.d))+ k = self.k_norm(self.k_proj(x).view(b, s, self.nkv, self.d))+ v = self.v_proj(x).view(b, s, self.nkv, self.d).transpose(1, 2).contiguous()+ q = torch_npu.npu_rotary_mul(q, cos, sin).transpose(1, 2).contiguous()+ k = torch_npu.npu_rotary_mul(k, cos, sin).transpose(1, 2).contiguous()+ if cache is not None:+ ck, cv = cache+ dynamic = isinstance(offset, torch.Tensor)+ if dynamic:+ torch_npu.scatter_update_(ck, offset, k, axis=-2)+ torch_npu.scatter_update_(cv, offset, v, axis=-2)+ else:+ ck[:, :, offset:offset + s].copy_(k)+ cv[:, :, offset:offset + s].copy_(v)+ if s == 1:+ out = torch_npu.npu_incre_flash_attention(+ q, ck, cv, num_heads=self.nh, num_key_value_heads=self.nkv,+ input_layout='BNSD', scale_value=self.scale,+ actual_seq_lengths=None if dynamic else [offset + 1] * b, atten_mask=mask,+ inner_precise=0)+ return self.o_proj(out.transpose(1, 2).reshape(b, s, -1))+ out = torch_npu.npu_fusion_attention(+ q, k, v, self.nh, 'BNSD', atten_mask=mask, scale=self.scale,+ keep_prob=1.0, sparse_mode=1, inner_precise=2)[0]+ return self.o_proj(out.transpose(1, 2).reshape(b, s, -1))+++class MLP(nn.Module):+ def __init__(self, cfg):+ super().__init__()+ h, i = cfg['hidden_size'], cfg['intermediate_size']+ self.gate_proj = nn.Linear(h, i, bias=False, dtype=torch.bfloat16)+ self.up_proj = nn.Linear(h, i, bias=False, dtype=torch.bfloat16)+ self.down_proj = nn.Linear(i, h, bias=False, dtype=torch.bfloat16)++ def forward(self, x):+ return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))+++class Block(nn.Module):+ def __init__(self, cfg):+ super().__init__()+ self.self_attn = Attention(cfg)+ self.mlp = MLP(cfg)+ self.input_layernorm = RMSNorm(cfg['hidden_size'], cfg['rms_norm_eps'])+ self.post_attention_layernorm = RMSNorm(cfg['hidden_size'], cfg['rms_norm_eps'])++ def forward(self, x, cos, sin, mask, cache=None, offset=0):+ x = x + self.self_attn(self.input_layernorm(x), cos, sin, mask, cache, offset)+ return x + self.mlp(self.post_attention_layernorm(x))+++class Backbone(nn.Module):+ def __init__(self, cfg):+ super().__init__()+ self.embed_tokens = nn.Embedding(cfg['vocab_size'], cfg['hidden_size'], dtype=torch.bfloat16)+ self.layers = nn.ModuleList([Block(cfg) for _ in range(cfg['num_hidden_layers'])])+ self.norm = RMSNorm(cfg['hidden_size'], cfg['rms_norm_eps'])+++class Qwen(nn.Module):+ def __init__(self, cfg):+ super().__init__()+ self.cfg = cfg+ self.model = Backbone(cfg)+ self.lm_head = nn.Linear(cfg['hidden_size'], cfg['vocab_size'], bias=False, dtype=torch.bfloat16)+ self.register_buffer('cos_table', None, persistent=False)+ self.register_buffer('sin_table', None, persistent=False)++ def init_rope(self, length=4096):+ d = self.cfg['head_dim']+ device = next(self.parameters()).device+ inv = 1.0 / (self.cfg['rope_theta'] ** (torch.arange(0, d, 2, device=device).float() / d))+ freq = torch.arange(length, device=device).float()[:, None] * inv[None, :]+ emb = torch.cat((freq, freq), dim=-1)+ self.cos_table, self.sin_table = emb.cos().bfloat16(), emb.sin().bfloat16()++ def hidden(self, ids, positions, mask, caches=None, offset=0):+ x = self.model.embed_tokens(ids)+ cos = self.cos_table[positions].unsqueeze(2)+ sin = self.sin_table[positions].unsqueeze(2)+ for i, layer in enumerate(self.model.layers):+ x = layer(x, cos, sin, mask, None if caches is None else caches[i], offset)+ return self.model.norm(x)++ def cache(self, batch, length):+ shape = (batch, self.cfg['num_key_value_heads'], length, self.cfg['head_dim'])+ device = next(self.parameters()).device+ return [(torch.zeros(shape, dtype=torch.bfloat16, device=device),+ torch.zeros(shape, dtype=torch.bfloat16, device=device)) for _ in self.model.layers]+++def load_model(path, device):+ cfg = json.loads((Path(path) / 'config.json').read_text())+ # Meta construction prevents random initialization and double allocation.+ with torch.device('meta'):+ model = Qwen(cfg)+ model.to_empty(device=device)+ params = dict(model.named_parameters())+ loaded = set()+ with torch.no_grad():+ for shard in sorted(Path(path).glob('*.safetensors')):+ with safe_open(shard, framework='pt', device='cpu') as f:+ for name in f.keys():+ if name not in params:+ raise ValueError(f'Unexpected checkpoint tensor: {name}')+ params[name].copy_(f.get_tensor(name))+ loaded.add(name)+ if loaded != set(params):+ raise ValueError(f'Missing tensors: {set(params) - loaded}')+ model.init_rope()+ return model+++@torch.no_grad()+def refresh(actor, rollout):+ for dst, src in zip(rollout.parameters(), actor.parameters(), strict=True):+ dst.copy_(src)+ torch.npu.synchronize(next(rollout.parameters()).device)+++def training_batch(rows, prompt_tokens, device):+ sequences = [prompt_tokens[r['prompt_id']] + r['response_token_ids'] for r in rows]+ length = max(len(s) for s in sequences)+ ids = torch.full((len(rows), length), 151643, dtype=torch.long)+ bi, ti, targets, old, adv = [], [], [], [], []+ for b, (row, seq) in enumerate(zip(rows, sequences, strict=True)):+ ids[b, :len(seq)] = torch.tensor(seq)+ n = len(row['response_token_ids'])+ p = len(prompt_tokens[row['prompt_id']])+ bi.extend([b] * n)+ ti.extend(range(p - 1, p - 1 + n))+ targets.extend(row['response_token_ids'])+ old.extend(row['old_logprobs'])+ adv.extend([row['advantage']] * n)+ positions = torch.arange(length, device=device).unsqueeze(0).expand(len(rows), -1)+ mask = torch.ones((length, length), dtype=torch.bool, device=device).triu(1)+ return (ids.to(device), positions, mask,+ torch.tensor(bi, device=device), torch.tensor(ti, device=device),+ torch.tensor(targets, device=device), torch.tensor(old, device=device),+ torch.tensor(adv, device=device))+++def token_logprobs(model, batch):+ ids, positions, mask, bi, ti, targets, _, _ = batch+ hidden = model.hidden(ids, positions, mask)+ logits = model.lm_head(hidden[bi, ti])+ return -F.cross_entropy(logits.float(), targets, reduction='none')diff --git a/solution/optimizer.py b/solution/optimizer.pynew file mode 100644index 0000000000000000000000000000000000000000..a68cb967343955da07167d787fdc4919b688b063--- /dev/null+++ b/solution/optimizer.py@@ -0,0 +1,73 @@+"""Full-parameter AdamW with BF16 model tensors and FP32 optimizer state."""+import math++import torch+++class MasterAdamW:+ def __init__(self, model):+ self.named = list(model.named_parameters())+ assert all(p.dtype == torch.bfloat16 for _, p in self.named)+ self.master = {name: p.detach().float() for name, p in self.named}+ self.first = {name: torch.zeros_like(self.master[name]) for name, _ in self.named}+ self.second = {name: torch.zeros_like(self.master[name]) for name, _ in self.named}+ self.step_count = 0+ self.lr, self.decay, self.beta1, self.beta2, self.eps = 1e-6, 0.01, 0.9, 0.999, 1e-8++ def zero_grad(self):+ for _, p in self.named:+ p.grad = None++ @torch.no_grad()+ def step(self):+ missing = [name for name, p in self.named if p.grad is None]+ if missing:+ raise RuntimeError(f'Full-parameter update has missing gradients: {missing}')+ norm = torch.stack([torch.linalg.vector_norm(p.grad, dtype=torch.float32)+ for _, p in self.named]).norm()+ norm_value = float(norm.item())+ if not math.isfinite(norm_value):+ raise FloatingPointError('Non-finite global gradient norm')+ scale = (1.0 / (norm + 1e-6)).clamp(max=1.0)+ self.step_count += 1+ bc1 = 1 - self.beta1 ** self.step_count+ bc2 = 1 - self.beta2 ** self.step_count+ for name, p in self.named:+ # Bound temporary storage even for the large vocabulary matrices.+ master, first, second = (d[name].view(-1) for d in (self.master, self.first, self.second))+ grad = p.grad.view(-1)+ target = p.view(-1)+ for start in range(0, p.numel(), 8 * 1024 * 1024):+ end = min(start + 8 * 1024 * 1024, p.numel())+ g = grad[start:end].float() * scale+ m, v, w = first[start:end], second[start:end], master[start:end]+ m.mul_(self.beta1).add_(g, alpha=1 - self.beta1)+ v.mul_(self.beta2).addcmul_(g, g, value=1 - self.beta2)+ denom = (v / bc2).sqrt_().add_(self.eps)+ w.mul_(1 - self.lr * self.decay).addcdiv_(m, denom, value=-self.lr / bc1)+ target[start:end].copy_(w)+ p.grad = None+ return norm_value++ @torch.no_grad()+ def projection(self):+ # Fixed linear projection of real FP32 master weights, sampling every+ # tensor. FP64 reduction on the host retains small AdamW update changes.+ pieces = []+ for i, (name, _) in enumerate(self.named):+ w = self.master[name].view(-1)+ stride = max(1, w.numel() // 128)+ sample = w[::stride][:128]+ pieces.append(sample * ((i % 17 + 1) / 17.0))+ return float(torch.cat(pieces).cpu().double().sum().item())++ @torch.no_grad()+ def restore(self, root):+ from checkpoint_io import restore_tensors+ restore_tensors(root, dict(model=self.master, first=self.first, second=self.second))+ for name, p in self.named:+ p.copy_(self.master[name])++ def save(self, root):+ from checkpoint_io import save_tensors+ return save_tensors(root, dict(model=self.master, first=self.first, second=self.second))diff --git a/solution/prepare.sh b/solution/prepare.shnew file mode 100755index 0000000000000000000000000000000000000000..81d8860c8509a402d8b7f75a28c5ef22a22987c4--- /dev/null+++ b/solution/prepare.sh@@ -0,0 +1,9 @@+#!/usr/bin/env bash+set -euo pipefail+cd "$(dirname "$0")"+export OMP_NUM_THREADS=8+export MKL_NUM_THREADS=8+export TOKENIZERS_PARALLELISM=false+# Populate only the task-owned Python cache during untimed preparation.+unset PYTHONDONTWRITEBYTECODE+exec python3 -u lifecycle.py preparediff --git a/solution/probe.sh b/solution/probe.shnew file mode 100755index 0000000000000000000000000000000000000000..57c688413caf6158dc539600ea51653390148c03--- /dev/null+++ b/solution/probe.sh@@ -0,0 +1,4 @@+#!/usr/bin/env bash+set -euo pipefail+cd "$(dirname "$0")"+exec python3 -u algorithm.py "$@"diff --git a/solution/rollout.py b/solution/rollout.pynew file mode 100644index 0000000000000000000000000000000000000000..6ed9c5d7d9a67265ea26eaa895f77a9bc299931e--- /dev/null+++ b/solution/rollout.py@@ -0,0 +1,94 @@+"""Batched autoregressive sampling with an independent stream per request."""+import random+import time+import os++import torch+from decode_graph import DecodeGraph, sample+++def request_seed(base, update, version, prompt, response):+ return base + update * 100000 + version * 10000 + prompt * 4 + response+++@torch.inference_mode()+def generate(model, tokenizer, prompts, prompt_tokens, base_seed, update, version):+ device = next(model.parameters()).device+ specs = [(p, r) for p in prompts for r in range(4)]+ seeds = [request_seed(base_seed, update, version, p['ordinal'], r) for p, r in specs]+ # Uniform random variates are bookkeeping; all policy logits, filtering and+ # categorical selection execute on NPU. Streams do not depend on batching.+ streams = [random.Random(seed) for seed in seeds]+ draws = torch.tensor([[rng.random() for rng in streams] for _ in range(256)],+ dtype=torch.float32, device=device)+ batch = len(specs)+ lengths = [len(prompt_tokens[p['id']]) for p, _ in specs]+ plen = max(lengths)+ capacity = plen + 256+ ids = torch.full((batch, plen), 151643, dtype=torch.long)+ positions = torch.zeros_like(ids)+ prefix_padding = torch.zeros((batch, capacity), dtype=torch.bool)+ for b, ((p, _), length) in enumerate(zip(specs, lengths, strict=True)):+ ids[b, plen - length:] = torch.tensor(prompt_tokens[p['id']])+ positions[b, plen - length:] = torch.arange(length)+ prefix_padding[b, :plen - length] = True+ causal = torch.ones((plen, plen), dtype=torch.bool).triu(1)+ prefill_mask = causal[None, None, :, :] | prefix_padding[:, None, None, :plen]+ # Padded query positions are irrelevant; give them a finite self-attention+ # row, so their unused hidden states cannot introduce NaNs.+ for b, length in enumerate(lengths):+ for i in range(plen - length):+ prefill_mask[b, 0, i, i] = False+ use_graph = os.environ.get('OPENBUILD_GRAPH_DECODE', '1') == '1'+ graph = None+ if use_graph:+ graph = getattr(model, '_decode_graph', None)+ if graph is None or (graph.batch, graph.capacity) != (batch, capacity):+ graph = DecodeGraph(model, batch, capacity)+ model._decode_graph = graph+ caches = graph.caches+ else:+ caches = model.cache(batch, capacity)+ ids, positions = ids.to(device), positions.to(device)+ hidden = model.hidden(ids, positions, prefill_mask.to(device), caches=caches)+ logits = model.lm_head(hidden[:, -1]).float()+ del hidden+ decode_mask = prefix_padding[:, None, None, :].to(device)+ cache_positions = torch.arange(capacity, device=device)[None, None, None, :]+ base_positions = torch.tensor(lengths, device=device)[:, None]+ responses, logprobs = [[] for _ in specs], [[] for _ in specs]+ active = [True] * batch+ active_tensor = torch.ones(batch, device=device, dtype=torch.bool)+ started = time.monotonic()+ for step in range(256):+ if step == 0 or graph is None:+ token, old = sample(logits, draws[step], active_tensor)+ else:+ offset = plen + step - 1+ mask = decode_mask | (cache_positions > offset)+ token, old = graph.run(token, base_positions + step - 1, offset, mask, draws[step], active_tensor)+ # One host synchronization per decode step, for EOS and output records.+ values = torch.stack((token.float(), old), dim=1).cpu().tolist()+ for b, (tid, lp) in enumerate(values):+ if active[b]:+ responses[b].append(int(tid))+ logprobs[b].append(lp)+ if int(tid) in (151645, 151643):+ active[b] = False+ if not any(active) or step == 255:+ break+ active_tensor.logical_and_((token != 151645) & (token != 151643))+ token = token.masked_fill(~active_tensor, 151643)+ if graph is None:+ hidden = model.hidden(token[:, None], base_positions + step, decode_mask,+ caches=caches, offset=plen + step)+ logits = model.lm_head(hidden[:, -1]).float()+ torch.npu.synchronize(device)+ rows = []+ for (p, r), seed, tokens, old in zip(specs, seeds, responses, logprobs, strict=True):+ rows.append(dict(update=update, prompt_id=p['id'], prompt_ordinal=p['ordinal'],+ response_ordinal=r, request_seed=seed, generating_policy_version=version,+ response_token_ids=tokens, response_text=tokenizer.decode(tokens, skip_special_tokens=True),+ old_logprobs=old))+ print(f'rollout update={update} tokens={sum(map(len, responses))} decode_steps={step + 1} decode_seconds={time.monotonic() - started:.3f}', flush=True)+ return rowsdiff --git a/solution/tokenizer.py b/solution/tokenizer.pynew file mode 100644index 0000000000000000000000000000000000000000..392be89d932ca88fcde99840daa822833d9cfc97--- /dev/null+++ b/solution/tokenizer.py@@ -0,0 +1,31 @@+"""Small runtime tokenizer for the fixed two-message Qwen3 input interface.++Preparation checks this chat rendering against the supplied model's template.+Token IDs and decoding use the supplied tokenizer.json, without alterations.+"""+import json+from pathlib import Path++from tokenizers import Tokenizer+++class QwenTokenizer:+ def __init__(self, root):+ root = Path(root)+ self.backend = Tokenizer.from_file(str(root / 'tokenizer.json'))+ config = json.loads((root / 'tokenizer_config.json').read_text())+ if config.get('clean_up_tokenization_spaces', False):+ raise ValueError('Unexpected tokenizer text cleanup semantics')++ @staticmethod+ def render(system, question):+ return ('<|im_start|>system\n' + system + '<|im_end|>\n'+ '<|im_start|>user\n' + question + '<|im_end|>\n'+ '<|im_start|>assistant\n<think>\n\n</think>\n\n')++ def prompt_ids(self, prompt):+ return self.backend.encode(self.render(prompt['system_prompt'], prompt['question']),+ add_special_tokens=False).ids++ def decode(self, ids, skip_special_tokens=True):+ return self.backend.decode(ids, skip_special_tokens=skip_special_tokens)diff --git a/solution/train.py b/solution/train.pynew file mode 100644index 0000000000000000000000000000000000000000..bf9c324892fdd8944bf8cb57b7195caa1a2037a8--- /dev/null+++ b/solution/train.py@@ -0,0 +1,257 @@+"""Offline-replayable online GRPO: rollout -> verifier -> actor -> refresh."""+import argparse+import json+import os+import random+import time+import urllib.request+import contextlib+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path++import torch+import torch_npu++from algorithm import advantages, policy_terms+from model import Qwen, load_model, refresh, token_logprobs, training_batch+from optimizer import MasterAdamW+from rollout import generate+from tokenizer import QwenTokenizer++TASK_ID = 'openbuild_rl_qwen3_1_7b_online_grpo_rlvr_2dev_v1'+++def write_json(path, payload):+ tmp = path.with_suffix(path.suffix + '.tmp')+ tmp.write_text(json.dumps(payload, allow_nan=False, indent=2) + '\n')+ tmp.replace(path)+++def score(rows):+ body = json.dumps({'items': [dict(prompt_id=r['prompt_id'], response_text=r['response_text']) for r in rows]}).encode()+ request = urllib.request.Request(+ os.environ['OPENBUILD_REWARD_URL'].rstrip('/') + '/score_batch', data=body,+ headers={'Authorization': 'Bearer ' + os.environ['OPENBUILD_REWARD_TOKEN'], 'Content-Type': 'application/json'})+ with urllib.request.urlopen(request, timeout=120) as response:+ rewards = json.load(response)['rewards']+ if len(rewards) != len(rows) or any(r not in (0.0, 1.0) for r in rewards):+ raise ValueError('Verifier returned an invalid reward batch')+ for row, reward in zip(rows, rewards, strict=True):+ row['reward'] = float(reward)+ for offset in range(0, len(rows), 4):+ group = rows[offset:offset + 4]+ for row, adv in zip(group, advantages([r['reward'] for r in group]), strict=True):+ row['advantage'] = adv+++@torch.no_grad()+def freshness(actor, rollout, rows, prompts, update):+ # Independent forward passes on the two physical policy copies, after sync.+ row = dict(rows[0])+ row['response_token_ids'] = row['response_token_ids'][:16]+ row['old_logprobs'] = row['old_logprobs'][:16]+ left = token_logprobs(actor, training_batch([row], prompts, next(actor.parameters()).device)).cpu().tolist()+ right = token_logprobs(rollout, training_batch([row], prompts, next(rollout.parameters()).device)).cpu().tolist()+ return dict(update=update, policy_version=update, actor_logprobs=left,+ rollout_logprobs=right, prompt_id=row['prompt_id'],+ response_token_ids=row['response_token_ids'])+++def update_actor(actor, optimizer, rows, prompts, observations, update, first_update, microbatch):+ total = sum(len(r['response_token_ids']) for r in rows)+ device = next(actor.parameters()).device+ sums = torch.zeros(3, dtype=torch.float32, device=device)+ optimizer.zero_grad()+ for start in range(0, len(rows), microbatch):+ batch = training_batch(rows[start:start + microbatch], prompts, device)+ current = token_logprobs(actor, batch)+ old, adv = batch[-2:]+ losses, kls, clipped = policy_terms(current, old, adv)+ if start == 0 and update == first_update:+ n = min(16, len(rows[0]['response_token_ids']))+ observations['old_logprob_checks'].append(dict(update=update,+ actor_logprobs=current[:n].detach().cpu().tolist(),+ rollout_logprobs=old[:n].cpu().tolist(), prompt_id=rows[0]['prompt_id']))+ sums += torch.stack((losses.detach().sum(), kls.detach().sum(), clipped.float().sum()))+ (losses.sum() / total).backward()+ del batch, current, old, adv, losses, kls, clipped+ norm = optimizer.step()+ policy_loss, approx_kl, clip_fraction = (sums / total).cpu().tolist()+ torch.npu.synchronize(device)+ return dict(policy_loss=policy_loss, approx_kl=approx_kl, clip_fraction=clip_fraction,+ global_grad_norm=norm, parameter_projection=optimizer.projection())+++def save_checkpoint(optimizer, root, seed, input_id, observations):+ root.mkdir(parents=True, exist_ok=True)+ tensor_files = optimizer.save(root)+ state = dict(committed_update=8, next_update=9, actor_policy_version=8,+ rollout_policy_version=8, optimizer_step=optimizer.step_count,+ scheduler={'kind': 'constant', 'learning_rate': optimizer.lr, 'last_epoch': 8},+ data_cursor={'input_id': input_id, 'seed': seed, 'next_update': 9,+ 'prompt_ordinal': 0, 'response_ordinal': 0},+ optimizer={'lr': optimizer.lr, 'weight_decay': optimizer.decay,+ 'betas': [optimizer.beta1, optimizer.beta2], 'eps': optimizer.eps},+ parameter_projection=optimizer.projection(),+ parameter_tensor_count=len(optimizer.named))+ write_json(root / 'state.json', state)+ torch.save({'torch': torch.get_rng_state(), 'python': random.getstate(),+ 'npu': torch.npu.get_rng_state_all()}, root / 'rng.pt')+ write_json(root / 'manifest.json', dict(schema_version=1, kind='openbuild_rl_checkpoint',+ task_id=TASK_ID, committed_update=8, next_update=9,+ state_components=['model', 'optimizer', 'scheduler', 'committed_update', 'policy_version', 'data_cursor', 'rng'],+ files=[*tensor_files, 'state.json', 'rng.pt']))+++def main():+ parser = argparse.ArgumentParser()+ parser.add_argument('--input-manifest', required=True)+ parser.add_argument('--output-dir', required=True)+ args = parser.parse_args()+ payload = json.loads(Path(args.input_manifest).read_text())+ out = Path(args.output_dir)+ out.mkdir(parents=True, exist_ok=True)+ action = os.environ['OPENBUILD_ACTION']+ restart = action == 'restart'+ first_update = 9 if restart else 1+ final_update = 9 if restart else int(payload['committed_updates'])+ assert payload['responses_per_prompt'] == 4+ devices = [int(d) for d in os.environ['OPENBUILD_DEVICE_IDS'].split(',')]+ assert devices and len(devices) <= 2 and set(devices).issubset({0, 1})+ from lifecycle import register_execution+ register_execution(devices)+ actor_device, rollout_device = f'npu:{devices[0]}', f'npu:{devices[-1]}'+ torch.set_num_threads(8)+ torch.npu.set_device(actor_device)+ torch.npu.set_compile_mode(jit_compile=False)+ torch.manual_seed(int(payload['seed']))+ random.seed(int(payload['seed']))+ model_path = os.environ['OPENBUILD_MODEL_PATH']+ loaded = time.monotonic()+ actor = load_model(model_path, actor_device)+ actor.train()+ optimizer = MasterAdamW(actor)+ if restart:+ ready = json.loads((Path(os.environ['OPENBUILD_STATE_DIR']) / 'ready.json').read_text())+ checkpoint = Path(ready['checkpoint'])+ state = json.loads((checkpoint / 'state.json').read_text())+ assert state['committed_update'] == 8 and state['optimizer_step'] == 8+ assert state['actor_policy_version'] == state['rollout_policy_version'] == 8+ assert state['data_cursor']['next_update'] == 9+ assert state['next_update'] == payload['target_update'] == 9+ assert state['optimizer'] == dict(lr=1e-6, weight_decay=.01, betas=[.9, .999], eps=1e-8)+ assert state['scheduler'] == dict(kind='constant', learning_rate=1e-6, last_epoch=8)+ optimizer.restore(checkpoint)+ optimizer.step_count = state['optimizer_step']+ optimizer.lr = state['scheduler']['learning_rate']+ first_update = state['data_cursor']['next_update']+ assert optimizer.projection() == state['parameter_projection'], 'Restored model projection differs'+ rng = torch.load(checkpoint / 'rng.pt', weights_only=False, map_location='cpu')+ torch.set_rng_state(rng['torch'])+ random.setstate(rng['python'])+ torch.npu.set_rng_state_all(rng['npu'])+ with torch.device('meta'):+ rollout = Qwen(actor.cfg)+ rollout.to_empty(device=rollout_device)+ rollout.init_rope()+ rollout.requires_grad_(False).eval()+ refresh(actor, rollout)+ tokenizer = QwenTokenizer(os.environ['OPENBUILD_TOKENIZER_PATH'])+ prompts = {p['id']: tokenizer.prompt_ids(p) for p in payload['prompts']}+ print(f'loaded in {time.monotonic() - loaded:.3f}s parameters={sum(p.numel() for p in actor.parameters())}', flush=True)+ projection = optimizer.projection()+ observations = dict(initial={'parameter_projection': projection}, updates={}, freshness=[], old_logprob_checks=[],+ logical_parameter_count=sum(p.numel() for p in actor.parameters()),+ parameter_tensor_count=len(list(actor.parameters())), compute_dtype='bfloat16', optimizer_state_dtypes=['float32'],+ placement={'actor': actor_device, 'rollout': rollout_device}, timing={})+ if restart:+ observations['restart'] = dict(parameter_projection=projection, source_update=8,+ restored_optimizer_step=optimizer.step_count)+ events, accepted, consumed = [], 0, 0+ microbatch = int(os.environ.get('OPENBUILD_MICROBATCH', '4'))+ if microbatch <= 0:+ raise ValueError('Microbatch size must be positive')+ pipeline = (len(devices) == 2 and not restart and+ os.environ.get('OPENBUILD_PIPELINE', '1') == '1')+ observations['pipeline'] = pipeline++ def do_rollout(update, version):+ start = time.monotonic()+ with torch.npu.device(rollout_device):+ rows = generate(rollout, tokenizer, payload['prompts'], prompts,+ int(payload['seed']), update, version)+ return rows, time.monotonic() - start++ def do_actor(rows, update):+ start = time.monotonic()+ with torch.npu.device(actor_device):+ metrics = update_actor(actor, optimizer, rows, prompts, observations, update, first_update, microbatch)+ return metrics, time.monotonic() - start++ prefetched = None+ pool_context = ThreadPoolExecutor(max_workers=1, thread_name_prefix='actor') if pipeline else contextlib.nullcontext(None)+ with pool_context as pool, (out / 'trajectories.jsonl').open('w') as trajectory_file:+ for update in range(first_update, final_update + 1):+ started = time.monotonic()+ if prefetched is None:+ rows, rollout_seconds = do_rollout(update, update - 1)+ else:+ rows, rollout_seconds = prefetched+ prefetched = None+ reward_started = time.monotonic()+ score(rows)+ reward_seconds = time.monotonic() - reward_started+ prefetch_seconds = 0.0+ if pipeline and update < final_update:+ # The next batch uses the current rollout snapshot while the+ # independent actor copy trains. It is consumed at lag one.+ # Never modify rollout weights until this generation finishes.+ future = pool.submit(do_actor, rows, update)+ prefetched = do_rollout(update + 1, update - 1)+ prefetch_seconds = prefetched[1]+ metrics, actor_seconds = future.result()+ else:+ metrics, actor_seconds = do_actor(rows, update)+ sync_started = time.monotonic()+ refresh(actor, rollout)+ refresh_seconds = time.monotonic() - sync_started+ observations['updates'][str(update)] = metrics+ version = rows[0]['generating_policy_version']+ lag = update - 1 - version+ assert lag in (0, 1) and all(r['generating_policy_version'] == version for r in rows)+ events.append(dict(update=update, trajectory=version, actor_before=update - 1,+ actor_after=update, rollout_after_sync=update, lag=lag))+ if update in {first_update, final_update}:+ observations['freshness'].append(freshness(actor, rollout, rows, prompts, update))+ for row in rows:+ trajectory_file.write(json.dumps(row, allow_nan=False) + '\n')+ trajectory_file.flush()+ accepted += len(rows)+ consumed += sum(len(row['response_token_ids']) for row in rows)+ timing = dict(rollout_seconds=rollout_seconds, reward_seconds=reward_seconds,+ actor_seconds=actor_seconds, refresh_seconds=refresh_seconds,+ overlapped_next_rollout_seconds=prefetch_seconds,+ total_seconds=time.monotonic() - started)+ observations['timing'][str(update)] = timing+ write_json(out / 'observations.json', observations)+ print(f'committed update={update} rewards={[r["reward"] for r in rows]} metrics={metrics} timing={timing}', flush=True)+ checkpoint_path = None+ if final_update == 8:+ started = time.monotonic()+ save_checkpoint(optimizer, out / 'checkpoint', int(payload['seed']), payload['input_id'], observations)+ checkpoint_path = 'checkpoint/manifest.json'+ observations['checkpoint_seconds'] = time.monotonic() - started+ write_json(out / 'observations.json', observations)+ for device in devices:+ torch.npu.synchronize(device)+ observations['peak_npu_memory_bytes'] = {str(d): torch.npu.max_memory_allocated(d) for d in devices}+ observations['runtime_versions'] = {'torch': torch.__version__, 'torch_npu': torch_npu.__version__}+ write_json(out / 'observations.json', observations)+ write_json(out / 'result.json', dict(schema_version=1, kind='openbuild_rl_result', task_id=TASK_ID,+ status='completed', action=action, committed_updates=final_update, accepted_trajectories=accepted,+ consumed_response_tokens=consumed, logical_device_ids=devices, policy_versions=events,+ trajectory_path='trajectories.jsonl', observation_path='observations.json', checkpoint_manifest_path=checkpoint_path))+++if __name__ == '__main__':+ main()diff --git a/solution/validation.json b/solution/validation.jsonnew file mode 100644index 0000000000000000000000000000000000000000..a025c9592d5877338fcf7d65e696c887d275c340--- /dev/null+++ b/solution/validation.json@@ -0,0 +1,421 @@+{+ "schema_version": 1,+ "kind": "openbuild_solution_validation_record",+ "task_id": "openbuild_rl_qwen3_1_7b_online_grpo_rlvr_2dev_v1",+ "model": "Qwen/Qwen3-1.7B",+ "recorded_at_utc": "REDACTED_DATE",+ "purpose": "Documentation of observed local checks. This file is not read by runtime entrypoints and is not a formal measurement result.",+ "runtime": {+ "logical_device_ids": [+ 0,+ 1+ ],+ "hardware": "2 Ascend 910B1",+ "versions": {+ "torch": "2.9.0+cpu",+ "torch_npu": "2.9.0.post2"+ },+ "offline_dependencies": "Supplied base runtime and model utilities plus solution/vendor/libzstd.so.1; bootstrap installs nothing."+ },+ "lifecycle_commands": {+ "describe": {+ "command": "bash \"$TASK_DIR/run/describe.sh\"",+ "status": "passed"+ },+ "smoke": {+ "command": "bash \"$TASK_DIR/run/smoke.sh\"",+ "report": {+ "cleanup": {+ "attempted": true,+ "cleanup_returncode": 0,+ "complete": true,+ "details": {+ "cleanup_entrypoint_exited": true,+ "ports_released": true,+ "process_groups_stopped": true+ },+ "ports_released": true,+ "process_groups_stopped": true,+ "transient_runtime_artifacts": {+ "complete": true,+ "errors": [],+ "removed": [+ "environment"+ ]+ }+ },+ "details": {+ "accepted_trajectories": 4,+ "algorithm_probe": null,+ "committed_updates": 1,+ "consumed_response_tokens": 411,+ "end_to_end_seconds": 28.052451594732702+ },+ "gates": {+ "actor_update_valid": true,+ "advantage_valid": true,+ "algorithm_probe": true,+ "checkpoint_complete": true,+ "cleanup_complete": true,+ "device_execution": true,+ "freshness_valid": true,+ "hardware_available": true,+ "offline_bootstrap": true,+ "old_logprobs_valid": true,+ "policy_versions_valid": true,+ "prepare_ready": true,+ "restart_valid": true,+ "reward_valid": true,+ "runtime_identity": true,+ "solution_contract": true,+ "work_complete": true+ },+ "kind": "benchmark_task_smoke",+ "measurement_valid": false,+ "metrics": null,+ "mode": "smoke",+ "model": "Qwen/Qwen3-1.7B",+ "reason": null,+ "runtime_id": "openbuild_rl_ascend_910b1_fullstack_v1",+ "schema_version": 1,+ "status": "passed",+ "task_id": "openbuild_rl_qwen3_1_7b_online_grpo_rlvr_2dev_v1"+ }+ },+ "development_correctness": {+ "command": "bash \"$TASK_DIR/run/development_correctness.sh\"",+ "report": {+ "cleanup": {+ "attempted": true,+ "cleanup_returncode": 0,+ "complete": true,+ "details": {+ "cleanup_entrypoint_exited": true,+ "ports_released": true,+ "process_groups_stopped": true+ },+ "ports_released": true,+ "process_groups_stopped": true,+ "transient_runtime_artifacts": {+ "complete": true,+ "errors": [],+ "removed": [+ "environment",+ "correctness-online-output/checkpoint"+ ]+ }+ },+ "details": {+ "accepted_trajectories": 256,+ "algorithm_probe": {+ "passed": true,+ "probe_id": "public-development-1"+ },+ "committed_updates": 8,+ "consumed_response_tokens": 19394,+ "end_to_end_seconds": 53.99812263250351+ },+ "gates": {+ "actor_update_valid": true,+ "advantage_valid": true,+ "algorithm_probe": true,+ "checkpoint_complete": true,+ "cleanup_complete": true,+ "device_execution": true,+ "freshness_valid": true,+ "hardware_available": true,+ "offline_bootstrap": true,+ "old_logprobs_valid": true,+ "policy_versions_valid": true,+ "prepare_ready": true,+ "restart_valid": true,+ "reward_valid": true,+ "runtime_identity": true,+ "solution_contract": true,+ "work_complete": true+ },+ "kind": "openbuild_rl_development_correctness",+ "measurement_valid": false,+ "metrics": null,+ "mode": "correctness",+ "model": "Qwen/Qwen3-1.7B",+ "reason": null,+ "runtime_id": "openbuild_rl_ascend_910b1_fullstack_v1",+ "schema_version": 1,+ "status": "passed",+ "task_id": "openbuild_rl_qwen3_1_7b_online_grpo_rlvr_2dev_v1"+ }+ },+ "correctness": {+ "command": "bash \"$TASK_DIR/run/correctness.sh\"",+ "report": {+ "cleanup": {+ "attempted": true,+ "complete": true,+ "details": {}+ },+ "details": null,+ "gates": {+ "cleanup_complete": true,+ "evaluation_input_available": false,+ "hardware_available": true+ },+ "kind": "benchmark_task_correctness",+ "measurement_valid": false,+ "metrics": null,+ "mode": "correctness",+ "model": "Qwen/Qwen3-1.7B",+ "reason": "evaluation input bundle is unavailable",+ "runtime_id": "openbuild_rl_ascend_910b1_fullstack_v1",+ "schema_version": 1,+ "status": "failed",+ "task_id": "openbuild_rl_qwen3_1_7b_online_grpo_rlvr_2dev_v1"+ }+ },+ "measurement": {+ "command": "bash \"$TASK_DIR/run/measurement.sh\"",+ "report": {+ "cleanup": {+ "attempted": true,+ "complete": true,+ "details": {}+ },+ "details": null,+ "gates": {+ "cleanup_complete": true,+ "evaluation_input_available": false,+ "hardware_available": true+ },+ "kind": "benchmark_measurement",+ "measurement_valid": false,+ "metrics": null,+ "mode": "normal",+ "model": "Qwen/Qwen3-1.7B",+ "reason": "evaluation input bundle is unavailable",+ "runtime_id": "openbuild_rl_ascend_910b1_fullstack_v1",+ "schema_version": 1,+ "status": "failed",+ "task_id": "openbuild_rl_qwen3_1_7b_online_grpo_rlvr_2dev_v1"+ }+ },+ "cleanup": {+ "command": "bash \"$TASK_DIR/run/cleanup.sh\"",+ "report": {+ "attempted": true,+ "cleanup_returncode": 0,+ "complete": true,+ "details": {+ "cleanup_entrypoint_exited": true,+ "ports_released": true,+ "process_groups_stopped": true+ },+ "kind": "benchmark_task_cleanup",+ "measurement_valid": false,+ "ports_released": true,+ "process_groups_stopped": true,+ "runtime_id": "openbuild_rl_ascend_910b1_fullstack_v1",+ "schema_version": 1,+ "status": "passed",+ "task_id": "openbuild_rl_qwen3_1_7b_online_grpo_rlvr_2dev_v1"+ }+ }+ },+ "fresh_runtime_audit": {+ "isolation": "Re-ran the task development command with fresh TASK_HOME and TASK_OUTPUT_DIR subdirectories, including empty run-owned environment, state, and Python cache.",+ "report": {+ "cleanup": {+ "attempted": true,+ "cleanup_returncode": 0,+ "complete": true,+ "details": {+ "cleanup_entrypoint_exited": true,+ "ports_released": true,+ "process_groups_stopped": true+ },+ "ports_released": true,+ "process_groups_stopped": true,+ "transient_runtime_artifacts": {+ "complete": true,+ "errors": [],+ "removed": [+ "environment",+ "correctness-online-output/checkpoint"+ ]+ }+ },+ "details": {+ "accepted_trajectories": 256,+ "algorithm_probe": {+ "passed": true,+ "probe_id": "public-development-1"+ },+ "committed_updates": 8,+ "consumed_response_tokens": 19394,+ "end_to_end_seconds": 53.688368732109666+ },+ "gates": {+ "actor_update_valid": true,+ "advantage_valid": true,+ "algorithm_probe": true,+ "checkpoint_complete": true,+ "cleanup_complete": true,+ "device_execution": true,+ "freshness_valid": true,+ "hardware_available": true,+ "offline_bootstrap": true,+ "old_logprobs_valid": true,+ "policy_versions_valid": true,+ "prepare_ready": true,+ "restart_valid": true,+ "reward_valid": true,+ "runtime_identity": true,+ "solution_contract": true,+ "work_complete": true+ },+ "kind": "openbuild_rl_development_correctness",+ "measurement_valid": false,+ "metrics": null,+ "mode": "correctness",+ "model": "Qwen/Qwen3-1.7B",+ "reason": null,+ "runtime_id": "openbuild_rl_ascend_910b1_fullstack_v1",+ "schema_version": 1,+ "status": "passed",+ "task_id": "openbuild_rl_qwen3_1_7b_online_grpo_rlvr_2dev_v1"+ },+ "derived_consumed_response_tokens_per_execute_second": 361.232804385821,+ "formal_measurement": false,+ "online_update_intervals_total_seconds": 18.63702230900526,+ "checkpoint_seconds": 7.999294279143214,+ "update_stage_timings": {+ "1": {+ "rollout_seconds": 2.957558418624103,+ "reward_seconds": 0.015888428315520287,+ "actor_seconds": 1.8641029549762607,+ "refresh_seconds": 0.19625787809491158,+ "overlapped_next_rollout_seconds": 1.7661181027069688,+ "total_seconds": 5.136389082297683+ },+ "2": {+ "rollout_seconds": 1.7661181027069688,+ "reward_seconds": 0.0023617343977093697,+ "actor_seconds": 1.191783788613975,+ "refresh_seconds": 0.19630075804889202,+ "overlapped_next_rollout_seconds": 1.8531290777027607,+ "total_seconds": 2.054806338623166+ },+ "3": {+ "rollout_seconds": 1.8531290777027607,+ "reward_seconds": 0.0023090457543730736,+ "actor_seconds": 1.147295270115137,+ "refresh_seconds": 0.1963725285604596,+ "overlapped_next_rollout_seconds": 1.8072685804218054,+ "total_seconds": 2.0090047419071198+ },+ "4": {+ "rollout_seconds": 1.8072685804218054,+ "reward_seconds": 0.002618076279759407,+ "actor_seconds": 1.1578608555719256,+ "refresh_seconds": 0.19629273936152458,+ "overlapped_next_rollout_seconds": 1.8068971578031778,+ "total_seconds": 2.008828902617097+ },+ "5": {+ "rollout_seconds": 1.8068971578031778,+ "reward_seconds": 0.0023621851578354836,+ "actor_seconds": 1.1140787219628692,+ "refresh_seconds": 0.19636291917413473,+ "overlapped_next_rollout_seconds": 1.7408295553177595,+ "total_seconds": 1.942597716115415+ },+ "6": {+ "rollout_seconds": 1.7408295553177595,+ "reward_seconds": 0.003064149059355259,+ "actor_seconds": 1.1208765245974064,+ "refresh_seconds": 0.19628516770899296,+ "overlapped_next_rollout_seconds": 1.8233589101582766,+ "total_seconds": 2.0257306369021535+ },+ "7": {+ "rollout_seconds": 1.8233589101582766,+ "reward_seconds": 0.0033939313143491745,+ "actor_seconds": 1.173397502861917,+ "refresh_seconds": 0.19636325910687447,+ "overlapped_next_rollout_seconds": 1.8123037805780768,+ "total_seconds": 2.015024220570922+ },+ "8": {+ "rollout_seconds": 1.8123037805780768,+ "reward_seconds": 0.002918778918683529,+ "actor_seconds": 1.1491530807688832,+ "refresh_seconds": 0.19630667939782143,+ "overlapped_next_rollout_seconds": 0.0,+ "total_seconds": 1.4446406699717045+ }+ },+ "timing_note": "Rollout and actor intervals overlap; do not sum individual stage times to estimate execute wall time.",+ "peak_pytorch_allocated_npu_memory_bytes": {+ "0": 36853614080,+ "1": 5452641792+ },+ "logical_parameter_count": 2031739904,+ "parameter_tensor_count": 311,+ "compute_dtype": "bfloat16",+ "optimizer_state_dtypes": [+ "float32"+ ],+ "restart": {+ "status": "completed",+ "committed_update": 9,+ "newly_accepted_trajectories": 4,+ "newly_consumed_response_tokens": 634,+ "policy_versions": [+ {+ "update": 9,+ "trajectory": 8,+ "actor_before": 8,+ "actor_after": 9,+ "rollout_after_sync": 9,+ "lag": 0+ }+ ],+ "checkpoint_parameter_projection": 17370.376972572376,+ "restored_parameter_projection": 17370.376972572376,+ "after_update_9_parameter_projection": 17370.37691519113,+ "restored_optimizer_step": 8+ }+ },+ "additional_checks": {+ "python3 solution/check_math.py": "passed: group normalization, clipped-loss gradients, sampling boundaries, FP32 master AdamW versus PyTorch",+ "python3 solution/check_decode.py": "passed: captured NPU decode versus eager KV and dense teacher forcing, in-place weight refresh",+ "python3 solution/checkpoint_io.py": "passed: CPU bitwise state round trip and truncated-chunk rejection",+ "python3 solution/checkpoint_io.py --npu": "passed: NPU transfer bitwise state round trip and truncated-chunk rejection",+ "python3 solution/check_lifecycle.py": "passed: process identity protection, termination, repeated cleanup"+ },+ "final_device_cleanup": {+ "check": "npu-smi info after task cleanup",+ "result": "No running processes found on either assigned NPU."+ },+ "formal_validation_limitation": "Correctness and measurement both returned evaluation input bundle is unavailable. No task-owned formal input bundle or formal reward access was supplied; no formal score is claimed.",+ "runtime_source_sha256": {+ "algorithm.py": "80a4ab7d859cccf1d9a94a08a24cfcbca0cb82d1f7fc5dd56478e788187d879a",+ "bootstrap.sh": "1daa8963cd24bdb7e743e36c4ffe0ef708b1d46a4dcd6311743d41c34fc092a0",+ "check_decode.py": "ed1a5c3895e0c6d18e6730191b4cdb39154d3137ef9bc8ccd2f4c3d500d4d2e0",+ "check_lifecycle.py": "9d849178a4a0fc1256874bff0dcfa7cfcbe908fc9fc21e59bc3ce8f4cc8abb9f",+ "check_math.py": "e1e8bf649e4092e3a0acfa2627339f8a8916122328fa7dfff2d18c1303c26444",+ "checkpoint_io.py": "a32e579de5b25c9d7bb183c21985160f2fb615268aa023add90fd7ff60f90af5",+ "cleanup.sh": "326c8b47271b233d9ecf7479e34cf14e9a51ed29b30e8a9582cfd1ace8689dfe",+ "decode_graph.py": "ec279b434cde821c796c53776a918fe31d4d64b68b079067d1cbe934a1260073",+ "execute.sh": "680b7bb047ebf5bf7263f1feeb376254c0b129fa384982e7bf502e8b464b881d",+ "lifecycle.py": "5cb36dc56a0acbfaed49543eb1b406b801b3deaa45eaedd0a94a43556e1f93db",+ "manifest.json": "b3c718ae300f0242e671788ecda05c19a56f74e2273fed469bbc3edef28185fe",+ "model.py": "f619a6c3c53e8ffed8ed8fc0b464d1cebfa9a7178d7c6c407e3950ad83485ebd",+ "optimizer.py": "014c7ec42cf15b465b28d32e962d03a20e6e3c10070e42dabd84a77449d4213d",+ "prepare.sh": "f785286501743507ae0fb3d8abffea9d831b6bb4b2e838d968d0a13b55ad951e",+ "probe.sh": "8c22ce23a135ccce574d81bdf9626c1b01eb1026034e82ee73a062246e47253d",+ "rollout.py": "2e1f9b9412a4e2510c1dbec7e79d87cbf1ba6eb6da62828edafa0f0a4b84075d",+ "tokenizer.py": "be533d69466f7726e7a4888e3c0fa4581ef39d80f8ab57a4dc4eac2e3b8913e8",+ "train.py": "aa65dd9a15954b710cba0d28e5b29d0f0a2d3696435a43e86e91c232eb5ecf1c",+ "vendor/libzstd.so.1": "a1561916ef6f9bfdcf3246b4cb1eab98771a9f689422cae645d89e3cc589035d"+ }+}diff --git a/solution/vendor/README.md b/solution/vendor/README.mdnew file mode 100644index 0000000000000000000000000000000000000000..28aadf8bc8175b767ca9040cb1555a9876155fbf--- /dev/null+++ b/solution/vendor/README.md@@ -0,0 +1,9 @@+# Vendored lossless compression runtime++`libzstd.so.1` is the AArch64 Debian libzstd 1.4.8 binary supplied by the build+environment, copied as a regular file so offline replay has no system-package+dependency. SHA256:+`a1561916ef6f9bfdcf3246b4cb1eab98771a9f689422cae645d89e3cc589035d`.++The upstream project is https://github.com/facebook/zstd. The BSD license and+Debian package copyright notices are preserved in `ZSTD-COPYRIGHT`.diff --git a/solution/vendor/ZSTD-COPYRIGHT b/solution/vendor/ZSTD-COPYRIGHTnew file mode 100644index 0000000000000000000000000000000000000000..1045de1f34b4d2d3dd58476298114366bca017b6--- /dev/null+++ b/solution/vendor/ZSTD-COPYRIGHT@@ -0,0 +1,117 @@+Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/+Upstream-Name: Zstd+Source: https://github.com/facebook/zstd+Files-Excluded: appveyor.yml+ build/*+ programs/windres/*+ .travis.yml+ .buckversion+ .buckconfig+ .circleci/*+ .cirrus.yml++Files: *+Copyright: 2013-2018, Yann Collet+ 2016, Przemyslaw Skibinski+ 2016-2018, Facebook, Inc.+License: BSD-3-clause and GPL-2+Comment: Starting from 1.3.1 zstd's patent claim is removed+ see: https://github.com/facebook/zstd/pull/801++Files: zlibWrapper/examples/*.c+Copyright: 1995-2006, 2011 Jean-loup Gailly+License: zlib++Files: zlibWrapper/gz*.c+Copyright: (C) 2004, 2005, 2010, 2011, 2012, 2013 Mark Adler+License: zlib++License: zlib+ This software is provided 'as-is', without any express or implied+ warranty. In no event will the authors be held liable for any damages+ arising from the use of this software.+ .+ Permission is granted to anyone to use this software for any purpose,+ including commercial applications, and to alter it and redistribute it+ freely, subject to the following restrictions:+ .+ 1. The origin of this software must not be misrepresented; you must not+ claim that you wrote the original software. If you use this software+ in a product, an acknowledgement in the product documentation would be+ appreciated but is not required.+ 2. Altered source versions must be plainly marked as such, and must not be+ misrepresented as being the original software.+ 3. This notice may not be removed or altered from any source distribution.++Files: lib/dictBuilder/divsufsort.*+Copyright: 2003-2008, Yuta Mori+License: Expat++Files: examples/*+Copyright: 2016-present, Yann Collet, Facebook, Inc.+License: BSD-3-clause and GPL-2++Files: debian/*+Copyright: 2015-2016 Kevin Murray <redacted@example.invalid>+License: Expat++License: Expat+ Permission is hereby granted, free of charge, to any person obtaining+ a copy of this software and associated documentation files (the+ "Software"), to deal in the Software without restriction, including+ without limitation the rights to use, copy, modify, merge, publish,+ distribute, sublicense, and/or sell copies of the Software, and to+ permit persons to whom the Software is furnished to do so, subject to+ the following conditions:+ .+ The above copyright notice and this permission notice shall be+ included in all copies or substantial portions of the Software.+ .+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS+ BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN+ ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+ SOFTWARE.++License: GPL-2+ This program is free software; you can redistribute it and/or modify+ it under the terms of the GNU General Public License, v2, as+ published by the Free Software Foundation+ .+ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU General Public License for more details.+ .+ You should have received a copy of the GNU General Public License along+ with this program; if not, write to the Free Software Foundation, Inc.,+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.+ .+ On Debian systems, the complete text of the GNU General Public+ License version 2 can be found in `/usr/share/common-licenses/GPL-2'.++License: BSD-3-clause+ 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 of cereal 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 RANDOLPH VOORHIES OR SHANE GRANT 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.