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
4.9 KiB107 linesraw
1"""tools/image/gate/test_vae_convert.py - TEST-ONLY: src/image/vae/convert.hpp (the VAE decoder's weight conversion at
2open, split over threads) gives the same bytes with 1 thread and with several, on every bf16 bit pattern (zeros,
3subnormals, infinities, NaN payloads, values that round up into the next exponent), agrees with numpy's float16
4rounding on every non-NaN pattern, keeps NaN a NaN, and lays a convolution's weights out as [oc][tap][ic].
5Builds a small C++ program with the host compiler; skipped when there is none.
6
7    python -m pytest tools/image/gate/test_vae_convert.py"""
8import shutil
9import subprocess
10import tempfile
11import unittest
12from pathlib import Path
13
14import numpy as np
15
16ROOT = Path(__file__).resolve().parents[3]
17CXX = shutil.which("g++") or shutil.which("clang++")
18
19PROGRAM = r'''
20#include "convert.hpp"
21#include <cstdio>
22#include <cstdlib>
23#include <vector>
24// argv: in.bin (bf16 bytes) oc ic taps threads out.bin  -> out: f32 of every value, then the f16 conv layout
25int main(int argc, char** argv) {
26    FILE* f = std::fopen(argv[1], "rb");
27    std::vector<unsigned char> raw;
28    int c;
29    while ((c = std::fgetc(f)) != EOF) raw.push_back((unsigned char) c);
30    std::fclose(f);
31    const int oc = std::atoi(argv[2]), ic = std::atoi(argv[3]), taps = std::atoi(argv[4]), th = std::atoi(argv[5]);
32    const size_t n = raw.size() / 2;
33    std::vector<float> w(n);
34    strata::image::bf16_to_f32(raw.data(), n, w.data(), th);
35    std::vector<uint16_t> h((size_t) oc * ic * taps);
36    strata::image::bf16_conv_to_f16(raw.data(), oc, ic, taps, h.data(), th);
37    FILE* o = std::fopen(argv[6], "wb");
38    std::fwrite(w.data(), 4, n, o);
39    std::fwrite(h.data(), 2, h.size(), o);
40    std::fclose(o);
41    return 0;
42}
43'''
44
45
46@unittest.skipUnless(CXX, "no host C++ compiler")
47class Convert(unittest.TestCase):
48    @classmethod
49    def setUpClass(cls):
50        cls.tmp = tempfile.TemporaryDirectory()
51        d = Path(cls.tmp.name)
52        (d / "t.cpp").write_text(PROGRAM)
53        cls.exe = d / "conv_test"
54        subprocess.run([CXX, "-std=c++17", "-O2", "-pthread", "-I", str(ROOT / "src" / "image" / "vae"),
55                        "-I", str(ROOT / "include"), str(d / "t.cpp"), "-o", str(cls.exe)], check=True)
56
57    @classmethod
58    def tearDownClass(cls):
59        cls.tmp.cleanup()
60
61    def run_prog(self, bits: np.ndarray, oc, ic, taps, threads):
62        d = Path(self.tmp.name)
63        (d / "in.bin").write_bytes(bits.astype("<u2").tobytes())
64        subprocess.run([str(self.exe), str(d / "in.bin"), str(oc), str(ic), str(taps), str(threads),
65                        str(d / "out.bin")], check=True)
66        out = (d / "out.bin").read_bytes()
67        n = bits.size
68        return np.frombuffer(out[:4 * n], dtype="<f4"), np.frombuffer(out[4 * n:], dtype="<u2")
69
70    def test_every_bf16_pattern_same_bytes_for_any_thread_count(self):
71        bits = np.arange(65536, dtype=np.uint32).astype(np.uint16)           # oc 256 x ic 64 x taps 4
72        f1, h1 = self.run_prog(bits, 256, 64, 4, 1)
73        for th in (2, 7, 16):
74            with self.subTest(threads=th):
75                fn, hn = self.run_prog(bits, 256, 64, 4, th)
76                self.assertEqual(f1.tobytes(), fn.tobytes())
77                self.assertEqual(h1.tobytes(), hn.tobytes())
78
79    def test_values_against_numpy(self):
80        bits = np.arange(65536, dtype=np.uint32).astype(np.uint16)
81        f, h = self.run_prog(bits, 65536, 1, 1, 3)                             # layout = identity for ic = taps = 1
82        want_f = (bits.astype(np.uint32) << 16).view(np.float32)
83        self.assertEqual(f.view(np.uint32).tolist(), want_f.view(np.uint32).tolist())     # bf16 -> f32 is exact
84        nan = np.isnan(want_f)
85        with np.errstate(over="ignore"):
86            want_h = want_f.astype(np.float16).view(np.uint16)
87        self.assertEqual(h[~nan].tolist(), want_h[~nan].tolist())               # RNE, subnormals, overflow -> inf
88        self.assertTrue(np.isnan(h[nan].view(np.float16)).all())                # a NaN stays a NaN
89        # the interesting cases are really in the set
90        hv = h.view(np.float16)
91        self.assertTrue(((want_f != 0) & (np.abs(want_f) < 2 ** -14) & (hv != 0)).any())   # f16 subnormals
92        self.assertTrue(np.isinf(hv[np.isfinite(want_f)]).any())                # finite bf16 that overflows f16
93        self.assertTrue(np.isinf(want_f).any() and nan.any())
94
95    def test_layout(self):
96        rng = np.random.default_rng(5)
97        oc, ic, taps = 3, 4, 9
98        w = rng.standard_normal((oc, ic, taps)).astype(np.float32)
99        bits = (w.view(np.uint32) >> 16).astype(np.uint16)                      # truncate to bf16
100        _, h = self.run_prog(bits.reshape(-1), oc, ic, taps, 2)
101        wf = (bits.astype(np.uint32) << 16).view(np.float32)
102        want = wf.transpose(0, 2, 1).reshape(oc, taps * ic).astype(np.float16).view(np.uint16)
103        self.assertEqual(h.reshape(oc, taps * ic).tolist(), want.tolist())
104
105
106if __name__ == "__main__":
107    unittest.main()