okami.mom/strata

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

Niko1221Merge f-0213-secure (f374b5029) into f-0213-int97da46cc1

main
2.7 KiB74 linesraw
1"""quant_formats.py --hf reads each shard's header over HTTP range requests with gguf_reader's bounds checks (#5075): the
2header knows the file's size from the Hugging Face tree, so a complete header parses and a cut one is refused with a
3ValueError that names the file.  Over a minimal GGUF v3 header written here (no network, no model).
4
5    python -m unittest tools.test_quant_formats_hf
6"""
7from __future__ import annotations
8
9import io
10import json
11import re
12import struct
13import sys
14import unittest
15from pathlib import Path
16from unittest import mock
17
18sys.path.insert(0, str(Path(__file__).resolve().parent))
19import quant_formats as Q  # noqa: E402
20
21
22def gstr(s: bytes) -> bytes:
23    return struct.pack("<Q", len(s)) + s
24
25
26def shard() -> bytes:
27    """One Q8_0 [32, 4] tensor `blk.0.ffn_down_exps.weight` (type 8), data at offset 0 after a 32-byte alignment."""
28    head = struct.pack("<IIQQ", 0x46554747, 3, 1, 0) + gstr(b"blk.0.ffn_down_exps.weight") + struct.pack("<I", 2)
29    head += struct.pack("<QQ", 32, 4) + struct.pack("<IQ", 8, 0)
30    head += bytes(-len(head) % 32)
31    return head + bytes(4 * 34)
32
33
34class Response(io.BytesIO):
35    def __enter__(self):
36        return self
37
38    def __exit__(self, *a):
39        return False
40
41
42def serve(files: dict[str, bytes]):
43    def urlopen(req, timeout=None):
44        url = req if isinstance(req, str) else req.full_url
45        if "/api/models/" in url:
46            return Response(json.dumps([{"type": "file", "path": p, "size": len(b)} for p, b in files.items()]).encode())
47        name = url.rsplit("/", 1)[1]
48        lo, hi = map(int, re.match(r"bytes=([0-9]+)-([0-9]+)", req.get_header("Range")).groups())
49        return Response(files[name][lo:hi + 1])
50    return mock.patch.object(Q.urllib.request, "urlopen", urlopen)
51
52
53class HfHeaders(unittest.TestCase):
54    def test_a_shard_header_is_read_over_range_requests(self):
55        with serve({"m-00001-of-00001.gguf": shard()}):
56            heads = Q.hf_headers("org/repo", "rev", "dir")
57        self.assertEqual([t.name for t in heads[0].tensors], ["blk.0.ffn_down_exps.weight"])
58
59    def test_a_cut_header_is_refused_with_the_file_name(self):
60        with serve({"m-00001-of-00001.gguf": shard()[:40]}):
61            with self.assertRaises(ValueError) as cm:
62                Q.hf_headers("org/repo", "rev", "dir")
63        self.assertIn("m-00001-of-00001.gguf", str(cm.exception))
64
65    def test_a_huge_name_length_is_refused_not_allocated(self):
66        head = struct.pack("<IIQQ", 0x46554747, 3, 1, 0) + struct.pack("<Q", 2 ** 64 - 16) + bytes(32)
67        with serve({"m.gguf": head}):
68            with self.assertRaises(ValueError) as cm:
69                Q.hf_headers("org/repo", "rev", "dir")
70        self.assertIn("m.gguf", str(cm.exception))
71
72
73if __name__ == "__main__":
74    unittest.main()