"""Focused pack compatibility tests; run .venv/bin/python -m unittest discover -s tools -p test_iq_pack.py.""" import contextlib import hashlib import io import json from pathlib import Path import sys import tempfile import unittest from unittest.mock import patch import numpy as np sys.path.insert(0, str(Path(__file__).resolve().parent)) # runnable from the repo root too from _paths import add_gguf_py add_gguf_py() from gguf import GGUFWriter, GGMLQuantizationType as Q, quants import iq_pack def write_gguf(path, tensors, split=None, arch=True, kv=None, architecture="qwen4exp"): """`split` = (no, count, tensors): llama.cpp's gguf-split keys (0-based split.no); `kv` = extra u32 keys; `architecture` = the general.architecture string (qwen4exp, or qwen35moe for the Qwen3.6 fixtures).""" writer = GGUFWriter(path, architecture) if not arch: # a later shard of a split: no model metadata writer.kv_data[0].pop("general.architecture", None) for key, value in (kv or {}).items(): writer.add_uint32(key, value) if split is not None: writer.add_uint16("split.no", split[0]) writer.add_uint16("split.count", split[1]) writer.add_int32("split.tensors.count", split[2]) for name, values, kind in tensors: writer.add_tensor(name, quants.quantize(values, kind), raw_dtype=kind) writer.write_header_to_file() writer.write_kv_data_to_file() writer.write_tensors_to_file() writer.close() class CompatibilityTests(unittest.TestCase): def test_bf16_halfway_rounds_to_even(self): values = np.array([0x3F808000, 0x3F818000, 0xBF808000, 0xBF818000], dtype=np.uint32) got = np.frombuffer(iq_pack.bf16_bytes(values.view(np.uint8), "F32"), dtype=np.uint16) np.testing.assert_array_equal(got, [0x3F80, 0x3F82, 0xBF80, 0xBF82]) def test_nonfinite_conversion_refused(self): with self.assertRaisesRegex(ValueError, "non-finite"): iq_pack.bf16_bytes(np.array([np.nan], dtype=np.float32).view(np.uint8), "F32") def test_projection_conversion_and_native_bytes(self): with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: root = Path(tmp) source = root / "model.gguf" values = np.linspace(-1, 1, 256, dtype=np.float32).reshape(2, 128) router = np.full((2, 128), 0.10001, dtype=np.float32) names = ["blk.0.hc_attn_down.weight", "output_hc_up.weight", "blk.0.ssm_alpha.weight", "blk.3.indexer.q_proj.weight", "blk.1.ple_value.weight"] write_gguf(source, [(n, values, Q.Q8_0) for n in names] + [ ("blk.1.ple_key.weight", values, Q.Q8_0), ("blk.0.ffn_gate_inp.weight", router, Q.F32), ("blk.0.attn_qkv.weight", values, Q.Q8_0), ("per_layer_token_embd.weight", values, Q.Q8_0), ]) before = source.read_bytes() model = iq_pack.Model(source) with contextlib.redirect_stdout(io.StringIO()): self.assertEqual(iq_pack.index_standalone(source, root, model, True), 0) _, rows = iq_pack.read_index(root / "index.txt") dense = (root / "dense.bin").read_bytes() # A scalar oracle independent of the BF16 encoder: choose the nearest BF16 value, # using the even representation at exact ties. decoded = quants.dequantize(quants.quantize(values, Q.Q8_0), Q.Q8_0).ravel() def rounded(x): bits = int(np.float32(x).view(np.uint32)) return (bits >> 16) + ((bits & 65535) > 32768 or ((bits & 65535) == 32768 and (bits >> 16) & 1)) expected = np.array([rounded(x) for x in decoded], dtype=np.uint16) for name in names: row = rows[name] self.assertEqual(row[2], "4") offset, size = int(row[3]), int(row[4]) np.testing.assert_array_equal(np.frombuffer(dense[offset:offset + size], dtype=np.uint16), expected) for name in ["blk.0.attn_qkv.weight", "blk.1.ple_key.weight"]: # a Q8_0 PLE key stays native native = rows[name] self.assertEqual(native[2], "0") self.assertEqual(native[4], "0") self.assertEqual(native[9], "8") self.assertNotIn("per_layer_token_embd.weight", rows) self.assertEqual(source.read_bytes(), before) self.assertEqual(len(json.loads((root / "compat-bf16.json").read_text())["tensors"]), 6) conv = json.loads((root / "conversions.json").read_text()) self.assertEqual(sorted(r["name"] for r in conv["tensors"]), sorted(names + ["blk.0.ffn_gate_inp.weight"])) def test_default_still_refuses_inexact_f32_router(self): with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: root = Path(tmp) source = root / "model.gguf" write_gguf(source, [("blk.0.ffn_gate_inp.weight", np.full((2, 32), 0.10001, np.float32), Q.F32)]) with contextlib.redirect_stdout(io.StringIO()): self.assertEqual(iq_pack.index_standalone(source, root, iq_pack.Model(source)), 1) def test_existing_bf16_pack_remains_byte_identical(self): with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: root = Path(tmp) source = root / "model.gguf" values = np.linspace(-2, 2, 256, dtype=np.float32).reshape(2, 128) write_gguf(source, [("blk.0.hc_attn_down.weight", values, Q.BF16)]) with contextlib.redirect_stdout(io.StringIO()): self.assertEqual(iq_pack.index_standalone(source, root, iq_pack.Model(source)), 0) self.assertEqual((root / "dense.bin").read_bytes(), quants.quantize(values, Q.BF16).tobytes()) def test_quantized_control_weights_need_explicit_conversion(self): with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: root = Path(tmp) source = root / "model.gguf" write_gguf(source, [("blk.0.hc_attn_down.weight", np.ones((2, 32), np.float32), Q.Q8_0)]) (root / "dense.bin").write_bytes(b"previous pack") with contextlib.redirect_stdout(io.StringIO()): self.assertEqual(iq_pack.index_standalone(source, root, iq_pack.Model(source)), 1) self.assertEqual((root / "dense.bin").read_bytes(), b"previous pack") def test_q2_ple_and_large_tensors_stay_native(self): self.assertFalse(iq_pack.needs_bf16("blk.1.ple_key.weight", "Q2_0")) self.assertFalse(iq_pack.needs_bf16("blk.1.ple_key.weight", "Q8_0")) self.assertTrue(iq_pack.needs_bf16("blk.1.ple_key.weight", "IQ3_XXS")) for name in ["blk.0.ffn_gate_exps.weight", "token_embd.weight", "output.weight", "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_layout_only_writes_the_table_and_the_census(self): """--layout-only (the Qwen3.6 port's step 2): native_experts.txt alone, the census printed, nothing else.""" with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: root = Path(tmp) out = root / "pack" path = root / "m.gguf" write_gguf(path, [("blk.%d.ffn_gate_inp.weight" % l, np.ones((4, 32), np.float32), Q.F32) for l in range(2)] + [("blk.%d.ffn_%s_exps.weight" % (l, r), np.arange(4 * 2 * 32, dtype=np.float32).reshape(4, 2, 32) / 256, Q.Q8_0) for l in range(2) for r in ("gate", "up", "down")]) log = io.StringIO() with patch.object(sys, "argv", ["iq_pack.py", "--gguf", str(path), "--out", str(out), "--layout-only"]), \ contextlib.redirect_stdout(log): self.assertEqual(iq_pack.main(), 0) self.assertEqual(sorted(p.name for p in out.iterdir()), ["native_experts.txt"]) text = (out / "native_experts.txt").read_text() rows = [line.split() for line in text.splitlines() if line and not line.startswith("#")] self.assertEqual([r[0] for r in rows], ["0", "1"]) blob = 3 * 2 * 32 * 34 // 32 # gate | up | down, Q8_0 rows of 32 values = 34 bytes self.assertEqual([int(r[4]) for r in rows], [blob, blob]) self.assertIn("(n_expert 4, total %d;" % (2 * 4 * blob), text.splitlines()[0]) self.assertIn("2 layers x 4 experts", log.getvalue()) self.assertIn("gate/up Q8_0 down Q8_0 blob %9d B: layers [0, 1]" % blob, log.getvalue()) self.assertIn("wrote %s" % (out / "native_experts.txt"), log.getvalue()) def test_nextn_block_is_left_out_of_the_layout(self): """nextn_predict_layers 1 (the -MTP files): the last block's experts belong to the drafter's pack.""" with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: root = Path(tmp) out = root / "pack" path = root / "mtp.gguf" write_gguf(path, [("blk.%d.ffn_gate_inp.weight" % l, np.ones((4, 32), np.float32), Q.F32) for l in range(3)] + [("blk.%d.ffn_%s_exps.weight" % (l, r), 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")], kv={"qwen4exp.nextn_predict_layers": 1}) log = io.StringIO() with patch.object(sys, "argv", ["iq_pack.py", "--gguf", str(path), "--out", str(out), "--layout-only"]), \ contextlib.redirect_stdout(log): self.assertEqual(iq_pack.main(), 0) rows = [line.split() for line in (out / "native_experts.txt").read_text().splitlines() if line and not line.startswith("#")] self.assertEqual([r[0] for r in rows], ["0", "1"]) self.assertIn("1 draft (nextn) block(s) at blk.2 and up are left to the MTP pack; 2 trunk layers", log.getvalue()) self.assertIn("2 layers x 4 experts", log.getvalue()) def test_fused_gate_up_experts_are_refused_by_name(self): """llama.cpp's fused ffn_gate_up_exps form: refused before anything is written.""" with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: root = Path(tmp) out = root / "pack" path = root / "fused.gguf" write_gguf(path, [("blk.0.ffn_gate_inp.weight", np.ones((4, 32), np.float32), Q.F32), ("blk.0.ffn_gate_up_exps.weight", np.arange(4 * 4 * 32, dtype=np.float32).reshape(4, 4, 32) / 256, Q.Q8_0), ("blk.0.ffn_down_exps.weight", np.arange(4 * 2 * 32, dtype=np.float32).reshape(4, 2, 32) / 256, Q.Q8_0)]) log = io.StringIO() with patch.object(sys, "argv", ["iq_pack.py", "--gguf", str(path), "--out", str(out), "--layout-only"]), \ contextlib.redirect_stdout(log): self.assertEqual(iq_pack.main(), 1) self.assertIn("blk.0.ffn_gate_up_exps.weight: the experts are fused", log.getvalue()) self.assertFalse((out / "native_experts.txt").exists()) def test_snapshot_symlinks_keep_split_discovery(self): with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: root = Path(tmp) snap = root / "snapshot" snap.mkdir() first = snap / "model-00001-of-00002.gguf" second = snap / "model-00002-of-00002.gguf" write_gguf(root / "blob1", [ ("blk.0.hc_attn_down.weight", np.ones((2, 32), np.float32), Q.Q8_0), ("blk.0.ffn_gate_inp.weight", np.ones((512, 32), np.float32), Q.BF16), ], split=(0, 2, 5)) write_gguf(root / "blob2", [(f"blk.0.ffn_{r}_exps.weight", np.ones((512, 2, 32), np.float32), Q.Q8_0) for r in ("gate", "up", "down")], split=(1, 2, 5), arch=False) try: first.symlink_to(root / "blob1") except OSError: # Windows without Developer Mode or admin rights self.skipTest("symlinks are not available here") with self.assertRaisesRegex(FileNotFoundError, "missing model shards"): iq_pack.Model(first) second.symlink_to(root / "blob2") out = root / "pack" (out / "tokenizer").mkdir(parents=True) for name in ["vocab.json", "chat_template.jinja"]: (out / "tokenizer" / name).touch() with patch.object(sys, "argv", ["iq_pack.py", "--gguf", str(first), "--out", str(out), "--compat-bf16"]): with contextlib.redirect_stdout(io.StringIO()): self.assertEqual(iq_pack.main(), 0) expert_index = (out / "native_experts.txt").read_text() self.assertIn(second.name, expert_index) self.assertIn("n_expert 512,", expert_index) (root / "blob2").write_bytes((root / "blob2").read_bytes()[:-64]) with self.assertRaisesRegex(ValueError, "truncated tensor"): iq_pack.Model(first) def bits(u32): return np.array(u32, dtype=np.uint32).view(np.float32) def pack_one(root, tensors, *flags): """A one-file model of `tensors` packed into `root` (index only): (rc, printed, rows, dense, conversions).""" source = root / "model.gguf" write_gguf(source, tensors) buf = io.StringIO() with contextlib.redirect_stdout(buf): rc = iq_pack.index_standalone(source, root, iq_pack.Model(source), *flags) if rc: return rc, buf.getvalue(), None, None, None _, rows = iq_pack.read_index(root / "index.txt") conv = json.loads((root / "conversions.json").read_text()) return rc, buf.getvalue(), rows, (root / "dense.bin").read_bytes(), conv def stored(rows, dense, name, dtype): row = rows[name] return np.frombuffer(dense[int(row[3]):int(row[3]) + int(row[4])], dtype=dtype) class ConversionTests(unittest.TestCase): """CS2: FORM decides the engine's form; exact F32->BF16 by default, rounding only with --compat-bf16, the PLE conv F32 -> F16 by the loader (index kind 3), non-finite values refused, every conversion in conversions.json.""" def test_exact_f32_to_bf16_by_default(self): with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: x = bits(np.arange(64, dtype=np.uint32).reshape(2, 32) << 16 | 0x3F000000) # BF16 values held as F32 rc, log, rows, dense, conv = pack_one(Path(tmp), [("blk.0.hc_attn_inject.weight", x, Q.F32), ("blk.0.ssm_beta.weight", x, Q.F32), ("blk.0.ssm_norm.weight", x, Q.F32)]) self.assertEqual(rc, 0, log) for name in ["blk.0.hc_attn_inject.weight", "blk.0.ssm_beta.weight"]: self.assertEqual(rows[name][2], "4") np.testing.assert_array_equal(stored(rows, dense, name, "> 16).ravel()) self.assertEqual(rows["blk.0.ssm_norm.weight"][2], "2") # F32 form: as stored recs = {r["name"]: r for r in conv["tensors"]} self.assertEqual(set(recs), {"blk.0.hc_attn_inject.weight", "blk.0.ssm_beta.weight"}) r = recs["blk.0.ssm_beta.weight"] self.assertEqual((r["src_type"], r["dst_type"], r["exact"], r["max_abs_err"], r["shard"]), ("F32", "BF16", True, 0.0, "model.gguf")) self.assertEqual(r["source_sha256"], hashlib.sha256(x.tobytes()).hexdigest()) self.assertEqual(conv["schema"], 1) self.assertEqual(conv["source_shards"], [{"name": "model.gguf", "size": (Path(tmp) / "model.gguf").stat().st_size}]) def test_inexact_f32_rounds_only_with_compat(self): with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: x = np.linspace(-1, 1, 64, dtype=np.float32).reshape(2, 32) + np.float32(1e-4) rc, log, *_ = pack_one(Path(tmp), [("blk.0.hc_ffn_inject.weight", x, Q.F32)]) self.assertEqual(rc, 1) self.assertIn("not BF16", log) rc, log, rows, dense, conv = pack_one(Path(tmp), [("blk.0.hc_ffn_inject.weight", x, Q.F32)], True) self.assertEqual(rc, 0, log) got = stored(rows, dense, "blk.0.hc_ffn_inject.weight", "