okami.mom/strata

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

Niko1221Int3 merge f-0291-df2-spark (15165e170)6360274c8

main
8.5 KiB177 linesraw
1#!/usr/bin/env python3
2"""tools/dflash2_pack.py reads a .safetensors file with numpy alone (the person's PC has neither torch nor the safetensors package) and writes
3the same runtime file the torch-based version wrote.
4
5    python tools/test_dflash2_pack.py
6"""
7import importlib.util
8import json
9import struct
10import subprocess
11import sys
12import tempfile
13import unittest
14from pathlib import Path
15
16import numpy as np
17
18HERE = Path(__file__).resolve().parent
19sys.path.insert(0, str(HERE))
20import dflash2_pack as new  # noqa: E402
21
22L, H, INTER, HEADS, KV, HD, RANK, VOCAB = 2, 64, 96, 2, 1, 32, 32, 128
23CFG = {"num_hidden_layers": L, "hidden_size": H, "num_attention_heads": HEADS, "num_key_value_heads": KV, "head_dim": HD,
24       "intermediate_size": INTER, "sliding_window": 128, "rope_parameters": {"rope_theta": 1000000.0}, "rms_norm_eps": 1e-6, "vocab_size": VOCAB,
25       "dflash_config": {"block_size": 8, "conv_group_size": 16, "conv_kernel_size": 2, "mask_token_id": 7, "selector_rank": RANK, "selector_top_k": 4,
26                         "target_layer_ids": [1, 2, 3]}}
27
28
29def bf16(a):
30    """float32 -> BF16 bytes by truncation (what torch's .to(bfloat16) does for these values up to rounding; the test only needs a valid BF16 file)."""
31    return (np.ascontiguousarray(a, np.float32).view(np.uint32) >> 16).astype(np.uint16)
32
33
34def tensors():
35    rng = np.random.default_rng(7)
36    r = lambda *shape: rng.standard_normal(shape).astype(np.float32) * 0.1
37    t = {"fc.weight": r(H, H * 3), "hidden_norm.weight": r(H), "norm.weight": r(H)}
38    for l in range(L):
39        p = "layers.%d." % l
40        t[p + "self_attn.q_proj.weight"] = r(HEADS * HD, H)
41        t[p + "self_attn.k_proj.weight"] = r(KV * HD, H)
42        t[p + "self_attn.v_proj.weight"] = r(KV * HD, H)
43        t[p + "self_attn.o_proj.weight"] = r(H, HEADS * HD)
44        t[p + "mlp.gate_proj.weight"] = r(INTER, H)
45        t[p + "mlp.up_proj.weight"] = r(INTER, H)
46        t[p + "mlp.down_proj.weight"] = r(H, INTER)
47        t[p + "attention_conv.kernel_projection.weight"] = r(32, H)
48        t[p + "mlp_conv.kernel_projection.weight"] = r(32, H)
49        for n in ("input_layernorm", "post_attention_layernorm", "self_attn.q_norm", "self_attn.k_norm"):
50            t[p + n + ".weight"] = r(HD if "_norm" in n else H)
51        t[p + "attention_conv.base_kernel"] = r(2, 16)
52        t[p + "mlp_conv.base_kernel"] = r(2, 16)
53    t["candidate_selector.hidden_projection.weight"] = r(RANK, H)
54    t["candidate_selector.predecessor_codebook"] = r(VOCAB, RANK)
55    t["candidate_selector.successor_codebook"] = r(VOCAB, RANK)
56    return t
57
58
59def write_safetensors(path, arrays):
60    """A BF16 safetensors file written by hand (the format is documented: u64 header length, JSON header, raw data)."""
61    header, blobs, at = {}, [], 0
62    for name, a in arrays.items():
63        data = bf16(a).tobytes()
64        header[name] = {"dtype": "BF16", "shape": list(a.shape), "data_offsets": [at, at + len(data)]}
65        blobs.append(data)
66        at += len(data)
67    js = json.dumps(header).encode()
68    js += b" " * ((8 - len(js) % 8) % 8)
69    with open(path, "wb") as fh:
70        fh.write(struct.pack("<Q", len(js)) + js + b"".join(blobs))
71
72
73class PackWithoutTorch(unittest.TestCase):
74    @classmethod
75    def setUpClass(cls):
76        cls.tmp = tempfile.TemporaryDirectory()
77        cls.dir = Path(cls.tmp.name)
78        cls.arrays = tensors()
79        write_safetensors(cls.dir / "model.safetensors", cls.arrays)
80        (cls.dir / "config.json").write_text(json.dumps(CFG))
81
82    @classmethod
83    def tearDownClass(cls):
84        cls.tmp.cleanup()
85
86    def pack(self, out):
87        return new.pack(str(self.dir / "model.safetensors"), str(self.dir / "config.json"), str(out), say=lambda *_: None)
88
89    def test_reader_widens_bf16_exactly(self):
90        f = new.SafeTensors(str(self.dir / "model.safetensors"))
91        got = f.get_float32("fc.weight")
92        want = (bf16(self.arrays["fc.weight"]).astype(np.uint32) << 16).view(np.float32)
93        self.assertTrue(np.array_equal(got, want))
94        self.assertEqual(f.get_bf16_bits("candidate_selector.predecessor_codebook").dtype, np.uint16)
95        self.assertEqual(f.raw("norm.weight")[0], "BF16")
96
97    def test_the_file_has_the_header_the_engine_reads(self):
98        out = self.dir / "out.pack"
99        size = self.pack(out)
100        data = out.read_bytes()
101        self.assertEqual(data[:4], b"DF2P")
102        version, index_len = struct.unpack("<II", data[4:12])
103        self.assertEqual(version, 1)
104        self.assertEqual((12 + index_len) % 4096, 0, "the data starts on a 4096 multiple")
105        index = data[12:12 + index_len].decode().splitlines()
106        self.assertTrue(any(l.startswith("cfg hidden %d" % H) for l in index))
107        self.assertIn("end", [l.strip() for l in index])
108        names = [l.split()[1] for l in index if l.startswith("t ")]
109        self.assertIn("fc.weight", names)
110        self.assertIn("candidate_selector.successor_codebook", names)
111        self.assertEqual(len(data), size)
112
113    def test_a_matrix_is_ggml_q8_0_of_the_widened_values(self):
114        out = self.dir / "q8.pack"
115        self.pack(out)
116        data = out.read_bytes()
117        index_len = struct.unpack("<I", data[8:12])[0]
118        base = 12 + index_len
119        row = next(l.split() for l in data[12:base].decode().splitlines() if l.startswith("t fc.weight "))
120        _t, _name, dtype, rows, cols, off, nbytes = row
121        self.assertEqual(dtype, "q8_0")
122        got = data[base + int(off): base + int(off) + int(nbytes)]
123        widened = (bf16(self.arrays["fc.weight"]).astype(np.uint32) << 16).view(np.float32)
124        self.assertEqual(got, new.quant_q8_0(widened))
125
126    def test_q4_0_blocks_are_ggml_q4_0_and_only_the_matrices_change(self):
127        q8, q4 = self.dir / "q8b.pack", self.dir / "q4.pack"
128        self.pack(q8)
129        new.pack(str(self.dir / "model.safetensors"), str(self.dir / "config.json"), str(q4), say=lambda *_: None, q4=True)
130        rows = {}
131        for path in (q8, q4):
132            data = path.read_bytes()
133            index_len = struct.unpack("<I", data[8:12])[0]
134            rows[path] = (data, 12 + index_len, {l.split()[1]: l.split() for l in data[12:12 + index_len].decode().splitlines() if l.startswith("t ")})
135        d8, b8, t8 = rows[q8]
136        d4, b4, t4 = rows[q4]
137        self.assertEqual(set(t8), set(t4))
138        for name, r in t4.items():
139            dtype4, nbytes4 = r[2], int(r[6])
140            if t8[name][2] == "q8_0":
141                self.assertEqual(dtype4, "q4_0", name)
142                self.assertEqual(nbytes4, int(r[3]) * int(r[4]) // 32 * 18, name)
143            else:   # norms, conv kernels and the codebooks are byte for byte the same
144                self.assertEqual(d4[b4 + int(r[5]): b4 + int(r[5]) + nbytes4], d8[b8 + int(t8[name][5]): b8 + int(t8[name][5]) + int(t8[name][6])], name)
145        # one matrix: dequantize the blocks and check the error is within one step of each block scale (the +8 end is clamped to 7)
146        w = (bf16(self.arrays["fc.weight"]).astype(np.uint32) << 16).view(np.float32)
147        r = t4["fc.weight"]
148        blocks = np.frombuffer(d4[b4 + int(r[5]): b4 + int(r[5]) + int(r[6])], np.uint8).reshape(w.shape[0], w.shape[1] // 32, 18)
149        d = blocks[..., :2].copy().view(np.float16)[..., 0].astype(np.float32)
150        q = np.concatenate([blocks[..., 2:] & 15, blocks[..., 2:] >> 4], axis=-1).astype(np.float32) - 8
151        deq = (q * d[..., None]).reshape(w.shape)
152        step = np.abs(d)[..., None].repeat(32, -1).reshape(w.shape)
153        self.assertTrue(np.all(np.abs(deq - w) <= 1.01 * step + 1e-6))
154
155    def test_it_matches_the_torch_version_when_torch_is_here(self):
156        try:
157            import torch  # noqa: F401
158            import safetensors  # noqa: F401
159        except ImportError:
160            self.skipTest("torch or safetensors is not installed here (the point of the change)")
161        old_src = subprocess.run(["git", "show", "f1b6a2144:tools/dflash2_pack.py"], cwd=HERE, capture_output=True, text=True)
162        if old_src.returncode != 0:
163            self.skipTest("the earlier version is not in this clone")
164        old_path = self.dir / "old_pack.py"
165        old_path.write_text(old_src.stdout)
166        spec = importlib.util.spec_from_file_location("old_pack", old_path)
167        old = importlib.util.module_from_spec(spec)
168        spec.loader.exec_module(old)
169        a, b = self.dir / "a.pack", self.dir / "b.pack"
170        sys.argv = ["x", str(self.dir / "model.safetensors"), str(self.dir / "config.json"), str(a)]
171        old.main()
172        self.pack(b)
173        self.assertEqual(a.read_bytes(), b.read_bytes(), "byte for byte the same file")
174
175
176if __name__ == "__main__":
177    unittest.main()