Inspect · Source & workspace
Requested workspace inspection related to source & workspace.
1 call · #0001–#0001
echo <val>ls -l -a <val> <n> > <path>trueKimi K3 · RL
OpenBuild Qwen3-1.7B online GRPO 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 agentKimi K3 · 125 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 related to source & workspace.
1 call · #0001–#0001
echo <val>ls -l -a <val> <n> > <path>trueRequested file and log inspection related to task requirements.
2 calls · #0002–#0003
Read <path>Requested file and log inspection related to source & workspace.
1 call · #0004–#0004
Read <path>Requested workspace inspection related to task requirements.
1 call · #0005–#0005
ls -l -a <path> <path> <path> <path> <path> <path>Requested file and log inspection related to source & workspace.
3 calls · #0006–#0008
cd <path><command> <args>cat <val>Read <path>Requested file and log inspection related to task requirements.
1 call · #0009–#0009
cd <path><command> <args>cat <val>echoRequested file and log inspection related to source & workspace.
1 call · #0010–#0010
cd <path><command> <args>cat <val>echoRequested environment setup or inspection, source searches and runtime inspection related to device memory.
1 call · #0011–#0011
envgrep -E <val>sortecho <flag>npu-smi info <n> >& <path>head -n <n>cat <val> <n> > <path>Requested script or workload execution, file and log inspection and workspace inspection related to source & workspace.
3 calls · #0012–#0014
python3 -c <script> <n> >& <path>tail -n <n>ls <path>echo <flag>python3 -c <script>cat <path>df -h <path> <path>catfree -ghead -n <n><command> <args>Requested script or workload execution related to device memory.
1 call · #0015–#0015
cd <path>timeout <n> <val> -c <path>Requested file and log inspection, script or workload execution and source searches related to device memory.
1 call · #0016–#0016
cd <path>cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>Requested file and log inspection, script or workload execution and source searches related to source & workspace.
6 calls · #0017–#0022
cd <path>cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>ls <path>grep -n <val> -r <path>headgrep -n <val> <path>sed -n <val> <path>grep -n <val> -A <n> <path>sed -n <val>Requested file and log inspection and script or workload execution related to task requirements.
1 call · #0023–#0023
cd <path>cat <val>echo <flag>python3 -c <script>Requested source searches and file and log inspection related to source & workspace.
1 call · #0024–#0024
grep -n <val> -A <n> <path>head -n <n>Requested code edits related to source & workspace.
1 call · #0025–#0025
Write <path>Requested source searches and file and log inspection related to source & workspace.
2 calls · #0026–#0027
grep -n <val> -A <n> <path>grep -n <val> -A <n>head -n <n>sed -n <val> <path>Requested code edits related to source & workspace.
1 call · #0028–#0028
Write <path>Requested script or workload execution and source searches related to source & workspace.
1 call · #0029–#0029
cd <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>Requested script or workload execution and file and log inspection related to attention kernels.
2 calls · #0030–#0031
python3 -c <script> <n> >& <path>tail -n <n>python3 - <script>Requested code edits, script or workload execution and source searches related to attention kernels.
1 call · #0032–#0032
cd <path>sed -i <path> <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>Requested file and log inspection, script or workload execution and source searches related to attention kernels.
1 call · #0033–#0033
cd <path>cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>Requested code edits, script or workload execution and source searches related to source & workspace.
1 call · #0034–#0034
cd <path>sed -i <val> <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>Requested script or workload execution and source searches related to source & workspace.
1 call · #0035–#0035
cd <path>python3 - <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>Requested source searches related to attention kernels.
1 call · #0036–#0036
grep -n <val> -A <n> <path>Requested script or workload execution and source searches related to source & workspace.
1 call · #0037–#0037
cd <path>python3 - <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>Requested code edits, script or workload execution and source searches related to source & workspace.
1 call · #0038–#0038
cd <path>sed -i <val> <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>Requested file and log inspection related to source & workspace.
2 calls · #0039–#0040
sed -n <val> <path>Requested file and log inspection, script or workload execution and source searches related to attention kernels.
2 calls · #0041–#0042
cd <path>cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>Requested code edits, script or workload execution and source searches related to source & workspace.
1 call · #0043–#0043
cd <path>sed -i <val> <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>Requested script or workload execution and source searches related to source & workspace.
4 calls · #0044–#0047
cd <path>python3 - <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>Requested file and log inspection, script or workload execution and source searches related to attention kernels.
2 calls · #0048–#0049
cd <path>cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>Requested file and log inspection, script or workload execution and source searches related to precision & numerical checks.
1 call · #0050–#0050
cd <path>cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>Requested workspace inspection and file and log inspection related to source & workspace.
1 call · #0051–#0051
date -uls -l -a <path>cat <path>Requested code edits related to source & workspace.
12 calls · #0052–#0063
Write <path>Requested code edits related to task requirements.
1 call · #0064–#0064
Write <path>Requested code edits related to source & workspace.
2 calls · #0065–#0066
Edit <path>Write <path>Requested script or workload execution, source searches and file and log inspection related to source & workspace.
2 calls · #0067–#0068
cd <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>python3 - <script>Requested code edits related to source & workspace.
1 call · #0069–#0069
Edit <path>Requested script or workload execution, source searches and file and log inspection related to source & workspace.
1 call · #0070–#0070
cd <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>Requested file and log inspection, script or workload execution and source searches related to batching & scheduling.
1 call · #0071–#0071
cd <path>cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>Requested code edits related to source & workspace.
1 call · #0072–#0072
Edit <path>Requested script or workload execution, source searches and file and log inspection related to source & workspace.
2 calls · #0073–#0074
cd <path>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>chmod <val> <path>mkdir -p <val>Requested script or workload execution and file and log inspection related to benchmark & validation setup.
2 calls · #0075–#0076
cd <path>timeout <n> <val> <path> <n> >& <path>tail -n <n>bash <script> > <path> <n> >& <path>echo <val> >> <path>Requested execution waits, file and log inspection and workspace inspection related to source & workspace.
1 call · #0077–#0077
sleep <n>tail -n <n> <path> <n> > <path>ls -l -a <path> <n> > <path>Requested execution waits, file and log inspection and workspace inspection related to checkpoints & weight state.
1 call · #0078–#0078
sleep <n>tail -n <n> <path>ls <path> <n> > <path>du <flag> <args>Requested workspace inspection and file and log inspection related to source & workspace.
1 call · #0079–#0079
ls <path>tail -n <n>echo <val>tail -n <n> <path> <n> > <path>echo <val> <val>ls -l -a <path> <n> > <path>Requested code edits related to source & workspace.
1 call · #0080–#0080
Edit <path>Requested script or workload execution, source searches and file and log inspection related to benchmark & validation setup.
2 calls · #0081–#0082
cd <path>bash <script> > <path> <n> >& <path>echo <val> >> <path>python3 -c <script> <n> > <path>grep -o <val> <path>head -n <n>Requested script or workload execution related to attention kernels.
1 call · #0083–#0083
python3 - <script>Requested file and log inspection and script or workload execution related to source & workspace.
1 call · #0084–#0084
tail -n <n> <path>head -n <n>python3 -c <script>Requested environment setup or inspection, workspace file updates and workspace inspection related to benchmark & validation setup.
2 calls · #0085–#0086
env <vars>rm -rf <path> <path> <path> <path> <path> <path> <path> <path> <path> <path> <args>ls <val>cd <path>bash <script> > <path> <n> >& <path>echo <val> >> <path>Requested file and log inspection, script or workload execution and source searches related to source & workspace.
1 call · #0087–#0087
cd <path>cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>Requested file and log inspection, script or workload execution and source searches related to attention kernels.
1 call · #0088–#0088
cd <path>cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>Requested file and log inspection related to source & workspace.
1 call · #0089–#0089
Read <path>Requested code edits related to source & workspace.
1 call · #0090–#0090
Edit <path>Requested script or workload execution related to checkpoints & weight state.
1 call · #0091–#0091
cd <path>python3 - <script>python3 -c <script>Requested script or workload execution related to reward & policy updates.
1 call · #0092–#0092
cd <path>python3 - <script>python3 -c <script>Requested file and log inspection and script or workload execution related to source & workspace.
1 call · #0093–#0093
tail -n <n> <path>head -n <n>python3 -c <script>Requested environment setup or inspection, workspace inspection and script or workload execution related to reward & policy updates.
1 call · #0094–#0094
env <vars>ls <path> <n> > <path>python3 - <script>Requested file and log inspection, script or workload execution and source searches related to reward & policy updates.
2 calls · #0095–#0096
cd <path>cat > <path> <script>timeout <n> <val> <path> <n> >& <path>grep -v <val>tail -n <n>Requested script or workload execution related to task requirements.
1 call · #0097–#0097
python3 - <script>Requested code edits related to source & workspace.
1 call · #0098–#0098
Write <path>Requested script or workload execution related to source & workspace.
1 call · #0099–#0099
cd <path>python3 <script> > <path> <n> >& <path>echo <val> >> <path>Requested script or workload execution and file and log inspection related to benchmark & validation setup.
2 calls · #0100–#0101
cd <path>timeout <n> <val> <path> <n> >& <path>tail -n <n>python3 -c <script>Requested source searches and file and log inspection related to source & workspace.
2 calls · #0102–#0103
grep -E <val> <path>tail -n <n>Read <path>Requested code edits related to source & workspace.
1 call · #0104–#0104
Edit <path>Requested script or workload execution related to checkpoints & weight state.
1 call · #0105–#0105
cd <path>python3 - <script>python3 <script> > <path> <n> >& <path>echo <val> >> <path>Requested environment setup or inspection, workspace file updates and script or workload execution related to benchmark & validation setup.
3 calls · #0106–#0108
env <vars>rm -rf <path> <path> <path> <path> <path> <path> <path> <path> <path> <path> <args>cd <path>timeout <n> <val> <path> <n> >& <path>tail -n <n> > <path>python3 -c <script>tail -c <n> <path>echoecho <val>tail -n <n> <path> <n> > <path>Requested script or workload execution related to reward & policy updates.
1 call · #0109–#0109
python3 - <script>Requested source searches and file and log inspection related to device memory.
1 call · #0110–#0110
grep -E <val> <path>tail -n <n>Requested script or workload execution related to reward & policy updates.
1 call · #0111–#0111
cd <path>python3 - <script>python3 -c <script>Requested source searches and file and log inspection related to source & workspace.
2 calls · #0112–#0113
cd <path>grep -n <val> <path>head -n <n>Read <path>Requested code edits related to source & workspace.
1 call · #0114–#0114
Edit <path>Requested source searches and file and log inspection related to source & workspace.
2 calls · #0115–#0116
cd <path>grep -n <val> <path>Read <path>Requested code edits related to source & workspace.
1 call · #0117–#0117
Edit <path>Requested file and log inspection related to source & workspace.
1 call · #0118–#0118
Read <path>Requested code edits related to source & workspace.
1 call · #0119–#0119
Edit <path>Requested script or workload execution, environment setup or inspection and workspace file updates related to benchmark & validation setup.
2 calls · #0120–#0121
python3 -c <script>env <vars>rm -rf <path> <path> <path> <path> <path> <path> <path> <path>cd <path>timeout <n> <val> <path> > <path> <n> >& <path>bash <script> > <path> <n> >& <path>echo <val> >> <path>Requested workspace inspection and script or workload execution related to source & workspace.
1 call · #0122–#0122
cd <path>find <val> -type <val>sortdu <flag> <args>python3 -c <script>Requested execution waits related to source & workspace.
1 call · #0123–#0123
Wait for <task>Requested file and log inspection and script or workload execution related to source & workspace.
1 call · #0124–#0124
tail -n <n> <path>head -n <n>python3 -c <script>Requested script or workload execution, file and log inspection and runtime inspection related to device memory.
1 call · #0125–#0125
cd <path>timeout <n> <val> <path> <n> >& <path>tail -n <n>pgrep <flag> <args>echo <val>npu-smi info <n> > <path>grep -E <val>head -n <n>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,7 @@+#!/usr/bin/env bash+# Offline bootstrap: the solution needs no extra packages beyond the neutral+# base runtime (torch, torch_npu, transformers, numpy, safetensors, tokenizers).+# Idempotent; installs nothing; never touches the base Python surface.+set -euo pipefail+command -v python3 >/dev/null+exit 0@@ -0,0 +1,5 @@+#!/usr/bin/env bash+set -euo pipefail+SOL="${OPENBUILD_SOLUTION_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"+env PYTHONPATH="$SOL" python3 -m grpo_engine.cleanup+exit 0@@ -0,0 +1,4 @@+#!/usr/bin/env bash+set -euo pipefail+SOL="${OPENBUILD_SOLUTION_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"+exec env PYTHONPATH="$SOL" python3 -m grpo_engine.client "$@"@@ -0,0 +1,51 @@+"""Stop the worker process group and release the port. Safe to call repeatedly."""+from __future__ import annotations++import json+import os+import signal+import time+from pathlib import Path+++def _group_alive(pgid: int) -> bool:+ try:+ os.killpg(pgid, 0)+ except ProcessLookupError:+ return False+ except PermissionError:+ return True+ return True+++def main() -> int:+ state_dir = Path(os.environ.get("OPENBUILD_STATE_DIR", ""))+ meta_path = state_dir / "worker.json"+ if meta_path.is_file():+ try:+ meta = json.loads(meta_path.read_text())+ pgid = int(meta["pgid"])+ except Exception: # noqa: BLE001+ pgid = None+ if pgid is not None and pgid > 1 and _group_alive(pgid):+ try:+ os.killpg(pgid, signal.SIGTERM)+ except ProcessLookupError:+ pass+ deadline = time.monotonic() + 25.0+ while time.monotonic() < deadline and _group_alive(pgid):+ time.sleep(0.2)+ if _group_alive(pgid):+ try:+ os.killpg(pgid, signal.SIGKILL)+ except ProcessLookupError:+ pass+ deadline = time.monotonic() + 10.0+ while time.monotonic() < deadline and _group_alive(pgid):+ time.sleep(0.2)+ meta_path.unlink(missing_ok=True)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())@@ -0,0 +1,48 @@+"""Execute-time client: forwards the scored run request to the warm worker."""+from __future__ import annotations++import argparse+import json+import os+import sys+import urllib.request+from pathlib import Path+++def main() -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--input-manifest", required=True)+ parser.add_argument("--output-dir", required=True)+ args = parser.parse_args()++ state_dir = Path(os.environ["OPENBUILD_STATE_DIR"])+ meta = json.loads((state_dir / "worker.json").read_text())+ port = int(meta["port"])+ payload = {+ "input_manifest": args.input_manifest,+ "output_dir": args.output_dir,+ "reward_url": os.environ["OPENBUILD_REWARD_URL"],+ "reward_token": os.environ["OPENBUILD_REWARD_TOKEN"],+ "action": os.environ.get("OPENBUILD_ACTION", ""),+ }+ req = urllib.request.Request(+ f"http://127.0.0.1:{port}/run",+ data=json.dumps(payload).encode(),+ headers={"Content-Type": "application/json"},+ )+ try:+ with urllib.request.urlopen(req, timeout=6900) as resp:+ body = json.loads(resp.read())+ except urllib.error.HTTPError as exc:+ detail = exc.read().decode(errors="replace")+ print(f"worker run failed: HTTP {exc.code}\n{detail}", file=sys.stderr)+ return 1+ if not body.get("ok"):+ print(f"worker run failed:\n{body.get('error')}", file=sys.stderr)+ return 1+ print(json.dumps(body["result"], sort_keys=True))+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())@@ -0,0 +1,532 @@+"""Core online GRPO/RLVR engine for Qwen3-1.7B on Ascend 910B.++Single-device design:+- Rollout: HF prefill into a StaticCache + a custom decode step captured as an+ NPUGraph (static shapes, in-place KV cache updates, device-side sampling).+- Sampling: temperature 0.7, top-k 20, top-p 0.8, seeded per request with the+ public seed derivation. The per-request seed drives a dedicated numpy PCG64+ stream of Gumbel noise; sampling is exact Gumbel-max over the filtered+ candidate set (distribution-identical to multinomial sampling).+- Actor: full-parameter training with HF backbone (gradient checkpointing),+ chunked lm_head loss, token-mean clipped PPO/GRPO loss, global grad clip 1.0,+ AdamW over FP32 master weights (BF16 compute), masters copied back in place.+"""+from __future__ import annotations++import json+import math+import statistics+import time+import urllib.request+from pathlib import Path++TASK_ID = "openbuild_rl_qwen3_1_7b_online_grpo_rlvr_2dev_v1"+MODEL_ID = "Qwen/Qwen3-1.7B"++TEMP = 0.7+TOP_P = 0.8+TOP_K = 20+MAXNEW = 256+LP = 128 # fixed padded prompt length for the decode graph+SMAX = LP + MAXNEW # static KV cache length+BMAX = 32 # fixed decode batch (8 prompts x 4 responses)+EOS_IDS = (151645, 151643) # <|im_end|>, <|endoftext|>+PAD_ID = 151643+EOS_CHECK = 16 # host EOS poll granularity (decode steps)+FRESH_N = 16 # freshness probe continuation length+PROBE_PREFIX = 16 # tokens compared in the old-logprob check++ADV_EPS = 1e-6+CLIP_LO = 0.2+CLIP_HI = 0.2+LR = 1e-6+WD = 0.01+BETAS = (0.9, 0.999)+ADAM_EPS = 1e-8+GRAD_CLIP = 1.0+++def derive_seed(base: int, update: int, version: int, prompt_ordinal: int, response_ordinal: int) -> int:+ """Public per-request seed derivation."""+ return base + update * 100000 + version * 10000 + prompt_ordinal * 4 + response_ordinal+++def group_advantages(rewards: list[float]) -> list[float]:+ """Sample-standard-deviation group normalization, epsilon 1e-6."""+ mean = statistics.fmean(rewards)+ std = statistics.stdev(rewards)+ if std == 0:+ return [0.0] * len(rewards)+ return [(value - mean) / (std + ADV_EPS) for value in rewards]+++def post_rewards(url: str, token: str, items: list[dict], retries: int = 6) -> list[float]:+ body = json.dumps({"items": items}).encode()+ last_exc: Exception | None = None+ for attempt in range(retries):+ try:+ req = urllib.request.Request(+ url.rstrip("/") + "/score_batch",+ data=body,+ headers={"Content-Type": "application/json", "Authorization": f"Bearer {token}"},+ )+ with urllib.request.urlopen(req, timeout=120) as resp:+ payload = json.loads(resp.read())+ rewards = payload["rewards"]+ if len(rewards) != len(items):+ raise ValueError("reward count mismatch")+ return [float(value) for value in rewards]+ except Exception as exc: # noqa: BLE001 - retry any transient failure+ last_exc = exc+ time.sleep(min(2 ** attempt, 16))+ raise RuntimeError(f"reward service failed: {last_exc}")+++class Engine:+ """Holds the model, optimizer, static decode graph, and checkpoint IO."""++ def __init__(self) -> None:+ self.torch = None+ self.model = None+ self.tokenizer = None++ # ------------------------------------------------------------------ load+ def load(self, model_path: str, tokenizer_path: str, checkpoint: str | None = None, device: str = "npu:0") -> None:+ import numpy as np # noqa: F401+ import torch+ import torch_npu+ from transformers import AutoModelForCausalLM, AutoTokenizer, StaticCache++ self.np = np+ self.torch = torch+ self.tn = torch_npu+ self.device = device+ torch.npu.set_device(device)+ self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)+ self.model = AutoModelForCausalLM.from_pretrained(model_path, dtype=torch.bfloat16, attn_implementation="sdpa")+ self.model.to(device)+ self.model.eval()+ cfg = self.model.config+ self.cfg = cfg+ self.NH = cfg.num_attention_heads+ self.NK = cfg.num_key_value_heads+ self.HD = cfg.head_dim+ self.REP = self.NH // self.NK+ self.SCALE = self.HD ** -0.5+ core = self.model.model+ self.core = core+ self.emb = core.embed_tokens+ self.layers = core.layers+ self.final_norm = core.norm+ self.lm_head = self.model.lm_head+ self.inv_freq = core.rotary_emb.inv_freq.detach().float().to(device)++ # FP32 master weights + AdamW (state fp32).+ self.params = list(self.model.parameters())+ self.masters = [p.detach().clone().float().requires_grad_(True) for p in self.params]+ for m in self.masters:+ m.grad = torch.zeros_like(m)+ self.optimizer = torch.optim.AdamW(+ self.masters, lr=LR, weight_decay=WD, betas=BETAS, eps=ADAM_EPS,+ )+ self.model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})++ self.param_names = [f"param_{i}" for i in range(len(self.params))]+ self.logical_parameter_count = sum(p.numel() for p in self.params)+ self.parameter_tensor_count = len(self.params)+ self.committed_update = 0+ self.policy_version = 0+ if checkpoint is not None:+ self._load_checkpoint(checkpoint)++ # Reference snapshot for the relative parameter projection.+ self._proj_ref = [m.detach().clone() for m in self.masters]++ # Static rollout state.+ self.past = StaticCache(config=cfg, max_cache_len=SMAX)+ self.arange_s = torch.arange(SMAX, device=device)+ self.cur_ids = torch.zeros(BMAX, 1, dtype=torch.long, device=device)+ self.pos = torch.zeros(1, dtype=torch.long, device=device)+ self.step = torch.zeros(1, dtype=torch.long, device=device)+ self.pos_off = torch.zeros(BMAX, dtype=torch.long, device=device)+ self.valid_mask = torch.zeros(BMAX, SMAX, dtype=torch.bool, device=device)+ self.gumbel_all = torch.zeros(BMAX, MAXNEW, TOP_K, dtype=torch.float32, device=device)+ self.all_tokens = torch.zeros(BMAX, MAXNEW, dtype=torch.long, device=device)+ self.all_logps = torch.zeros(BMAX, MAXNEW, dtype=torch.float32, device=device)+ self.graph = None++ def warmup_and_capture(self) -> None:+ """Warm allocator/kernels (no parameter change) and capture the decode graph."""+ torch = self.torch+ # dummy generation warm-up, then graph capture+ dummy = [list(range(1000, 1040))] * BMAX+ self._prefill(dummy)+ with torch.no_grad():+ for s in range(1, 3):+ self.step.fill_(s)+ self._decode_step()+ self.pos.add_(1)+ # training-path warm-up (backward only, no optimizer step, grads cleared)+ self._warmup_backward()+ g = torch.npu.NPUGraph()+ side = torch.npu.Stream()+ side.wait_stream(torch.npu.current_stream())+ with torch.no_grad(), torch.npu.stream(side):+ for _ in range(2):+ self._decode_step()+ torch.npu.current_stream().wait_stream(side)+ torch.npu.synchronize()+ with torch.no_grad(), torch.npu.graph(g):+ self._decode_step()+ torch.npu.synchronize()+ self.graph = g++ def _warmup_backward(self) -> None:+ torch = self.torch+ self.model.train()+ ids = torch.randint(1000, 50000, (2, 16), device=self.device)+ mask = torch.ones_like(ids)+ with torch.enable_grad():+ hidden = self.core(input_ids=ids, attention_mask=mask, use_cache=False).last_hidden_state+ loss = self.lm_head(hidden[:, -1]).float().sum() * 0.0+ loss.backward()+ self.model.zero_grad(set_to_none=True)+ self.model.eval()+ torch.npu.synchronize()++ # -------------------------------------------------------------- sampling+ def _rms(self, x, w, eps):+ torch = self.torch+ xf = x.float()+ return (xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + eps)).to(x.dtype) * w++ def _decode_step(self) -> None:+ """One decode step for all BMAX rows; writes token/logp at self.step.++ Reads self.cur_ids (last token), self.pos (absolute cache position),+ self.valid_mask / self.pos_off (prompt padding), self.gumbel_all.+ """+ torch = self.torch+ B = BMAX+ NH, NK, HD, REP = self.NH, self.NK, self.HD, self.REP+ h = self.emb(self.cur_ids[:, 0])+ pos_vec = self.pos + self.pos_off+ freqs = pos_vec.float()[:, None] * self.inv_freq[None, :]+ embf = torch.cat([freqs, freqs], dim=-1)+ cos = embf.cos()[:, None, :]+ sin = embf.sin()[:, None, :]+ bias = torch.where((self.arange_s[None, :] <= self.pos) & self.valid_mask, 0.0, float("-inf"))+ for li, layer in enumerate(self.layers):+ sa = layer.self_attn+ res = h+ hn = self._rms(h, layer.input_layernorm.weight, layer.input_layernorm.variance_epsilon)+ q = sa.q_proj(hn).view(B, NH, HD)+ k = sa.k_proj(hn).view(B, NK, HD)+ v = sa.v_proj(hn).view(B, NK, HD)+ q = self._rms(q, sa.q_norm.weight, sa.q_norm.variance_epsilon)+ k = self._rms(k, sa.k_norm.weight, sa.k_norm.variance_epsilon)+ q = (q * cos + torch.cat([-q[..., HD // 2:], q[..., :HD // 2]], dim=-1) * sin).to(torch.bfloat16)+ k = (k * cos + torch.cat([-k[..., HD // 2:], k[..., :HD // 2]], dim=-1) * sin).to(torch.bfloat16)+ ck = self.past.layers[li].keys+ cv = self.past.layers[li].values+ ck.index_copy_(2, self.pos, k.unsqueeze(2))+ cv.index_copy_(2, self.pos, v.unsqueeze(2))+ qg = q.view(B, NK, REP, HD)+ scores = torch.matmul(qg, ck.transpose(-1, -2)) * self.SCALE+ scores = scores.float() + bias[:, None, None, :]+ attn = torch.softmax(scores, dim=-1).to(torch.bfloat16)+ o = torch.matmul(attn, cv).reshape(B, NH * HD)+ h = res + sa.o_proj(o)+ res = h+ hn = self._rms(h, layer.post_attention_layernorm.weight, layer.post_attention_layernorm.variance_epsilon)+ m = layer.mlp+ h = res + m.down_proj(torch.nn.functional.silu(m.gate_proj(hn)) * m.up_proj(hn))+ h = self._rms(h, self.final_norm.weight, self.final_norm.variance_epsilon)+ logits = self.lm_head(h).float()+ nxt, lp = self._sample_tail(logits, self.step)+ self.all_tokens.index_copy_(1, self.step, nxt)+ self.all_logps.index_copy_(1, self.step, lp)+ self.cur_ids.copy_(nxt)++ def _sample_tail(self, logits_f32, step_tensor):+ """temperature -> top-k 20 -> top-p 0.8 -> seeded Gumbel-max; plus raw logprob."""+ torch = self.torch+ lg = logits_f32 / TEMP+ v20, i20 = torch.topk(lg, TOP_K, dim=-1)+ p = torch.softmax(v20, dim=-1)+ c = torch.cumsum(p, dim=-1)+ v20 = torch.where((c - p) > TOP_P, float("-inf"), v20)+ g = self.gumbel_all.index_select(1, step_tensor).squeeze(1)+ sel = torch.argmax(v20 + g, dim=-1, keepdim=True)+ nxt = torch.gather(i20, 1, sel)+ lp = torch.gather(torch.log_softmax(logits_f32, dim=-1), 1, nxt)+ return nxt, lp++ def _prefill(self, prompt_ids: list[list[int]]) -> None:+ """Left-pad prompts to LP and run the HF prefill into the static cache."""+ torch = self.torch+ B = len(prompt_ids)+ pad_lens = [LP - len(p) for p in prompt_ids]+ if min(pad_lens) < 0:+ raise ValueError("prompt longer than LP")+ ids = torch.stack([+ torch.cat([torch.full((pl,), PAD_ID, dtype=torch.long), torch.tensor(p, dtype=torch.long)])+ for p, pl in zip(prompt_ids, pad_lens)+ ]).to(self.device)+ mask = torch.stack([+ torch.cat([torch.zeros(pl, dtype=torch.long), torch.ones(len(p), dtype=torch.long)])+ for p, pl in zip(prompt_ids, pad_lens)+ ]).to(self.device)+ pos_ids = (mask.cumsum(-1) - 1).clamp(min=0)+ self.past.reset()+ with torch.no_grad():+ out = self.model(+ input_ids=ids, attention_mask=mask, position_ids=pos_ids,+ past_key_values=self.past, use_cache=True,+ )+ logits = out.logits[:, -1, :].float()+ self.pos.fill_(LP)+ self.pos_off.copy_(-torch.tensor(pad_lens, dtype=torch.long, device=self.device))+ self.valid_mask.zero_()+ for b, pl in enumerate(pad_lens):+ # everything from the first real prompt token onward is attendable;+ # the causal term (arange <= pos) hides not-yet-written positions+ self.valid_mask[b, pl:] = True+ self.step.fill_(0)+ nxt, lp = self._sample_tail(logits, self.step)+ self.all_tokens[:, 0:1].copy_(nxt)+ self.all_logps[:, 0:1].copy_(lp)+ self.cur_ids.copy_(nxt)++ def generate_batch(self, prompt_ids: list[list[int]], seeds: list[int]) -> tuple:+ """Generate up to MAXNEW tokens per row; returns (tokens, logps) host lists."""+ torch = self.torch+ np = self.np+ B = len(prompt_ids)+ assert B == BMAX+ noise = np.stack([+ -np.log(-np.log(np.random.Generator(np.random.PCG64(int(s))).random((MAXNEW, TOP_K), dtype=np.float32)))+ for s in seeds+ ])+ self.gumbel_all.copy_(torch.from_numpy(noise).to(self.device))+ self._prefill(prompt_ids)+ finished = [False] * B+ first_eos = [MAXNEW] * B+ first_col = self.all_tokens[:, 0].cpu().numpy()+ for b in range(B):+ if first_col[b] in EOS_IDS:+ finished[b] = True+ first_eos[b] = 1+ n_steps = 1+ if not all(finished):+ for chunk in range(1, MAXNEW, EOS_CHECK):+ hi = min(chunk + EOS_CHECK, MAXNEW)+ for s in range(chunk, hi):+ self.step.fill_(s)+ if self.graph is not None:+ self.graph.replay()+ else:+ with torch.no_grad():+ self._decode_step()+ self.pos.add_(1)+ window = self.all_tokens[:, chunk:hi].cpu().numpy()+ n_steps = hi+ for b in range(B):+ if finished[b]:+ continue+ for col in range(window.shape[1]):+ if window[b, col] in EOS_IDS:+ finished[b] = True+ first_eos[b] = min(first_eos[b], chunk + col + 1) # inclusive length+ break+ if all(finished):+ break+ host_tokens = self.all_tokens.cpu().numpy()+ host_logps = self.all_logps.cpu().numpy()+ tokens_out, logps_out = [], []+ for b in range(B):+ seq = host_tokens[b, : min(first_eos[b], n_steps)]+ lps = host_logps[b, : len(seq)]+ tokens_out.append([int(t) for t in seq])+ logps_out.append([float(v) for v in lps])+ return tokens_out, logps_out++ def actor_eval_logprobs(self, ids: list[int], n_resp: int) -> list[float]:+ """No-grad logprobs of the last n_resp tokens of one sequence (actor path)."""+ torch = self.torch+ t = torch.tensor([ids], dtype=torch.long, device=self.device)+ with torch.no_grad():+ logits = self.model(input_ids=t).logits[0].float()+ logp = torch.log_softmax(logits, dim=-1)+ L = len(ids)+ out = []+ for j in range(n_resp):+ out.append(float(logp[L - n_resp + j - 1, ids[L - n_resp + j]]))+ return out++ # -------------------------------------------------------------- training+ def train_update(self, batch: list[dict]) -> tuple[dict, list[float]]:+ """One full-parameter PPO/GRPO epoch over the batch (token-mean loss).++ batch items: prompt_ids (list[int]), resp_ids (list[int]),+ old_logps (list[float]), advantage (float).+ Returns (metrics, first_row_current_logprobs_prefix).+ """+ torch = self.torch+ B = len(batch)+ seqs = [item["prompt_ids"] + item["resp_ids"] for item in batch]+ plens = [len(item["prompt_ids"]) for item in batch]+ maxlen = max(len(s) for s in seqs)+ ids = torch.full((B, maxlen), PAD_ID, dtype=torch.long)+ mask = torch.zeros(B, maxlen, dtype=torch.long)+ for i, s in enumerate(seqs):+ ids[i, : len(s)] = torch.tensor(s, dtype=torch.long)+ mask[i, : len(s)] = 1+ ids = ids.to(self.device)+ mask = mask.to(self.device)+ pos_ids = (mask.cumsum(-1) - 1).clamp(min=0)++ sel_batch, sel_pos, sel_tgt, sel_old, sel_adv = [], [], [], [], []+ for i, item in enumerate(batch):+ for j, tok in enumerate(item["resp_ids"]):+ sel_batch.append(i)+ sel_pos.append(plens[i] + j - 1)+ sel_tgt.append(tok)+ sel_old.append(item["old_logps"][j])+ sel_adv.append(item["advantage"])+ total_n = len(sel_tgt)+ sel_batch_t = torch.tensor(sel_batch, dtype=torch.long, device=self.device)+ sel_pos_t = torch.tensor(sel_pos, dtype=torch.long, device=self.device)+ sel_tgt_t = torch.tensor(sel_tgt, dtype=torch.long, device=self.device)+ sel_old_t = torch.tensor(sel_old, dtype=torch.float32, device=self.device)+ sel_adv_t = torch.tensor(sel_adv, dtype=torch.float32, device=self.device)++ self.model.train()+ hidden = self.core(+ input_ids=ids, attention_mask=mask, position_ids=pos_ids, use_cache=False,+ ).last_hidden_state+ # Detached selection becomes the gradient boundary: each lm_head chunk is+ # an independent short graph (freed right after its backward), and the+ # backbone gets a single backward with the scattered h_sel gradient.+ h_sel = hidden[sel_batch_t, sel_pos_t].detach().requires_grad_(True)++ chunk = 1024+ policy_loss_sum = 0.0+ kl_sum = 0.0+ clip_sum = 0.0+ row0_cur: list[float] = []+ n_chunks = (total_n + chunk - 1) // chunk+ for ci in range(n_chunks):+ lo, hi = ci * chunk, min((ci + 1) * chunk, total_n)+ logits = self.lm_head(h_sel[lo:hi]).float()+ logp = torch.log_softmax(logits, dim=-1)+ cur = logp.gather(1, sel_tgt_t[lo:hi, None]).squeeze(1)+ old = sel_old_t[lo:hi]+ adv = sel_adv_t[lo:hi]+ log_ratio = cur - old+ ratio = log_ratio.exp()+ tok_loss = -torch.minimum(ratio * adv, ratio.clamp(1.0 - CLIP_LO, 1.0 + CLIP_HI) * adv)+ with torch.no_grad():+ policy_loss_sum += float(tok_loss.sum())+ kl_sum += float((torch.exp(-log_ratio) + log_ratio - 1.0).sum())+ clip_sum += float(((ratio < 1.0 - CLIP_LO) | (ratio > 1.0 + CLIP_HI)).float().sum())+ if ci == 0:+ row0_cur = [float(v) for v in cur[: PROBE_PREFIX]]+ (tok_loss.sum() / total_n).backward()+ grad_hidden = torch.zeros_like(hidden)+ grad_hidden[sel_batch_t, sel_pos_t] = h_sel.grad+ hidden.backward(gradient=grad_hidden)++ # transfer grads to FP32 masters, clip globally, AdamW step, copy back+ for p, m in zip(self.params, self.masters):+ if p.grad is not None:+ m.grad.copy_(p.grad)+ else:+ m.grad.zero_()+ total_norm = torch.nn.utils.clip_grad_norm_(self.masters, GRAD_CLIP)+ self.optimizer.step()+ with torch.no_grad():+ for p, m in zip(self.params, self.masters):+ p.data.copy_(m)+ self.model.zero_grad(set_to_none=True)+ self.model.eval()+ metrics = {+ "policy_loss": policy_loss_sum / total_n,+ "approx_kl": kl_sum / total_n,+ "clip_fraction": clip_sum / total_n,+ "global_grad_norm": float(total_norm),+ "parameter_projection": self.parameter_projection(),+ }+ return metrics, row0_cur++ def parameter_projection(self) -> float:+ """Linear parameter projection relative to the loaded reference state.++ sum over tensors of sum(master - reference): per-tensor fp32 reduction,+ host-side float64 accumulation. Sensitive enough to register the small+ committed AdamW drift of a zero-advantage update (momentum/weight decay).+ """+ torch = self.torch+ with torch.no_grad():+ sums = torch.stack([(m - r).sum() for m, r in zip(self.masters, self._proj_ref)])+ return float(sums.to(torch.float64).sum().cpu())++ # ------------------------------------------------------------ checkpoint+ def save_checkpoint(self, root: str) -> None:+ from safetensors.torch import save_file++ path = Path(root)+ path.mkdir(parents=True, exist_ok=False)+ cpu_masters = {name: m.detach().cpu() for name, m in zip(self.param_names, self.masters)}+ save_file(cpu_masters, str(path / "model.safetensors"))+ opt_state: dict = {}+ for name, m in zip(self.param_names, self.masters):+ state = self.optimizer.state.get(m, {})+ if "exp_avg" in state:+ opt_state[name + ".exp_avg"] = state["exp_avg"].detach().cpu()+ opt_state[name + ".exp_avg_sq"] = state["exp_avg_sq"].detach().cpu()+ save_file(opt_state, str(path / "optimizer.safetensors"))+ step_value = 0+ if self.masters and "step" in self.optimizer.state.get(self.masters[0], {}):+ step_value = int(self.optimizer.state[self.masters[0]]["step"])+ state = {+ "committed_update": self.committed_update,+ "policy_version": self.policy_version,+ "optimizer_step": step_value,+ "optimizer": {"kind": "adamw", "lr": LR, "weight_decay": WD, "betas": list(BETAS), "eps": ADAM_EPS},+ "scheduler": {"kind": "constant", "lr": LR},+ "data_cursor": {"next_update": self.committed_update + 1},+ }+ (path / "state.json").write_text(json.dumps(state, indent=2, sort_keys=True) + "\n")+ manifest = {+ "schema_version": 1,+ "kind": "openbuild_rl_checkpoint",+ "task_id": TASK_ID,+ "committed_update": self.committed_update,+ "next_update": self.committed_update + 1,+ "state_components": ["model", "optimizer", "scheduler", "committed_update", "policy_version", "data_cursor"],+ "files": ["manifest.json", "model.safetensors", "optimizer.safetensors", "state.json"],+ }+ (path / "manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n")++ def _load_checkpoint(self, root: str) -> None:+ from safetensors.torch import load_file++ path = Path(root)+ state = json.loads((path / "state.json").read_text())+ masters = load_file(str(path / "model.safetensors"))+ opt = load_file(str(path / "optimizer.safetensors"))+ with self.torch.no_grad():+ for name, m, p in zip(self.param_names, self.masters, self.params):+ tensor = masters[name].to(self.device)+ m.copy_(tensor)+ p.data.copy_(m)+ step_value = float(state["optimizer_step"])+ for name, m in zip(self.param_names, self.masters):+ self.optimizer.state[m] = {+ "step": self.torch.tensor(step_value, dtype=self.torch.float32, device=self.device),+ "exp_avg": opt[name + ".exp_avg"].to(self.device),+ "exp_avg_sq": opt[name + ".exp_avg_sq"].to(self.device),+ }+ self.committed_update = int(state["committed_update"])+ self.policy_version = int(state["policy_version"])@@ -0,0 +1,61 @@+"""Fixed-trajectory GRPO algorithm probe: published math, no rollout sampling."""+from __future__ import annotations++import argparse+import json+import math+import statistics+from pathlib import Path+++def compute_probe(probe: dict) -> dict:+ epsilon = float(probe["group_normalization_epsilon"])+ low = float(probe["clip_ratio_low"])+ high = float(probe["clip_ratio_high"])+ grouped_advantages: list[list[float]] = []+ losses: list[float] = []+ kls: list[float] = []+ clipped: list[float] = []+ for group in probe["groups"]:+ rewards = [float(value) for value in group["rewards"]]+ mean = statistics.fmean(rewards)+ std = statistics.stdev(rewards)+ advantages = [0.0] * len(rewards) if std == 0 else [+ (value - mean) / (std + epsilon) for value in rewards+ ]+ grouped_advantages.append(advantages)+ for advantage, old_row, current_row in zip(+ advantages, group["old_logprobs"], group["current_logprobs"]+ ):+ for old, current in zip(old_row, current_row):+ log_ratio = float(current) - float(old)+ ratio = math.exp(log_ratio)+ unclipped = ratio * advantage+ clipped_ratio = min(max(ratio, 1.0 - low), 1.0 + high)+ losses.append(-min(unclipped, clipped_ratio * advantage))+ kls.append(math.exp(-log_ratio) + log_ratio - 1.0)+ clipped.append(1.0 if ratio < 1.0 - low or ratio > 1.0 + high else 0.0)+ return {+ "schema_version": 1,+ "kind": "openbuild_rl_algorithm_probe_result",+ "probe_id": probe["probe_id"],+ "advantages": grouped_advantages,+ "policy_loss": statistics.fmean(losses),+ "approx_kl": statistics.fmean(kls),+ "clip_fraction": statistics.fmean(clipped),+ }+++def main() -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--input-manifest", required=True)+ parser.add_argument("--output", required=True)+ args = parser.parse_args()+ probe = json.loads(Path(args.input_manifest).read_text())+ result = compute_probe(probe)+ Path(args.output).write_text(json.dumps(result, allow_nan=False, indent=2, sort_keys=True) + "\n")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())@@ -0,0 +1,244 @@+"""Online GRPO run orchestration: updates, rewards, advantages, evidence files."""+from __future__ import annotations++import json+import time+from pathlib import Path++from .core import (+ BMAX,+ EOS_IDS,+ FRESH_N,+ MODEL_ID,+ PROBE_PREFIX,+ TASK_ID,+ Engine,+ derive_seed,+ group_advantages,+ post_rewards,+)++MAIN_FRESHNESS_UPDATES = (1, 8)+++def _tokenize_prompts(engine: Engine, prompts: list[dict]) -> list[list[int]]:+ tok = engine.tokenizer+ out = []+ for item in prompts:+ messages = [+ {"role": "system", "content": item["system_prompt"]},+ {"role": "user", "content": item["question"]},+ ]+ encoded = tok.apply_chat_template(+ messages, tokenize=True, add_generation_prompt=True, enable_thinking=False,+ )+ ids = encoded["input_ids"] if not isinstance(encoded, list) else encoded+ if ids and isinstance(ids[0], list):+ ids = ids[0]+ out.append([int(v) for v in ids])+ return out+++def run_online(+ engine: Engine,+ *,+ input_manifest_path: str,+ output_dir: str,+ reward_url: str,+ reward_token: str,+ action: str,+) -> dict:+ payload = json.loads(Path(input_manifest_path).read_text())+ kind = payload["kind"]+ is_restart = kind == "openbuild_rl_restart_input"+ if is_restart:+ assert engine.committed_update == 8, "restart requires the update-8 checkpoint state"+ updates = [int(payload["target_update"])]+ prompts = payload["prompts"]+ base_seed = int(payload["seed"])+ freshness_updates = {updates[0]}+ old_logprob_check_update = updates[0]+ else:+ assert kind == "openbuild_rl_online_input"+ n_updates = int(payload["committed_updates"])+ updates = list(range(1, n_updates + 1))+ prompts = payload["prompts"]+ base_seed = int(payload["seed"])+ freshness_updates = {1} if n_updates == 1 else set(MAIN_FRESHNESS_UPDATES)+ old_logprob_check_update = 1++ out_root = Path(output_dir)+ out_root.mkdir(parents=True, exist_ok=True)+ prompt_ids = _tokenize_prompts(engine, prompts)+ n_real = len(prompts) * 4++ observations = {+ "initial": {"parameter_projection": engine.parameter_projection()},+ "updates": {},+ "freshness": [],+ "old_logprob_checks": [],+ "logical_parameter_count": engine.logical_parameter_count,+ "parameter_tensor_count": engine.parameter_tensor_count,+ "compute_dtype": "bfloat16",+ "optimizer_state_dtypes": ["float32"],+ }+ if is_restart:+ observations["restart"] = {"parameter_projection": observations["initial"]["parameter_projection"]}++ policy_events: list[dict] = []+ trajectory_rows: list[dict] = []+ consumed_tokens = 0+ accepted = 0++ for update in updates:+ t_upd = time.time()+ version = update - 1 # fully synchronous: trajectories come from actor_before+ # ---- build the 32-row rollout batch (pad to BMAX with dummies)+ req_prompt_ids: list[list[int]] = []+ req_seeds: list[int] = []+ req_keys: list[tuple[int, int]] = [] # (prompt index, response ordinal)+ for pi, item in enumerate(prompts):+ for r in range(4):+ req_prompt_ids.append(prompt_ids[pi])+ req_seeds.append(derive_seed(base_seed, update, version, int(item["ordinal"]), r))+ req_keys.append((pi, r))+ while len(req_prompt_ids) < BMAX:+ req_prompt_ids.append(prompt_ids[0])+ req_seeds.append(derive_seed(base_seed, update, version, 0, 0) + 500_000_000)+ req_keys.append((-1, -1))++ t0 = time.time()+ tokens, logps = engine.generate_batch(req_prompt_ids, req_seeds)+ t_gen = time.time() - t0+ t0 = time.time()++ # ---- truncate, decode text, score real rows+ items = []+ row_data = []+ for b in range(n_real):+ ids_b = tokens[b]+ text = engine.tokenizer.decode(ids_b, skip_special_tokens=True)+ items.append({"prompt_id": prompts[req_keys[b][0]]["id"], "response_text": text})+ row_data.append((ids_b, logps[b], text))+ rewards = post_rewards(reward_url, reward_token, items)+ t_rew = time.time() - t0++ # ---- group-relative advantages (per prompt, in response-ordinal order)+ advantages: list[float] = []+ for pi in range(len(prompts)):+ group = rewards[pi * 4: pi * 4 + 4]+ advantages.extend(group_advantages(group))++ # ---- actor update+ train_batch = []+ for b in range(n_real):+ ids_b, lps_b, _ = row_data[b]+ train_batch.append({+ "prompt_ids": prompt_ids[req_keys[b][0]],+ "resp_ids": ids_b,+ "old_logps": lps_b,+ "advantage": advantages[b],+ })+ t0 = time.time()+ metrics, row0_cur = engine.train_update(train_batch)+ t_train = time.time() - t0++ # ---- old-logprob agreement check on the first accepted batch+ if update == old_logprob_check_update:+ ids0, lps0, _ = row_data[0]+ k = min(PROBE_PREFIX, len(ids0), len(row0_cur))+ observations["old_logprob_checks"].append({+ "update": update,+ "actor_logprobs": row0_cur[:k],+ "rollout_logprobs": lps0[:k],+ })++ # ---- commit: rollout policy refresh (in-place weights => immediate)+ engine.committed_update = update+ engine.policy_version = update+ observations["updates"][str(update)] = metrics+ policy_events.append({+ "update": update,+ "trajectory": version,+ "actor_before": version,+ "actor_after": update,+ "rollout_after_sync": update,+ "lag": 0,+ })++ # ---- freshness observation with the refreshed rollout policy+ if update in freshness_updates:+ probe_ids = prompt_ids[0]+ fresh_tokens, fresh_logps = engine.generate_batch(+ [probe_ids] * BMAX,+ [derive_seed(base_seed, update, update, 9000, 0) + i for i in range(BMAX)],+ )+ ft = fresh_tokens[0][:FRESH_N]+ fl = fresh_logps[0][:FRESH_N]+ actor_lps = engine.actor_eval_logprobs(probe_ids + ft, len(ft))+ observations["freshness"].append({+ "update": update,+ "policy_version": update,+ "actor_logprobs": actor_lps,+ "rollout_logprobs": fl,+ })++ print(+ f"[timing] update={update} gen={t_gen:.2f}s reward={t_rew:.2f}s "+ f"train={t_train:.2f}s total={time.time() - t_upd:.2f}s",+ flush=True,+ )++ # ---- trajectory records+ for b in range(n_real):+ ids_b, lps_b, text = row_data[b]+ pi, r = req_keys[b]+ trajectory_rows.append({+ "update": update,+ "prompt_id": prompts[pi]["id"],+ "prompt_ordinal": int(prompts[pi]["ordinal"]),+ "response_ordinal": r,+ "request_seed": req_seeds[b],+ "generating_policy_version": version,+ "response_token_ids": ids_b,+ "response_text": text,+ "old_logprobs": lps_b,+ "reward": float(rewards[b]),+ "advantage": float(advantages[b]),+ })+ consumed_tokens += len(ids_b)+ accepted += 1++ # ---- evidence files+ traj_path = out_root / "trajectories.jsonl"+ with traj_path.open("w", encoding="utf-8") as handle:+ for row in trajectory_rows:+ handle.write(json.dumps(row, allow_nan=False) + "\n")+ (out_root / "observations.json").write_text(+ json.dumps(observations, allow_nan=False, indent=2, sort_keys=True) + "\n"+ )++ checkpoint_manifest = None+ if action == "correctness":+ engine.save_checkpoint(str(out_root / "checkpoint"))+ checkpoint_manifest = "checkpoint/manifest.json"++ result = {+ "schema_version": 1,+ "kind": "openbuild_rl_result",+ "task_id": TASK_ID,+ "status": "completed",+ "action": action,+ "committed_updates": updates[-1],+ "accepted_trajectories": accepted,+ "consumed_response_tokens": consumed_tokens,+ "logical_device_ids": [0],+ "policy_versions": policy_events,+ "trajectory_path": "trajectories.jsonl",+ "observation_path": "observations.json",+ "checkpoint_manifest_path": checkpoint_manifest,+ }+ (out_root / "result.json").write_text(+ json.dumps(result, allow_nan=False, indent=2, sort_keys=True) + "\n"+ )+ return result@@ -0,0 +1,104 @@+"""Prepare-time worker: loads and warms the engine, serves run requests.++Started by prepare.sh in its own session. Writes ready.json once the model is+loaded, the decode graph is captured, and warm-up has completed. All work is+performed in this foreground-attached process group; cleanup.sh stops it.+"""+from __future__ import annotations++import json+import os+import signal+import socket+import sys+import traceback+from http.server import BaseHTTPRequestHandler, HTTPServer+from pathlib import Path+++def _find_port(base: int, span: int) -> int:+ for offset in range(1, span):+ port = base + offset+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:+ probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ try:+ probe.bind(("127.0.0.1", port))+ except OSError:+ continue+ return port+ raise RuntimeError("no free port in the assigned span")+++def main() -> int:+ state_dir = Path(os.environ["OPENBUILD_STATE_DIR"])+ state_dir.mkdir(parents=True, exist_ok=True)+ log = state_dir / "worker.log"+ try:+ _run(state_dir)+ except Exception:+ (state_dir / "worker.failed").write_text(traceback.format_exc())+ traceback.print_exc()+ return 1+ return 0+++def _run(state_dir: Path) -> None:+ from .core import Engine+ from .runner import run_online++ port_base = int(os.environ["OPENBUILD_PORT_BASE"])+ port_span = int(os.environ.get("OPENBUILD_PORT_SPAN", "16"))+ port = _find_port(port_base, port_span)++ engine = Engine()+ engine.load(+ os.environ["OPENBUILD_MODEL_PATH"],+ os.environ["OPENBUILD_TOKENIZER_PATH"],+ checkpoint=os.environ.get("OPENBUILD_RESTART_CHECKPOINT") or None,+ )+ engine.warmup_and_capture()++ class Handler(BaseHTTPRequestHandler):+ def do_POST(self) -> None: # noqa: N802+ if self.path != "/run":+ self.send_error(404)+ return+ try:+ length = int(self.headers.get("Content-Length", "0"))+ payload = json.loads(self.rfile.read(length))+ result = run_online(+ engine,+ input_manifest_path=payload["input_manifest"],+ output_dir=payload["output_dir"],+ reward_url=payload["reward_url"],+ reward_token=payload["reward_token"],+ action=payload["action"],+ )+ body = json.dumps({"ok": True, "result": result}).encode()+ self.send_response(200)+ except Exception:+ body = json.dumps({"ok": False, "error": traceback.format_exc()}).encode()+ self.send_response(500)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def log_message(self, format, *args) -> None: # noqa: A002+ return++ server = HTTPServer(("127.0.0.1", port), Handler)++ def _term(signum, frame): # noqa: ARG001+ raise SystemExit(0)++ signal.signal(signal.SIGTERM, _term)+ meta = {"pid": os.getpid(), "pgid": os.getpgid(0), "port": port}+ (state_dir / "worker.json").write_text(json.dumps(meta) + "\n")+ ready = {"status": "ready", "process_group_ids": [os.getpgid(0)], "ports": [port]}+ (state_dir / "ready.json").write_text(json.dumps(ready, indent=2) + "\n")+ server.serve_forever()+++if __name__ == "__main__":+ raise SystemExit(main())@@ -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": "custom torch/torch_npu online GRPO (no external RL or rollout framework)",+ "bootstrap": "bootstrap.sh",+ "prepare": "prepare.sh",+ "execute": "execute.sh",+ "probe": "probe.sh",+ "cleanup": "cleanup.sh"+}@@ -0,0 +1,29 @@+#!/usr/bin/env bash+# Start the engine worker (loads model, captures the decode graph, warms up),+# wait for ready.json, then return. The worker stays attached to the harness+# lifecycle via the process group id published in ready.json; cleanup.sh stops it.+set -euo pipefail+SOL="${OPENBUILD_SOLUTION_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"+STATE="$OPENBUILD_STATE_DIR"+mkdir -p "$STATE"+rm -f "$STATE/worker.failed"++setsid env PYTHONPATH="$SOL" python3 -m grpo_engine.worker >"$STATE/worker.log" 2>&1 &++deadline=$(( $(date +%s) + 800 ))+while :; do+ if [[ -f "$STATE/ready.json" ]]; then+ exit 0+ fi+ if [[ -f "$STATE/worker.failed" ]]; then+ echo "worker failed during prepare:" >&2+ cat "$STATE/worker.failed" >&2+ exit 1+ fi+ if (( $(date +%s) > deadline )); then+ echo "prepare timed out waiting for ready.json" >&2+ tail -50 "$STATE/worker.log" >&2 || true+ exit 1+ fi+ sleep 0.5+done@@ -0,0 +1,4 @@+#!/usr/bin/env bash+set -euo pipefail+SOL="${OPENBUILD_SOLUTION_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}"+exec env PYTHONPATH="$SOL" python3 -m grpo_engine.probe "$@"