okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
736266e87
main
1"""tools/image/gate/vae_ref.py - TEST-ONLY (OWN-5 gate harness): a numpy reference of Qwen-Image-2.1's VAE decoder, as 2stable-diffusion.cpp 2988060 runs it for one picture (src/model/vae/wan_vae.hpp, VERSION_QWEN_IMAGE_2_1, 2D weights). 3 4It is the oracle for our own GPU decoder (src/image/vae): the per-stage values, the activation ranges (what must fit 5the f16 operands), and the f32 picture our decode is measured against besides sd.cpp's own. "f16op" uses our decoder's per-layer operand 6shifts (CONV_SHIFTS; shifts=False for sd.cpp's 2^-7 everywhere). 7 8The decoder, pixel-major (HWC, float32): latent (64 ch) -> post_quant_conv 1x1 -> conv_in 3x3 (1152) -> mid block 9(resnet, attention, resnet) -> up_blocks 0..4 (1152, 1152, 576, 288, 144 channels; 3 resnets each; blocks 0-3 end in 10nearest-2x + 3x3 conv and add a channel-to-space "DupUp" shortcut of the block's input) -> norm_out -> SiLU -> conv_out 113x3 (4 channels: RGBA in [-1, 1]). A resnet is h = shortcut(x); x = conv2(silu(norm2(conv1(silu(norm1(x)))))) + h; 12the norm is an RMS norm over the channels of each pixel (eps 1e-12) times gamma. The attention is one head over all 13latent pixels, dim 1152, scale 1/sqrt(1152), q/k/v = channels [0,C), [C,2C), [2C,3C) of to_qkv. 14The temporal parts of the Wan decoder (time_conv, the frame cache) do nothing for one picture and are left out. 15 16Two arithmetic modes: 17"f32" weights bf16 -> f32 (exact), every operation in float32 (matmuls in float64, rounded to float32). 18"f16op" the operands of every convolution as sd.cpp and our GPU decoder see them: weights bf16 -> f16 (round to 19nearest even), inputs x * 2^-7 rounded to f16, the product accumulated exactly (float64) and x 2^7; the rest 20float32. This is "f16 operands, exact accumulation": our GPU decode (f32 accumulation) must be close to it. 21 22python -I -B vae_ref.py <vae.safetensors> <latent.bin> <out.npy> [--mode f32|f16op] [--stats] 23latent.bin: float32 [64, H, W] as run_set.py --dump writes it (the diffusion-space latent; shape file says 24"W H 64 1"); out.npy: float32 [H*16, W*16, 4] in [-1, 1] before sd.cpp's 0-1 scaling 25python -I -B vae_ref.py --png <out.npy> <out.png> sd.cpp's 8-bit conversion, RGBA PNG (needs Pillow)""" 26from __future__import annotations 27 28import json 29import struct 30import sys 31from pathlib import Path 32 33import numpy as np 34 35# wan_vae.hpp get_latents_mean_std, VERSION_QWEN_IMAGE_2_1, 64 channels 36LATENT_MEAN = [0.5126 ,0.7721 ,- 0.0631 ,1.3506 ,- 0.7855 ,- 2.1025 ,- 0.3458 ,1.3722 , 371.8873 ,- 1.7177 ,- 0.6510 ,0.2732 ,0.7562 ,- 0.6163 ,- 1.0277 ,3.8363 , 382.0210 ,0.0472 ,0.9320 ,2.0087 ,2.4954 ,- 0.1391 ,- 1.4249 ,1.8464 , 39- 0.5236 ,1.2826 ,3.7046 ,- 1.3035 ,2.7286 ,- 1.4518 ,- 1.9036 ,- 1.9955 , 40- 0.0342 ,- 1.0265 ,- 0.7636 ,3.0555 ,0.0746 ,- 3.0751 ,- 0.1076 ,1.7376 , 41- 1.0914 ,- 1.9435 ,- 0.2784 ,- 1.3680 ,0.4809 ,- 0.4433 ,0.3764 ,0.5729 , 42- 2.0595 ,1.0960 ,- 1.3260 ,- 2.0211 ,- 5.0179 ,0.5275 ,4.0162 ,1.8505 , 430.3026 ,1.9373 ,1.4937 ,0.2632 ,0.5547 ,- 1.7121 ,- 0.1562 ,0.0304 ] 44LATENT_STD = [3.2001 ,3.2936 ,3.4321 ,3.0091 ,3.1061 ,4.0379 ,4.0705 ,3.7910 , 453.0785 ,3.6500 ,3.9308 ,3.0904 ,2.8778 ,3.7675 ,3.7320 ,5.0756 , 463.2864 ,4.0397 ,3.1317 ,4.0443 ,2.9249 ,3.9454 ,3.0988 ,4.2489 , 473.4896 ,3.8513 ,3.9323 ,3.4719 ,3.7498 ,4.2830 ,3.5694 ,4.2467 , 483.9037 ,3.2947 ,5.0770 ,3.5075 ,3.2700 ,3.4767 ,2.8063 ,5.1125 , 493.5327 ,4.7833 ,3.1286 ,4.1819 ,3.8527 ,3.8312 ,3.5605 ,4.3875 , 503.9624 ,4.0168 ,3.5643 ,4.0550 ,5.5614 ,4.2963 ,4.4080 ,3.4959 , 513.8747 ,3.7608 ,3.5735 ,3.1490 ,3.7662 ,3.6746 ,3.4563 ,3.8161 ] 52 53CONV_SCALE = np .float32 (1.0 / 128.0 )# wan_vae.hpp: "Keep large VAE activations within the FP16 convolution range" 54# Strata's decoder (src/image/vae/wan_vae.cu conv_shift) uses other fixed shifts for these layers (f16 headroom) 55CONV_SHIFTS = {"decoder.up_blocks.4.resnets.0.conv_shortcut" :11 } 56F16_MAX = 65504.0 57# up block i: (in, out, DupUp factor_t, has upsampler); wan_vae.hpp temperal_upsample {true, true, true, false} 58UP_BLOCKS = [(1152 ,1152 ,2 ,True ), (1152 ,1152 ,2 ,True ), (1152 ,576 ,2 ,True ), (576 ,288 ,1 ,True ), (288 ,144 ,1 ,False )] 59 60 61def bf16_to_f32 (raw :bytes )-> np .ndarray : 62u = np .frombuffer (raw ,dtype = np .uint16 ).astype (np .uint32 )<< 16 63return u .view (np .float32 ) 64 65 66def load_safetensors (path ,prefix = "" )-> dict : 67"""name -> float32 array (bf16 and f32 tensors only), for names starting with prefix.""" 68out = {} 69with open (path ,"rb" )as f : 70n = struct .unpack ("<Q" ,f .read (8 ))[0 ] 71hdr = json .loads (f .read (n )) 72base = 8 + n 73for name ,e in hdr .items (): 74if name == "__metadata__" or not name .startswith (prefix ): 75continue 76a ,b = e ["data_offsets" ] 77f .seek (base + a ) 78raw = f .read (b - a ) 79if e ["dtype" ]== "BF16" : 80arr = bf16_to_f32 (raw ) 81elif e ["dtype" ]== "F32" : 82arr = np .frombuffer (raw ,dtype = np .float32 ).copy () 83else : 84raise ValueError (f" { name } : dtype { e [ 'dtype' ] } " ) 85out [name ]= arr .reshape (e ["shape" ]) 86return out 87 88 89class Decoder : 90def __init__ (self ,weights :dict ,mode :str = "f32" ,stats :bool = False ,shifts :bool = True ): 91"""shifts: Strata's per-layer operand shifts (CONV_SHIFTS); False = sd.cpp's 2^-7 everywhere ("f16op" only 92differs; in "f32" a power-of-two scale is exact).""" 93assert mode in ("f32" ,"f16op" ) 94self .w ,self .mode ,self .shifts = weights ,mode ,shifts 95self .stats = {}if stats else None 96self .cache = {} 97 98# --- building blocks ---------------------------------------------------------------------------------------- 99def _conv_w (self ,name ): 100"""[OC, IC, KH, KW] -> [KH*KW*IC, OC] (row index (ky, kx, ic)), float64, with the mode's weight rounding.""" 101if name not in self .cache : 102w = self .w [name + ".weight" ] 103if self .mode == "f16op" : 104w = w .astype (np .float16 ).astype (np .float32 ) 105oc ,ic ,kh ,kw = w .shape 106self .cache [name ]= (w .transpose (2 ,3 ,1 ,0 ).reshape (kh * kw * ic ,oc ).astype (np .float64 ),kh , 107self .w [name + ".bias" ].astype (np .float32 )) 108return self .cache [name ] 109 110def _note (self ,name ,x ): 111if self .stats is not None : 112self .stats [name ]= float (np .abs (x ).max ()) 113 114def conv (self ,name ,x ,rows_per_chunk = None ): 115"""3x3 (pad 1) or 1x1 conv of x [H, W, IC] -> [H, W, OC]; the input scaled by 2^-7 like sd.cpp.""" 116wm ,k ,bias = self ._conv_w (name ) 117H ,W ,C = x .shape 118scale = np .float32 (2.0 ** - CONV_SHIFTS .get (name ,7 ))if self .shifts else CONV_SCALE 119xs = x * scale 120self ._note (name + ":in_scaled" ,xs ) 121if self .mode == "f16op" : 122if np .abs (xs ).max ()> F16_MAX : 123raise OverflowError (f" { name } : conv input exceeds the f16 range after its scale" ) 124xs = xs .astype (np .float16 ).astype (np .float32 ) 125oc = wm .shape [1 ] 126out = np .empty ((H ,W ,oc ),dtype = np .float32 ) 127if k == 1 : 128out [:]= (xs .reshape (- 1 ,C ).astype (np .float64 ) @wm ).reshape (H ,W ,oc ) 129else : 130pad = np .zeros ((H + 2 ,W + 2 ,C ),dtype = np .float32 ) 131pad [1 :- 1 ,1 :- 1 ]= xs 132step = rows_per_chunk or max (1 , (1 << 26 )// (W * 9 * C )) 133for y0 in range (0 ,H ,step ): 134y1 = min (H ,y0 + step ) 135cols = np .concatenate ([pad [y0 + dy :y1 + dy ,dx :dx + W ]for dy in range (3 )for dx in range (3 )],axis = 2 ) 136out [y0 :y1 ]= (cols .reshape (- 1 ,9 * C ).astype (np .float64 ) @wm ).reshape (y1 - y0 ,W ,oc ) 137out = out / scale # x 2^shift: exact 138out += bias 139return out 140 141def rms (self ,name ,x ): 142"""RMS norm over channels, eps 1e-12, times gamma (ggml_rms_norm: mean of squares in float32 terms).""" 143g = self .w [name + ".gamma" ].reshape (- 1 ).astype (np .float32 ) 144ms = np .mean (x .astype (np .float64 )** 2 ,axis = 2 ,keepdims = True ) 145return (x * (1.0 / np .sqrt (ms + 1e-12 )).astype (np .float32 ))* g 146 147@staticmethod 148def silu (x ): 149return x / (np .float32 (1.0 )+ np .exp (- x )) 150 151def resnet (self ,p ,x ): 152h = self .conv (p + ".conv_shortcut" ,x )if (p + ".conv_shortcut.weight" )in self .w else x 153t = self .conv (p + ".conv1" ,self .silu (self .rms (p + ".norm1" ,x ))) 154t = self .conv (p + ".conv2" ,self .silu (self .rms (p + ".norm2" ,t ))) 155self ._note (p ,t + h ) 156return t + h 157 158def attention (self ,p ,x ): 159H ,W ,C = x .shape 160qkv = self .conv (p + ".to_qkv" ,self .rms (p + ".norm" ,x )).reshape (H * W ,3 * C ).astype (np .float64 ) 161q ,k ,v = qkv [:, :C ],qkv [:,C :2 * C ],qkv [:,2 * C :] 162s = (q @k .T )/ np .sqrt (C ) 163s -= s .max (axis = 1 ,keepdims = True ) 164e = np .exp (s ) 165a = ((e / e .sum (axis = 1 ,keepdims = True )) @v ).astype (np .float32 ).reshape (H ,W ,C ) 166return self .conv (p + ".proj" ,a )+ x 167 168@staticmethod 169def dup_up (x ,out_c ,ft ,fs = 2 ): 170"""wan_vae.hpp DupUp3D for one frame (first_chunk): output channel oc at sub-position (i, j) of each 2x2 cell 171takes input channel (oc*ft*fs*fs + (ft-1)*fs*fs + i*fs + j) // repeats.""" 172H ,W ,C = x .shape 173repeats = out_c * ft * fs * fs // C 174y = np .empty ((H * fs ,W * fs ,out_c ),dtype = np .float32 ) 175oc = np .arange (out_c ) 176for i in range (fs ): 177for j in range (fs ): 178src = (oc * ft * fs * fs + (ft - 1 )* fs * fs + i * fs + j )// repeats 179y [i ::fs ,j ::fs ]= x [:, :,src ] 180return y 181 182@staticmethod 183def up2 (x ): 184return x .repeat (2 ,axis = 0 ).repeat (2 ,axis = 1 ) 185 186# --- the decoder -------------------------------------------------------------------------------------------- 187def decode (self ,latent_chw :np .ndarray ,dump = None )-> np .ndarray : 188"""latent_chw: the diffusion-space latent [64, h, w] -> float32 [16h, 16w, 4] in about [-1, 1].""" 189mean = np .array (LATENT_MEAN ,dtype = np .float32 ).reshape (64 ,1 ,1 ) 190std = np .array (LATENT_STD ,dtype = np .float32 ).reshape (64 ,1 ,1 ) 191z = (latent_chw .astype (np .float32 )* std )/ np .float32 (1.0 )+ mean # diffusion_to_vae_latents 192x = np .ascontiguousarray (z .transpose (1 ,2 ,0 )) 193d = dump if dump is not None else {} 194x = self .conv ("post_quant_conv" ,x ) 195x = self .conv ("decoder.conv_in" ,x ) 196d ["conv_in" ]= x 197x = self .resnet ("decoder.mid_block.resnets.0" ,x ) 198x = self .attention ("decoder.mid_block.attentions.0" ,x ) 199d ["mid_attn" ]= x 200x = self .resnet ("decoder.mid_block.resnets.1" ,x ) 201d ["mid" ]= x 202for i , (_ ,_ ,ft ,up )in enumerate (UP_BLOCKS ): 203p = f"decoder.up_blocks. { i } " 204x0 = x 205for j in range (3 ): 206x = self .resnet (f" { p } .resnets. { j } " ,x ) 207if up : 208x = self .conv (f" { p } .upsampler.resample.1" ,self .up2 (x ))+ self .dup_up (x0 ,x .shape [2 ],ft ) 209d [f"up { i } " ]= x 210x = self .conv ("decoder.conv_out" ,self .silu (self .rms ("decoder.norm_out" ,x ))) 211d ["out" ]= x 212return x 213 214 215def to_u8 (img :np .ndarray )-> np .ndarray : 216"""sd.cpp: v = clamp((x + 1) * 0.5, 0, 1); u8 = v <= 0 ? 0 : v >= 1 ? 255 : (uint8)(v * 255 + 0.5).""" 217v = np .clip ((img .astype (np .float32 )+ np .float32 (1 ))* np .float32 (0.5 ),0 ,1 ) 218u = (v * np .float32 (255 )+ np .float32 (0.5 )).astype (np .uint8 ) 219u [v <= 0 ]= 0 220u [v >= 1 ]= 255 221return u 222 223 224def read_latent (path )-> np .ndarray : 225shape_file = Path (str (path )[:- 4 ]+ ".shape" ) 226w ,h ,c = [int (s )for s in shape_file .read_text ().split ()[:3 ]] 227return np .fromfile (path ,dtype = np .float32 ).reshape (c ,h ,w ) 228 229 230def main (argv ): 231if argv [:1 ]== ["--png" ]: 232from PIL import Image 233Image .fromarray (to_u8 (np .load (argv [1 ])),"RGBA" ).save (argv [2 ]) 234return 0 235if len (argv )< 3 : 236__doc__ ) 237return 2 238mode = argv [argv .index ("--mode" )+ 1 ]if "--mode" in argv else "f32" 239dec = Decoder (load_safetensors (argv [0 ]),mode = mode ,stats = "--stats" in argv ) 240out = dec .decode (read_latent (argv [1 ])) 241np .save (argv [2 ],out ) 242f"decoded { out . shape } mode { mode } : min { out . min ():.4f } max { out . max ():.4f } " ) 243if dec .stats is not None : 244worst = max (dec .stats .items (),key = lambda kv :kv [1 ]if kv [0 ].endswith (":in_scaled" )else - 1 ) 245f"largest conv input after the 2^-7 scale: { worst [ 1 ]:.1f } at { worst [ 0 ] } (f16 max { F16_MAX } )" ) 246for k ,v in dec .stats .items (): 247f" { k } { v :.4g } " ) 248return 0 249 250 251if __name__ == "__main__" : 252sys .exit (main (sys .argv [1 :]))