okami.mom/strata

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

Niko1221Merge f-own-5 56630caca into f-own-int (round 14: Strata's own VAE decoder for sd-cli and the images "vae_decoder" switch)736266e87

main
12.5 KiB252 linesraw
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
19          nearest even), inputs x * 2^-7 rounded to f16, the product accumulated exactly (float64) and x 2^7; the rest
20          float32.  This is "f16 operands, exact accumulation": our GPU decode (f32 accumulation) must be close to it.
21
22    python -I -B vae_ref.py <vae.safetensors> <latent.bin> <out.npy> [--mode f32|f16op] [--stats]
23        latent.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
25    python -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,
37               1.8873, -1.7177, -0.6510, 0.2732, 0.7562, -0.6163, -1.0277, 3.8363,
38               2.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,
43               0.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,
45              3.0785, 3.6500, 3.9308, 3.0904, 2.8778, 3.7675, 3.7320, 5.0756,
46              3.2864, 4.0397, 3.1317, 4.0443, 2.9249, 3.9454, 3.0988, 4.2489,
47              3.4896, 3.8513, 3.9323, 3.4719, 3.7498, 4.2830, 3.5694, 4.2467,
48              3.9037, 3.2947, 5.0770, 3.5075, 3.2700, 3.4767, 2.8063, 5.1125,
49              3.5327, 4.7833, 3.1286, 4.1819, 3.8527, 3.8312, 3.5605, 4.3875,
50              3.9624, 4.0168, 3.5643, 4.0550, 5.5614, 4.2963, 4.4080, 3.4959,
51              3.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:
62    u = np.frombuffer(raw, dtype=np.uint16).astype(np.uint32) << 16
63    return 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."""
68    out = {}
69    with open(path, "rb") as f:
70        n = struct.unpack("<Q", f.read(8))[0]
71        hdr = json.loads(f.read(n))
72        base = 8 + n
73        for name, e in hdr.items():
74            if name == "__metadata__" or not name.startswith(prefix):
75                continue
76            a, b = e["data_offsets"]
77            f.seek(base + a)
78            raw = f.read(b - a)
79            if e["dtype"] == "BF16":
80                arr = bf16_to_f32(raw)
81            elif e["dtype"] == "F32":
82                arr = np.frombuffer(raw, dtype=np.float32).copy()
83            else:
84                raise ValueError(f"{name}: dtype {e['dtype']}")
85            out[name] = arr.reshape(e["shape"])
86    return out
87
88
89class Decoder:
90    def __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
92        differs; in "f32" a power-of-two scale is exact)."""
93        assert mode in ("f32", "f16op")
94        self.w, self.mode, self.shifts = weights, mode, shifts
95        self.stats = {} if stats else None
96        self.cache = {}
97
98    # --- building blocks ----------------------------------------------------------------------------------------
99    def _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."""
101        if name not in self.cache:
102            w = self.w[name + ".weight"]
103            if self.mode == "f16op":
104                w = w.astype(np.float16).astype(np.float32)
105            oc, ic, kh, kw = w.shape
106            self.cache[name] = (w.transpose(2, 3, 1, 0).reshape(kh * kw * ic, oc).astype(np.float64), kh,
107                                self.w[name + ".bias"].astype(np.float32))
108        return self.cache[name]
109
110    def _note(self, name, x):
111        if self.stats is not None:
112            self.stats[name] = float(np.abs(x).max())
113
114    def 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."""
116        wm, k, bias = self._conv_w(name)
117        H, W, C = x.shape
118        scale = np.float32(2.0 ** -CONV_SHIFTS.get(name, 7)) if self.shifts else CONV_SCALE
119        xs = x * scale
120        self._note(name + ":in_scaled", xs)
121        if self.mode == "f16op":
122            if np.abs(xs).max() > F16_MAX:
123                raise OverflowError(f"{name}: conv input exceeds the f16 range after its scale")
124            xs = xs.astype(np.float16).astype(np.float32)
125        oc = wm.shape[1]
126        out = np.empty((H, W, oc), dtype=np.float32)
127        if k == 1:
128            out[:] = (xs.reshape(-1, C).astype(np.float64) @ wm).reshape(H, W, oc)
129        else:
130            pad = np.zeros((H + 2, W + 2, C), dtype=np.float32)
131            pad[1:-1, 1:-1] = xs
132            step = rows_per_chunk or max(1, (1 << 26) // (W * 9 * C))
133            for y0 in range(0, H, step):
134                y1 = min(H, y0 + step)
135                cols = np.concatenate([pad[y0 + dy:y1 + dy, dx:dx + W] for dy in range(3) for dx in range(3)], axis=2)
136                out[y0:y1] = (cols.reshape(-1, 9 * C).astype(np.float64) @ wm).reshape(y1 - y0, W, oc)
137        out = out / scale               # x 2^shift: exact
138        out += bias
139        return out
140
141    def rms(self, name, x):
142        """RMS norm over channels, eps 1e-12, times gamma (ggml_rms_norm: mean of squares in float32 terms)."""
143        g = self.w[name + ".gamma"].reshape(-1).astype(np.float32)
144        ms = np.mean(x.astype(np.float64) ** 2, axis=2, keepdims=True)
145        return (x * (1.0 / np.sqrt(ms + 1e-12)).astype(np.float32)) * g
146
147    @staticmethod
148    def silu(x):
149        return x / (np.float32(1.0) + np.exp(-x))
150
151    def resnet(self, p, x):
152        h = self.conv(p + ".conv_shortcut", x) if (p + ".conv_shortcut.weight") in self.w else x
153        t = self.conv(p + ".conv1", self.silu(self.rms(p + ".norm1", x)))
154        t = self.conv(p + ".conv2", self.silu(self.rms(p + ".norm2", t)))
155        self._note(p, t + h)
156        return t + h
157
158    def attention(self, p, x):
159        H, W, C = x.shape
160        qkv = self.conv(p + ".to_qkv", self.rms(p + ".norm", x)).reshape(H * W, 3 * C).astype(np.float64)
161        q, k, v = qkv[:, :C], qkv[:, C:2 * C], qkv[:, 2 * C:]
162        s = (q @ k.T) / np.sqrt(C)
163        s -= s.max(axis=1, keepdims=True)
164        e = np.exp(s)
165        a = ((e / e.sum(axis=1, keepdims=True)) @ v).astype(np.float32).reshape(H, W, C)
166        return self.conv(p + ".proj", a) + x
167
168    @staticmethod
169    def 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
171        takes input channel (oc*ft*fs*fs + (ft-1)*fs*fs + i*fs + j) // repeats."""
172        H, W, C = x.shape
173        repeats = out_c * ft * fs * fs // C
174        y = np.empty((H * fs, W * fs, out_c), dtype=np.float32)
175        oc = np.arange(out_c)
176        for i in range(fs):
177            for j in range(fs):
178                src = (oc * ft * fs * fs + (ft - 1) * fs * fs + i * fs + j) // repeats
179                y[i::fs, j::fs] = x[:, :, src]
180        return y
181
182    @staticmethod
183    def up2(x):
184        return x.repeat(2, axis=0).repeat(2, axis=1)
185
186    # --- the decoder --------------------------------------------------------------------------------------------
187    def 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]."""
189        mean = np.array(LATENT_MEAN, dtype=np.float32).reshape(64, 1, 1)
190        std = np.array(LATENT_STD, dtype=np.float32).reshape(64, 1, 1)
191        z = (latent_chw.astype(np.float32) * std) / np.float32(1.0) + mean    # diffusion_to_vae_latents
192        x = np.ascontiguousarray(z.transpose(1, 2, 0))
193        d = dump if dump is not None else {}
194        x = self.conv("post_quant_conv", x)
195        x = self.conv("decoder.conv_in", x)
196        d["conv_in"] = x
197        x = self.resnet("decoder.mid_block.resnets.0", x)
198        x = self.attention("decoder.mid_block.attentions.0", x)
199        d["mid_attn"] = x
200        x = self.resnet("decoder.mid_block.resnets.1", x)
201        d["mid"] = x
202        for i, (_, _, ft, up) in enumerate(UP_BLOCKS):
203            p = f"decoder.up_blocks.{i}"
204            x0 = x
205            for j in range(3):
206                x = self.resnet(f"{p}.resnets.{j}", x)
207            if up:
208                x = self.conv(f"{p}.upsampler.resample.1", self.up2(x)) + self.dup_up(x0, x.shape[2], ft)
209            d[f"up{i}"] = x
210        x = self.conv("decoder.conv_out", self.silu(self.rms("decoder.norm_out", x)))
211        d["out"] = x
212        return 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)."""
217    v = np.clip((img.astype(np.float32) + np.float32(1)) * np.float32(0.5), 0, 1)
218    u = (v * np.float32(255) + np.float32(0.5)).astype(np.uint8)
219    u[v <= 0] = 0
220    u[v >= 1] = 255
221    return u
222
223
224def read_latent(path) -> np.ndarray:
225    shape_file = Path(str(path)[:-4] + ".shape")
226    w, h, c = [int(s) for s in shape_file.read_text().split()[:3]]
227    return np.fromfile(path, dtype=np.float32).reshape(c, h, w)
228
229
230def main(argv):
231    if argv[:1] == ["--png"]:
232        from PIL import Image
233        Image.fromarray(to_u8(np.load(argv[1])), "RGBA").save(argv[2])
234        return 0
235    if len(argv) < 3:
236        print(__doc__)
237        return 2
238    mode = argv[argv.index("--mode") + 1] if "--mode" in argv else "f32"
239    dec = Decoder(load_safetensors(argv[0]), mode=mode, stats="--stats" in argv)
240    out = dec.decode(read_latent(argv[1]))
241    np.save(argv[2], out)
242    print(f"decoded {out.shape} mode {mode}: min {out.min():.4f} max {out.max():.4f}")
243    if dec.stats is not None:
244        worst = max(dec.stats.items(), key=lambda kv: kv[1] if kv[0].endswith(":in_scaled") else -1)
245        print(f"largest conv input after the 2^-7 scale: {worst[1]:.1f} at {worst[0]} (f16 max {F16_MAX})")
246        for k, v in dec.stats.items():
247            print(f"  {k} {v:.4g}")
248    return 0
249
250
251if __name__ == "__main__":
252    sys.exit(main(sys.argv[1:]))