okami.mom/strata

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

Niko1221Merge f-own-5b adfcf9028 into f-own-int (round 16: the strata-image test program and its parts, DiT runner, sampler, noise, PNG writer; hooked into no build)e4309aaf3

main
3.9 KiB81 linesraw
1"""tools/image/gate/test_dit_ref.py - TEST-ONLY: dit_ref.py's pieces against their definitions (no model file needed).
2
3    python -m pytest tools/image/gate/test_dit_ref.py"""
4import math
5import sys
6import unittest
7from pathlib import Path
8
9import numpy as np
10
11sys.path.insert(0, str(Path(__file__).resolve().parent))
12import dit_ref as R  # noqa: E402
13
14
15class Layout(unittest.TestCase):
16    def test_positions(self):
17        p = R.layout_positions(3, 2, 3)
18        self.assertEqual(p.shape, (3 + 6, 3))
19        self.assertEqual(p[:3].tolist(), [[0, 0, 0], [1, 1, 1], [2, 2, 2]])
20        # image tokens: (text length, h - (H - H/2), w - (W - W/2)), token h*W + w
21        self.assertEqual(p[3].tolist(), [3, -1, -2])
22        self.assertEqual(p[3 + 5].tolist(), [3, 0, 0])
23
24    def test_rope_table_and_rotation(self):
25        pos = R.layout_positions(4, 4, 4)
26        c, s = R.rope_table(pos)
27        self.assertEqual(c.shape, (4 + 16, 64))
28        self.assertTrue(np.all(c[0] == 1) and np.all(s[0] == 0))          # position 0: no rotation
29        x = np.random.default_rng(2).standard_normal((20, 3, 128)).astype(np.float32)
30        y = R.apply_rope(x, c, s)
31        self.assertTrue(np.allclose(np.linalg.norm(y, axis=-1), np.linalg.norm(x, axis=-1), rtol=1e-5))
32        self.assertTrue(np.array_equal(y[0], x[0]))
33
34
35class Modes(unittest.TestCase):
36    def test_three_modes(self):
37        rng = np.random.default_rng(5)
38        x = rng.standard_normal((6, 256)).astype(np.float32)
39        Wm = rng.standard_normal((32, 256)).astype(np.float32)
40        f32, ex, acc = (R.make_mode(n) for n in ("f32", "f16op", "f16acc32"))
41        self.assertFalse(f32.f16)
42        self.assertTrue(ex.f16 and acc.f16)                                 # both emulations round Q / K / V and P
43        y32, yex, yacc = f32.gemm(x, f32.w(Wm)), ex.gemm(x, ex.w(Wm)), acc.gemm(x, acc.w(Wm))
44        x16, w16 = R.f16r(x).astype(np.float64), R.f16r(Wm).astype(np.float64)
45        self.assertTrue(np.array_equal(yex, (x16 @ w16.T).astype(np.float32)))    # exact sums, rounded once
46        self.assertTrue(np.allclose(yacc, yex, rtol=1e-5, atol=1e-5))            # float32 sums: same up to rounding
47        self.assertFalse(np.allclose(y32, yex, rtol=1e-5, atol=1e-5))            # f16 operands change the result
48        with self.assertRaises(SystemExit):
49            R.make_mode("f16")
50
51
52class Pieces(unittest.TestCase):
53    def test_timestep_embedding(self):
54        e = R.timestep_embedding(np.array([0.0, 500.0], dtype=np.float32))
55        self.assertTrue(np.all(e[0, :128] == 1) and np.all(e[0, 128:] == 0))
56        j = 7
57        f = math.exp(-math.log(10000) * j / 128)
58        self.assertAlmostEqual(float(e[1, j]), math.cos(500 * f), places=5)
59        self.assertAlmostEqual(float(e[1, 128 + j]), math.sin(500 * f), places=5)
60
61    def test_norms_and_activations(self):
62        x = np.random.default_rng(1).standard_normal((5, 64)).astype(np.float32) * 3 + 1
63        y = R.layer_norm(x)
64        self.assertTrue(np.allclose(y.mean(-1), 0, atol=1e-5) and np.allclose(y.std(-1), 1, atol=1e-3))
65        self.assertAlmostEqual(float(R.gelu_tanh(np.float32([1.0]))[0]), 0.8411920, places=5)
66        self.assertAlmostEqual(float(R.silu(np.float32([1.0]))[0]), 1 / (1 + math.exp(-1)), places=6)
67
68    def test_attention_mask(self):
69        rng = np.random.default_rng(4)
70        q, k, v = (rng.standard_normal((7, 2, 128)).astype(np.float32) for _ in range(3))
71        o = R.attention(q, k, v, 3, False)
72        self.assertTrue(np.allclose(o[0], v[0], atol=1e-6))                 # first text token sees only itself
73        o2 = R.attention(q[:3], k[:3], v[:3], 3, False)                     # text rows ignore the image tokens
74        self.assertTrue(np.allclose(o[:3], o2, atol=1e-6))
75        k2 = k.copy()
76        k2[5] += 1                                                          # image rows see every token
77        self.assertFalse(np.allclose(R.attention(q, k2, v, 3, False)[6], o[6]))
78
79
80if __name__ == "__main__":
81    unittest.main()