"""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 gguf_lib import iq_pack # needs numpy + gguf_reader only: import it unguarded try: _gguf = gguf_lib() # tools/strata_gguf.py (STRATA_GGUF_PY selects llama.cpp's gguf-py; it exits when that is not a gguf-py folder) GGUFWriter, Q, quants = _gguf.GGUFWriter, _gguf.GGMLQuantizationType, _gguf.quants except SystemExit: GGUF_PY = None else: GGUF_PY = "found" def require_gguf_py(test): """setUpClass for the classes that build GGUF fixtures: skip (not fail) on a checkout without llama.cpp.""" @classmethod def setUpClass(cls): if GGUF_PY is None: raise unittest.SkipTest("STRATA_GGUF_PY does not name a gguf-py folder") return setUpClass def write_gguf(path, tensors, split=None, arch=True): """`split` = (no, count, tensors): llama.cpp's gguf-split keys (0-based split.no).""" writer = GGUFWriter(path, "qwen4exp") if not arch: # a later shard of a split: no model metadata writer.remove_key("general.architecture") 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): setUpClass = require_gguf_py(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.assertFalse(iq_pack.needs_bf16("blk.1.ple_key.weight", "IQ3_XXS")) self.assertFalse(iq_pack.needs_bf16("blk.1.ple_key.weight", "IQ4_XS")) self.assertTrue(iq_pack.needs_bf16("blk.1.ple_key.weight", "Q6_K")) 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_iq_ple_keys_are_indexed_without_conversion(self): for kind, block_bytes in [(Q.IQ3_XXS, 98), (Q.IQ4_XS, 136)]: with self.subTest(kind=kind), tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: root = Path(tmp) source = root / "model.gguf" writer = GGUFWriter(source, "qwen4exp") writer.add_tensor("blk.1.ple_key.weight", np.zeros((2, block_bytes), dtype=np.uint8), raw_dtype=kind) writer.write_header_to_file() writer.write_kv_data_to_file() writer.write_tensors_to_file() writer.close() before = source.read_bytes() with contextlib.redirect_stdout(io.StringIO()): self.assertEqual(iq_pack.index_standalone(source, root, iq_pack.Model(source)), 0) _, rows = iq_pack.read_index(root / "index.txt") row = rows["blk.1.ple_key.weight"] self.assertEqual(row[2], "0") self.assertEqual((root / "dense.bin").read_bytes(), b"") self.assertEqual(json.loads((root / "conversions.json").read_text())["tensors"], []) self.assertEqual(source.read_bytes(), before) 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) 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.""" setUpClass = require_gguf_py(unittest.TestCase) 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", " hadamard.txt; anything the engine cannot rotate is refused.""" N_EMBD, N_FF = 256, 128 def meta(self, **kw): names = ["blk.%d.ffn_%s_exps.weight" % (l, r) for l in range(2) for r in ("gate", "up", "down")] m = {"prism.hadamard.version": 1, "prism.hadamard.block_size": 128, "prism.hadamard.transform": "normalized-sylvester-walsh-hadamard", "prism.hadamard.axis": "input-last-dimension", "prism.hadamard.sign_mode": "explicit", "prism.hadamard.weight_names": names, "prism.hadamard.sign_widths": [self.N_FF, self.N_EMBD], "prism.hadamard.sign_values": [1, -1] * (self.N_FF // 2) + [-1, 1] * (self.N_EMBD // 2)} m.update(kw) return m def layout(self, gu=145, d=146): return [(l, gu, d, 0, 0, None) for l in range(2)] def test_no_metadata(self): self.assertIsNone(iq_pack.hadamard_spec({}, self.layout(), self.N_EMBD, self.N_FF)) def test_explicit_signs_written(self): text = iq_pack.hadamard_spec(self.meta(), self.layout(), self.N_EMBD, self.N_FF) lines = text.splitlines() self.assertTrue(lines[0].startswith("# strata hadamard v1")) self.assertEqual(lines[1], "block 128") self.assertEqual(lines[2].split()[:4], ["signs", str(self.N_FF), "1", "-1"]) self.assertEqual(len(lines[3].split()), 2 + self.N_EMBD) self.assertEqual(lines[4:], ["layer 0 1 1 1", "layer 1 1 1 1"]) def test_refusals(self): bad = { "transform": self.meta(**{"prism.hadamard.transform": "dct"}), "dense weight": self.meta(**{"prism.hadamard.weight_names": ["blk.0.attn_q.weight"]}), "inverse": self.meta(**{"prism.hadamard.inverse_weight_names": ["token_embd.weight"]}), "gate only": self.meta(**{"prism.hadamard.weight_names": ["blk.0.ffn_gate_exps.weight"]}), "missing width": self.meta(**{"prism.hadamard.sign_widths": [self.N_EMBD], "prism.hadamard.sign_values": [1] * self.N_EMBD}), "bad sign": self.meta(**{"prism.hadamard.sign_values": [2] * (self.N_FF + self.N_EMBD)}), "block": self.meta(**{"prism.hadamard.block_size": 96}), } for what, m in bad.items(): with self.subTest(what): got = iq_pack.hadamard_spec(m, self.layout(), self.N_EMBD, self.N_FF) self.assertIsInstance(got, str) self.assertFalse(got.startswith("# strata hadamard")) got = iq_pack.hadamard_spec(self.meta(), self.layout(gu=42), self.N_EMBD, self.N_FF) self.assertIn("Q2_0", got) class V31HeaderOnlyLayoutTests(unittest.TestCase): """Round 0214: the pack's expert table (iq_pack.expert_layout) read from the REAL tensor directories of Unsloth's v3.1 sets (tests/fixtures/unsloth_v31, header-only: no weights), so the gate == up rule and the Q5_0 downs are checked without a download.""" @staticmethod def layout(set_name): import unsloth_v31_fixture as FX import gguf_reader as G class Map: size = 1 << 62 with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as t: m = iq_pack.Model.__new__(iq_pack.Model) m.where = {} first = None for s in FX.load()["sets"][set_name]["shards"]: if not s["header"]: continue p = FX.materialize(s, Path(t) / s["name"]) g = G.GGUFFile(p) first = first or p for ti in g.tensors: m.where[ti.name] = (g, ti, Map, p) return iq_pack.expert_layout(m, first) def test_gate_and_up_must_agree_ud_iq1_s_is_refused(self): self.assertEqual(self.layout("UD-IQ1_S"), "layer 18: gate and up differ in type") def test_q5_0_downs_are_packed_with_their_type_id(self): for set_name, n_q5 in (("UD-IQ4_XS", 33), ("UD-Q3_K_XL", 20), ("UD-IQ2_XS", 1), ("UD-Q2_K_XL", 1), ("UD-IQ3_XXS", 0), ("UD-IQ1_M", 0)): with self.subTest(set=set_name): layout, text, n_expert, total = self.layout(set_name) self.assertEqual(n_expert, 512) self.assertEqual(len(layout), 48) self.assertEqual(sum(1 for row in layout if row[5][2].type_name == "Q5_0"), n_q5) rows = [ln.split() for ln in text.splitlines()[1:]] self.assertEqual(sum(1 for r in rows if r[2] == "6"), n_q5) # d_type 6 = Q5_0 self.assertEqual(total, sum(r[4] * 512 for r in layout)) def test_a_layer_across_shards_makes_a_v4_table(self): layout, text, _n, _t = self.layout("UD-IQ3_XXS") self.assertTrue(text.startswith("# strata native experts v4:")) self.assertEqual(sum(1 for ln in text.splitlines()[1:] if "," in ln.split()[-1]), 1) class NativeExpertsV5Tests(unittest.TestCase): """The v5 mark (Hadamard-folded experts) rewrites only the tables the packer writes, v3 and v4.""" setUpClass = require_gguf_py(unittest.TestCase) # test_packer_refuses_before_writing builds GGUF fixtures ROWS = "0 145 146 0 100 1 2 3\n1 145 146 100 100 4 5 6\n" def table(self, version, tail="(n_expert 2, total 200)"): return "# strata native experts v%s: layer gu_type d_type offset ... %s\n" % (version, tail) + self.ROWS def test_v3_and_v4_become_v5(self): for v in ("3", "4"): with self.subTest(v): got = iq_pack.native_experts_v5(self.table(v)) head, rest = got.split("\n", 1) self.assertTrue(head.startswith("# strata native experts v5: layer gu_type")) self.assertTrue(head.endswith("(n_expert 2, total 200) - v5: Hadamard-folded experts, see hadamard.txt")) self.assertEqual(rest, self.ROWS) def test_other_versions_are_refused_by_name(self): for v in ("2", "5", "6", "10"): with self.subTest(v): got = iq_pack.native_experts_v5(self.table(v)) self.assertFalse(got.startswith("# strata native experts")) self.assertIn("v%s" % v, got) self.assertIn("v3 and v4", got) got = iq_pack.native_experts_v5("# something else\n" + self.ROWS) self.assertIn("without a version header", got) def test_packer_refuses_before_writing(self): real = iq_pack.expert_layout def v6_layout(model, src): layout, text, n_expert, offset = real(model, src) return layout, text.replace("native experts v3:", "native experts v6:", 1), n_expert, offset with tempfile.TemporaryDirectory() as d: root = Path(d) paths = split_model(root, split_layer=False) out = root / "pack" with patch.object(iq_pack, "expert_layout", v6_layout), \ patch.object(iq_pack, "hadamard_spec", return_value="# strata hadamard v1\nblock 32\n"): rc, log = run_pack(paths[0], out) self.assertEqual(rc, 1) self.assertIn("native_experts.txt v6", log) self.assertIn("only v3 and v4", log) self.assertFalse((out / "native_experts.txt").exists()) self.assertFalse((out / "hadamard.txt").exists()) if __name__ == "__main__": unittest.main()