okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-2b (cc8c29f31) into f-own-int: our own GGUF reader/writer and quantizers (gguf-py out of the pack tools)0f1e5e4cb

main
43.0 KiB804 linesraw
1"""Focused pack compatibility tests; run .venv/bin/python -m unittest discover -s tools -p test_iq_pack.py."""
2import contextlib
3import hashlib
4import io
5import json
6from pathlib import Path
7import sys
8import tempfile
9import unittest
10from unittest.mock import patch
11
12import numpy as np
13
14sys.path.insert(0, str(Path(__file__).resolve().parent))   # runnable from the repo root too
15
16from _paths import gguf_lib
17import iq_pack                         # needs numpy + gguf_reader only: import it unguarded
18
19try:
20    _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)
21    GGUFWriter, Q, quants = _gguf.GGUFWriter, _gguf.GGMLQuantizationType, _gguf.quants
22except SystemExit:
23    GGUF_PY = None
24else:
25    GGUF_PY = "found"
26
27
28def require_gguf_py(test):
29    """setUpClass for the classes that build GGUF fixtures: skip (not fail) on a checkout without llama.cpp."""
30    @classmethod
31    def setUpClass(cls):
32        if GGUF_PY is None:
33            raise unittest.SkipTest("STRATA_GGUF_PY does not name a gguf-py folder")
34    return setUpClass
35
36
37def write_gguf(path, tensors, split=None, arch=True):
38    """`split` = (no, count, tensors): llama.cpp's gguf-split keys (0-based split.no)."""
39    writer = GGUFWriter(path, "qwen4exp")
40    if not arch:                                   # a later shard of a split: no model metadata
41        writer.remove_key("general.architecture")
42    if split is not None:
43        writer.add_uint16("split.no", split[0])
44        writer.add_uint16("split.count", split[1])
45        writer.add_int32("split.tensors.count", split[2])
46    for name, values, kind in tensors:
47        writer.add_tensor(name, quants.quantize(values, kind), raw_dtype=kind)
48    writer.write_header_to_file()
49    writer.write_kv_data_to_file()
50    writer.write_tensors_to_file()
51    writer.close()
52
53
54class CompatibilityTests(unittest.TestCase):
55    setUpClass = require_gguf_py(unittest.TestCase)
56    def test_bf16_halfway_rounds_to_even(self):
57        values = np.array([0x3F808000, 0x3F818000, 0xBF808000, 0xBF818000], dtype=np.uint32)
58        got = np.frombuffer(iq_pack.bf16_bytes(values.view(np.uint8), "F32"), dtype=np.uint16)
59        np.testing.assert_array_equal(got, [0x3F80, 0x3F82, 0xBF80, 0xBF82])
60
61    def test_nonfinite_conversion_refused(self):
62        with self.assertRaisesRegex(ValueError, "non-finite"):
63            iq_pack.bf16_bytes(np.array([np.nan], dtype=np.float32).view(np.uint8), "F32")
64
65    def test_projection_conversion_and_native_bytes(self):
66        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
67            root = Path(tmp)
68            source = root / "model.gguf"
69            values = np.linspace(-1, 1, 256, dtype=np.float32).reshape(2, 128)
70            router = np.full((2, 128), 0.10001, dtype=np.float32)
71            names = ["blk.0.hc_attn_down.weight", "output_hc_up.weight",
72                     "blk.0.ssm_alpha.weight", "blk.3.indexer.q_proj.weight", "blk.1.ple_value.weight"]
73            write_gguf(source, [(n, values, Q.Q8_0) for n in names] + [
74                ("blk.1.ple_key.weight", values, Q.Q8_0),
75                ("blk.0.ffn_gate_inp.weight", router, Q.F32),
76                ("blk.0.attn_qkv.weight", values, Q.Q8_0),
77                ("per_layer_token_embd.weight", values, Q.Q8_0),
78            ])
79            before = source.read_bytes()
80            model = iq_pack.Model(source)
81            with contextlib.redirect_stdout(io.StringIO()):
82                self.assertEqual(iq_pack.index_standalone(source, root, model, True), 0)
83            _, rows = iq_pack.read_index(root / "index.txt")
84            dense = (root / "dense.bin").read_bytes()
85            # A scalar oracle independent of the BF16 encoder: choose the nearest BF16 value,
86            # using the even representation at exact ties.
87            decoded = quants.dequantize(quants.quantize(values, Q.Q8_0), Q.Q8_0).ravel()
88            def rounded(x):
89                bits = int(np.float32(x).view(np.uint32))
90                return (bits >> 16) + ((bits & 65535) > 32768 or
91                                      ((bits & 65535) == 32768 and (bits >> 16) & 1))
92            expected = np.array([rounded(x) for x in decoded], dtype=np.uint16)
93            for name in names:
94                row = rows[name]
95                self.assertEqual(row[2], "4")
96                offset, size = int(row[3]), int(row[4])
97                np.testing.assert_array_equal(np.frombuffer(dense[offset:offset + size], dtype=np.uint16), expected)
98            for name in ["blk.0.attn_qkv.weight", "blk.1.ple_key.weight"]:   # a Q8_0 PLE key stays native
99                native = rows[name]
100                self.assertEqual(native[2], "0")
101                self.assertEqual(native[4], "0")
102                self.assertEqual(native[9], "8")
103            self.assertNotIn("per_layer_token_embd.weight", rows)
104            self.assertEqual(source.read_bytes(), before)
105            self.assertEqual(len(json.loads((root / "compat-bf16.json").read_text())["tensors"]), 6)
106            conv = json.loads((root / "conversions.json").read_text())
107            self.assertEqual(sorted(r["name"] for r in conv["tensors"]), sorted(names + ["blk.0.ffn_gate_inp.weight"]))
108
109    def test_default_still_refuses_inexact_f32_router(self):
110        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
111            root = Path(tmp)
112            source = root / "model.gguf"
113            write_gguf(source, [("blk.0.ffn_gate_inp.weight", np.full((2, 32), 0.10001, np.float32), Q.F32)])
114            with contextlib.redirect_stdout(io.StringIO()):
115                self.assertEqual(iq_pack.index_standalone(source, root, iq_pack.Model(source)), 1)
116
117    def test_existing_bf16_pack_remains_byte_identical(self):
118        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
119            root = Path(tmp)
120            source = root / "model.gguf"
121            values = np.linspace(-2, 2, 256, dtype=np.float32).reshape(2, 128)
122            write_gguf(source, [("blk.0.hc_attn_down.weight", values, Q.BF16)])
123            with contextlib.redirect_stdout(io.StringIO()):
124                self.assertEqual(iq_pack.index_standalone(source, root, iq_pack.Model(source)), 0)
125            self.assertEqual((root / "dense.bin").read_bytes(), quants.quantize(values, Q.BF16).tobytes())
126
127    def test_quantized_control_weights_need_explicit_conversion(self):
128        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
129            root = Path(tmp)
130            source = root / "model.gguf"
131            write_gguf(source, [("blk.0.hc_attn_down.weight", np.ones((2, 32), np.float32), Q.Q8_0)])
132            (root / "dense.bin").write_bytes(b"previous pack")
133            with contextlib.redirect_stdout(io.StringIO()):
134                self.assertEqual(iq_pack.index_standalone(source, root, iq_pack.Model(source)), 1)
135            self.assertEqual((root / "dense.bin").read_bytes(), b"previous pack")
136
137    def test_q2_ple_and_large_tensors_stay_native(self):
138        self.assertFalse(iq_pack.needs_bf16("blk.1.ple_key.weight", "Q2_0"))
139        self.assertFalse(iq_pack.needs_bf16("blk.1.ple_key.weight", "Q8_0"))
140        self.assertFalse(iq_pack.needs_bf16("blk.1.ple_key.weight", "IQ3_XXS"))
141        self.assertFalse(iq_pack.needs_bf16("blk.1.ple_key.weight", "IQ4_XS"))
142        self.assertTrue(iq_pack.needs_bf16("blk.1.ple_key.weight", "Q6_K"))
143        for name in ["blk.0.ffn_gate_exps.weight", "token_embd.weight", "output.weight",
144                     "per_layer_token_embd.weight", "blk.0.attn_qkv.weight"]:
145            self.assertFalse(iq_pack.needs_bf16(name, "IQ3_XXS"))
146
147    def test_iq_ple_keys_are_indexed_without_conversion(self):
148        for kind, block_bytes in [(Q.IQ3_XXS, 98), (Q.IQ4_XS, 136)]:
149            with self.subTest(kind=kind), tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
150                root = Path(tmp)
151                source = root / "model.gguf"
152                writer = GGUFWriter(source, "qwen4exp")
153                writer.add_tensor("blk.1.ple_key.weight", np.zeros((2, block_bytes), dtype=np.uint8),
154                                  raw_dtype=kind)
155                writer.write_header_to_file()
156                writer.write_kv_data_to_file()
157                writer.write_tensors_to_file()
158                writer.close()
159                before = source.read_bytes()
160                with contextlib.redirect_stdout(io.StringIO()):
161                    self.assertEqual(iq_pack.index_standalone(source, root, iq_pack.Model(source)), 0)
162                _, rows = iq_pack.read_index(root / "index.txt")
163                row = rows["blk.1.ple_key.weight"]
164                self.assertEqual(row[2], "0")
165                self.assertEqual((root / "dense.bin").read_bytes(), b"")
166                self.assertEqual(json.loads((root / "conversions.json").read_text())["tensors"], [])
167                self.assertEqual(source.read_bytes(), before)
168
169    def test_experts_bin_is_kept_only_with_this_ggufs_blobs(self):
170        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
171            root = Path(tmp)
172            out = root / "pack"
173            (out / "tokenizer").mkdir(parents=True)
174            for name in ["vocab.json", "chat_template.jinja"]:
175                (out / "tokenizer" / name).touch()
176
177            def model(name, scale):
178                path = root / name
179                write_gguf(path, [("blk.%d.hc_attn_down.weight" % l, np.ones((2, 32), np.float32), Q.BF16)
180                                  for l in range(3)] +
181                                 [("blk.%d.ffn_gate_inp.weight" % l, np.ones((4, 32), np.float32), Q.BF16)
182                                  for l in range(3)] +
183                                 [("blk.%d.ffn_%s_exps.weight" % (l, r),
184                                   scale * np.arange(4 * 2 * 32, dtype=np.float32).reshape(4, 2, 32) / 256, Q.Q8_0)
185                                  for l in range(3) for r in ("gate", "up", "down")])
186                return path
187
188            def pack(path):
189                log = io.StringIO()
190                argv = ["iq_pack.py", "--gguf", str(path), "--out", str(out), "--experts-bin"]
191                with patch.object(sys, "argv", argv), contextlib.redirect_stdout(log):
192                    self.assertEqual(iq_pack.main(), 0)
193                return log.getvalue()
194
195            first = model("a.gguf", 1)
196            pack(first)
197            written = (out / "experts.bin").read_bytes()
198            self.assertIn("not rewritten", pack(first))
199            self.assertEqual((out / "experts.bin").read_bytes(), written)
200            # the same geometry with other weights under the same file name: the size and the sidecar (shard names
201            # and sizes, native_experts.txt) match, the contents do not
202            second = model("a.gguf", -1)
203            self.assertIn("not this GGUF's expert blobs", pack(second))
204            rewritten = (out / "experts.bin").read_bytes()
205            self.assertEqual(len(rewritten), len(written))
206            self.assertNotEqual(rewritten, written)
207            self.assertIn("not rewritten", pack(second))
208
209    def test_snapshot_symlinks_keep_split_discovery(self):
210        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
211            root = Path(tmp)
212            snap = root / "snapshot"
213            snap.mkdir()
214            first = snap / "model-00001-of-00002.gguf"
215            second = snap / "model-00002-of-00002.gguf"
216            write_gguf(root / "blob1", [
217                ("blk.0.hc_attn_down.weight", np.ones((2, 32), np.float32), Q.Q8_0),
218                ("blk.0.ffn_gate_inp.weight", np.ones((512, 32), np.float32), Q.BF16),
219            ], split=(0, 2, 5))
220            write_gguf(root / "blob2", [(f"blk.0.ffn_{r}_exps.weight", np.ones((512, 2, 32), np.float32), Q.Q8_0)
221                                       for r in ("gate", "up", "down")], split=(1, 2, 5), arch=False)
222            try:
223                first.symlink_to(root / "blob1")
224            except OSError:                              # Windows without Developer Mode or admin rights
225                self.skipTest("symlinks are not available here")
226            with self.assertRaisesRegex(FileNotFoundError, "missing model shards"):
227                iq_pack.Model(first)
228            second.symlink_to(root / "blob2")
229            out = root / "pack"
230            (out / "tokenizer").mkdir(parents=True)
231            for name in ["vocab.json", "chat_template.jinja"]:
232                (out / "tokenizer" / name).touch()
233            with patch.object(sys, "argv", ["iq_pack.py", "--gguf", str(first), "--out", str(out), "--compat-bf16"]):
234                with contextlib.redirect_stdout(io.StringIO()):
235                    self.assertEqual(iq_pack.main(), 0)
236            expert_index = (out / "native_experts.txt").read_text()
237            self.assertIn(second.name, expert_index)
238            self.assertIn("n_expert 512,", expert_index)
239            (root / "blob2").write_bytes((root / "blob2").read_bytes()[:-64])
240            with self.assertRaisesRegex(ValueError, "truncated tensor"):
241                iq_pack.Model(first)
242
243
244
245def bits(u32):
246    return np.array(u32, dtype=np.uint32).view(np.float32)
247
248
249def pack_one(root, tensors, *flags):
250    """A one-file model of `tensors` packed into `root` (index only): (rc, printed, rows, dense, conversions)."""
251    source = root / "model.gguf"
252    write_gguf(source, tensors)
253    buf = io.StringIO()
254    with contextlib.redirect_stdout(buf):
255        rc = iq_pack.index_standalone(source, root, iq_pack.Model(source), *flags)
256    if rc:
257        return rc, buf.getvalue(), None, None, None
258    _, rows = iq_pack.read_index(root / "index.txt")
259    conv = json.loads((root / "conversions.json").read_text())
260    return rc, buf.getvalue(), rows, (root / "dense.bin").read_bytes(), conv
261
262
263def stored(rows, dense, name, dtype):
264    row = rows[name]
265    return np.frombuffer(dense[int(row[3]):int(row[3]) + int(row[4])], dtype=dtype)
266
267
268class ConversionTests(unittest.TestCase):
269    """CS2: FORM decides the engine's form; exact F32->BF16 by default, rounding only with --compat-bf16, the PLE
270    conv F32 -> F16 by the loader (index kind 3), non-finite values refused, every conversion in conversions.json."""
271
272    setUpClass = require_gguf_py(unittest.TestCase)
273
274    def test_exact_f32_to_bf16_by_default(self):
275        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
276            x = bits(np.arange(64, dtype=np.uint32).reshape(2, 32) << 16 | 0x3F000000)   # BF16 values held as F32
277            rc, log, rows, dense, conv = pack_one(Path(tmp), [("blk.0.hc_attn_inject.weight", x, Q.F32),
278                                                              ("blk.0.ssm_beta.weight", x, Q.F32),
279                                                              ("blk.0.ssm_norm.weight", x, Q.F32)])
280            self.assertEqual(rc, 0, log)
281            for name in ["blk.0.hc_attn_inject.weight", "blk.0.ssm_beta.weight"]:
282                self.assertEqual(rows[name][2], "4")
283                np.testing.assert_array_equal(stored(rows, dense, name, "<u2"), (x.view(np.uint32) >> 16).ravel())
284            self.assertEqual(rows["blk.0.ssm_norm.weight"][2], "2")               # F32 form: as stored
285            recs = {r["name"]: r for r in conv["tensors"]}
286            self.assertEqual(set(recs), {"blk.0.hc_attn_inject.weight", "blk.0.ssm_beta.weight"})
287            r = recs["blk.0.ssm_beta.weight"]
288            self.assertEqual((r["src_type"], r["dst_type"], r["exact"], r["max_abs_err"], r["shard"]),
289                             ("F32", "BF16", True, 0.0, "model.gguf"))
290            self.assertEqual(r["source_sha256"], hashlib.sha256(x.tobytes()).hexdigest())
291            self.assertEqual(conv["schema"], 1)
292            self.assertEqual(conv["source_shards"], [{"name": "model.gguf",
293                                                      "size": (Path(tmp) / "model.gguf").stat().st_size}])
294
295    def test_inexact_f32_rounds_only_with_compat(self):
296        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
297            x = np.linspace(-1, 1, 64, dtype=np.float32).reshape(2, 32) + np.float32(1e-4)
298            rc, log, *_ = pack_one(Path(tmp), [("blk.0.hc_ffn_inject.weight", x, Q.F32)])
299            self.assertEqual(rc, 1)
300            self.assertIn("not BF16", log)
301            rc, log, rows, dense, conv = pack_one(Path(tmp), [("blk.0.hc_ffn_inject.weight", x, Q.F32)], True)
302            self.assertEqual(rc, 0, log)
303            got = stored(rows, dense, "blk.0.hc_ffn_inject.weight", "<u2")
304            np.testing.assert_array_equal(got, np.frombuffer(iq_pack.bf16_bytes(x.view(np.uint8).ravel(), "F32"),
305                                                             dtype="<u2"))
306            r = conv["tensors"][0]
307            back = (got.astype(np.uint32) << 16).view(np.float32)
308            self.assertFalse(r["exact"])
309            self.assertAlmostEqual(r["max_abs_err"], float(np.max(np.abs(back - x.ravel()))))
310            self.assertLessEqual(r["max_abs_err"], 2.0 ** -8)
311            self.assertIn("--compat-bf16", r["method"])
312
313    def test_non_finite_is_refused(self):
314        for bad in (0x7FC00000, 0x7F800000, 0xFF800000):          # NaN and +-Inf: their low 16 bits are zero too
315            with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
316                x = bits([[0x3F800000] * 31 + [bad]] * 2)
317                (Path(tmp) / "dense.bin").write_bytes(b"previous pack")
318                for flags in ((), (True,)):
319                    rc, log, *_ = pack_one(Path(tmp), [("blk.0.ssm_alpha.weight", x, Q.F32)], *flags)
320                    self.assertEqual(rc, 1, (hex(bad), flags))
321                    self.assertIn("non-finite", log)
322                self.assertEqual((Path(tmp) / "dense.bin").read_bytes(), b"previous pack")
323                self.assertFalse((Path(tmp) / "dense.bin.tmp").exists())
324                rc, log, *_ = pack_one(Path(tmp), [("blk.1.ple_conv1d.weight", x, Q.F32)])
325                self.assertEqual(rc, 1)
326                self.assertIn("non-finite", log)
327
328    def test_ple_conv1d_f32_is_narrowed_by_the_loader(self):
329        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
330            conv1d = np.random.default_rng(3).normal(0, 0.0062, (32, 4)).astype(np.float32)
331            rc, log, rows, dense, conv = pack_one(Path(tmp), [("blk.1.ple_conv1d.weight", conv1d, Q.F32)])
332            self.assertEqual(rc, 0, log)                                          # no --compat-bf16 needed
333            row = rows["blk.1.ple_conv1d.weight"]
334            self.assertEqual((row[2], row[4], row[6]), ("3", str(conv1d.nbytes), str(conv1d.nbytes // 2)))
335            np.testing.assert_array_equal(stored(rows, dense, "blk.1.ple_conv1d.weight", "<f4"), conv1d.ravel())
336            r = conv["tensors"][0]
337            self.assertEqual((r["src_type"], r["dst_type"]), ("F32", "F16"))
338            self.assertIn("index kind 3", r["method"])
339            h = conv1d.astype(np.float16).astype(np.float32)
340            self.assertEqual(r["exact"], bool(np.array_equal(h, conv1d)))
341            self.assertAlmostEqual(r["max_abs_err"], float(np.max(np.abs(h - conv1d))))
342            self.assertIn("narrowed to F16 by the loader", log)
343            # an F16 conv (the GSQ-RCO files) stays as it is: index kind 5, nothing recorded
344            rc, log, rows, dense, conv = pack_one(Path(tmp), [("blk.1.ple_conv1d.weight", conv1d, Q.F16)])
345            self.assertEqual((rows["blk.1.ple_conv1d.weight"][2], conv["tensors"]), ("5", []))
346            # beyond F16's range: refused, not saturated
347            rc, log, *_ = pack_one(Path(tmp), [("blk.1.ple_conv1d.weight", conv1d * 1e7, Q.F32)])
348            self.assertEqual(rc, 1)
349            self.assertIn("beyond F16", log)
350
351    def test_q8_0_projections_need_compat_and_are_recorded(self):
352        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
353            v = np.random.default_rng(4).normal(0, 0.05, (4, 64)).astype(np.float32)
354            tensors = [("blk.1.ple_value.weight", v, Q.Q8_0), ("blk.2.hc_attn_up.weight", v, Q.Q8_0),
355                       ("blk.1.ple_key.weight", v, Q.Q8_0)]
356            rc, log, *_ = pack_one(Path(tmp), tensors)
357            self.assertEqual(rc, 1)
358            self.assertIn("use --compat-bf16", log)
359            self.assertNotIn("ple_key", log)                                      # the Q8_0 key stays native
360            rc, log, rows, dense, conv = pack_one(Path(tmp), tensors, True)
361            self.assertEqual(rc, 0, log)
362            self.assertEqual(rows["blk.1.ple_key.weight"][2], "0")
363            recs = {r["name"]: r for r in conv["tensors"]}
364            self.assertEqual(set(recs), {"blk.1.ple_value.weight", "blk.2.hc_attn_up.weight"})
365            deq = quants.dequantize(quants.quantize(v, Q.Q8_0), Q.Q8_0).ravel()
366            got = (stored(rows, dense, "blk.1.ple_value.weight", "<u2").astype(np.uint32) << 16).view(np.float32)
367            r = recs["blk.1.ple_value.weight"]
368            self.assertEqual((r["src_type"], r["dst_type"]), ("Q8_0", "BF16"))
369            self.assertAlmostEqual(r["max_abs_err"], float(np.max(np.abs(got - deq))))
370            self.assertEqual(conv["compat_bf16"], True)
371
372
373# ---- split artifacts: Unsloth's UD-Q4_K_XL in miniature.  Shard 1 holds the metadata and no tensor; shard 2 the
374# routers, layer 0 and layer 1's down; shard 3 layer 1's gate and up (a shard boundary inside a layer, like its
375# layer 11); shard 4 one float tensor.  4 experts of 32 x 32, Q8_0 and F32.
376N_EXPERT = 4
377
378
379def expert(seed, shape):
380    return np.random.default_rng(seed).standard_normal((N_EXPERT, *shape)).astype(np.float32)
381
382
383def split_model(root, name="model", split_layer=True, dup=False, split_no=None, gate1=None, seed=0):
384    """Writes the 4 shards; returns their paths."""
385    gate1 = Q.Q8_0 if gate1 is None else gate1      # not a default arg: the module imports without gguf-py
386    gu, dn = (32, 32), (32, 32)
387    router = [(f"blk.{l}.ffn_gate_inp.weight", np.full((N_EXPERT, 32), 0.5, np.float32), Q.F32) for l in (0, 1)]
388    l0 = [(f"blk.0.ffn_{r}_exps.weight", expert(seed + 10 + i, gu if r != "down" else dn), Q.Q8_0)
389          for i, r in enumerate(("gate", "up", "down"))]
390    l1_gu = [("blk.1.ffn_gate_exps.weight", expert(seed + 20, gu), gate1),
391             ("blk.1.ffn_up_exps.weight", expert(seed + 21, gu), Q.Q8_0)]
392    l1_d = [("blk.1.ffn_down_exps.weight", expert(seed + 22, dn), Q.F32)]
393    shards = [[], router + l0 + (l1_d if split_layer else []), l1_gu + ([] if split_layer else l1_d),
394              [("output_norm.weight", np.ones(32, np.float32), Q.F32)]]
395    if dup:
396        shards[3].append(l1_gu[1])
397    total = sum(len(s) for s in shards)
398    paths = []
399    for i, tensors in enumerate(shards):
400        p = root / f"{name}-{i + 1:05d}-of-00004.gguf"
401        no = split_no.get(i, i) if split_no else i
402        write_gguf(p, tensors, split=(no, 4, total), arch=i == 0)
403        paths.append(p)
404    return paths
405
406
407def run_pack(first, out, *extra):
408    (out / "tokenizer").mkdir(parents=True, exist_ok=True)
409    for n in ["vocab.json", "chat_template.jinja"]:
410        (out / "tokenizer" / n).touch()
411    buf = io.StringIO()
412    with patch.object(sys, "argv", ["iq_pack.py", "--gguf", str(first), "--out", str(out), *extra]):
413        with contextlib.redirect_stdout(buf):
414            rc = iq_pack.main()
415    return rc, buf.getvalue()
416
417
418def expected_experts(model):
419    """experts.bin from first principles: per layer, per expert, gate | up | down slices."""
420    parts = []
421    for l in (0, 1):
422        ts = [model.bytes(f"blk.{l}.ffn_{r}_exps.weight").reshape(N_EXPERT, -1) for r in ("gate", "up", "down")]
423        parts.append(np.concatenate(ts, axis=1).tobytes())
424    return b"".join(parts)
425
426
427class SplitArtifactTests(unittest.TestCase):
428    setUpClass = require_gguf_py(unittest.TestCase)
429    def test_four_shards_and_a_layer_split_per_role(self):
430        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
431            root = Path(tmp)
432            paths = split_model(root)
433            rc, log = run_pack(paths[0], root / "pack", "--experts-bin")
434            self.assertEqual(rc, 0, log)
435            text = (root / "pack" / "native_experts.txt").read_text()
436            head, line0, line1 = text.splitlines()
437            self.assertTrue(head.startswith("# strata native experts v4:"), head)
438            self.assertIn("(n_expert 4,", head)
439            s2, s3 = paths[1].name, paths[2].name
440            self.assertEqual(line0.split()[8:], [s2])
441            self.assertEqual(line1.split()[8:], [f"{s3},{s3},{s2}"])
442            # every role's offset is absolute in ITS shard: shard 3's data_start for gate/up, shard 2's for down
443            m = iq_pack.Model(paths[0])
444            for line, l in ((line0, 0), (line1, 1)):
445                f = line.split()
446                for r, role in enumerate(("gate", "up", "down")):
447                    g, t, _, _ = m.where[f"blk.{l}.ffn_{role}_exps.weight"]
448                    self.assertEqual(int(f[5 + r]), g.data_start + t.offset)
449            self.assertNotEqual(m.where["blk.1.ffn_gate_exps.weight"][0].data_start,
450                                m.where["blk.1.ffn_down_exps.weight"][0].data_start)
451            self.assertEqual((root / "pack" / "experts.bin").read_bytes(), expected_experts(m))
452            side = json.loads((root / "pack" / "experts.bin.src.json").read_text())
453            self.assertEqual([s["name"] for s in side["shards"]], [p.name for p in paths])
454            self.assertFalse(list((root / "pack").glob("*.tmp")))
455            # the index: routers as BF16, nothing of the experts
456            _, rows = iq_pack.read_index(root / "pack" / "index.txt")
457            self.assertNotIn("blk.1.ffn_gate_exps.weight", rows)
458            self.assertEqual(rows["blk.1.ffn_gate_inp.weight"][2], "4")
459
460    def test_unsplit_layers_keep_the_v3_file(self):
461        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
462            root = Path(tmp)
463            paths = split_model(root, split_layer=False)
464            rc, log = run_pack(paths[0], root / "pack")
465            self.assertEqual(rc, 0, log)
466            head, line0, line1 = (root / "pack" / "native_experts.txt").read_text().splitlines()
467            self.assertTrue(head.startswith("# strata native experts v3: layer gu_type d_type offset blob_bytes "
468                                            "gate_off up_off down_off [shard] (n_expert 4, total "), head)
469            self.assertEqual(line1.split()[8:], [paths[2].name])
470
471    def test_missing_shard(self):
472        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
473            paths = split_model(Path(tmp))
474            paths[3].unlink()
475            with self.assertRaisesRegex(FileNotFoundError, "missing model shards.*00004-of-00004"):
476                iq_pack.Model(paths[0])
477
478    def test_duplicate_tensor_across_shards(self):
479        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
480            paths = split_model(Path(tmp), dup=True)
481            with self.assertRaisesRegex(ValueError, "duplicate tensor blk.1.ffn_up_exps.weight"):
482                iq_pack.Model(paths[0])
483
484    def test_shard_of_another_split(self):
485        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
486            paths = split_model(Path(tmp), split_no={2: 1})
487            with self.assertRaisesRegex(ValueError, "does not declare itself shard 3 of 4"):
488                iq_pack.Model(paths[0])
489
490    def test_truncated_shard(self):
491        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
492            paths = split_model(Path(tmp))
493            paths[2].write_bytes(paths[2].read_bytes()[:-64])
494            with self.assertRaisesRegex(ValueError, "truncated tensor"):
495                iq_pack.Model(paths[0])
496
497    def test_wrong_type_or_shape_leaves_the_pack_alone(self):
498        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
499            root = Path(tmp)
500            paths = split_model(root, gate1=Q.F32)            # layer 1: gate F32, up Q8_0
501            pack = root / "pack"
502            pack.mkdir()
503            (pack / "native_experts.txt").write_text("previous pack")
504            rc, log = run_pack(paths[0], pack)
505            self.assertEqual(rc, 1)
506            self.assertIn("layer 1: gate and up differ in type", log)
507            self.assertEqual((pack / "native_experts.txt").read_text(), "previous pack")
508            self.assertFalse((pack / "dense.bin").exists())
509
510    def test_interrupted_pack(self):
511        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
512            root = Path(tmp)
513            paths = split_model(root)
514            pack = root / "pack"
515            real = np.concatenate
516            calls = []
517
518            def dies_on_layer_1(parts, axis):
519                calls.append(1)
520                if len(calls) == 2:
521                    raise KeyboardInterrupt("stopped part-way")
522                return real(parts, axis=axis)
523            with patch.object(iq_pack.np, "concatenate", dies_on_layer_1):
524                with self.assertRaises(KeyboardInterrupt):
525                    run_pack(paths[0], pack, "--experts-bin")
526            self.assertFalse((pack / "experts.bin").exists())
527            self.assertFalse((pack / "experts.bin.src.json").exists())
528            # the index stops part-way too: the old pack's files stay as they were
529            before = {n: (pack / n).read_bytes() for n in ("index.txt", "dense.bin", "native_experts.txt")}
530            with patch.object(iq_pack, "write_index", side_effect=KeyboardInterrupt("stopped")):
531                with self.assertRaises(KeyboardInterrupt):
532                    run_pack(paths[0], pack)
533            self.assertEqual(before, {n: (pack / n).read_bytes() for n in before})
534            rc, log = run_pack(paths[0], pack, "--experts-bin")
535            self.assertEqual(rc, 0, log)
536            self.assertEqual((pack / "experts.bin").read_bytes(), expected_experts(iq_pack.Model(paths[0])))
537
538    def test_interrupted_pack_continues_at_the_next_layer(self):
539        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
540            root = Path(tmp)
541            paths = split_model(root)
542            pack = root / "pack"
543            real = np.concatenate
544            calls = []
545
546            def dies_on_layer_1(parts, axis):
547                calls.append(1)
548                if len(calls) == 2:
549                    raise KeyboardInterrupt("killed")
550                return real(parts, axis=axis)
551            with patch.object(iq_pack.np, "concatenate", dies_on_layer_1):
552                with self.assertRaises(KeyboardInterrupt):
553                    run_pack(paths[0], pack, "--experts-bin")
554            want = expected_experts(iq_pack.Model(paths[0]))
555            lines = [ln.split() for ln in (pack / "native_experts.txt").read_text().splitlines() if ln and not ln.startswith("#")]
556            one_layer = int(lines[1][3])                                                  # where layer 1 starts
557            self.assertFalse((pack / "experts.bin").exists())
558            self.assertEqual((pack / "experts.bin.tmp").stat().st_size, one_layer)       # layer 0 is on disk
559            self.assertEqual(json.loads((pack / "experts.bin.tmp.json").read_text())["layers"], 1)
560            # a partial write after the recorded layer (the kill came mid-write) is cut off
561            with open(pack / "experts.bin.tmp", "ab") as f:
562                f.write(b"garbage")
563            written = []
564            real_layer = iq_pack.np.concatenate
565
566            def counting(parts, axis):
567                written.append(1)
568                return real_layer(parts, axis=axis)
569            with patch.object(iq_pack.np, "concatenate", counting):
570                rc, log = run_pack(paths[0], pack, "--experts-bin")
571            self.assertEqual(rc, 0, log)
572            self.assertIn("keeping its first 1 of 2 layers and continuing with layer 1", log)
573            self.assertEqual((pack / "experts.bin").read_bytes(), want)
574            self.assertEqual(len(written), 2)                  # one layer re-read to check the kept one, one layer written
575            self.assertFalse((pack / "experts.bin.tmp").exists())
576            self.assertFalse((pack / "experts.bin.tmp.json").exists())
577            self.assertEqual(json.loads((pack / "experts.bin.src.json").read_text())["bytes"], len(want))
578
579    def test_interrupted_pack_of_another_model_is_not_continued(self):
580        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
581            root = Path(tmp)
582            (root / "a").mkdir()
583            (root / "b").mkdir()
584            other = split_model(root / "a", name="other", seed=100)
585            paths = split_model(root / "b")
586            pack = root / "pack"
587            real = np.concatenate
588            calls = []
589
590            def dies_on_layer_1(parts, axis):
591                calls.append(1)
592                if len(calls) == 2:
593                    raise KeyboardInterrupt("killed")
594                return real(parts, axis=axis)
595            with patch.object(iq_pack.np, "concatenate", dies_on_layer_1):
596                with self.assertRaises(KeyboardInterrupt):
597                    run_pack(other[0], pack, "--experts-bin")
598            rc, log = run_pack(paths[0], pack, "--experts-bin")          # the same geometry, other weights
599            self.assertEqual(rc, 0, log)
600            self.assertIn("cannot be continued: starting it again", log)
601            self.assertEqual((pack / "experts.bin").read_bytes(), expected_experts(iq_pack.Model(paths[0])))
602
603    def test_a_kept_layer_that_no_longer_matches_is_not_trusted(self):
604        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
605            root = Path(tmp)
606            paths = split_model(root)
607            pack = root / "pack"
608            real = np.concatenate
609            calls = []
610
611            def dies_on_layer_1(parts, axis):
612                calls.append(1)
613                if len(calls) == 2:
614                    raise KeyboardInterrupt("killed")
615                return real(parts, axis=axis)
616            with patch.object(iq_pack.np, "concatenate", dies_on_layer_1):
617                with self.assertRaises(KeyboardInterrupt):
618                    run_pack(paths[0], pack, "--experts-bin")
619            data = bytearray((pack / "experts.bin.tmp").read_bytes())
620            data[0] ^= 0xFF                                               # the disk lost a bit
621            (pack / "experts.bin.tmp").write_bytes(bytes(data))
622            rc, log = run_pack(paths[0], pack, "--experts-bin")
623            self.assertEqual(rc, 0, log)
624            self.assertIn("cannot be continued", log)
625            self.assertEqual((pack / "experts.bin").read_bytes(), expected_experts(iq_pack.Model(paths[0])))
626
627    def test_stale_same_size_experts_bin(self):
628        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
629            root = Path(tmp)
630            (root / "a").mkdir()
631            (root / "b").mkdir()
632            other = split_model(root / "a", name="other", seed=100)
633            paths = split_model(root / "b")
634            pack = root / "pack"
635            rc, log = run_pack(other[0], pack, "--experts-bin")    # another model, the same geometry
636            self.assertEqual(rc, 0, log)
637            stale = (pack / "experts.bin").read_bytes()
638            want = expected_experts(iq_pack.Model(paths[0]))
639            self.assertEqual(len(stale), len(want))
640            self.assertNotEqual(stale, want)
641            # without --experts-bin the engine would read it: refused, nothing rewritten
642            rc, log = run_pack(paths[0], pack)
643            self.assertEqual(rc, 1)
644            self.assertIn("another source", log)
645            self.assertEqual((pack / "experts.bin").read_bytes(), stale)
646            # with it: rewritten, not reused by its size
647            rc, log = run_pack(paths[0], pack, "--experts-bin")
648            self.assertEqual(rc, 0, log)
649            self.assertEqual((pack / "experts.bin").read_bytes(), want)
650            # and now reused
651            rc, log = run_pack(paths[0], pack, "--experts-bin")
652            self.assertIn("not rewritten", log)
653            # an experts.bin without its sidecar (an older packer) is rewritten too
654            (pack / "experts.bin.src.json").unlink()
655            (pack / "experts.bin").write_bytes(stale)
656            rc, log = run_pack(paths[0], pack, "--experts-bin")
657            self.assertEqual((pack / "experts.bin").read_bytes(), want)
658
659
660class HadamardTests(unittest.TestCase):
661    """prism.hadamard (Agention's APR files) -> hadamard.txt; anything the engine cannot rotate is refused."""
662    N_EMBD, N_FF = 256, 128
663
664    def meta(self, **kw):
665        names = ["blk.%d.ffn_%s_exps.weight" % (l, r) for l in range(2) for r in ("gate", "up", "down")]
666        m = {"prism.hadamard.version": 1, "prism.hadamard.block_size": 128,
667             "prism.hadamard.transform": "normalized-sylvester-walsh-hadamard",
668             "prism.hadamard.axis": "input-last-dimension", "prism.hadamard.sign_mode": "explicit",
669             "prism.hadamard.weight_names": names,
670             "prism.hadamard.sign_widths": [self.N_FF, self.N_EMBD],
671             "prism.hadamard.sign_values": [1, -1] * (self.N_FF // 2) + [-1, 1] * (self.N_EMBD // 2)}
672        m.update(kw)
673        return m
674
675    def layout(self, gu=145, d=146):
676        return [(l, gu, d, 0, 0, None) for l in range(2)]
677
678    def test_no_metadata(self):
679        self.assertIsNone(iq_pack.hadamard_spec({}, self.layout(), self.N_EMBD, self.N_FF))
680
681    def test_explicit_signs_written(self):
682        text = iq_pack.hadamard_spec(self.meta(), self.layout(), self.N_EMBD, self.N_FF)
683        lines = text.splitlines()
684        self.assertTrue(lines[0].startswith("# strata hadamard v1"))
685        self.assertEqual(lines[1], "block 128")
686        self.assertEqual(lines[2].split()[:4], ["signs", str(self.N_FF), "1", "-1"])
687        self.assertEqual(len(lines[3].split()), 2 + self.N_EMBD)
688        self.assertEqual(lines[4:], ["layer 0 1 1 1", "layer 1 1 1 1"])
689
690    def test_refusals(self):
691        bad = {
692            "transform": self.meta(**{"prism.hadamard.transform": "dct"}),
693            "dense weight": self.meta(**{"prism.hadamard.weight_names": ["blk.0.attn_q.weight"]}),
694            "inverse": self.meta(**{"prism.hadamard.inverse_weight_names": ["token_embd.weight"]}),
695            "gate only": self.meta(**{"prism.hadamard.weight_names": ["blk.0.ffn_gate_exps.weight"]}),
696            "missing width": self.meta(**{"prism.hadamard.sign_widths": [self.N_EMBD],
697                                          "prism.hadamard.sign_values": [1] * self.N_EMBD}),
698            "bad sign": self.meta(**{"prism.hadamard.sign_values": [2] * (self.N_FF + self.N_EMBD)}),
699            "block": self.meta(**{"prism.hadamard.block_size": 96}),
700        }
701        for what, m in bad.items():
702            with self.subTest(what):
703                got = iq_pack.hadamard_spec(m, self.layout(), self.N_EMBD, self.N_FF)
704                self.assertIsInstance(got, str)
705                self.assertFalse(got.startswith("# strata hadamard"))
706        got = iq_pack.hadamard_spec(self.meta(), self.layout(gu=42), self.N_EMBD, self.N_FF)
707        self.assertIn("Q2_0", got)
708
709
710class V31HeaderOnlyLayoutTests(unittest.TestCase):
711    """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,
712    header-only: no weights), so the gate == up rule and the Q5_0 downs are checked without a download."""
713
714    @staticmethod
715    def layout(set_name):
716        import unsloth_v31_fixture as FX
717        import gguf_reader as G
718
719        class Map:
720            size = 1 << 62
721        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as t:
722            m = iq_pack.Model.__new__(iq_pack.Model)
723            m.where = {}
724            first = None
725            for s in FX.load()["sets"][set_name]["shards"]:
726                if not s["header"]:
727                    continue
728                p = FX.materialize(s, Path(t) / s["name"])
729                g = G.GGUFFile(p)
730                first = first or p
731                for ti in g.tensors:
732                    m.where[ti.name] = (g, ti, Map, p)
733            return iq_pack.expert_layout(m, first)
734
735    def test_gate_and_up_must_agree_ud_iq1_s_is_refused(self):
736        self.assertEqual(self.layout("UD-IQ1_S"), "layer 18: gate and up differ in type")
737
738    def test_q5_0_downs_are_packed_with_their_type_id(self):
739        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)):
740            with self.subTest(set=set_name):
741                layout, text, n_expert, total = self.layout(set_name)
742                self.assertEqual(n_expert, 512)
743                self.assertEqual(len(layout), 48)
744                self.assertEqual(sum(1 for row in layout if row[5][2].type_name == "Q5_0"), n_q5)
745                rows = [ln.split() for ln in text.splitlines()[1:]]
746                self.assertEqual(sum(1 for r in rows if r[2] == "6"), n_q5)         # d_type 6 = Q5_0
747                self.assertEqual(total, sum(r[4] * 512 for r in layout))
748
749    def test_a_layer_across_shards_makes_a_v4_table(self):
750        layout, text, _n, _t = self.layout("UD-IQ3_XXS")
751        self.assertTrue(text.startswith("# strata native experts v4:"))
752        self.assertEqual(sum(1 for ln in text.splitlines()[1:] if "," in ln.split()[-1]), 1)
753
754
755class NativeExpertsV5Tests(unittest.TestCase):
756    """The v5 mark (Hadamard-folded experts) rewrites only the tables the packer writes, v3 and v4."""
757    setUpClass = require_gguf_py(unittest.TestCase)   # test_packer_refuses_before_writing builds GGUF fixtures
758    ROWS = "0 145 146 0 100 1 2 3\n1 145 146 100 100 4 5 6\n"
759
760    def table(self, version, tail="(n_expert 2, total 200)"):
761        return "# strata native experts v%s: layer gu_type d_type offset ... %s\n" % (version, tail) + self.ROWS
762
763    def test_v3_and_v4_become_v5(self):
764        for v in ("3", "4"):
765            with self.subTest(v):
766                got = iq_pack.native_experts_v5(self.table(v))
767                head, rest = got.split("\n", 1)
768                self.assertTrue(head.startswith("# strata native experts v5: layer gu_type"))
769                self.assertTrue(head.endswith("(n_expert 2, total 200) - v5: Hadamard-folded experts, see hadamard.txt"))
770                self.assertEqual(rest, self.ROWS)
771
772    def test_other_versions_are_refused_by_name(self):
773        for v in ("2", "5", "6", "10"):
774            with self.subTest(v):
775                got = iq_pack.native_experts_v5(self.table(v))
776                self.assertFalse(got.startswith("# strata native experts"))
777                self.assertIn("v%s" % v, got)
778                self.assertIn("v3 and v4", got)
779        got = iq_pack.native_experts_v5("# something else\n" + self.ROWS)
780        self.assertIn("without a version header", got)
781
782    def test_packer_refuses_before_writing(self):
783        real = iq_pack.expert_layout
784
785        def v6_layout(model, src):
786            layout, text, n_expert, offset = real(model, src)
787            return layout, text.replace("native experts v3:", "native experts v6:", 1), n_expert, offset
788
789        with tempfile.TemporaryDirectory() as d:
790            root = Path(d)
791            paths = split_model(root, split_layer=False)
792            out = root / "pack"
793            with patch.object(iq_pack, "expert_layout", v6_layout), \
794                    patch.object(iq_pack, "hadamard_spec", return_value="# strata hadamard v1\nblock 32\n"):
795                rc, log = run_pack(paths[0], out)
796            self.assertEqual(rc, 1)
797            self.assertIn("native_experts.txt v6", log)
798            self.assertIn("only v3 and v4", log)
799            self.assertFalse((out / "native_experts.txt").exists())
800            self.assertFalse((out / "hadamard.txt").exists())
801
802
803if __name__ == "__main__":
804    unittest.main()