okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-5 fccdb48a3 (image noise switch, step 1 only) into f-own-int150c2394f

main
4.3 KiB95 linesraw
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:
7    for each step i:  denoised = v_i * c_out + x * c_skip      (two tensor products, then one sum: three float loops)
8                      d        = (x - denoised) / sigma_i      (one subtraction loop, one division loop)
9                      x        = x + d * (sigma_i+1 - sigma_i) (one product loop, one sum loop)
10    the 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
14    python -I -B sampler_ref.py <stage root> <tag>          e.g. stage st_cuda_stock_A (run_set.py --dump: noise, vel_0..7,
15                                                            latent per picture); prints identical / total
16    python -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:
29    return 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)."""
34    f = np.float32
35    assert noise.dtype == np.float32 and len(velocities) == len(sigmas) - 1
36    x = noise.copy()
37    for i, v in enumerate(velocities):
38        sigma, nxt = sigmas[i], sigmas[i + 1]
39        if sigma == nxt:
40            continue
41        c_skip, c_out = f(1.0), f(-sigma)
42        denoised = (v * c_out) + (x * c_skip)
43        d = (x - denoised) / sigma
44        x = x + d * f(nxt - sigma)
45    return x
46
47
48def load(path: Path) -> np.ndarray:
49    return np.fromfile(path, dtype="<f4")
50
51
52def check(root: Path, tag: str) -> tuple[int, int]:
53    sig = sigmas_f32()
54    ok = total = 0
55    for d in sorted((root / tag).glob("dump_p*_s*")):
56        try:
57            noise = load(d / "noise.bin")
58            vels = [load(d / f"vel_{k}.bin") for k in range(len(sig) - 1)]
59            want = load(d / "latent.bin")
60        except OSError:
61            continue
62        got = euler_flow(noise, vels, sig)
63        same = bool(np.array_equal(got.view(np.uint32), want.view(np.uint32)))
64        total += 1
65        ok += same
66        if not same:
67            diff = np.flatnonzero(got.view(np.uint32) != want.view(np.uint32))
68            print(f"{d.name}: {len(diff)} of {got.size} values differ, max abs {float(np.abs(got - want).max()):.3g}")
69        else:
70            print(f"{d.name}: identical ({got.size} values)")
71    print(f"SAMPLER-REF {tag}: identical {ok} of {total}")
72    return ok, total
73
74
75def self_test() -> None:
76    rng = np.random.default_rng(1)
77    noise = rng.standard_normal(1000).astype(np.float32)
78    vels = [rng.standard_normal(1000).astype(np.float32) for _ in range(8)]
79    sig = sigmas_f32()
80    a = euler_flow(noise, vels, sig)
81    assert 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)
83    s = sig[0]
84    one = euler_flow(noise, [vels[0]] + [np.zeros(1000, np.float32)] * 7, np.array([sig[0], sig[1]] + [sig[1]] * 7, np.float32))
85    assert one.shape == noise.shape
86    assert sig[-1] == 0 and len(sig) == 9 and float(s) == 1.0
87    print("SELF-TEST-OK")
88
89
90if __name__ == "__main__":
91    if sys.argv[1:] == ["--self-test"]:
92        self_test()
93        sys.exit(0)
94    ok, total = check(Path(sys.argv[1]), sys.argv[2])
95    sys.exit(0 if total and ok == total else 1)