From f80501f0d7da658cc5dddd4fc2466c42919fa216 Mon Sep 17 00:00:00 2001 From: Ronald Tse Date: Sat, 21 Nov 2026 11:30:47 +0800 Subject: [PATCH 1/8] WO92 ship-gate job: run-094 export + int8-static + parity + golden in one in-job pass Precedent: models PRs #447-#449 (the int8 RC publication round) + the crown plane export graph. torch fp32 reference decode of the committed 600-row eval600 heb slice (sha-verified in-job, single-row greedy K=3, the shipped decode mode), fp32 plane ONNX (input_ids + plane_ids - the mask-predict feedback is the shipped decode contract, WO51 law), int8 STATIC quantization (QDQ, calibration over slice rows with realistic plane_ids mix per the deepseek/WO20u static verdict), ORT CPU x86 decode, parity gates (mean per-row CER <= 2.0pp, flips <= 1%), candidate zip (kind: plane, RC lane id - final version = owner decision) + golden jsonl + SHA256SUMS to isx-training:/wo92-rc/. --- wo92_shipgate_hf.py | 386 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 386 insertions(+) create mode 100644 wo92_shipgate_hf.py diff --git a/wo92_shipgate_hf.py b/wo92_shipgate_hf.py new file mode 100644 index 0000000..bdd8d67 --- /dev/null +++ b/wo92_shipgate_hf.py @@ -0,0 +1,386 @@ +# /// script +# requires-python = ">=3.11" +# dependencies = [ +# "torch==2.5.1", +# "transformers==4.46.3", +# "onnx==1.17.0", +# "onnxruntime==1.20.1", +# "numpy>=1.26", +# ] +# /// +"""WO92 ship-gate job — run-094 best: export + int8-static + parity + golden. + +Precedent: models PRs #447-#449 (the int8 RC publication round) and the +crown plane export (export_plane_onnx_hf.py). One job produces every +ship-gate artifact for the run-094 lane: + + 1. torch fp32 reference decode of the 600-row eval600 heb slice + (single-row greedy K=3 — the shipped decode mode), slice sha + verified against the committed manifest; + 2. fp32 plane ONNX export (input_ids + plane_ids — the mask-predict + feedback is the shipped decode contract, WO51 law) at opset 17; + 3. int8 STATIC quantization (quantize_static QDQ + calibration reader + over slice rows with realistic plane_ids: MASK rows and reference + prediction rows both fed — the deepseek/WO20u static verdict); + 4. ORT CPU (x86) decode of the same 600 rows; + 5. parity gates: mean per-row CER(candidate, reference) <= 2.0pp AND + output flip rate <= 1.0% (the published round's gates); + 6. artifacts to isx-training:/wo92-rc/ with SHA256SUMS sidecars: + plane fp32+int8static onnx, candidate zip (kind: plane, + precision int8-static, k_passes 3), golden jsonl + ({"input", "output"} x 600), parity report. + +Publish boundary: nothing here ships — no models.yaml entry, no index +bump, no release, NO VERSION NUMBER (owner decision, WO92 ledger). +""" + +from __future__ import annotations + +import hashlib +import json +import sys +import time +import zipfile +from pathlib import Path + +sys.path.insert(0, "/code") +sys.path.insert(0, "/code/src") + +DATA = Path("/train_data") +CKPT = Path("/ckpt") +RC = CKPT / "wo92-rc" +INIT_RUN = "run-094-heb-gold-sft" +BACKBONE = "google/byt5-base" +SLICE_ROWS = 600 +SLICE_SHA = "993581cc411b73f3196e6441d0e4f8ae2a01810c2e2e7974a2651b179cdce5c3" +CHANNEL_SHA = "77e9b5dc3a3b9e7d70924e670f7361455b714ec8212e046662ea04187b153ccc" +K_PASSES = 3 +CER_GATE_PP = 2.0 +FLIP_GATE = 0.01 +CALIB_ROWS = 100 + +import os + +import torch +import torch.nn as nn +from transformers import AutoTokenizer + +import nikud_planes as NP + + +def log(*a): + print("[shipgate]", *a, flush=True) + + +def sha256_file(path: Path) -> str: + h = hashlib.sha256() + with path.open("rb") as f: + for chunk in iter(lambda: f.read(1 << 20), b""): + h.update(chunk) + return h.hexdigest() + + +def cer(a: str, b: str) -> float: + """Character error rate between two strings (Levenshtein / len(ref)).""" + if not b: + return 0.0 if not a else 1.0 + prev = list(range(len(b) + 1)) + for i, ca in enumerate(a, 1): + cur = [i] + for j, cb in enumerate(b, 1): + cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb))) + prev = cur + return prev[-1] / len(b) + + +def load_slice() -> list[dict]: + path = DATA / "test.jsonl" + digest = sha256_file(path) + if digest != CHANNEL_SHA: + raise RuntimeError(f"eval channel sha mismatch: {digest}") + rows = [] + with path.open(encoding="utf-8") as f: + for line in f: + if len(rows) >= SLICE_ROWS: + break + if line.strip(): + rows.append(json.loads(line)) + blob = "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in rows).encode("utf-8") + slice_sha = hashlib.sha256(blob).hexdigest() + if slice_sha != SLICE_SHA: + raise RuntimeError(f"eval600 slice sha mismatch: {slice_sha}") + log(f"slice: {len(rows)} rows, sha verified against the committed manifest") + return rows + + +class PlaneOnnx(nn.Module): + """The crown export graph: embed + byt5 encoder + per-char head.""" + + def __init__(self, encoder, plane_emb, head): + super().__init__() + self.encoder = encoder + self.plane_emb = plane_emb + self.head = head + + def forward(self, input_ids, plane_ids): + embeds = self.encoder.embed_tokens(input_ids) + self.plane_emb(plane_ids) + out = self.encoder(inputs_embeds=embeds) + return self.head(out.last_hidden_state) + + +def main() -> None: + from transformers import AutoModelForSeq2SeqLM + + t0 = time.time() + RC.mkdir(parents=True, exist_ok=True) + + # ---- inventory + checkpoint ---- + inv_path = CKPT / INIT_RUN / "inventory.json" + classes = json.loads(inv_path.read_text(encoding="utf-8")) + digest = hashlib.sha256(inv_path.read_bytes()).hexdigest()[:12] + if digest != "edd595d96d09": + raise RuntimeError(f"inventory digest mismatch: {digest}") + n_classes = len(classes) + MASK_ID = n_classes + class_to_id = {c: i for i, c in enumerate(classes)} + sd = torch.load(CKPT / INIT_RUN / "best" / "model.pt", + map_location="cpu", weights_only=True) + log(f"inventory {n_classes} classes (digest {digest}); ckpt loaded") + + tok = AutoTokenizer.from_pretrained(BACKBONE) + + def encode_ids(text: str) -> list[int]: + return tok(text).input_ids[:-1] # ByT5 byte table; drop EOS + + def render(classes_ids, skel: str, preds) -> str: + pos = 0 + char_preds: list[str] = [] + for ch in skel: + n = len(ch.encode("utf-8")) + votes = preds[0, pos: pos + n].tolist() + cid = max(set(votes), key=votes.count) + char_preds.append(classes[cid] if cid < n_classes else "") + pos += n + return NP.render(skel, char_preds) + + # ---- 1. torch fp32 reference decode (shipped decode mode) ---- + backbone = AutoModelForSeq2SeqLM.from_pretrained(BACKBONE) + encoder = backbone.encoder.cuda().eval() + d_model = encoder.config.d_model + plane_emb = nn.Embedding(n_classes + 1, d_model).cuda().eval() + head = nn.Linear(d_model, n_classes).cuda().eval() + encoder.load_state_dict(sd["encoder"]) + plane_emb.load_state_dict(sd["plane_emb"]) + head.load_state_dict(sd["head"]) + + def torch_predict(ids: list[int]) -> torch.Tensor: + t = torch.tensor([ids], device="cuda") + am = torch.ones_like(t) + plane = torch.full_like(t, MASK_ID) + preds = None + for _ in range(K_PASSES): + with torch.autocast("cuda", torch.bfloat16): + embeds = encoder.embed_tokens(t) + plane_emb(plane) + out = encoder(inputs_embeds=embeds, attention_mask=am) + logits = head(out.last_hidden_state) + preds = logits.argmax(-1) + plane = preds + return preds + + slice_rows = load_slice() + ref_rows = [] + for i, row in enumerate(slice_rows): + src = row["src"] + skel, _ = NP.split_planes(src) + preds = torch_predict(encode_ids(skel)) + ref_rows.append({"input": src, "output": render(None, skel, preds)}) + if (i + 1) % 100 == 0: + log(f"reference decode {i + 1}/{len(slice_rows)} " + f"({time.time() - t0:.0f}s)", flush=True) + ref_path = RC / "reference-torch-fp32.jsonl" + ref_path.write_text( + "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in ref_rows), + encoding="utf-8") + log(f"reference decode done ({time.time() - t0:.0f}s)") + + # ---- 2. fp32 ONNX export ---- + plane_onnx = PlaneOnnx(encoder.cpu(), plane_emb.cpu(), head.cpu()).eval() + fp32_path = RC / "plane-fp32.onnx" + dummy_ids = torch.ones((1, 16), dtype=torch.long) + dummy_plane = torch.full_like(dummy_ids, MASK_ID) + torch.onnx.export( + plane_onnx, + (dummy_ids, dummy_plane), + str(fp32_path), + input_names=["input_ids", "plane_ids"], + output_names=["class_logits"], + dynamic_axes={"input_ids": {0: "batch", 1: "seq"}, + "plane_ids": {0: "batch", 1: "seq"}, + "class_logits": {0: "batch", 1: "seq"}}, + opset_version=17, dynamo=False, + ) + log(f"fp32 onnx {fp32_path.stat().st_size / 1e6:.1f} MB") + + # ---- 3. int8 static quantization (calibration with realistic plane_ids) ---- + from onnxruntime.quantization import CalibrationDataReader, QuantFormat, QuantType, quantize_static + + calib_rows = slice_rows[:CALIB_ROWS] + calib_planes: list = [] + for row in calib_rows: + skel, _ = NP.split_planes(row["src"]) + ids = encode_ids(skel) + preds = torch_predict(ids).cpu() + calib_planes.append(preds) + # mix MASK rows (decode pass 1) with reference-prediction rows (passes 2-3) + calib_items = [] + for preds in calib_planes: + calib_items.append(preds) + for preds in calib_planes[::2]: + calib_items.append(torch.full_like(preds, MASK_ID)) + + class PlaneCalibReader(CalibrationDataReader): + def __init__(self): + self._items = iter(calib_items) + + def get_next(self): + try: + preds = next(self._items) + except StopIteration: + return None + ids = torch.ones_like(preds) + return {"input_ids": ids.numpy(), "plane_ids": preds.numpy()} + + int8_path = RC / "plane-int8static.onnx" + quantize_static( + str(fp32_path), str(int8_path), + calibration_data_reader=PlaneCalibReader(), + quant_format=QuantFormat.QDQ, + activation_type=QuantType.QInt8, + weight_type=QuantType.QInt8, + ) + log(f"int8static onnx {int8_path.stat().st_size / 1e6:.1f} MB " + f"({len(calib_items)} calibration rows)") + + # ---- 4. ORT CPU (x86) decode of the candidate ---- + import onnxruntime as ort + + so = ort.SessionOptions() + so.intra_op_num_threads = 8 + sess = ort.InferenceSession(str(int8_path), so, + providers=["CPUExecutionProvider"]) + log("ort providers: " + str(sess.get_providers())) + + cand_rows = [] + t_onnx = time.time() + for i, row in enumerate(slice_rows): + skel, _ = NP.split_planes(row["src"]) + ids = torch.tensor([encode_ids(skel)], dtype=torch.long) + plane = torch.full_like(ids, MASK_ID) + preds = None + for _ in range(K_PASSES): + logits = sess.run(None, {"input_ids": ids.numpy(), + "plane_ids": plane.numpy()})[0] + preds = torch.from_numpy(logits).argmax(-1) + plane = preds + cand_rows.append({"input": row["src"], "output": render(None, skel, preds)}) + if (i + 1) % 100 == 0: + log(f"ort decode {i + 1}/{len(slice_rows)} ({time.time() - t_onnx:.0f}s)", + flush=True) + + # ---- 5. parity gates ---- + deltas = [cer(c["output"], r["output"]) for c, r in zip(cand_rows, ref_rows)] + flips = sum(1 for c, r in zip(cand_rows, ref_rows) if c["output"] != r["output"]) + mean_delta_pp = 100.0 * sum(deltas) / len(deltas) + max_delta_pp = 100.0 * max(deltas) + flip_rate = flips / len(cand_rows) + parity_pass = mean_delta_pp <= CER_GATE_PP and flip_rate <= FLIP_GATE + report = { + "lane": "WO92 run-094 ship-gate (heb plane int8static RC)", + "init": INIT_RUN, + "slice": {"file": "conformance/wo20/eval600/heb_eval_600.jsonl", + "rows": len(slice_rows), "sha256": SLICE_SHA}, + "decode_mode": "single-row greedy K=3 (shipped)", + "ort_providers": sess.get_providers(), + "parity": { + "mean_cer_delta_pp": round(mean_delta_pp, 4), + "max_cer_delta_pp": round(max_delta_pp, 4), + "flips": flips, + "flip_rate": round(flip_rate, 6), + "samples": len(cand_rows), + "gates": {"cer_delta_pp_max": CER_GATE_PP, "flip_rate_max": FLIP_GATE}, + "pass": parity_pass, + }, + "reference": "torch fp32 CUDA bf16-autocast (run-094 best; itself " + "verdict-gated at DER 6.6078 on the full 1,864-row set)", + "date_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + } + (RC / "parity-report.json").write_text(json.dumps(report, indent=1), + encoding="utf-8") + log(f"parity: mean_delta={mean_delta_pp:.4f}pp max={max_delta_pp:.4f}pp " + f"flips={flips}/{len(cand_rows)} pass={parity_pass}") + + # ---- 6. candidate zip + golden + SHA256SUMS ---- + classes_bytes = json.dumps(classes, ensure_ascii=False, indent=1).encode("utf-8") + onnx_bytes = int8_path.read_bytes() + meta = ( + "id: heb-vocalized-plane-wo92rc # RC lane id; final heb-vocalized-plane-{major.minor} = owner decision\n" + "task: diacritization\n" + "target: Hebr\n" + "kind: plane\n" + "precision: int8-static\n" + "k_passes: 3\n" + "decode: single-row-greedy\n" + "license: BSD-3-Clause\n" + "trained_from: interscript-train train_hebrew_sft_hf.py (WO92 stage-2 gold SFT)\n" + " on run-093-heb-weak-pretrain best (knesset-v6 deduped weak-pretrain + gold);\n" + " checkpoint isx-training:/run-094-heb-gold-sft/best/model.pt\n" + "metrics:\n" + "- name: der_total_greedy\n" + " value: 6.6078\n" + " protocol: crown protocol (greedy K=3, seq2seq_der), Nakdimon test 1,864 rows\n" + " source: isx-training:/run-094-heb-gold-sft/verdict.json\n" + "parity:\n" + f" samples: {len(cand_rows)}\n" + f" cer_delta: {round(mean_delta_pp, 4)}\n" + f" flip_rate: {round(flip_rate, 6)}\n" + "sha256:\n" + f" plane-int8static.onnx: {hashlib.sha256(onnx_bytes).hexdigest()}\n" + f" classes.json: {hashlib.sha256(classes_bytes).hexdigest()}\n" + ) + zip_buf = __import__("io").BytesIO() + with zipfile.ZipFile(zip_buf, "w", zipfile.ZIP_STORED) as zf: + zf.writestr("metadata.yaml", meta) + zf.writestr("classes.json", classes_bytes) + zf.writestr("plane-int8static.onnx", onnx_bytes) + zip_path = RC / "heb-vocalized-plane-wo92rc-int8static.zip" + zip_path.write_bytes(zip_buf.getvalue()) + + golden_path = RC / "heb-vocalized-plane-wo92rc-int8-golden.jsonl" + golden_path.write_text( + "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in cand_rows), + encoding="utf-8") + + sums = [ + f"{sha256_file(fp32_path)} plane-fp32.onnx", + f"{sha256_file(int8_path)} plane-int8static.onnx", + f"{sha256_file(zip_path)} {zip_path.name}", + f"{sha256_file(golden_path)} {golden_path.name}", + f"{sha256_file(ref_path)} reference-torch-fp32.jsonl", + f"{hashlib.sha256((RC / 'parity-report.json').read_bytes()).hexdigest()} parity-report.json", + ] + (RC / "SHA256SUMS.txt").write_text("\n".join(sums) + "\n", encoding="utf-8") + + summary = {"parity_pass": parity_pass, + "mean_cer_delta_pp": round(mean_delta_pp, 4), + "flip_rate": round(flip_rate, 6), + "samples": len(cand_rows), + "zip": zip_path.name, + "zip_bytes": zip_path.stat().st_size, + "elapsed_s": round(time.time() - t0)} + (RC / "SHIPGATE_DONE").write_text(json.dumps(summary, indent=1) + "\n", + encoding="utf-8") + log("summary " + json.dumps(summary)) + + +if __name__ == "__main__": + main() From 5b01ea67b560b8b3c25e760367df6b75a671a189 Mon Sep 17 00:00:00 2001 From: Ronald Tse Date: Sat, 21 Nov 2026 11:35:14 +0800 Subject: [PATCH 2/8] WO92 shipgate: drop stray flush kwargs on log() calls (log already flushes; the kwarg crashed at row 100) --- wo92_shipgate_hf.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/wo92_shipgate_hf.py b/wo92_shipgate_hf.py index bdd8d67..03df28b 100644 --- a/wo92_shipgate_hf.py +++ b/wo92_shipgate_hf.py @@ -196,7 +196,7 @@ def torch_predict(ids: list[int]) -> torch.Tensor: ref_rows.append({"input": src, "output": render(None, skel, preds)}) if (i + 1) % 100 == 0: log(f"reference decode {i + 1}/{len(slice_rows)} " - f"({time.time() - t0:.0f}s)", flush=True) + f"({time.time() - t0:.0f}s)") ref_path = RC / "reference-torch-fp32.jsonl" ref_path.write_text( "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in ref_rows), @@ -284,8 +284,7 @@ def get_next(self): plane = preds cand_rows.append({"input": row["src"], "output": render(None, skel, preds)}) if (i + 1) % 100 == 0: - log(f"ort decode {i + 1}/{len(slice_rows)} ({time.time() - t_onnx:.0f}s)", - flush=True) + log(f"ort decode {i + 1}/{len(slice_rows)} ({time.time() - t_onnx:.0f}s)") # ---- 5. parity gates ---- deltas = [cer(c["output"], r["output"]) for c, r in zip(cand_rows, ref_rows)] From 27af7623ab38b39b232b7da6f3445d07a25ca7ec Mon Sep 17 00:00:00 2001 From: Ronald Tse Date: Sat, 21 Nov 2026 11:41:51 +0800 Subject: [PATCH 3/8] WO92 shipgate: calibrate from tensors captured during the reference decode (device fix + real input_ids in the calibration reader) --- wo92_shipgate_hf.py | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/wo92_shipgate_hf.py b/wo92_shipgate_hf.py index 03df28b..5b7a797 100644 --- a/wo92_shipgate_hf.py +++ b/wo92_shipgate_hf.py @@ -189,11 +189,17 @@ def torch_predict(ids: list[int]) -> torch.Tensor: slice_rows = load_slice() ref_rows = [] + calib_inputs: list[torch.Tensor] = [] # real encoded ids (cpu) + calib_preds: list[torch.Tensor] = [] # reference predictions (cpu) for i, row in enumerate(slice_rows): src = row["src"] skel, _ = NP.split_planes(src) - preds = torch_predict(encode_ids(skel)) + ids_cpu = torch.tensor([encode_ids(skel)], dtype=torch.long) + preds = torch_predict(ids_cpu.tolist()) ref_rows.append({"input": src, "output": render(None, skel, preds)}) + if i < CALIB_ROWS: + calib_inputs.append(ids_cpu) + calib_preds.append(preds.detach().cpu()) if (i + 1) % 100 == 0: log(f"reference decode {i + 1}/{len(slice_rows)} " f"({time.time() - t0:.0f}s)") @@ -224,31 +230,25 @@ def torch_predict(ids: list[int]) -> torch.Tensor: # ---- 3. int8 static quantization (calibration with realistic plane_ids) ---- from onnxruntime.quantization import CalibrationDataReader, QuantFormat, QuantType, quantize_static - calib_rows = slice_rows[:CALIB_ROWS] - calib_planes: list = [] - for row in calib_rows: - skel, _ = NP.split_planes(row["src"]) - ids = encode_ids(skel) - preds = torch_predict(ids).cpu() - calib_planes.append(preds) - # mix MASK rows (decode pass 1) with reference-prediction rows (passes 2-3) - calib_items = [] - for preds in calib_planes: - calib_items.append(preds) - for preds in calib_planes[::2]: - calib_items.append(torch.full_like(preds, MASK_ID)) + # calibration rows: reference predictions (passes 2..K) + MASK rows + # (pass 1), captured during the reference decode — no GPU work after + # the modules move to CPU for export. + calib_preds_all = list(calib_preds) + calib_inputs_all = list(calib_inputs) + for j in range(0, len(calib_preds), 2): + calib_preds_all.append(torch.full_like(calib_preds[j], MASK_ID)) + calib_inputs_all.append(calib_inputs[j]) + log(f"calibration rows: {len(calib_preds_all)} " + f"(predictions + MASK mix from the first {len(calib_preds)} slice rows)") class PlaneCalibReader(CalibrationDataReader): def __init__(self): - self._items = iter(calib_items) + self._iter = iter(zip(calib_inputs_all, calib_preds_all)) def get_next(self): - try: - preds = next(self._items) - except StopIteration: - return None - ids = torch.ones_like(preds) - return {"input_ids": ids.numpy(), "plane_ids": preds.numpy()} + for ids, preds in self._iter: + return {"input_ids": ids.numpy(), "plane_ids": preds.numpy()} + return None int8_path = RC / "plane-int8static.onnx" quantize_static( @@ -259,7 +259,7 @@ def get_next(self): weight_type=QuantType.QInt8, ) log(f"int8static onnx {int8_path.stat().st_size / 1e6:.1f} MB " - f"({len(calib_items)} calibration rows)") + f"({len(calib_preds_all)} calibration rows)") # ---- 4. ORT CPU (x86) decode of the candidate ---- import onnxruntime as ort From 39c8595866ab5e71e17a4c1614254d5c96c961c8 Mon Sep 17 00:00:00 2001 From: Ronald Tse Date: Sat, 21 Nov 2026 11:44:19 +0800 Subject: [PATCH 4/8] WO92 shipgate: pass the encoded tensor to torch_predict (tolist() doubled the batch dim -> 3D input crash) --- wo92_shipgate_hf.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/wo92_shipgate_hf.py b/wo92_shipgate_hf.py index 5b7a797..6a0406d 100644 --- a/wo92_shipgate_hf.py +++ b/wo92_shipgate_hf.py @@ -173,8 +173,9 @@ def render(classes_ids, skel: str, preds) -> str: plane_emb.load_state_dict(sd["plane_emb"]) head.load_state_dict(sd["head"]) - def torch_predict(ids: list[int]) -> torch.Tensor: - t = torch.tensor([ids], device="cuda") + def torch_predict(ids) -> torch.Tensor: + # accepts a cpu long tensor of shape [1, seq] or a flat id list + t = ids.to("cuda") if isinstance(ids, torch.Tensor) else torch.tensor([ids], device="cuda") am = torch.ones_like(t) plane = torch.full_like(t, MASK_ID) preds = None @@ -195,7 +196,7 @@ def torch_predict(ids: list[int]) -> torch.Tensor: src = row["src"] skel, _ = NP.split_planes(src) ids_cpu = torch.tensor([encode_ids(skel)], dtype=torch.long) - preds = torch_predict(ids_cpu.tolist()) + preds = torch_predict(ids_cpu) ref_rows.append({"input": src, "output": render(None, skel, preds)}) if i < CALIB_ROWS: calib_inputs.append(ids_cpu) From a026bac099d1c80fadb8f3c0012e397271554b4b Mon Sep 17 00:00:00 2001 From: Ronald Tse Date: Sat, 21 Nov 2026 11:52:48 +0800 Subject: [PATCH 5/8] =?UTF-8?q?WO92=20shipgate:=20replicate=20the=20crown?= =?UTF-8?q?=20export=20invocation=20exactly=20(no=5Fgrad=20tracing,=20zero?= =?UTF-8?q?s=2064-seq=20dummy)=20=E2=80=94=20the=20T5=20rel-attention-bias?= =?UTF-8?q?=20Gather=20mis-traces=20otherwise?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- wo92_shipgate_hf.py | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/wo92_shipgate_hf.py b/wo92_shipgate_hf.py index 6a0406d..fcbb60c 100644 --- a/wo92_shipgate_hf.py +++ b/wo92_shipgate_hf.py @@ -213,19 +213,23 @@ def torch_predict(ids) -> torch.Tensor: # ---- 2. fp32 ONNX export ---- plane_onnx = PlaneOnnx(encoder.cpu(), plane_emb.cpu(), head.cpu()).eval() fp32_path = RC / "plane-fp32.onnx" - dummy_ids = torch.ones((1, 16), dtype=torch.long) + # crown export invocation replicated exactly (export_plane_onnx_hf.py): + # no_grad around tracing, zeros dummy at seq 64, MASK plane ids — the + # T5 relative-attention-bias Gather mis-traces without these + dummy_ids = torch.zeros((1, 64), dtype=torch.long) dummy_plane = torch.full_like(dummy_ids, MASK_ID) - torch.onnx.export( - plane_onnx, - (dummy_ids, dummy_plane), - str(fp32_path), - input_names=["input_ids", "plane_ids"], - output_names=["class_logits"], - dynamic_axes={"input_ids": {0: "batch", 1: "seq"}, - "plane_ids": {0: "batch", 1: "seq"}, - "class_logits": {0: "batch", 1: "seq"}}, - opset_version=17, dynamo=False, - ) + with torch.no_grad(): + torch.onnx.export( + plane_onnx, + (dummy_ids, dummy_plane), + str(fp32_path), + input_names=["input_ids", "plane_ids"], + output_names=["class_logits"], + dynamic_axes={"input_ids": {0: "batch", 1: "seq"}, + "plane_ids": {0: "batch", 1: "seq"}, + "class_logits": {0: "batch", 1: "seq"}}, + opset_version=17, dynamo=False, + ) log(f"fp32 onnx {fp32_path.stat().st_size / 1e6:.1f} MB") # ---- 3. int8 static quantization (calibration with realistic plane_ids) ---- From 58980486978ef653d264c38f2283cdf7b8350297 Mon Sep 17 00:00:00 2001 From: Ronald Tse Date: Sat, 21 Nov 2026 12:01:20 +0800 Subject: [PATCH 6/8] =?UTF-8?q?WO92=20shipgate:=20adopt=20the=20house=20st?= =?UTF-8?q?atic-int8=20recipe=20(run-070:=20MatMul/Gemm=20only,=20QUInt8?= =?UTF-8?q?=20activations)=20+=20smoke=20row=20=E2=80=94=20QDQ=20over=20th?= =?UTF-8?q?e=20T5=20bias=20subgraph=20corrupts=20its=20int64=20indices?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- wo92_shipgate_hf.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/wo92_shipgate_hf.py b/wo92_shipgate_hf.py index fcbb60c..c31fcef 100644 --- a/wo92_shipgate_hf.py +++ b/wo92_shipgate_hf.py @@ -260,8 +260,12 @@ def get_next(self): str(fp32_path), str(int8_path), calibration_data_reader=PlaneCalibReader(), quant_format=QuantFormat.QDQ, - activation_type=QuantType.QInt8, + activation_type=QuantType.QUInt8, weight_type=QuantType.QInt8, + # the house static recipe (run-070 ara large static): quantize the + # compute MatMuls/Gemms ONLY — quantizing the T5 relative-attention + # bias subgraph corrupts its int64 bucket indices at runtime + op_types_to_quantize=["MatMul", "Gemm"], ) log(f"int8static onnx {int8_path.stat().st_size / 1e6:.1f} MB " f"({len(calib_preds_all)} calibration rows)") @@ -275,6 +279,15 @@ def get_next(self): providers=["CPUExecutionProvider"]) log("ort providers: " + str(sess.get_providers())) + # smoke: row 0 must decode before the 600-row loop (fail fast with a + # clear signal instead of a mid-loop ORT crash) + _smoke_skel, _ = NP.split_planes(slice_rows[0]["src"]) + _smoke_ids = torch.tensor([encode_ids(_smoke_skel)], dtype=torch.long) + _smoke_plane = torch.full_like(_smoke_ids, MASK_ID) + sess.run(None, {"input_ids": _smoke_ids.numpy(), + "plane_ids": _smoke_plane.numpy()}) + log("ort smoke row decoded OK") + cand_rows = [] t_onnx = time.time() for i, row in enumerate(slice_rows): From e408e6b04346a59c49f04063cb535283262e5228 Mon Sep 17 00:00:00 2001 From: Ronald Tse Date: Sat, 21 Nov 2026 12:17:39 +0800 Subject: [PATCH 7/8] WO92 shipgate: the fp32 ONNX artifact is the parity reference (the published round's definition); torch bf16 decode demoted to sanity lane + informational slice DERs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Attempt 6 measured 47.7% flips against the bf16-autocast torch decode — the reference carried autocast noise. The precedent compares the candidate against the fp32 ARTIFACT under ORT (itself torch-parity-0.0 in the published round); gates unchanged (2.0pp CER, 1% flips). --- wo92_shipgate_hf.py | 104 +++++++++++++++++++++++++++++++++----------- 1 file changed, 79 insertions(+), 25 deletions(-) diff --git a/wo92_shipgate_hf.py b/wo92_shipgate_hf.py index c31fcef..e0f85c5 100644 --- a/wo92_shipgate_hf.py +++ b/wo92_shipgate_hf.py @@ -189,7 +189,7 @@ def torch_predict(ids) -> torch.Tensor: return preds slice_rows = load_slice() - ref_rows = [] + torch_rows = [] calib_inputs: list[torch.Tensor] = [] # real encoded ids (cpu) calib_preds: list[torch.Tensor] = [] # reference predictions (cpu) for i, row in enumerate(slice_rows): @@ -197,18 +197,18 @@ def torch_predict(ids) -> torch.Tensor: skel, _ = NP.split_planes(src) ids_cpu = torch.tensor([encode_ids(skel)], dtype=torch.long) preds = torch_predict(ids_cpu) - ref_rows.append({"input": src, "output": render(None, skel, preds)}) + torch_rows.append({"input": src, "output": render(None, skel, preds)}) if i < CALIB_ROWS: calib_inputs.append(ids_cpu) calib_preds.append(preds.detach().cpu()) if (i + 1) % 100 == 0: - log(f"reference decode {i + 1}/{len(slice_rows)} " + log(f"torch decode {i + 1}/{len(slice_rows)} " f"({time.time() - t0:.0f}s)") - ref_path = RC / "reference-torch-fp32.jsonl" - ref_path.write_text( - "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in ref_rows), + torch_path = RC / "reference-torch-bf16.jsonl" + torch_path.write_text( + "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in torch_rows), encoding="utf-8") - log(f"reference decode done ({time.time() - t0:.0f}s)") + log(f"torch decode done ({time.time() - t0:.0f}s)") # ---- 2. fp32 ONNX export ---- plane_onnx = PlaneOnnx(encoder.cpu(), plane_emb.cpu(), head.cpu()).eval() @@ -288,29 +288,68 @@ def get_next(self): "plane_ids": _smoke_plane.numpy()}) log("ort smoke row decoded OK") - cand_rows = [] + # ---- 4b. THE reference: the fp32 ONNX artifact decoded under ORT ---- + # (the published round's definition: the shipped fp32 zip is the + # parity reference; the torch bf16-autocast decode is a sanity lane — + # autocast noise is NOT the reference) + from rababa.evaluate import seq2seq_der + + fp32_sess = ort.InferenceSession(str(fp32_path), so, + providers=["CPUExecutionProvider"]) + + def ort_decode(session, rows): + out_rows = [] + for i, row in enumerate(rows): + skel, _ = NP.split_planes(row["src"]) + ids = torch.tensor([encode_ids(skel)], dtype=torch.long) + plane = torch.full_like(ids, MASK_ID) + preds = None + for _ in range(K_PASSES): + logits = session.run(None, {"input_ids": ids.numpy(), + "plane_ids": plane.numpy()})[0] + preds = torch.from_numpy(logits).argmax(-1) + plane = preds + out_rows.append({"input": row["src"], + "output": render(None, skel, preds)}) + if (i + 1) % 100 == 0: + log(f"ort decode {i + 1}/{len(rows)} " + f"({time.time() - t_onnx:.0f}s)") + return out_rows + t_onnx = time.time() - for i, row in enumerate(slice_rows): - skel, _ = NP.split_planes(row["src"]) - ids = torch.tensor([encode_ids(skel)], dtype=torch.long) - plane = torch.full_like(ids, MASK_ID) - preds = None - for _ in range(K_PASSES): - logits = sess.run(None, {"input_ids": ids.numpy(), - "plane_ids": plane.numpy()})[0] - preds = torch.from_numpy(logits).argmax(-1) - plane = preds - cand_rows.append({"input": row["src"], "output": render(None, skel, preds)}) - if (i + 1) % 100 == 0: - log(f"ort decode {i + 1}/{len(slice_rows)} ({time.time() - t_onnx:.0f}s)") + ref_rows = ort_decode(fp32_sess, slice_rows) + ref_path = RC / "reference-fp32-onnx.jsonl" + ref_path.write_text( + "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in ref_rows), + encoding="utf-8") + sanity_flips = sum(1 for a, b in zip(ref_rows, torch_rows) + if a["output"] != b["output"]) + log(f"fp32 reference decode done ({time.time() - t_onnx:.0f}s); " + f"sanity fp32onnx-vs-torch flips={sanity_flips}/{len(ref_rows)}") + + # ---- 5. candidate: the int8static artifact under ORT ---- + cand_rows = ort_decode(sess, slice_rows) - # ---- 5. parity gates ---- + # ---- 6. parity gates (int8static vs the fp32 ONNX reference) ---- deltas = [cer(c["output"], r["output"]) for c, r in zip(cand_rows, ref_rows)] flips = sum(1 for c, r in zip(cand_rows, ref_rows) if c["output"] != r["output"]) mean_delta_pp = 100.0 * sum(deltas) / len(deltas) max_delta_pp = 100.0 * max(deltas) flip_rate = flips / len(cand_rows) parity_pass = mean_delta_pp <= CER_GATE_PP and flip_rate <= FLIP_GATE + + # informational: slice DER vs gold for fp32 / int8static / torch-bf16 + def slice_der(rows): + wrong, total = 0.0, 0 + for row, out in zip(slice_rows, rows): + d, n = seq2seq_der(out["output"], row["tgt"].strip()) + wrong += d * n + total += n + return 100.0 * wrong / max(1, total) + + der_fp32 = slice_der(ref_rows) + der_int8 = slice_der(cand_rows) + der_torch = slice_der(torch_rows) report = { "lane": "WO92 run-094 ship-gate (heb plane int8static RC)", "init": INIT_RUN, @@ -327,14 +366,28 @@ def get_next(self): "gates": {"cer_delta_pp_max": CER_GATE_PP, "flip_rate_max": FLIP_GATE}, "pass": parity_pass, }, - "reference": "torch fp32 CUDA bf16-autocast (run-094 best; itself " - "verdict-gated at DER 6.6078 on the full 1,864-row set)", + "reference": "the fp32 ONNX artifact decoded under ORT CPU (the " + "published round's definition); torch bf16-autocast " + "decode is a sanity lane only", + "sanity": { + "fp32onnx_vs_torch_flips": sanity_flips, + "note": "autocast noise indicator, not a gate", + }, + "informational_slice_der_pp": { + "fp32_onnx": round(der_fp32, 4), + "int8static": round(der_int8, 4), + "torch_bf16": round(der_torch, 4), + "note": "seq2seq_der vs gold on the 600-row slice; the full-set " + "verdict is 6.6078 (run-094 verdict.json)", + }, "date_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), } (RC / "parity-report.json").write_text(json.dumps(report, indent=1), encoding="utf-8") log(f"parity: mean_delta={mean_delta_pp:.4f}pp max={max_delta_pp:.4f}pp " f"flips={flips}/{len(cand_rows)} pass={parity_pass}") + log(f"slice DER pp: fp32={der_fp32:.4f} int8={der_int8:.4f} " + f"torch={der_torch:.4f}") # ---- 6. candidate zip + golden + SHA256SUMS ---- classes_bytes = json.dumps(classes, ensure_ascii=False, indent=1).encode("utf-8") @@ -382,7 +435,8 @@ def get_next(self): f"{sha256_file(int8_path)} plane-int8static.onnx", f"{sha256_file(zip_path)} {zip_path.name}", f"{sha256_file(golden_path)} {golden_path.name}", - f"{sha256_file(ref_path)} reference-torch-fp32.jsonl", + f"{sha256_file(ref_path)} reference-fp32-onnx.jsonl", + f"{sha256_file(torch_path)} reference-torch-bf16.jsonl", f"{hashlib.sha256((RC / 'parity-report.json').read_bytes()).hexdigest()} parity-report.json", ] (RC / "SHA256SUMS.txt").write_text("\n".join(sums) + "\n", encoding="utf-8") From 6ef0d6b5f93082e62fe5b427f56045cc3b006d7b Mon Sep 17 00:00:00 2001 From: Ronald Tse Date: Sat, 21 Nov 2026 12:40:53 +0800 Subject: [PATCH 8/8] WO92 shipgate: add the int8-DYNAMIC arm (the crown lineage's shipped mode) under the same gates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Static int8 measured NEGATIVE on the plane encoder (48.0% flips vs the fp32 reference, +1.21pp slice DER) — consistent with the WO20u verdict scope (static recipe is KV-only). The successor matrix needs the crown's own shipped quantization measured under the same gates before any owner decision; both arms now emit zips, goldens, parity reports, and SHA256SUMS. --- wo92_shipgate_hf.py | 131 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 129 insertions(+), 2 deletions(-) diff --git a/wo92_shipgate_hf.py b/wo92_shipgate_hf.py index e0f85c5..e1b2523 100644 --- a/wo92_shipgate_hf.py +++ b/wo92_shipgate_hf.py @@ -448,9 +448,136 @@ def slice_der(rows): "zip": zip_path.name, "zip_bytes": zip_path.stat().st_size, "elapsed_s": round(time.time() - t0)} - (RC / "SHIPGATE_DONE").write_text(json.dumps(summary, indent=1) + "\n", + log("summary_static " + json.dumps(summary)) + + # ---- 7. second arm: int8 DYNAMIC — the crown lineage's shipped mode ---- + # The static lever's verdict scope was KV-only (WO20u); the plane + # encoder measures it NEGATIVE above. The crown shipped int8 dynamic + # (quantize_dynamic QInt8), so the successor matrix needs that arm + # measured under the same gates before any owner decision. + from onnxruntime.quantization import quantize_dynamic + + dyn_path = RC / "plane-int8dynamic.onnx" + quantize_dynamic(str(fp32_path), str(dyn_path), weight_type=QuantType.QInt8) + log(f"int8dynamic onnx {dyn_path.stat().st_size / 1e6:.1f} MB") + dyn_sess = ort.InferenceSession(str(dyn_path), so, + providers=["CPUExecutionProvider"]) + dyn_sess.run(None, {"input_ids": _smoke_ids.numpy(), + "plane_ids": _smoke_plane.numpy()}) + log("ort dynamic smoke row decoded OK") + dyn_rows = ort_decode(dyn_sess, slice_rows) + + dyn_deltas = [cer(c["output"], r["output"]) for c, r in zip(dyn_rows, ref_rows)] + dyn_flips = sum(1 for c, r in zip(dyn_rows, ref_rows) if c["output"] != r["output"]) + dyn_mean_pp = 100.0 * sum(dyn_deltas) / len(dyn_deltas) + dyn_max_pp = 100.0 * max(dyn_deltas) + dyn_flip_rate = dyn_flips / len(dyn_rows) + dyn_pass = dyn_mean_pp <= CER_GATE_PP and dyn_flip_rate <= FLIP_GATE + der_dyn = slice_der(dyn_rows) + dyn_report = { + "lane": "WO92 run-094 ship-gate (heb plane int8-DYNAMIC arm)", + "init": INIT_RUN, + "slice": {"file": "conformance/wo20/eval600/heb_eval_600.jsonl", + "rows": len(slice_rows), "sha256": SLICE_SHA}, + "decode_mode": "single-row greedy K=3 (shipped)", + "ort_providers": dyn_sess.get_providers(), + "parity": { + "mean_cer_delta_pp": round(dyn_mean_pp, 4), + "max_cer_delta_pp": round(dyn_max_pp, 4), + "flips": dyn_flips, + "flip_rate": round(dyn_flip_rate, 6), + "samples": len(dyn_rows), + "gates": {"cer_delta_pp_max": CER_GATE_PP, "flip_rate_max": FLIP_GATE}, + "pass": dyn_pass, + }, + "reference": "the fp32 ONNX artifact decoded under ORT CPU (the " + "published round's definition)", + "informational_slice_der_pp": { + "fp32_onnx": round(der_fp32, 4), + "int8dynamic": round(der_dyn, 4), + "note": "seq2seq_der vs gold on the 600-row slice", + }, + "date_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + } + dyn_report_path = RC / "parity-report-int8dynamic.json" + dyn_report_path.write_text(json.dumps(dyn_report, indent=1), encoding="utf-8") + log(f"parity_dynamic: mean_delta={dyn_mean_pp:.4f}pp max={dyn_max_pp:.4f}pp " + f"flips={dyn_flips}/{len(dyn_rows)} pass={dyn_pass}") + log(f"slice DER pp (dynamic arm): int8dynamic={der_dyn:.4f}") + + # dynamic zip (crown zip layout; precision + parity from this arm) + onnx_dyn_bytes = dyn_path.read_bytes() + dyn_meta = ( + "id: heb-vocalized-plane-wo92rc # RC lane id; final heb-vocalized-plane-{major.minor} = owner decision\n" + "task: diacritization\n" + "target: Hebr\n" + "kind: plane\n" + "precision: int8-dynamic\n" + "k_passes: 3\n" + "decode: single-row-greedy\n" + "license: BSD-3-Clause\n" + "trained_from: interscript-train train_hebrew_sft_hf.py (WO92 stage-2 gold SFT)\n" + " on run-093-heb-weak-pretrain best (knesset-v6 deduped weak-pretrain + gold);\n" + " checkpoint isx-training:/run-094-heb-gold-sft/best/model.pt\n" + "metrics:\n" + "- name: der_total_greedy\n" + " value: 6.6078\n" + " protocol: crown protocol (greedy K=3, seq2seq_der), Nakdimon test 1,864 rows\n" + " source: isx-training:/run-094-heb-gold-sft/verdict.json\n" + "parity:\n" + f" samples: {len(dyn_rows)}\n" + f" cer_delta: {round(dyn_mean_pp, 4)}\n" + f" flip_rate: {round(dyn_flip_rate, 6)}\n" + "sha256:\n" + f" plane-int8dynamic.onnx: {hashlib.sha256(onnx_dyn_bytes).hexdigest()}\n" + f" classes.json: {hashlib.sha256(classes_bytes).hexdigest()}\n" + ) + dyn_zip_buf = __import__("io").BytesIO() + with zipfile.ZipFile(dyn_zip_buf, "w", zipfile.ZIP_STORED) as zf: + zf.writestr("metadata.yaml", dyn_meta) + zf.writestr("classes.json", classes_bytes) + zf.writestr("plane-int8dynamic.onnx", onnx_dyn_bytes) + dyn_zip_path = RC / "heb-vocalized-plane-wo92rc-int8dynamic.zip" + dyn_zip_path.write_bytes(dyn_zip_buf.getvalue()) + + dyn_golden_path = RC / "heb-vocalized-plane-wo92rc-int8dynamic-golden.jsonl" + dyn_golden_path.write_text( + "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in dyn_rows), + encoding="utf-8") + + sums = [ + f"{sha256_file(fp32_path)} plane-fp32.onnx", + f"{sha256_file(int8_path)} plane-int8static.onnx", + f"{sha256_file(zip_path)} {zip_path.name}", + f"{sha256_file(golden_path)} {golden_path.name}", + f"{sha256_file(dyn_path)} plane-int8dynamic.onnx", + f"{sha256_file(dyn_zip_path)} {dyn_zip_path.name}", + f"{sha256_file(dyn_golden_path)} {dyn_golden_path.name}", + f"{sha256_file(torch_path)} reference-torch-bf16.jsonl", + f"{sha256_file(ref_path)} reference-fp32-onnx.jsonl", + f"{hashlib.sha256((RC / 'parity-report.json').read_bytes()).hexdigest()} parity-report.json", + f"{hashlib.sha256(dyn_report_path.read_bytes()).hexdigest()} parity-report-int8dynamic.json", + ] + (RC / "SHA256SUMS.txt").write_text("\n".join(sums) + "\n", encoding="utf-8") + + final = { + "static": {"parity_pass": parity_pass, + "mean_cer_delta_pp": round(mean_delta_pp, 4), + "flip_rate": round(flip_rate, 6), + "slice_der_pp": round(der_int8, 4), + "zip": zip_path.name, "zip_bytes": zip_path.stat().st_size}, + "dynamic": {"parity_pass": dyn_pass, + "mean_cer_delta_pp": round(dyn_mean_pp, 4), + "flip_rate": round(dyn_flip_rate, 6), + "slice_der_pp": round(der_dyn, 4), + "zip": dyn_zip_path.name, "zip_bytes": dyn_zip_path.stat().st_size}, + "reference_slice_der_pp": round(der_fp32, 4), + "samples": len(slice_rows), + "elapsed_s": round(time.time() - t0), + } + (RC / "SHIPGATE_DONE").write_text(json.dumps(final, indent=1) + "\n", encoding="utf-8") - log("summary " + json.dumps(summary)) + log("summary " + json.dumps(final)) if __name__ == "__main__":