okami.mom/strata

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

Niko1221Merge f-own-5b 9b242bb5b into f-own-int (round 15: the own text encoder and tokenizer as test programs, the DiT reference tool and position tables; committed work only)11c8c701a

main
7.8 KiB205 linesraw
1"""tools/image/gate/test_te_ref.py - TEST-ONLY: te_ref.py's pieces against independent scalar forms of the same maths
2(the GGUF block formats as include/strata/artifact/dequant.hpp writes them, the prompt-weight parser's documented cases),
3and the encoder on a tiny random model (no model file needed).
4
5    python -m pytest tools/image/gate/test_te_ref.py"""
6import math
7import struct
8import sys
9import unittest
10from pathlib import Path
11
12import numpy as np
13
14sys.path.insert(0, str(Path(__file__).resolve().parent))
15import te_ref as T  # noqa: E402
16
17F = np.float32
18
19
20def h2f(u):
21    return F(np.frombuffer(struct.pack("<H", u), "<f2")[0])
22
23
24def scale_min_k4(j, q):
25    if j < 4:
26        return q[j] & 63, q[j + 4] & 63
27    return (q[j + 4] & 0x0F) | ((q[j - 4] >> 6) << 4), (q[j + 4] >> 4) | ((q[j] >> 6) << 4)
28
29
30def scalar_q4_k(b):
31    d, mn = h2f(b[0] | b[1] << 8), h2f(b[2] | b[3] << 8)
32    sc, q, y, is_ = b[4:16], b[16:144], [], 0
33    for j in range(0, 256, 64):
34        s, m = scale_min_k4(is_, sc)
35        d1, m1 = F(d * F(s)), F(mn * F(m))
36        s, m = scale_min_k4(is_ + 1, sc)
37        d2, m2 = F(d * F(s)), F(mn * F(m))
38        qq = q[j // 2:j // 2 + 32]
39        y += [F(F(d1 * F(x & 0xF)) - m1) for x in qq]
40        y += [F(F(d2 * F(x >> 4)) - m2) for x in qq]
41        is_ += 2
42    return np.array(y, F)
43
44
45def scalar_q5_k(b):
46    d, mn = h2f(b[0] | b[1] << 8), h2f(b[2] | b[3] << 8)
47    sc, qh, ql, y, is_, u1, u2 = b[4:16], b[16:48], b[48:176], [], 0, 1, 2
48    for j in range(0, 256, 64):
49        s, m = scale_min_k4(is_, sc)
50        d1, m1 = F(d * F(s)), F(mn * F(m))
51        s, m = scale_min_k4(is_ + 1, sc)
52        d2, m2 = F(d * F(s)), F(mn * F(m))
53        qq = ql[j // 2:j // 2 + 32]
54        y += [F(F(d1 * F((qq[l] & 0xF) + (16 if qh[l] & u1 else 0))) - m1) for l in range(32)]
55        y += [F(F(d2 * F((qq[l] >> 4) + (16 if qh[l] & u2 else 0))) - m2) for l in range(32)]
56        is_ += 2
57        u1, u2 = (u1 << 2) & 0xFF, (u2 << 2) & 0xFF
58    return np.array(y, F)
59
60
61def scalar_q6_k(b):
62    ql, qh = b[0:128], b[128:192]
63    sc = np.frombuffer(bytes(b[192:208]), np.int8)
64    d = h2f(b[208] | b[209] << 8)
65    y = [F(0)] * 256
66    for n in range(2):
67        L, H, S, o = ql[64 * n:], qh[32 * n:], sc[8 * n:], 128 * n
68        for l in range(32):
69            is_ = l // 16
70            q1 = ((L[l] & 0xF) | (((H[l] >> 0) & 3) << 4)) - 32
71            q2 = ((L[l + 32] & 0xF) | (((H[l] >> 2) & 3) << 4)) - 32
72            q3 = ((L[l] >> 4) | (((H[l] >> 4) & 3) << 4)) - 32
73            q4 = ((L[l + 32] >> 4) | (((H[l] >> 6) & 3) << 4)) - 32
74            y[o + l] = F(F(d * F(S[is_])) * F(q1))
75            y[o + l + 32] = F(F(d * F(S[is_ + 2])) * F(q2))
76            y[o + l + 64] = F(F(d * F(S[is_ + 4])) * F(q3))
77            y[o + l + 96] = F(F(d * F(S[is_ + 6])) * F(q4))
78    return np.array(y, F)
79
80
81def scalar_iq4_xs(b):
82    d = h2f(b[0] | b[1] << 8)
83    sh, sl, qs, y = b[2] | b[3] << 8, b[4:8], b[8:136], []
84    for ib in range(8):
85        ls = ((sl[ib // 2] >> (4 * (ib % 2))) & 0xF) | (((sh >> (2 * ib)) & 3) << 4)
86        dl = F(d * F(ls - 32))
87        lo = [F(dl * T.KV_IQ4NL[qs[16 * ib + j] & 0xF]) for j in range(16)]
88        hi = [F(dl * T.KV_IQ4NL[qs[16 * ib + j] >> 4]) for j in range(16)]
89        y += lo + hi
90    return np.array(y, F)
91
92
93def random_blocks(rng, n, size, f16_at):
94    b = rng.integers(0, 256, size=(n, size), dtype=np.uint8)
95    for off in f16_at:                                  # finite, modest scales
96        v = rng.uniform(-0.02, 0.02, n).astype(np.float16).view(np.uint8).reshape(n, 2)
97        b[:, off:off + 2] = v
98    return b
99
100
101class Dequant(unittest.TestCase):
102    def check(self, fn, scalar, size, f16_at):
103        rng = np.random.default_rng(7)
104        b = random_blocks(rng, 6, size, f16_at)
105        got = fn(b.reshape(-1))
106        want = np.concatenate([scalar(list(map(int, row))) for row in b])
107        self.assertTrue(np.array_equal(got.view(np.uint32), want.view(np.uint32)))
108
109    def test_q4_k(self):
110        self.check(T.deq_q4_k, scalar_q4_k, 144, (0, 2))
111
112    def test_q5_k(self):
113        self.check(T.deq_q5_k, scalar_q5_k, 176, (0, 2))
114
115    def test_q6_k(self):
116        self.check(T.deq_q6_k, scalar_q6_k, 210, (208,))
117
118    def test_iq4_xs(self):
119        self.check(T.deq_iq4_xs, scalar_iq4_xs, 136, (0,))
120
121
122class PromptWeights(unittest.TestCase):
123    """The cases documented above sd.cpp's core/util.cpp parse_prompt_attention, as its code (not its comment) runs them."""
124
125    def same(self, text, want):
126        got = T.parse_prompt_attention(text)
127        self.assertEqual([g[0] for g in got], [w[0] for w in want])
128        for g, w in zip(got, want):
129            self.assertAlmostEqual(float(g[1]), w[1], places=5)
130
131    def test_cases(self):
132        self.same("normal text", [["normal text", 1.0]])
133        self.same("an (important) word", [["an ", 1.0], ["important", 1.1], [" word", 1.0]])
134        self.same("(unbalanced", [["unbalanced", 1.1]])
135        # the comment above sd.cpp's function says "(literal]"; its code unescapes only "\(" and keeps "\]" as text
136        self.same("\\(literal\\]", [["(literal\\]", 1.0]])
137        self.same("(unnecessary)(parens)", [["unnecessaryparens", 1.1]])
138        self.same("a (((house:1.3)) [on] a (hill:0.5), sun, (((sky))).",
139                  [["a ", 1.0], ["house", 1.573], [" ", 1.1], ["on", 1.0], [" a ", 1.1], ["hill", 0.55],
140                   [", sun, ", 1.1], ["sky", 1.4641], [".", 1.1]])
141
142    def test_gate_prompts_are_plain(self):
143        from run_set import PROMPTS
144        for p in PROMPTS:
145            self.assertEqual(T.parse_prompt_attention(p), [[p, np.float32(1.0)]])
146
147
148class Tokens(unittest.TestCase):
149    def test_bpe_and_specials(self):
150        bu = T.bytes_to_unicode()
151        sp = bu[ord(" ")]
152        tok = T.Qwen2Tok(["h e", "l l", "he ll", f"{sp} w", "o r"])
153        ids = tok.encode("<|im_start|>hello world<|im_end|>")
154        base = 256 + 5
155        self.assertEqual(ids[0], base + 1)
156        self.assertEqual(ids[-1], base + 2)
157        self.assertEqual(tok.vocab[ids[1]], "hell")
158        self.assertEqual("".join(tok.vocab[i] for i in ids[1:-1]), "hello" + sp + "world")
159
160    def test_split_specials(self):
161        self.assertEqual(T.split_with_special_tokens("a<|im_end|>\nb", T.SPECIALS), ["a", "<|im_end|>", "\nb"])
162
163
164class TinyModel(unittest.TestCase):
165    """The layer on random weights: causal (token t sees only 0..t), f16op close to f32, NEOX rope = rotation."""
166
167    def setUp(self):
168        rng = np.random.default_rng(3)
169        C, Hh, KV, D, Ff = 64, 4, 2, 16, 96
170
171        class W:
172            n_head, n_kv, hd, theta, eps = Hh, KV, D, 5e6, 1e-6
173
174        class L:
175            pass
176        self.W = W
177        L.attn_norm = rng.uniform(0.5, 1.5, C).astype(F)
178        L.ffn_norm = rng.uniform(0.5, 1.5, C).astype(F)
179        L.qn = rng.uniform(0.5, 1.5, D).astype(F)
180        L.kn = rng.uniform(0.5, 1.5, D).astype(F)
181        mk = lambda o, i: (rng.standard_normal((o, i)) / math.sqrt(i)).astype(F).astype(np.float64)  # noqa: E731
182        L.q, L.k, L.v, L.o = mk(Hh * D, C), mk(KV * D, C), mk(KV * D, C), mk(C, Hh * D)
183        L.g, L.u, L.d = mk(Ff, C), mk(Ff, C), mk(C, Ff)
184        self.L = L
185        self.x = rng.standard_normal((9, C)).astype(F)
186
187    def test_causal(self):
188        full = T.layer_forward(self.W, self.L, self.x, False, None, 0)
189        part = T.layer_forward(self.W, self.L, self.x[:5], False, None, 0)
190        self.assertTrue(np.allclose(full[:5], part, rtol=1e-6, atol=1e-6))
191
192    def test_f16op_close(self):
193        a = T.layer_forward(self.W, self.L, self.x, False, None, 0)
194        b = T.layer_forward(self.W, self.L, self.x, True, {}, 0)
195        self.assertLess(T.compare(b, a)["rel_l2"], 5e-3)
196
197    def test_rope_is_rotation(self):
198        x = np.random.default_rng(1).standard_normal((6, 2, 16)).astype(F)
199        r = T.rope_neox(x, 5e6)
200        self.assertTrue(np.allclose(np.linalg.norm(r, axis=-1), np.linalg.norm(x, axis=-1), rtol=1e-5))
201        self.assertTrue(np.array_equal(r[0], x[0]))
202
203
204if __name__ == "__main__":
205    unittest.main()