okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
150c2394f
main
1"""tools/image/gate/sampler_ref.py - TEST-ONLY (OWN-5 gate harness): the sampler contract for Qwen-Image-2.1-Turbo, written 2without any fused multiply-add and checked bit for bit against stable-diffusion.cpp 2988060's own final latent. 3 4What sd-cli does for one picture (sample_euler in src/runtime/denoiser.hpp, the denoise callback in 5src/pipeline/diffusion_engine.cpp, DiscreteFlowDenoiser): with the schedule `sigmas` (serve/images.py TURBO_SIGMAS, 9 6values ending in 0), CFG 1, the flow denoiser's scalings c_skip = 1, c_out = -sigma, c_in = 1, and the noise as x: 7for each step i: denoised = v_i * c_out + x * c_skip (two tensor products, then one sum: three float loops) 8d = (x - denoised) / sigma_i (one subtraction loop, one division loop) 9x = x + d * (sigma_i+1 - sigma_i) (one product loop, one sum loop) 10the final x is the latent (inverse noise scaling at sigma 0 is x * (1 / (1 - 0)) = x). 11Every elementwise operation of sd.cpp's Tensor class is its own loop with one float operation in it (src/core/tensor.hpp), 12so nothing can be fused; numpy float32 does the same. All values are float32, every operation rounds to float32. 13 14python -I -B sampler_ref.py <stage root> <tag> e.g. stage st_cuda_stock_A (run_set.py --dump: noise, vel_0..7, 15latent per picture); prints identical / total 16python -I -B sampler_ref.py --self-test""" 17from __future__import annotations 18 19import sys 20from pathlib import Path 21 22import numpy as np 23 24# serve/images.py TURBO_SIGMAS, as sd-cli reads the --sigmas list (strtof: the nearest float32 of each decimal) 25TURBO_SIGMAS = "1.0,0.978453,0.95418,0.926626,0.89508,0.845148,0.704534,0.414568,0.0" 26 27 28def sigmas_f32 (text :str = TURBO_SIGMAS )-> np .ndarray : 29return np .array ([float (x )for x in text .split ("," )],dtype = np .float32 ) 30 31 32def euler_flow (noise :np .ndarray ,velocities :list ,sigmas :np .ndarray )-> np .ndarray : 33"""The final latent from the starting noise and the DiT's output of each step (float32 in, float32 out).""" 34f = np .float32 35assert noise .dtype == np .float32 and len (velocities )== len (sigmas )- 1 36x = noise .copy () 37for i ,v in enumerate (velocities ): 38sigma ,nxt = sigmas [i ],sigmas [i + 1 ] 39if sigma == nxt : 40continue 41c_skip ,c_out = f (1.0 ),f (- sigma ) 42denoised = (v * c_out )+ (x * c_skip ) 43d = (x - denoised )/ sigma 44x = x + d * f (nxt - sigma ) 45return x 46 47 48def load (path :Path )-> np .ndarray : 49return np .fromfile (path ,dtype = "<f4" ) 50 51 52def check (root :Path ,tag :str )-> tuple [int ,int ]: 53sig = sigmas_f32 () 54ok = total = 0 55for d in sorted ((root / tag ).glob ("dump_p*_s*" )): 56try : 57noise = load (d / "noise.bin" ) 58vels = [load (d / f"vel_ { k } .bin" )for k in range (len (sig )- 1 )] 59want = load (d / "latent.bin" ) 60except OSError : 61continue 62got = euler_flow (noise ,vels ,sig ) 63same = bool (np .array_equal (got .view (np .uint32 ),want .view (np .uint32 ))) 64total += 1 65ok += same 66if not same : 67diff = np .flatnonzero (got .view (np .uint32 )!= want .view (np .uint32 )) 68f" { d . name } : { len ( diff ) } of { got . size } values differ, max abs { float ( np . abs ( got - want ). max ()):.3g } " ) 69else : 70f" { d . name } : identical ( { got . size } values)" ) 71f"SAMPLER-REF { tag } : identical { ok } of { total } " ) 72return ok ,total 73 74 75def self_test ()-> None : 76rng = np .random .default_rng (1 ) 77noise = rng .standard_normal (1000 ).astype (np .float32 ) 78vels = [rng .standard_normal (1000 ).astype (np .float32 )for _ in range (8 )] 79sig = sigmas_f32 () 80a = euler_flow (noise ,vels ,sig ) 81assert a .dtype == np .float32 and a .shape == noise .shape 82# one step by hand: denoised = v*-s + x ; d = (x - denoised)/s ; x + d*(0-s) -> x - (x - denoised) = denoised (+-1 ulp) 83s = sig [0 ] 84one = euler_flow (noise , [vels [0 ]]+ [np .zeros (1000 ,np .float32 )]* 7 ,np .array ([sig [0 ],sig [1 ]]+ [sig [1 ]]* 7 ,np .float32 )) 85assert one .shape == noise .shape 86assert sig [- 1 ]== 0 and len (sig )== 9 and float (s )== 1.0 87"SELF-TEST-OK" ) 88 89 90if __name__ == "__main__" : 91if sys .argv [1 :]== ["--self-test" ]: 92self_test () 93sys .exit (0 ) 94ok ,total = check (Path (sys .argv [1 ]),sys .argv [2 ]) 95sys .exit (0 if total and ok == total else 1 )