From 7f2c76e18db5ff81ab8cb3b422b4bbef172cd531 Mon Sep 17 00:00:00 2001 From: sergiywith Date: Wed, 30 Sep 2026 22:25:38 +0300 Subject: [PATCH] iq_pack: keep experts.bin only when its blobs match the GGUF An existing experts.bin was kept whenever its size matched the layout. A different checkpoint with the same geometry (a re-quantization or a fine-tune packed into the same folder) has the same size, so the engine silently served the old experts with the new model's dense weights. Before keeping the file, the first and last blobs of the first, middle and last layers are now compared with the GGUF; a mismatch rewrites it. The check reads six blobs, so an unchanged pack is still reused at once. Test: test_experts_bin_is_kept_only_with_this_ggufs_blobs packs two GGUFs of the same geometry into one folder (it fails on the previous code). Rebased onto 0.1.31 (Niko1221): 0.1.31 already refuses an experts.bin whose sidecar (experts.bin.src.json: shard names and sizes, the hash of native_experts.txt) does not match, so the six-blob comparison runs only when the sidecar says "reuse" - it catches the case the sidecar cannot (a re-quantized or fine-tuned checkpoint under the same file names and sizes). It reads each of the six expert blobs on its own instead of concatenating the whole layer. The test packs the second model under the first one's file name, so it reaches the new check. --- tools/iq_pack.py | 24 ++++++++++++++++++++---- tools/test_iq_pack.py | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 4 deletions(-) diff --git a/tools/iq_pack.py b/tools/iq_pack.py index 43994075..86766755 100644 --- a/tools/iq_pack.py +++ b/tools/iq_pack.py @@ -526,6 +526,25 @@ def main() -> int: sidecar = out / "experts.bin.src.json" want = experts_source(model, text, offset) reuse = path.exists() and path.stat().st_size == offset and read_json(sidecar) == want + + def layer_blobs(blob, ts): + chunk = np.concatenate([model.bytes(t.name).reshape(n_expert, -1) for t in ts], axis=1) + assert chunk.shape == (n_expert, blob) # (n_expert, blob): gate | up | down per expert + return chunk + + if reuse: + # the sidecar names the shards by name and size, which a re-quantized or fine-tuned checkpoint of the same + # geometry packed into the same folder can share: compare the first and last blobs of the first, middle and + # last layers with the GGUF too (six blobs, so an unchanged pack is still reused at once) + with open(path, "rb") as f: + for l, gt, dt, off, blob, ts in (layout[0], layout[len(layout) // 2], layout[-1]): + for e in (0, n_expert - 1): + f.seek(off + e * blob) + want_blob = b"".join(model.bytes(t.name).reshape(n_expert, -1)[e].tobytes() for t in ts) + if f.read(blob) != want_blob: + reuse = False + if not reuse: + print("%s matches %s but not this GGUF's expert blobs" % (path, sidecar.name)) if path.exists() and not reuse and not a.experts_bin: if sidecar.exists(): print("%s was cut from another source than this model (%s): the engine would read it instead of " @@ -567,10 +586,7 @@ def main() -> int: part = out / "experts.bin.tmp" with open(part, "wb") as fo: for l, gt, dt, off, blob, ts in layout: - parts = [model.bytes(t.name).reshape(n_expert, -1) for t in ts] - chunk = np.concatenate(parts, axis=1) # (n_expert, blob): gate | up | down per expert - assert chunk.shape == (n_expert, blob) - fo.write(chunk.tobytes()) + fo.write(layer_blobs(blob, ts).tobytes()) if l % 8 == 0: print(" layer %2d %-8s/%-7s blob %8d at %.2f GiB" % (l, ts[0].type_name, ts[2].type_name, blob, off / 2**30), flush=True) diff --git a/tools/test_iq_pack.py b/tools/test_iq_pack.py index 72339813..1c83db47 100644 --- a/tools/test_iq_pack.py +++ b/tools/test_iq_pack.py @@ -126,6 +126,46 @@ class CompatibilityTests(unittest.TestCase): "per_layer_token_embd.weight", "blk.0.attn_qkv.weight"]: self.assertFalse(iq_pack.needs_bf16(name, "IQ3_XXS")) + def test_experts_bin_is_kept_only_with_this_ggufs_blobs(self): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) + out = root / "pack" + (out / "tokenizer").mkdir(parents=True) + for name in ["vocab.json", "chat_template.jinja"]: + (out / "tokenizer" / name).touch() + + def model(name, scale): + path = root / name + write_gguf(path, [("blk.%d.hc_attn_down.weight" % l, np.ones((2, 32), np.float32), Q.BF16) + for l in range(3)] + + [("blk.%d.ffn_gate_inp.weight" % l, np.ones((4, 32), np.float32), Q.BF16) + for l in range(3)] + + [("blk.%d.ffn_%s_exps.weight" % (l, r), + scale * np.arange(4 * 2 * 32, dtype=np.float32).reshape(4, 2, 32) / 256, Q.Q8_0) + for l in range(3) for r in ("gate", "up", "down")]) + return path + + def pack(path): + log = io.StringIO() + argv = ["iq_pack.py", "--gguf", str(path), "--out", str(out), "--experts-bin"] + with patch.object(sys, "argv", argv), contextlib.redirect_stdout(log): + self.assertEqual(iq_pack.main(), 0) + return log.getvalue() + + first = model("a.gguf", 1) + pack(first) + written = (out / "experts.bin").read_bytes() + self.assertIn("not rewritten", pack(first)) + self.assertEqual((out / "experts.bin").read_bytes(), written) + # the same geometry with other weights under the same file name: the size and the sidecar (shard names + # and sizes, native_experts.txt) match, the contents do not + second = model("a.gguf", -1) + self.assertIn("not this GGUF's expert blobs", pack(second)) + rewritten = (out / "experts.bin").read_bytes() + self.assertEqual(len(rewritten), len(written)) + self.assertNotEqual(rewritten, written) + self.assertIn("not rewritten", pack(second)) + def test_snapshot_symlinks_keep_split_discovery(self): with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: root = Path(tmp)