okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
736266e87
main
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 7python -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) { 26FILE* f = std::fopen(argv[1], "rb"); 27std::vector<unsigned char> raw; 28int c; 29while ((c = std::fgetc(f)) != EOF) raw.push_back((unsigned char) c); 30std::fclose(f); 31const int oc = std::atoi(argv[2]), ic = std::atoi(argv[3]), taps = std::atoi(argv[4]), th = std::atoi(argv[5]); 32const size_t n = raw.size() / 2; 33std::vector<float> w(n); 34strata::image::bf16_to_f32(raw.data(), n, w.data(), th); 35std::vector<uint16_t> h((size_t) oc * ic * taps); 36strata::image::bf16_conv_to_f16(raw.data(), oc, ic, taps, h.data(), th); 37FILE* o = std::fopen(argv[6], "wb"); 38std::fwrite(w.data(), 4, n, o); 39std::fwrite(h.data(), 2, h.size(), o); 40std::fclose(o); 41return 0; 42} 43''' 44 45 46@ unittest . skipUnless ( CXX , "no host C++ compiler" ) 47class Convert (unittest .TestCase ): 48@classmethod 49def setUpClass (cls ): 50cls .tmp = tempfile .TemporaryDirectory () 51d = Path (cls .tmp .name ) 52 (d / "t.cpp" ).write_text (PROGRAM ) 53cls .exe = d / "conv_test" 54subprocess .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 58def tearDownClass (cls ): 59cls .tmp .cleanup () 60 61def run_prog (self ,bits :np .ndarray ,oc ,ic ,taps ,threads ): 62d = Path (self .tmp .name ) 63 (d / "in.bin" ).write_bytes (bits .astype ("<u2" ).tobytes ()) 64subprocess .run ([str (self .exe ),str (d / "in.bin" ),str (oc ),str (ic ),str (taps ),str (threads ), 65str (d / "out.bin" )],check = True ) 66out = (d / "out.bin" ).read_bytes () 67n = bits .size 68return np .frombuffer (out [:4 * n ],dtype = "<f4" ),np .frombuffer (out [4 * n :],dtype = "<u2" ) 69 70def test_every_bf16_pattern_same_bytes_for_any_thread_count (self ): 71bits = np .arange (65536 ,dtype = np .uint32 ).astype (np .uint16 )# oc 256 x ic 64 x taps 4 72f1 ,h1 = self .run_prog (bits ,256 ,64 ,4 ,1 ) 73for th in (2 ,7 ,16 ): 74with self .subTest (threads = th ): 75fn ,hn = self .run_prog (bits ,256 ,64 ,4 ,th ) 76self .assertEqual (f1 .tobytes (),fn .tobytes ()) 77self .assertEqual (h1 .tobytes (),hn .tobytes ()) 78 79def test_values_against_numpy (self ): 80bits = np .arange (65536 ,dtype = np .uint32 ).astype (np .uint16 ) 81f ,h = self .run_prog (bits ,65536 ,1 ,1 ,3 )# layout = identity for ic = taps = 1 82want_f = (bits .astype (np .uint32 )<< 16 ).view (np .float32 ) 83self .assertEqual (f .view (np .uint32 ).tolist (),want_f .view (np .uint32 ).tolist ())# bf16 -> f32 is exact 84nan = np .isnan (want_f ) 85with np .errstate (over = "ignore" ): 86want_h = want_f .astype (np .float16 ).view (np .uint16 ) 87self .assertEqual (h [~ nan ].tolist (),want_h [~ nan ].tolist ())# RNE, subnormals, overflow -> inf 88self .assertTrue (np .isnan (h [nan ].view (np .float16 )).all ())# a NaN stays a NaN 89# the interesting cases are really in the set 90hv = h .view (np .float16 ) 91self .assertTrue (((want_f != 0 )& (np .abs (want_f )< 2 ** - 14 )& (hv != 0 )).any ())# f16 subnormals 92self .assertTrue (np .isinf (hv [np .isfinite (want_f )]).any ())# finite bf16 that overflows f16 93self .assertTrue (np .isinf (want_f ).any ()and nan .any ()) 94 95def test_layout (self ): 96rng = np .random .default_rng (5 ) 97oc ,ic ,taps = 3 ,4 ,9 98w = rng .standard_normal ((oc ,ic ,taps )).astype (np .float32 ) 99bits = (w .view (np .uint32 )>> 16 ).astype (np .uint16 )# truncate to bf16 100_ ,h = self .run_prog (bits .reshape (- 1 ),oc ,ic ,taps ,2 ) 101wf = (bits .astype (np .uint32 )<< 16 ).view (np .float32 ) 102want = wf .transpose (0 ,2 ,1 ).reshape (oc ,taps * ic ).astype (np .float16 ).view (np .uint16 ) 103self .assertEqual (h .reshape (oc ,taps * ic ).tolist (),want .tolist ()) 104 105 106if __name__ == "__main__" : 107unittest .main ()