okami.mom/strata

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

Niko1221Merge f-own-5 56630caca into f-own-int (round 14: Strata's own VAE decoder for sd-cli and the images "vae_decoder" switch)736266e87

main
6.7 KiB151 linesraw
1"""tools/image/gate/test_vae_ref.py - TEST-ONLY: vae_ref.py's pieces against independent forms of the same maths, and
2the whole decoder on a tiny random model (no model file needed).
3
4    python -m pytest tools/image/gate/test_vae_ref.py"""
5import json
6import struct
7import sys
8import tempfile
9import unittest
10from pathlib import Path
11
12import numpy as np
13
14sys.path.insert(0, str(Path(__file__).resolve().parent))
15import vae_ref as V  # noqa: E402
16
17
18def dup_up_torch_form(x_chw, out_c, ft, fs=2):
19    """DupUp3D the way the Wan2.2 Python code writes it, for one frame:
20    repeat_interleave(repeats, dim=channel) -> view(out_c, ft, fs, fs, T, H, W) -> permute(out_c, T, ft, H, fs, W, fs)
21    -> view(out_c, T*ft, H*fs, W*fs) -> keep frames from ft-1 (first chunk)."""
22    C, H, W = x_chw.shape
23    repeats = out_c * ft * fs * fs // C
24    x = np.repeat(x_chw[:, None], 1, axis=1)                      # [C, T=1, H, W]
25    x = np.repeat(x, repeats, axis=0)                              # repeat_interleave over channels
26    x = x.reshape(out_c, ft, fs, fs, 1, H, W).transpose(0, 4, 1, 5, 2, 6, 3)
27    x = x.reshape(out_c, ft, H * fs, W * fs)
28    return x[:, ft - 1]                                            # [out_c, 2H, 2W]
29
30
31class Pieces(unittest.TestCase):
32    def test_dup_up_matches_the_torch_form(self):
33        rng = np.random.default_rng(1)
34        for c, out_c, ft in [(8, 8, 2), (8, 4, 2), (8, 4, 1), (12, 6, 1)]:
35            x = rng.standard_normal((3, 5, c)).astype(np.float32)
36            got = V.Decoder.dup_up(x, out_c, ft)
37            want = dup_up_torch_form(x.transpose(2, 0, 1), out_c, ft).transpose(1, 2, 0)
38            self.assertTrue(np.array_equal(got, want), (c, out_c, ft))
39
40    def test_conv3x3_matches_direct_loops(self):
41        rng = np.random.default_rng(2)
42        H, W, C, O = 5, 6, 3, 4
43        w = rng.standard_normal((O, C, 3, 3)).astype(np.float32)
44        b = rng.standard_normal(O).astype(np.float32)
45        x = rng.standard_normal((H, W, C)).astype(np.float32)
46        dec = V.Decoder({"c.weight": w, "c.bias": b})
47        got = dec.conv("c", x, rows_per_chunk=2)
48        pad = np.zeros((H + 2, W + 2, C), np.float64)
49        pad[1:-1, 1:-1] = x
50        want = np.zeros((H, W, O))
51        for y in range(H):
52            for xx in range(W):
53                for o in range(O):
54                    want[y, xx, o] = np.sum(pad[y:y + 3, xx:xx + 3, :] * w[o].transpose(1, 2, 0)) + b[o]
55        self.assertLess(np.abs(got - want).max(), 1e-5)
56
57    def test_rms_norm_by_hand(self):
58        dec = V.Decoder({"n.gamma": np.array([[[1.0]], [[2.0]]], np.float32)})
59        out = dec.rms("n", np.array([[[3.0, 4.0]]], np.float32))      # rms = sqrt(12.5)
60        r = np.sqrt(12.5)
61        self.assertTrue(np.allclose(out, [[[3 / r, 8 / r]]], rtol=1e-6))
62
63    def test_to_u8(self):
64        u = V.to_u8(np.array([-2.0, -1.0, 0.0, 1.0, 3.0, 0.5], np.float32))
65        self.assertEqual(u.tolist(), [0, 0, 128, 255, 255, 191])
66
67    def test_f16op_refuses_inputs_beyond_f16(self):
68        dec = V.Decoder({"c.weight": np.ones((1, 1, 1, 1), np.float32), "c.bias": np.zeros(1, np.float32)}, mode="f16op")
69        with self.assertRaises(OverflowError):
70            dec.conv("c", np.full((1, 1, 1), 70000.0 * 128, np.float32))
71
72    def test_shift_table_matches_the_decoder(self):
73        """vae_ref's CONV_SHIFTS is the table of src/image/vae/wan_vae.cu conv_shift(), so "f16op" models our operands."""
74        import re
75        cu = (Path(__file__).resolve().parents[3] / "src" / "image" / "vae" / "wan_vae.cu").read_text(encoding="utf-8")
76        body = cu[cu.index("int conv_shift(const std::string& name) {"):]
77        body = body[:body.index("\n}\n")]
78        table = {m.group(1): int(m.group(2)) for m in re.finditer(r'if \(name == "([^"]+)"\) return (\d+);', body)}
79        self.assertEqual(table, V.CONV_SHIFTS)
80        self.assertIn("return CONV_SHIFT;", body)
81        self.assertIn("constexpr int CONV_SHIFT = 7;", cu)
82
83    def test_bf16_reader(self):
84        vals = np.array([1.0, -2.5, 0.15625], np.float32)
85        raw = (vals.view(np.uint32) >> 16).astype(np.uint16).tobytes()
86        hdr = json.dumps({"t": {"dtype": "BF16", "shape": [3], "data_offsets": [0, len(raw)]}}).encode()
87        with tempfile.TemporaryDirectory() as d:
88            p = Path(d) / "m.safetensors"
89            p.write_bytes(struct.pack("<Q", len(hdr)) + hdr + raw)
90            self.assertEqual(V.load_safetensors(p)["t"].tolist(), vals.tolist())
91
92
93def tiny_model(rng, dims=(16, 16, 16, 8, 4, 2), z=64):
94    w = {}
95
96    def conv(name, o, i, k):
97        w[name + ".weight"] = (rng.standard_normal((o, i, k, k)) / np.sqrt(i * k * k)).astype(np.float32)
98        w[name + ".bias"] = (0.1 * rng.standard_normal(o)).astype(np.float32)
99
100    def norm(name, c):
101        w[name + ".gamma"] = (1 + 0.1 * rng.standard_normal((c, 1, 1, 1))).astype(np.float32)
102
103    def resnet(p, i, o):
104        norm(p + ".norm1", i)
105        conv(p + ".conv1", o, i, 3)
106        norm(p + ".norm2", o)
107        conv(p + ".conv2", o, o, 3)
108        if i != o:
109            conv(p + ".conv_shortcut", o, i, 1)
110
111    conv("post_quant_conv", z, z, 1)
112    conv("decoder.conv_in", dims[0], z, 3)
113    resnet("decoder.mid_block.resnets.0", dims[0], dims[0])
114    norm("decoder.mid_block.attentions.0.norm", dims[0])
115    conv("decoder.mid_block.attentions.0.to_qkv", 3 * dims[0], dims[0], 1)
116    conv("decoder.mid_block.attentions.0.proj", dims[0], dims[0], 1)
117    resnet("decoder.mid_block.resnets.1", dims[0], dims[0])
118    for i in range(5):
119        cin, cout = dims[i], dims[i + 1]
120        for j in range(3):
121            resnet(f"decoder.up_blocks.{i}.resnets.{j}", cin if j == 0 else cout, cout)
122        if V.UP_BLOCKS[i][3]:
123            conv(f"decoder.up_blocks.{i}.upsampler.resample.1", cout, cout, 3)
124    norm("decoder.norm_out", dims[-1])
125    conv("decoder.conv_out", 4, dims[-1], 3)
126    return w
127
128
129class TinyDecoder(unittest.TestCase):
130    def test_shapes_and_modes(self):
131        rng = np.random.default_rng(3)
132        w = tiny_model(rng)
133        lat = rng.standard_normal((64, 2, 3)).astype(np.float32)
134        a = V.Decoder(w, "f32").decode(lat)
135        b = V.Decoder(w, "f16op").decode(lat)
136        self.assertEqual(a.shape, (32, 48, 4))
137        self.assertTrue(np.isfinite(a).all())
138        rel = np.linalg.norm(a - b) / np.linalg.norm(a)
139        self.assertLess(rel, 1e-2)          # f16 operands move the result a little, not a lot
140        self.assertGreater(rel, 0.0)
141
142    def test_stage_dump(self):
143        rng = np.random.default_rng(4)
144        d = {}
145        V.Decoder(tiny_model(rng), "f32").decode(rng.standard_normal((64, 2, 2)).astype(np.float32), dump=d)
146        self.assertEqual([d[k].shape[:2] for k in ("conv_in", "up0", "up3", "up4", "out")],
147                         [(2, 2), (4, 4), (32, 32), (32, 32), (32, 32)])
148
149
150if __name__ == "__main__":
151    unittest.main()