Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
fp8: invert THE DESIGN LANDMINE ambiguous-shape collision to fmt=1
monotophicc709a443d0c9
diff --git a/c/colibri.c b/c/colibri.cindex 10005197..6eaa3f18 100644--- a/c/colibri.c+++ b/c/colibri.c@@ -1324,11 +1324,34 @@ static int qt_resolve_fmt(const char *name, int O, int I, int64_t nb, int64_t ns* unambiguous. But for small O (<=128) and/or small I, ceil(O/128)** ceil(I/128) can equal O exactly (e.g. O=1,I<=128 -> 1*1=1=O; O=2,I in* [129,256] -> 1*2=2=O; O=256,I in (16256,16384] -> 2*128=256=O) -- a- * tensor whose scale array satisfies BOTH conventions at once. Guessing- * either way risks silently reading a genuine per-row-int8 tensor as- * block-scaled FP8 (or vice versa), which would corrupt every weight- * without any error. Refuse instead (same "untrusted container"- * discipline as the rest of this function).+ * tensor whose scale array satisfies BOTH conventions at once.+ *+ * REVIEW FINDING (maintainer, #528): this collision is not a theoretical+ * corner case. GLM-5.2's own self_attn.o_proj.weight loads as+ * [D,H*v_head] = [6144,16384]: nblkO=ceil(6144/128)=48,+ * nblkI=ceil(16384/128)=128, nblkO*nblkI=6144==O -- a real, pre-existing,+ * VALID int8-row o_proj tensor hits this exact byte-count collision on+ * every GLM-5.2 checkpoint this engine has ever loaded. The general+ * family is any int8 tensor where O==ceil(O/128)*ceil(I/128) (see the+ * CENSUS SCAN, tools/fp8_collision_census.py, for the complete+ * enumerated set over this repo's own containers). An earlier revision+ * of this function refused unconditionally here -- exit(1) at load time+ * on an ordinary, already-shipping, valid model -- which is a strictly+ * worse failure mode than the misread it was guarding against.+ *+ * INVERSION: an ambiguous shape resolves to fmt=1 -- the incumbent,+ * already-on-disk, decodable format -- instead of refusing. This is sound+ * because the WRITER side (tools/repack_fp8_passthrough.py's+ * _check_geometry) now refuses to EMIT an fmt=7 container at any shape+ * satisfying this same collision predicate: no genuine fmt=7 tensor this+ * engine's own tooling can produce will ever reach this branch, so+ * resolving to fmt=1 here is not a guess against a live fmt=7 candidate --+ * it is the only remaining candidate for an UNSTAMPED container. A+ * self-describing __metadata__ stamp that lets a THIRD-PARTY fmt=7+ * container resolve at this same colliding shape is a separate mechanism+ * (see qt_verify_fmt_stamp / the stamped build of this function) -- this+ * (unstamped) function has no stamp to consult and always commits to the+ * incumbent format.** SCALE ENCODING IS A DECLARED PROPERTY, not a hardcoded constant: f32 (4* bytes/block, above) is what THIS build implements, but it is not the@@ -1362,12 +1385,16 @@ static int qt_resolve_fmt(const char *name, int O, int I, int64_t nb, int64_t nsint64_t nblkO=fp8_nblk(O), nblkI=fp8_nblk(I);int64_t ns_row=(int64_t)O*4, ns_blk=nblkO*nblkI*4, ns_blk_ue8m0=nblkO*nblkI;int is_row=(ns==ns_row), is_blk=(ns==ns_blk), is_blk_ue8m0=(ns==ns_blk_ue8m0);- if(is_row && is_blk){- fprintf(stderr,"%s: [%d,%d] scale array is %lld bytes — matches BOTH per-row "- "int8 (fmt=1) and per-128x128-block FP8 (fmt=7) scale geometry; refusing "- "rather than guessing (untrusted container, THE DESIGN LANDMINE)\n",- name,O,I,(long long)ns); exit(1);- }+ /* THE DESIGN LANDMINE, INVERTED (maintainer review, #528): is_row&&is_blk+ * used to exit(1) here unconditionally -- see the comment above this+ * function's "REVIEW FINDING"/"INVERSION" paragraphs for why that was+ * wrong. No explicit branch is needed to resolve it to fmt=1: `fmt` is+ * already 1 at this point (this whole `if(fmt==1)` block only runs when+ * nb==exp_i8, which is what set fmt=1 above), and the `is_blk && !is_row`+ * check further down evaluates false whenever is_row is true -- so an+ * is_row&&is_blk shape simply falls through unchanged to fmt=1. This+ * comment exists so a future reader doesn't mistake the missing branch+ * for an oversight. */if(is_blk_ue8m0){fprintf(stderr,"%s: [%d,%d] fp8-e4m3-b128 with ue8m0 scales recognized but not ""implemented; only f32 block scales are supported in this build (nb=%lld "diff --git a/c/tests/test_fp8_load.c b/c/tests/test_fp8_load.cindex f04cca02..49ca2e67 100644--- a/c/tests/test_fp8_load.c+++ b/c/tests/test_fp8_load.c@@ -14,18 +14,32 @@* The two are told apart ONLY by the scale array's byte count (per-row O*4 for* fmt=1, per-128x128-block ceil(O/128)*ceil(I/128)*4 for fmt=7, THIS build's* implemented f32 scale encoding). For some shapes those two counts coincide- * exactly -- qt_resolve_fmt must REFUSE (exit(1)) rather than guess. Refusal- * is tested via fork()+waitpid(), mirroring tests/test_st_pread.c's- * established convention for exit(1)-terminated paths.+ * exactly -- INVERSION (maintainer review, #528): qt_resolve_fmt used to+ * REFUSE (exit(1)) this ambiguous case; it now resolves to fmt=1 (the+ * incumbent, already-on-disk, decodable format) instead, because the+ * collision is not hypothetical (GLM-5.2's own self_attn.o_proj.weight hits+ * it, see qt_resolve_fmt's own "REVIEW FINDING"/"INVERSION" comment) and the+ * writer side (repack_fp8_passthrough.py's _check_geometry) now refuses to+ * ever EMIT an fmt=7 container at this same shape, so an unstamped ambiguous+ * tensor reaching this function is never a genuine fmt=7 candidate. The+ * former refusal-testing convention (fork()+waitpid(), mirroring+ * tests/test_st_pread.c's exit(1)-path idiom) is kept for the OTHER+ * refusing cases below (Part A2's fmt=6 collision, Part A3's UE8M0+ * recognized-not-implemented refusal, and the generic garbage-byte-count+ * refusal) -- only the is_row&&is_blk collision in this Part flipped from+ * expect_refuse to expect_fmt(...,1,...).** Part A2: fmt=6 (E8/IQ3, upstream #465) vs fmt=7 collision at [O<=128 or- * O in a 128-block-count range, I=98] -- SECOND DESIGN LANDMINE.+ * O in a 128-block-count range, I=98] -- SECOND DESIGN LANDMINE. Unchanged by+ * the #528 inversion above (a different collision predicate, still refused).** Part A3: fmt=7's scale ENCODING is a declared property, not a hardcoded* constant -- f32 (Part A/A2 above) is what this build implements. A UE8M0* (1 byte/block) encoding is a REAL, distinct byte signature (the DeepSeek-V4* checkpoint format for this identical weight geometry) this build recognizes- * and refuses BY NAME rather than misreading.+ * and refuses BY NAME rather than misreading. Unchanged by the #528+ * inversion (a stamp confirms the WEIGHT format, never a decoder this build+ * doesn't have -- see qt_resolve_fmt's own comment).** Part B: qt_from_disk loader-seam -- writes a real single-shard .safetensors* file containing an fmt=7 tensor (U8 weight + per-block F32 .qs) next to an@@ -34,12 +48,18 @@* fmt=1 correctly and the loaded weights dequantize identically to a reference.* Mirrors tests/test_int3_load.c's structure for fmt=5.*- * Part C: qt_bytes()/qt_scale_bytes() byte-accounting for fmt=7.+ * Part C: qt_bytes()/qt_scale_bytes() byte-accounting for fmt=7, plus+ * qt_wire_split() -- the shared weight/scale byte-range split qt_wire_mmap+ * and qt_unwire_mmap both now call (maintainer review, #528: qt_scale_bytes()+ * existed correctly but neither call site actually used it, a defect only+ * -Wno-unused-function's suppression let compile clean).** This build has NO container metadata stamp (see qt_resolve_fmt's own header- * comment) -- every ambiguous/unimplemented-encoding shape below refuses- * unconditionally; stamp-resolves-ambiguity behavior is a separate, follow-up- * PR (registry + metadata stamp), not exercised here. */+ * comment) -- every ambiguous/unimplemented-encoding shape below EXCEPT the+ * is_row&&is_blk collision (now resolved to fmt=1, see Part A above) refuses+ * unconditionally; stamp-resolves-ambiguity behavior for the OTHER+ * collisions is a separate, follow-up PR (registry + metadata stamp), not+ * exercised here. */#define main coli_glm_main_unused#include "../colibri.c"#undef main@@ -123,21 +143,46 @@ static void test_disambiguation(void){CHECK(expect_fmt(2048,6144,(int64_t)2048*6144,16LL*48*4,7,"fp8 2048x6144 (spec example)"));CHECK(expect_fmt(384,6144,(int64_t)384*6144,3LL*48*4,7,"fp8 384x6144 non-square block grid"));+ /* --- REGRESSION (maintainer review, #528): GLM-5.2's own+ * self_attn.o_proj.weight, [D,H*v_head]=[6144,16384]. nblkO=ceil(6144/128)=48,+ * nblkI=ceil(16384/128)=128, product=6144==O -- this shape hits the+ * is_row&&is_blk collision below on every GLM-5.2 checkpoint, and is a+ * REAL, pre-existing, valid int8-row tensor, not a hypothetical. Confirmed+ * against this repo's own v1 container header (o_proj weight U8+ * 100,663,296 B == 6144*16384; .qs scale blob 24,576 B == 6144*4 ==+ * 48*128*4, both at once) -- see the CENSUS SCAN+ * (tools/fp8_collision_census.py) for the full enumerated family. An+ * earlier revision of qt_resolve_fmt refused this shape unconditionally+ * (exit(1) at load time on an ordinary model); the INVERSION resolves it+ * to fmt=1 instead -- this is that non-refusal, asserted directly. */+ CHECK(expect_fmt(6144,16384,(int64_t)6144*16384,6144LL*4,1,+ "GLM-5.2 o_proj shape [6144,16384]: valid int8-row, ambiguous-by-byte-count, resolves fmt=1 (NOT a refusal)"));+/* --- degenerate shapes: O<=128 makes nblkO==1, so ns_blk==nblkI*4 can* equal ns_row==O*4 whenever nblkI==O. Exhaustive-in-spirit sweep of the- * boundary the design landmine describes. --- */- CHECK(expect_refuse(1,1, 1, 4, "degenerate O=1 I=1 (nblkI=1=O)"));- CHECK(expect_refuse(1,128, 128, 4, "degenerate O=1 I=128 (nblkI=1=O, I at block edge)"));- CHECK(expect_refuse(2,256, 2LL*256, 8, "degenerate O=2 I=256 (nblkI=2=O)"));- CHECK(expect_refuse(6,768, 6LL*768, 24, "degenerate O=6 I=768 (nblkI=6=O)"));- CHECK(expect_refuse(128,16384,128LL*16384, 512, "degenerate O=128 I=16384 (nblkO=1,nblkI=128=O)"));+ * boundary the design landmine describes. INVERSION (maintainer review,+ * #528): every one of these used to be an expect_refuse (exit(1)) -- the+ * general family this collision predicate describes (any int8 tensor+ * where O==ceil(O/128)*ceil(I/128)) includes real, valid, pre-existing+ * tensors (see the o_proj case just above), so refusing was the wrong+ * call across the board, not just for the three shapes the maintainer's+ * review named explicitly ([128,16384],[256,16384],[384,16384] below) --+ * every case in this sweep hits the exact same is_row&&is_blk branch and+ * is flipped here for the same reason. --- */+ CHECK(expect_fmt(1,1, 1, 4, 1, "degenerate O=1 I=1 (nblkI=1=O) -> fmt=1, was refuse"));+ CHECK(expect_fmt(1,128, 128, 4, 1, "degenerate O=1 I=128 (nblkI=1=O, I at block edge) -> fmt=1, was refuse"));+ CHECK(expect_fmt(2,256, 2LL*256, 8, 1, "degenerate O=2 I=256 (nblkI=2=O) -> fmt=1, was refuse"));+ CHECK(expect_fmt(6,768, 6LL*768, 24, 1, "degenerate O=6 I=768 (nblkI=6=O) -> fmt=1, was refuse"));+ /* the three shapes the maintainer's review named explicitly (his exact expect_refuse+ * calls, O=128/256/384 at I=16384) -- FLIPPED to assert fmt=1. */+ CHECK(expect_fmt(128,16384,128LL*16384, 512, 1, "degenerate O=128 I=16384 (nblkO=1,nblkI=128=O) -> fmt=1, was refuse"));/* O>128 degenerate case: nblkO=2, need nblkI=O/2 -- O=256,I=16384 -> nblkI=128, 2*128=256=O */- CHECK(expect_refuse(256,16384,256LL*16384, 1024, "degenerate O=256 I=16384 (nblkO=2,nblkI=128, product=O)"));+ CHECK(expect_fmt(256,16384,256LL*16384, 1024, 1, "degenerate O=256 I=16384 (nblkO=2,nblkI=128, product=O) -> fmt=1, was refuse"));/* k=3: the ambiguity isn't a one-off O=256 coincidence -- it's structural for ANY* O that's a multiple of 128 (nblkO=k), since nblkI==128 (I in (16256,16384]) always* makes nblkO*nblkI == k*128 == O. One more multiple (O=384=3*128) confirms the* condition generalizes past the k=2 worked example, not just a re-derivation. */- CHECK(expect_refuse(384,16384,384LL*16384, 1536, "degenerate O=384 I=16384 (nblkO=3,nblkI=128, k=3, product=O)"));+ CHECK(expect_fmt(384,16384,384LL*16384, 1536, 1, "degenerate O=384 I=16384 (nblkO=3,nblkI=128, k=3, product=O) -> fmt=1, was refuse"));/* --- boundary-ADJACENT non-degenerate cases: one step past each* degenerate case above, both interpretations now legitimately resolve. --- */diff --git a/c/tests/test_fp8_repack.py b/c/tests/test_fp8_repack.pyindex 283de225..64bb3dc3 100644--- a/c/tests/test_fp8_repack.py+++ b/c/tests/test_fp8_repack.py@@ -11,10 +11,14 @@ layout that convert_fp8_to_int4.py's dequant() reads) -- no real Z.ai shard isread or written by this suite, per the build's hard constraint. Covers:selection (resident kinds byte-preserved, routed experts / io / f32 excluded),byte-for-byte preservation of the fp8 weight and the .qs scale rename, the-scale-geometry refusal path (THE DESIGN LANDMINE's write-side twin: a-malformed source shard must be refused, not silently repacked into a-container the engine's qt_resolve_fmt would then misread), --dry-run writing-nothing, and the #383-class resume/params-guard behavior.+scale-geometry refusal path in TWO forms (THE DESIGN LANDMINE's write-side+twin) -- a malformed source shard (.qs shape doesn't match ceil(O/128)x+ceil(I/128) for its weight) must be refused, AND a well-formed-but-AMBIGUOUS+shape (nblkO*nblkI==O, where this tensor's block-scale byte count would+coincide with a per-row int8 scale byte count) must ALSO be refused+(maintainer review, #528: this is not hypothetical, GLM-5.2's own+self_attn.o_proj.weight is a real instance) -- --dry-run writing nothing, and+the #383-class resume/params-guard behavior."""import glob, json, os, struct, sys, tempfile, unittest@@ -153,6 +157,34 @@ class SelectionTest(unittest.TestCase):with self.assertRaises(ValueError):rp.shard_inventory(bad_path, n_layers=5)+ def test_geometry_refusal_on_ambiguous_shape(self):+ """WRITER-SIDE REFUSAL (maintainer review, #528): a WELL-FORMED .qs sidecar+ (correct nblkOxnblkI shape for [O,I], unlike the malformed case above) must+ still be refused when nblkO*nblkI==O -- the exact shape where this tensor's+ block-scale byte count (nblkO*nblkI*4) would coincide with a per-row int8+ scale byte count (O*4). Not hypothetical: GLM-5.2's own+ self_attn.o_proj.weight ([6144,16384], nblkO=48 nblkI=128 product=6144==O)+ is a real instance of this exact family; O=2,I=256 here is the smallest+ realistic analog (nblkO=1, nblkI=2, product=2==O), the same degenerate+ shape family c/tests/test_fp8_load.c's test_disambiguation() sweeps. The+ engine's qt_resolve_fmt reader resolves an unstamped collision at this+ shape to fmt=1 (int8-row) rather than refusing (see colibri.c's+ INVERSION) -- so this tool refusing to ever EMIT an fmt=7 container here+ is what keeps that reader-side resolution correct: an fmt=7 tensor this+ tool produced at this shape would be silently read back as plain int8."""+ amb_path = os.path.join(self.tmp.name, "ambiguous.safetensors")+ O, I_ = 2, 256+ w = torch.randn(O, I_).to(torch.float8_e4m3fn)+ nblkO, nblkI = (O + 127) // 128, (I_ + 127) // 128+ self.assertEqual(nblkO * nblkI, O, "fixture must actually hit the collision")+ scale = torch.ones(nblkO, nblkI, dtype=torch.float32) # WELL-FORMED for [O,I] -- passes the first check+ save_file({"model.layers.0.self_attn.o_proj.weight": w,+ "model.layers.0.self_attn.o_proj.weight_scale_inv": scale}, amb_path)+ with self.assertRaises(ValueError):+ rp.repack_shard(amb_path, n_layers=5)+ with self.assertRaises(ValueError):+ rp.shard_inventory(amb_path, n_layers=5)+class ResumeAndParamsGuardTest(unittest.TestCase):def setUp(self):diff --git a/c/tools/fp8_collision_census.py b/c/tools/fp8_collision_census.pynew file mode 100644index 00000000..99ea37f6--- /dev/null+++ b/c/tools/fp8_collision_census.py@@ -0,0 +1,191 @@+#!/usr/bin/env python3+"""fp8_collision_census.py: enumerate every RESIDENT-role tensor shape in a+safetensors container (JSON header parse ONLY -- no tensor data read, no+torch/safetensors import, no model load) and evaluate THE DESIGN LANDMINE's+collision predicate (qt_resolve_fmt in colibri.c): O == ceil(O/128)*ceil(I/128),+the shape family where an int8-row tensor's per-row scale byte count (O*4)+exactly equals a per-128x128-block fp8 scale byte count+(ceil(O/128)*ceil(I/128)*4) for the SAME [O,I].++Maintainer review, #528: this is not a hypothetical corner case. GLM-5.2's own+self_attn.o_proj.weight ([D,H*v_head] = [6144,16384]) hits it on every+checkpoint this engine has loaded. This script is the "enumerated, not+sampled" evidence for that finding, run against this repo's own containers.++WHY config.json, not just the safetensors header: a container's on-disk+weight tensor is stored FLATTENED (one dimension: O*I raw bytes for int8-row,+O*ceil(I/2) for int4-packed, etc. -- see colibri.c's qt_bytes()) -- the header+alone cannot recover O and I separately for [O,I]. This script instead+computes each tensor's [O,I] from the model's config.json (hidden_size,+q_lora_rank, kv_lora_rank, num_attention_heads, qk_rope_head_dim,+qk_nope_head_dim, v_head_dim, intermediate_size, moe_intermediate_size -- the+same dimensions colibri.c's own Cfg struct reads at load time and passes into+qt_resolve_fmt as O,I), for every tensor NAME the header actually contains+that this script's role table recognizes, then cross-checks the computed+byte count against the header's own raw byte count (int8-row: O*I; int4-+packed: O*ceil(I/2)) as a sanity check -- reported, not silently trusted.++Scope: RESIDENT-kind tensor roles only (o_proj, q_a/q_b_proj,+kv_a_proj_with_mqa, kv_b_proj, dense-MLP gate/up/down, shared-expert+gate/up/down) plus routed-expert gate/up/down for completeness -- these are+the only roles tools/repack_fp8_passthrough.py's RESIDENT_KINDS classify()+taxonomy could ever select for fmt=7 repacking (routed experts are excluded+by that tool's own design and stay on int4-g64/E8, but are included here+anyway since the collision predicate is a pure function of [O,I], independent+of current on-disk format). f32/norm/router/embed/lm_head tensors are not+quantized (no U8 weight) and are skipped.++Usage:+ python3 tools/fp8_collision_census.py <container_dir> [<container_dir> ...]+"""+import glob, json, os, struct, sys++BLOCK = 128+++def _nblk(n):+ return (n + BLOCK - 1) // BLOCK+++def is_ambiguous(O, I):+ """THE DESIGN LANDMINE's collision predicate (colibri.c qt_resolve_fmt):+ an int8-row tensor at this [O,I] has per-row scale bytes O*4 that exactly+ equal per-128x128-block fp8 scale bytes ceil(O/128)*ceil(I/128)*4."""+ return _nblk(O) * _nblk(I) == O+++def read_header(path):+ """Header-only read: 8-byte little-endian length prefix + that many bytes+ of JSON. Never reads a single byte of actual tensor data."""+ with open(path, "rb") as f:+ hlen = struct.unpack("<Q", f.read(8))[0]+ return json.loads(f.read(hlen).decode("utf-8"))+++def scan_tensor_headers(container_dir):+ """Union of every non-metadata tensor key -> header entry, across every+ shard in the container. Header (JSON) only, see read_header above."""+ entries = {}+ for path in sorted(glob.glob(os.path.join(container_dir, "*.safetensors"))):+ hdr = read_header(path)+ for k, v in hdr.items():+ if k == "__metadata__":+ continue+ entries[k] = v+ return entries+++def classify_shape(name, cfg):+ """Returns (kind, O, I) for a tensor name this census can size from+ config.json alone, or None if `name` isn't a role this script recognizes+ (norms/router/embed/lm_head/MTP-head-only tensors -- none of these carry+ a resident [O,I] weight this predicate applies to)."""+ D = cfg["hidden_size"]+ H = cfg["num_attention_heads"]+ q_lora = cfg["q_lora_rank"]+ kv_lora = cfg["kv_lora_rank"]+ qk_rope = cfg["qk_rope_head_dim"]+ qk_nope = cfg["qk_nope_head_dim"]+ v_head = cfg["v_head_dim"]+ inter = cfg["intermediate_size"]+ moe_inter = cfg["moe_intermediate_size"]+ qk_head = qk_nope + qk_rope++ if name.endswith("self_attn.o_proj.weight"):+ return ("self_attn.o_proj", D, H * v_head)+ if name.endswith("self_attn.q_a_proj.weight"):+ return ("self_attn.q_a_proj", q_lora, D)+ if name.endswith("self_attn.q_b_proj.weight"):+ return ("self_attn.q_b_proj", H * qk_head, q_lora)+ if name.endswith("self_attn.kv_a_proj_with_mqa.weight"):+ return ("self_attn.kv_a_proj_with_mqa", kv_lora + qk_rope, D)+ if name.endswith("self_attn.kv_b_proj.weight"):+ return ("self_attn.kv_b_proj (kvb -- excluded from fmt=7 repack, see tool docstring)",+ H * (qk_nope + v_head), kv_lora)+ if ".mlp.experts." in name and name.endswith("gate_proj.weight"):+ return ("mlp.experts.*.gate_proj (routed -- excluded from fmt=7 repack)", moe_inter, D)+ if ".mlp.experts." in name and name.endswith("up_proj.weight"):+ return ("mlp.experts.*.up_proj (routed -- excluded from fmt=7 repack)", moe_inter, D)+ if ".mlp.experts." in name and name.endswith("down_proj.weight"):+ return ("mlp.experts.*.down_proj (routed -- excluded from fmt=7 repack)", D, moe_inter)+ if "shared_experts" in name and name.endswith("gate_proj.weight"):+ return ("mlp.shared_experts.gate_proj", moe_inter, D)+ if "shared_experts" in name and name.endswith("up_proj.weight"):+ return ("mlp.shared_experts.up_proj", moe_inter, D)+ if "shared_experts" in name and name.endswith("down_proj.weight"):+ return ("mlp.shared_experts.down_proj", D, moe_inter)+ if name.endswith("mlp.gate_proj.weight") and ".experts." not in name:+ return ("mlp.gate_proj (dense)", inter, D)+ if name.endswith("mlp.up_proj.weight") and ".experts." not in name:+ return ("mlp.up_proj (dense)", inter, D)+ if name.endswith("mlp.down_proj.weight") and ".experts." not in name:+ return ("mlp.down_proj (dense)", D, inter)+ return None+++def _byte_check(nb_actual, O, I):+ if nb_actual == O * I:+ return "int8-row (nb=O*I)"+ if nb_actual == O * ((I + 1) // 2):+ return "int4-packed (nb=O*ceil(I/2))"+ return f"UNVERIFIED (nb={nb_actual}, neither O*I={O*I} nor O*ceil(I/2)={O*((I+1)//2)} -- " \+ f"likely int3-g64/E8-lattice, expected for routed experts in some containers)"+++def census(container_dir):+ cfg_path = os.path.join(container_dir, "config.json")+ with open(cfg_path) as f:+ cfg = json.load(f)+ entries = scan_tensor_headers(container_dir)+ by_pattern = {}+ unresolved = []+ for name, entry in entries.items():+ if name.endswith(".qs") or name.endswith("_scale_inv"):+ continue+ if entry.get("dtype") != "U8":+ continue+ cls = classify_shape(name, cfg)+ if cls is None:+ unresolved.append(name)+ continue+ kind, O, I = cls+ shp = entry.get("shape", [])+ nb_actual = 1+ for d in shp:+ nb_actual *= d+ key = (kind, O, I)+ rec = by_pattern.setdefault(key, {"kind": kind, "O": O, "I": I, "count": 0,+ "ambiguous": is_ambiguous(O, I),+ "byte_encodings": set()})+ rec["count"] += 1+ rec["byte_encodings"].add(_byte_check(nb_actual, O, I))+ return cfg, by_pattern, unresolved+++def main():+ dirs = sys.argv[1:]+ if not dirs:+ print("usage: fp8_collision_census.py <container_dir> [<container_dir> ...]", file=sys.stderr)+ sys.exit(1)+ any_ambig = False+ for d in dirs:+ base = os.path.basename(os.path.normpath(d))+ cfg, by_pattern, unresolved = census(d)+ print(f"=== {base} ({d}) ===")+ print(f"{'tensor name pattern':70s} {'O':>8s} {'I':>8s} {'nblkO*nblkI':>12s} {'count':>6s} ambiguous? on-disk encoding(s)")+ for (kind, O, I), rec in sorted(by_pattern.items()):+ nblk_prod = _nblk(O) * _nblk(I)+ flag = "AMBIGUOUS <---" if rec["ambiguous"] else "-"+ if rec["ambiguous"]:+ any_ambig = True+ enc = ", ".join(sorted(rec["byte_encodings"]))+ print(f"{kind:70s} {O:8d} {I:8d} {nblk_prod:12d} {rec['count']:6d} {flag:15s} {enc}")+ if unresolved:+ print(f" ({len(unresolved)} U8 tensor(s) in {base} not classified by this script's role "+ f"table -- inspect if unexpected: {sorted(unresolved)[:5]}{'...' if len(unresolved)>5 else ''})")+ print()+ print("RESULT:", "AMBIGUOUS family found (see table above)" if any_ambig else "no ambiguous family found")+++if __name__ == "__main__":+ main()diff --git a/c/tools/repack_fp8_passthrough.py b/c/tools/repack_fp8_passthrough.pyindex 6a1a3e0d..704703af 100644--- a/c/tools/repack_fp8_passthrough.py+++ b/c/tools/repack_fp8_passthrough.py@@ -19,13 +19,23 @@ comment): the engine tells fmt=7 (this tool's output) apart from fmt=1 (plainint8) ONLY by scale-array geometry -- per-row for fmt=1, per-128x128-block forfmt=7. This tool must therefore emit .qs sidecars whose byte count is EXACTLYceil(O/128)*ceil(I/128)*4, never anything that could coincide with O*4 by-accident for the shapes it targets (see _check_geometry below, which refuses-rather than silently emitting a container the engine might misread). At I=98-specifically, a single-block fp8 tensor's raw weight-byte count ALSO coincides-with a genuine fmt=6 (E8/IQ3) tensor's -- see qt_resolve_fmt's "SECOND DESIGN-LANDMINE" comment; this tool does not target I=98 shapes in practice (Z.ai's-real projections don't land there), but the engine's read-side refusal covers-it regardless.+accident for the shapes it targets -- ENFORCED, not just asserted, by+_check_geometry below (maintainer review, #528): it refuses to repack any+[O,I] where nblkO*nblkI==O, the exact shape where this tool's own block-scale+byte count would coincide with a per-row int8 scale byte count. This is not+hypothetical: GLM-5.2's own self_attn.o_proj.weight ([6144,16384]) is a real+instance (nblkO=48, nblkI=128, product=6144==O). It matters more now than it+used to, because the engine's UNSTAMPED read-side collision policy resolves an+ambiguous shape to fmt=1 rather than refusing (see qt_resolve_fmt's+INVERSION) -- so an fmt=7 container this tool emitted at such a shape would be+silently read back as plain int8, not caught by a read-side refusal. Avoiding+the collision at write time is therefore load-bearing, not a redundant+belt-and-braces check. At I=98 specifically, a single-block fp8 tensor's raw+weight-byte count ALSO coincides with a genuine fmt=6 (E8/IQ3) tensor's -- see+qt_resolve_fmt's "SECOND DESIGN LANDMINE" comment; this tool does not target+I=98 shapes in practice (Z.ai's real projections don't land there), and that+narrower collision is unchanged by this PR (still an unconditional read-side+refusal), so _check_geometry does not additionally guard against it here.SCALE ENCODING: this tool always emits f32 block scales (4 bytes/block, the`.to(torch.float32)` below) -- the ENCODING this build implements. It never@@ -112,13 +122,32 @@ def _check_geometry(name, O, I, nblkO, nblkI):doesn't match what qt_resolve_fmt expects for [O,I] -- the same "untrustedcontainer" discipline the C side applies on read, applied here on write so amalformed source checkpoint is caught at repack time, not at load time three- steps later with a confusing engine-side refusal."""+ steps later with a confusing engine-side refusal.++ WRITER-SIDE REFUSAL (maintainer review, #528): also refuses at the AMBIGUOUS+ shape THE DESIGN LANDMINE describes (qt_resolve_fmt in colibri.c) -- where+ O == ceil(O/128)*ceil(I/128), i.e. this tensor's block-scale byte count+ (nblkO*nblkI*4) exactly equals a per-row int8 scale byte count (O*4). GLM-5.2's+ own self_attn.o_proj.weight ([6144,16384]) is a REAL, non-hypothetical instance+ of this shape. The engine's reader now resolves an unstamped collision to fmt=1+ (the incumbent, decodable format) rather than refusing -- which makes it load+ bearing that THIS tool never emits an fmt=7 container at such a shape: this+ docstring's own opening promise ("never anything that could coincide with O*4+ by accident") is enforced here, not just asserted."""exp_nblkO, exp_nblkI = _nblk(O), _nblk(I)if (nblkO, nblkI) != (exp_nblkO, exp_nblkI):raise ValueError(f"{name}: scale_inv block shape ({nblkO},{nblkI}) != expected "f"({exp_nblkO},{exp_nblkI}) for [{O},{I}] -- refusing to repack a shape "f"the engine's qt_resolve_fmt would either refuse or (worse) misread")+ if nblkO * nblkI == O:+ raise ValueError(+ f"{name}: [{O},{I}] is an AMBIGUOUS fp8-e4m3-b128 shape -- its "+ f"block-scale byte count (nblkO*nblkI*4={nblkO*nblkI*4}) exactly "+ f"coincides with a per-row int8 scale byte count (O*4={O*4}) for the "+ f"same [O,I]; refusing to emit an fmt=7 container the engine's "+ f"qt_resolve_fmt collision policy would resolve to fmt=1 (int8-row), "+ f"not fmt=7, on an unstamped read (THE DESIGN LANDMINE, colibri.c)")def shard_inventory(path, n_layers):