okami.mom/strata

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

Niko1221Merge branch 'f-1402-w' into f-140253623e56f

main
9.0 KiB214 linesraw
1"""A missing or short model shard is named with its numbers, a pack's verify reads back the source hash its
2manifest recorded, and a pack's build refuses an output directory that already holds one - over a minimal GGUF
3written here (no download, no model, no GPU).
4
5    python -m unittest tools.test_shards
6"""
7from __future__ import annotations
8
9import contextlib
10import hashlib
11import io
12import json
13import struct
14import sys
15import tempfile
16import unittest
17from pathlib import Path
18
19ROOT = Path(__file__).resolve().parents[1]
20sys.path.insert(0, str(ROOT / "tools"))
21sys.path.insert(0, str(ROOT))
22import setup as S  # noqa: E402
23import strata_pack  # noqa: E402
24
25
26class Stop(Exception):
27    """setup.fail(), caught instead of exiting: the message is what the test reads."""
28
29
30def write_gguf(path: Path, names=("blk.0.attn_q.weight", "blk.0.attn_k.weight")) -> int:
31    """A GGUF v3 of F32[8] tensors 32 bytes apart from a 32-byte-aligned data start; returns its whole length."""
32    b = bytearray(struct.pack("<IIQQ", 0x46554747, 3, len(names), 0))
33    for i, n in enumerate(names):
34        b += struct.pack("<Q", len(n)) + n.encode() + struct.pack("<IQIQ", 1, 8, 0, 32 * i)
35    b += bytes(-len(b) % 32 + 32 * len(names))
36    path.write_bytes(b)
37    return len(b)
38
39
40class ShardCheck(unittest.TestCase):
41    def setUp(self):
42        self.tmp = tempfile.TemporaryDirectory()
43        self.dir = Path(self.tmp.name)
44        self.saved = S.fail
45        S.fail = lambda msg, hint=None: (_ for _ in ()).throw(Stop(msg))
46
47    def tearDown(self):
48        S.fail = self.saved
49        self.tmp.cleanup()
50
51    def test_whole_shards_pass(self):
52        shards = [self.dir / f"m-0000{i}-of-00002.gguf" for i in (1, 2)]
53        for s in shards:
54            write_gguf(s)
55        S.check_shards(shards)
56
57    def test_missing_shard_is_named(self):
58        shards = [self.dir / "m-00001-of-00002.gguf", self.dir / "m-00002-of-00002.gguf"]
59        write_gguf(shards[0])
60        with self.assertRaises(Stop) as cm:
61            S.check_shards(shards)
62        self.assertIn("m-00002-of-00002.gguf", str(cm.exception))
63
64    def test_short_shard_names_file_and_sizes(self):
65        s = self.dir / "m-00001-of-00002.gguf"
66        whole = write_gguf(s)
67        s.write_bytes(s.read_bytes()[:-40])
68        with self.assertRaises(Stop) as cm:
69            S.check_shards([s])
70        msg = str(cm.exception)
71        self.assertIn("m-00001-of-00002.gguf is short", msg)
72        self.assertIn(f"{whole - 40:,} of {whole:,} bytes", msg)
73        self.assertIn("40 missing", msg)
74
75    def test_single_tensor_shard_with_extra_bytes_is_refused(self):
76        # #657: the PLE table's shard is exactly as long as its one tensor; 612 extra bytes are a damaged file
77        s = self.dir / "m-00002-of-00002.gguf"
78        whole = write_gguf(s, names=("per_layer_token_embd.weight",))
79        S.check_shards([s])
80        s.write_bytes(s.read_bytes() + bytes(612))
81        with self.assertRaises(Stop) as cm:
82            S.check_shards([s])
83        msg = str(cm.exception)
84        self.assertIn("m-00002-of-00002.gguf is longer than its tensor", msg)
85        self.assertIn(f"{whole + 612:,} bytes, {whole:,} expected", msg)
86        # a shard with several tensors is not held to the rule
87        t = self.dir / "m-00001-of-00002.gguf"
88        write_gguf(t)
89        t.write_bytes(t.read_bytes() + bytes(612))
90        S.check_shards([t])
91
92    def test_truncated_header_is_refused(self):
93        s = self.dir / "m-00001-of-00002.gguf"
94        write_gguf(s)
95        s.write_bytes(s.read_bytes()[:12])
96        with self.assertRaises(Stop) as cm:
97            S.check_shards([s])
98        self.assertIn("m-00001-of-00002.gguf is not a whole GGUF shard", str(cm.exception))
99
100
101class PackVerifyHash(unittest.TestCase):
102    """verify over a manifest with no tensor entries: the only check left is the source hash."""
103
104    def setUp(self):
105        self.tmp = tempfile.TemporaryDirectory()
106        self.dir = Path(self.tmp.name)
107        self.gguf = self.dir / "m-00001-of-00002.gguf"
108        write_gguf(self.gguf)
109        self.digest = hashlib.sha256(self.gguf.read_bytes()).hexdigest()
110
111    def tearDown(self):
112        self.tmp.cleanup()
113
114    def run_verify(self, source, limit=None):
115        (self.dir / "manifest.json").write_text(json.dumps({"tensors": {}, "source": source}), encoding="utf-8")
116        out = io.StringIO()
117        with contextlib.redirect_stdout(out):
118            rc = strata_pack.verify(self.gguf, self.dir, limit, 0)
119        return rc, out.getvalue()
120
121    def test_matching_hash_passes(self):
122        rc, _ = self.run_verify({"shard1_sha256": self.digest})
123        self.assertEqual(rc, 0)
124
125    def test_wrong_hash_fails_naming_both(self):
126        rc, out = self.run_verify({"shard1_sha256": "0" * 64})
127        self.assertEqual(rc, 1)
128        self.assertIn("m-00001-of-00002.gguf: sha256 " + self.digest, out)
129        self.assertIn("built from " + "0" * 64, out)
130
131    def test_no_hash_or_limit_skips(self):
132        self.assertEqual(self.run_verify({})[0], 0)                                  # setup builds --skip-hash
133        self.assertEqual(self.run_verify({"shard1_sha256": "0" * 64}, limit=1)[0], 0)  # --limit stays quick
134
135
136class PackBuildOccupied(unittest.TestCase):
137    """build refuses an --out that already holds a pack before it opens the GGUF or writes a byte; an empty or absent
138    directory goes on into the build.  The GGUF reader is replaced by a sentinel, so "went on" is the sentinel
139    raised at the first thing build does after the check (a real build needs the model's shards)."""
140
141    def setUp(self):
142        self.tmp = tempfile.TemporaryDirectory()
143        self.dir = Path(self.tmp.name)
144        self.saved = strata_pack.G.GGUFFile
145        strata_pack.G.GGUFFile = lambda path: (_ for _ in ()).throw(Stop(str(path)))
146
147    def tearDown(self):
148        strata_pack.G.GGUFFile = self.saved
149        self.tmp.cleanup()
150
151    def run_build(self, out):
152        buf = io.StringIO()
153        with contextlib.redirect_stdout(buf):
154            rc = strata_pack.build(self.dir / "m-00001-of-00002.gguf", out, None, True)
155        return rc, buf.getvalue()
156
157    def test_occupied_dir_is_refused_naming_it(self):
158        for marker in ("manifest.json", "index.txt", "native_experts.txt"):   # strata_pack.PACK_MARKERS
159            with self.subTest(marker=marker):
160                out = self.dir / marker.replace(".", "-")
161                out.mkdir()
162                (out / marker).write_text("the pack that was there", encoding="utf-8")
163                (out / "experts.bin").write_bytes(b"its experts")
164                rc, text = self.run_build(out)
165                self.assertEqual(rc, 1)
166                self.assertIn(str(out), text)
167                self.assertIn(marker, text)
168                self.assertEqual(sorted(p.name for p in out.iterdir()), sorted(["experts.bin", marker]))
169                self.assertEqual((out / marker).read_text(encoding="utf-8"), "the pack that was there")
170                self.assertEqual((out / "experts.bin").read_bytes(), b"its experts")
171
172    def test_empty_or_absent_dir_proceeds(self):
173        empty = self.dir / "empty"
174        empty.mkdir()
175        for out in (empty, self.dir / "absent" / "pack"):
176            with self.subTest(out=out.name), self.assertRaises(Stop):
177                self.run_build(out)
178            self.assertTrue(out.is_dir())
179
180    def test_force_builds_into_an_occupied_dir(self):
181        # #634: setup rebuilds a pack that lost its index.txt or experts.bin with --force
182        out = self.dir / "forced"
183        out.mkdir()
184        (out / "manifest.json").write_text("the pack that was there", encoding="utf-8")
185        buf = io.StringIO()
186        with contextlib.redirect_stdout(buf), self.assertRaises(Stop):
187            strata_pack.build(self.dir / "m-00001-of-00002.gguf", out, None, True, True)
188
189    def test_force_unmakes_the_old_pack_before_building(self):
190        # #634 follow-up: --force drops the old pack's markers before the build opens the GGUF, so a forced build
191        # that stops part-way is an unfinished build (made again next time), not the old index.txt and manifest.json
192        # over partly new experts; the data files are left to the build, which rewrites each one
193        out = self.dir / "forced-markers"
194        out.mkdir()
195        for name in strata_pack.PACK_MARKERS:
196            (out / name).write_text("the pack that was there", encoding="utf-8")
197        (out / "experts.bin").write_bytes(b"its experts")
198        buf = io.StringIO()
199        with contextlib.redirect_stdout(buf), self.assertRaises(Stop):
200            strata_pack.build(self.dir / "m-00001-of-00002.gguf", out, None, True, True)
201        self.assertEqual([p.name for p in out.iterdir()], ["experts.bin"])
202        self.assertEqual((out / "experts.bin").read_bytes(), b"its experts")
203
204    def test_unfinished_build_is_rebuilt(self):
205        # experts.bin without manifest.json is a build that stopped before its last file: not a pack, rebuilt as before
206        out = self.dir / "unfinished"
207        out.mkdir()
208        (out / "experts.bin").write_bytes(b"part")
209        with self.assertRaises(Stop):
210            self.run_build(out)
211
212
213if __name__ == "__main__":
214    unittest.main()