okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
736266e87
main
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 4python -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: 20repeat_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).""" 22C ,H ,W = x_chw .shape 23repeats = out_c * ft * fs * fs // C 24x = np .repeat (x_chw [:,None ],1 ,axis = 1 )# [C, T=1, H, W] 25x = np .repeat (x ,repeats ,axis = 0 )# repeat_interleave over channels 26x = x .reshape (out_c ,ft ,fs ,fs ,1 ,H ,W ).transpose (0 ,4 ,1 ,5 ,2 ,6 ,3 ) 27x = x .reshape (out_c ,ft ,H * fs ,W * fs ) 28return x [:,ft - 1 ]# [out_c, 2H, 2W] 29 30 31class Pieces (unittest .TestCase ): 32def test_dup_up_matches_the_torch_form (self ): 33rng = np .random .default_rng (1 ) 34for c ,out_c ,ft in [(8 ,8 ,2 ), (8 ,4 ,2 ), (8 ,4 ,1 ), (12 ,6 ,1 )]: 35x = rng .standard_normal ((3 ,5 ,c )).astype (np .float32 ) 36got = V .Decoder .dup_up (x ,out_c ,ft ) 37want = dup_up_torch_form (x .transpose (2 ,0 ,1 ),out_c ,ft ).transpose (1 ,2 ,0 ) 38self .assertTrue (np .array_equal (got ,want ), (c ,out_c ,ft )) 39 40def test_conv3x3_matches_direct_loops (self ): 41rng = np .random .default_rng (2 ) 42H ,W ,C ,O = 5 ,6 ,3 ,4 43w = rng .standard_normal ((O ,C ,3 ,3 )).astype (np .float32 ) 44b = rng .standard_normal (O ).astype (np .float32 ) 45x = rng .standard_normal ((H ,W ,C )).astype (np .float32 ) 46dec = V .Decoder ({"c.weight" :w ,"c.bias" :b }) 47got = dec .conv ("c" ,x ,rows_per_chunk = 2 ) 48pad = np .zeros ((H + 2 ,W + 2 ,C ),np .float64 ) 49pad [1 :- 1 ,1 :- 1 ]= x 50want = np .zeros ((H ,W ,O )) 51for y in range (H ): 52for xx in range (W ): 53for o in range (O ): 54want [y ,xx ,o ]= np .sum (pad [y :y + 3 ,xx :xx + 3 , :]* w [o ].transpose (1 ,2 ,0 ))+ b [o ] 55self .assertLess (np .abs (got - want ).max (),1e-5 ) 56 57def test_rms_norm_by_hand (self ): 58dec = V .Decoder ({"n.gamma" :np .array ([[[1.0 ]], [[2.0 ]]],np .float32 )}) 59out = dec .rms ("n" ,np .array ([[[3.0 ,4.0 ]]],np .float32 ))# rms = sqrt(12.5) 60r = np .sqrt (12.5 ) 61self .assertTrue (np .allclose (out , [[[3 / r ,8 / r ]]],rtol = 1e-6 )) 62 63def test_to_u8 (self ): 64u = V .to_u8 (np .array ([- 2.0 ,- 1.0 ,0.0 ,1.0 ,3.0 ,0.5 ],np .float32 )) 65self .assertEqual (u .tolist (), [0 ,0 ,128 ,255 ,255 ,191 ]) 66 67def test_f16op_refuses_inputs_beyond_f16 (self ): 68dec = V .Decoder ({"c.weight" :np .ones ((1 ,1 ,1 ,1 ),np .float32 ),"c.bias" :np .zeros (1 ,np .float32 )},mode = "f16op" ) 69with self .assertRaises (OverflowError ): 70dec .conv ("c" ,np .full ((1 ,1 ,1 ),70000.0 * 128 ,np .float32 )) 71 72def 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.""" 74import re 75cu = (Path (__file__ ).resolve ().parents [3 ]/ "src" / "image" / "vae" / "wan_vae.cu" ).read_text (encoding = "utf-8" ) 76body = cu [cu .index ("int conv_shift(const std::string& name) {" ):] 77body = body [:body .index ("\n}\n" )] 78table = {m .group (1 ):int (m .group (2 ))for m in re .finditer (r'if \(name == "([^"]+)"\) return (\d+);' ,body )} 79self .assertEqual (table ,V .CONV_SHIFTS ) 80self .assertIn ("return CONV_SHIFT;" ,body ) 81self .assertIn ("constexpr int CONV_SHIFT = 7;" ,cu ) 82 83def test_bf16_reader (self ): 84vals = np .array ([1.0 ,- 2.5 ,0.15625 ],np .float32 ) 85raw = (vals .view (np .uint32 )>> 16 ).astype (np .uint16 ).tobytes () 86hdr = json .dumps ({"t" : {"dtype" :"BF16" ,"shape" : [3 ],"data_offsets" : [0 ,len (raw )]}}).encode () 87with tempfile .TemporaryDirectory ()as d : 88p = Path (d )/ "m.safetensors" 89p .write_bytes (struct .pack ("<Q" ,len (hdr ))+ hdr + raw ) 90self .assertEqual (V .load_safetensors (p )["t" ].tolist (),vals .tolist ()) 91 92 93def tiny_model (rng ,dims = (16 ,16 ,16 ,8 ,4 ,2 ),z = 64 ): 94w = {} 95 96def conv (name ,o ,i ,k ): 97w [name + ".weight" ]= (rng .standard_normal ((o ,i ,k ,k ))/ np .sqrt (i * k * k )).astype (np .float32 ) 98w [name + ".bias" ]= (0.1 * rng .standard_normal (o )).astype (np .float32 ) 99 100def norm (name ,c ): 101w [name + ".gamma" ]= (1 + 0.1 * rng .standard_normal ((c ,1 ,1 ,1 ))).astype (np .float32 ) 102 103def resnet (p ,i ,o ): 104norm (p + ".norm1" ,i ) 105conv (p + ".conv1" ,o ,i ,3 ) 106norm (p + ".norm2" ,o ) 107conv (p + ".conv2" ,o ,o ,3 ) 108if i != o : 109conv (p + ".conv_shortcut" ,o ,i ,1 ) 110 111conv ("post_quant_conv" ,z ,z ,1 ) 112conv ("decoder.conv_in" ,dims [0 ],z ,3 ) 113resnet ("decoder.mid_block.resnets.0" ,dims [0 ],dims [0 ]) 114norm ("decoder.mid_block.attentions.0.norm" ,dims [0 ]) 115conv ("decoder.mid_block.attentions.0.to_qkv" ,3 * dims [0 ],dims [0 ],1 ) 116conv ("decoder.mid_block.attentions.0.proj" ,dims [0 ],dims [0 ],1 ) 117resnet ("decoder.mid_block.resnets.1" ,dims [0 ],dims [0 ]) 118for i in range (5 ): 119cin ,cout = dims [i ],dims [i + 1 ] 120for j in range (3 ): 121resnet (f"decoder.up_blocks. { i } .resnets. { j } " ,cin if j == 0 else cout ,cout ) 122if V .UP_BLOCKS [i ][3 ]: 123conv (f"decoder.up_blocks. { i } .upsampler.resample.1" ,cout ,cout ,3 ) 124norm ("decoder.norm_out" ,dims [- 1 ]) 125conv ("decoder.conv_out" ,4 ,dims [- 1 ],3 ) 126return w 127 128 129class TinyDecoder (unittest .TestCase ): 130def test_shapes_and_modes (self ): 131rng = np .random .default_rng (3 ) 132w = tiny_model (rng ) 133lat = rng .standard_normal ((64 ,2 ,3 )).astype (np .float32 ) 134a = V .Decoder (w ,"f32" ).decode (lat ) 135b = V .Decoder (w ,"f16op" ).decode (lat ) 136self .assertEqual (a .shape , (32 ,48 ,4 )) 137self .assertTrue (np .isfinite (a ).all ()) 138rel = np .linalg .norm (a - b )/ np .linalg .norm (a ) 139self .assertLess (rel ,1e-2 )# f16 operands move the result a little, not a lot 140self .assertGreater (rel ,0.0 ) 141 142def test_stage_dump (self ): 143rng = np .random .default_rng (4 ) 144d = {} 145V .Decoder (tiny_model (rng ),"f32" ).decode (rng .standard_normal ((64 ,2 ,2 )).astype (np .float32 ),dump = d ) 146self .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__" : 151unittest .main ()