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
40.7 KiB835 linesraw
1// src/image/vae/wan_vae.cu - Strata's Qwen-Image-2.1 VAE decoder (see include/strata/image/wan_vae.hpp).
2//
3// Layout: every activation is pixel-major float32, [H][W][C] (a pixel is a row of C channels).  A convolution is
4//   gather   -> f16 operand rows for a band of PB output pixels: per pixel the k*k taps x C channels, each value
5//               optionally RMS-normed (x * inv_rms(pixel) * gamma) and SiLU'd, or read from the half-size tensor
6//               (nearest 2x upsample), then x 2^-7 and rounded to f16 (round to nearest even), zero outside the image;
7//   GEMM     -> cuBLAS / hipBLAS GemmEx, f16 x f16, f32 compute, f32 out: [PB][OC] = rows x W^T;
8//   epilogue -> x 2^7, + bias, + residual, + the DupUp shortcut, written to the output tensor.
9// That is sd.cpp's arithmetic (ggml_ext_conv_2d with scale 1/128: scale, im2col to f16, mul_mat, unscale, bias add)
10// except the accumulation, which sd.cpp does in f16 (CUBLAS_COMPUTE_16F) and we do in f32.
11// PB is a constant, the last band is padded with zero rows, so every GEMM of a layer has the same shape on every
12// picture size: the value of a pixel does not depend on the picture size or the memory of the card.
13// The mid-block attention (one head, dim 1152, over all latent pixels) is f32 SGEMM / softmax / SGEMM, like sd.cpp's
14// VAE (it does not use flash attention there).
15#include "strata/image/wan_vae.hpp"
16
17#include "convert.hpp"
18#include "safetensors_lite.hpp"
19#include "strata/kernels/bf16_bits.hpp"
20#include "strata/kernels/f16_bits.hpp"
21
22#if defined(__HIP__) || defined(__HIPCC__) || defined(__HIP_PLATFORM_AMD__)
23#include "strata/hip_compat/cuda_runtime.h"   // the engine's CUDA -> HIP names (cuBLAS -> hipBLAS)
24#include "strata/hip_compat/cublas_v2.h"
25#else
26#include <cuda_runtime.h>
27#include <cublas_v2.h>
28#endif
29
30#include <algorithm>
31#include <chrono>
32#include <cmath>
33#include <cstdint>
34#include <cstdio>
35#include <cstring>
36#include <map>
37#include <memory>
38#include <string>
39#include <vector>
40
41namespace strata::image {
42namespace {
43
44constexpr int PB = 8192;                  // pixels per GEMM band (fixed: see the file comment)
45constexpr int CONV_SHIFT = 7;             // inputs x 2^-7: wan_vae.hpp "Keep large VAE activations within the FP16 range"
46constexpr int RANGE_BINS = 258;           // range statistics: 256 float exponents of |scaled input|, zeros, max bits
47constexpr float RMS_EPS = 1e-12f;
48constexpr int Z_DIM = 64;
49
50enum GatherMode { G_PLAIN = 0, G_NORM = 1, G_NORM_SILU = 2, G_UP2 = 3 };
51
52#define VAE_CUDA(x)                                                                                        \
53    do {                                                                                                   \
54        cudaError_t e_ = (x);                                                                              \
55        if (e_ != cudaSuccess) return std::string("wan_vae: ") + #x + ": " + cudaGetErrorString(e_);       \
56    } while (0)
57#define VAE_BLAS(x)                                                                                        \
58    do {                                                                                                   \
59        auto s_ = (x);                                                                                     \
60        if (s_ != CUBLAS_STATUS_SUCCESS) return std::string("wan_vae: ") + #x + ": status " + std::to_string((int) s_); \
61    } while (0)
62#define VAE_TRY(x)                                                                                         \
63    do {                                                                                                   \
64        std::string r_ = (x);                                                                              \
65        if (!r_.empty()) return r_;                                                                        \
66    } while (0)
67
68// ---------------------------------------------------------------------------------------------------------------
69// kernels
70
71// inv[p] = 1 / sqrt(mean(x[p][:]^2) + eps); 8 pixels per block of 256 threads, 32 threads per pixel, fixed order.
72__global__ void rms_inv_kernel(const float* __restrict__ x, int64_t P, int C, float* __restrict__ inv) {
73    __shared__ float part[256];
74    const int g = threadIdx.x >> 5, lane = threadIdx.x & 31;
75    const int64_t p = (int64_t) blockIdx.x * 8 + g;
76    float s = 0.f;
77    if (p < P) {
78        const float* row = x + p * C;
79        for (int c = lane; c < C; c += 32) s += row[c] * row[c];
80    }
81    part[threadIdx.x] = s;
82    __syncthreads();
83    for (int w = 16; w > 0; w >>= 1) {
84        if (lane < w) part[threadIdx.x] += part[threadIdx.x + w];
85        __syncthreads();
86    }
87    if (lane == 0 && p < P) inv[p] = rsqrtf(part[threadIdx.x] / (float) C + RMS_EPS);
88}
89
90// One thread = 8 channels of one tap of one band pixel.  out: [PB][taps*C] f16 bits.
91template <int MODE>
92// Row windows (the small-card streaming): the source holds image rows [src_y0, src_y0 + Hs) of its picture, the
93// output band starts at image row dst_y0 of a conv-input grid H (image) rows high.  Zero padding only at the image's
94// own edges; a row outside the window is read as zero too, and the rows that depend on it are never used.
95__global__ void gather_kernel(const float* __restrict__ src, int Hs, int Ws, int C, int H, int W, int k,
96                              int64_t p0, int64_t P, const float* __restrict__ inv, const float* __restrict__ gamma,
97                              uint16_t* __restrict__ out, int src_y0, int dst_y0, float scale,
98                              unsigned int* __restrict__ hist) {
99    const int taps = k * k, c8n = C >> 3;
100    const int64_t total = (int64_t) PB * taps * c8n;
101    const int64_t t = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
102    if (t >= total) return;
103    const int c8 = (int) (t % c8n);
104    const int64_t rest = t / c8n;
105    const int tap = (int) (rest % taps);
106    const int64_t pl = rest / taps;
107    const int64_t p = p0 + pl;
108    uint16_t h[8] = {0, 0, 0, 0, 0, 0, 0, 0};
109    if (p >= 0 && p < P) {          // rows outside the window (a band's GEMM block reaching past it) stay zero
110        const int y = dst_y0 + (int) (p / W), xq = (int) (p % W);
111        const int yy = y + tap / k - k / 2, xx = xq + tap % k - k / 2;
112        const int ly = (MODE == G_UP2 ? (yy >> 1) : yy) - src_y0;
113        if (yy >= 0 && yy < H && xx >= 0 && xx < W && ly >= 0 && ly < Hs) {
114            const int sx = MODE == G_UP2 ? (xx >> 1) : xx;
115            const int64_t sp = (int64_t) ly * Ws + sx;
116            const float4* s4 = reinterpret_cast<const float4*>(src + sp * C + c8 * 8);
117            const float4 a = s4[0], b = s4[1];
118            float v[8] = {a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w};
119            const float r = (MODE == G_NORM || MODE == G_NORM_SILU) ? inv[sp] : 1.f;
120#pragma unroll
121            for (int i = 0; i < 8; ++i) {
122                float q = v[i];
123                if (MODE == G_NORM || MODE == G_NORM_SILU) q = (q * r) * gamma[c8 * 8 + i];
124                if (MODE == G_NORM_SILU) q = q / (1.0f + expf(-q));
125                q = q * scale;                       // an exact power of two (the layer's fixed shift)
126                if (hist) {                          // test-only range statistics (wan_vae_set_range_stats)
127                    const unsigned int b = __float_as_uint(q) & 0x7FFFFFFFu;
128                    atomicAdd(&hist[b ? (b >> 23) : 256], 1u);
129                    atomicMax(&hist[257], b);
130                }
131                h[i] = strata::kernels::f16_from_f32(q);
132            }
133        }
134    }
135    uint4 pk;
136    pk.x = (uint32_t) h[0] | ((uint32_t) h[1] << 16);
137    pk.y = (uint32_t) h[2] | ((uint32_t) h[3] << 16);
138    pk.z = (uint32_t) h[4] | ((uint32_t) h[5] << 16);
139    pk.w = (uint32_t) h[6] | ((uint32_t) h[7] << 16);
140    *reinterpret_cast<uint4*>(out + pl * ((int64_t) taps * C) + (int64_t) tap * C + c8 * 8) = pk;
141}
142
143// dst[p][oc] = ((acc * 2^7 + bias) + res) + dup; dup = the DupUp3D shortcut of x0 [Hs][Ws][C0] for an output of
144// [2Hs][2Ws][OC]: channel (oc*ft*4 + (ft-1)*4 + i*2 + j) / repeats of x0's pixel (Y/2, X/2), i = Y&1, j = X&1.
145__global__ void epilogue_kernel(const float* __restrict__ acc, int OC, int64_t p0, int64_t pl_lo, int64_t nvalid,
146                                const float* __restrict__ bias, const float* res, float* dst, int W,
147                                const float* __restrict__ x0, int C0, int ft, int dst_y0, int x0_y0, float unscale) {
148    const int64_t t = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
149    if (t >= nvalid * OC) return;
150    const int oc = (int) (t % OC);
151    const int64_t pl = pl_lo + t / OC, p = p0 + pl;
152    float v = acc[pl * OC + oc] * unscale;
153    v = v + bias[oc];
154    if (res) v = v + res[p * OC + oc];
155    if (x0) {
156        const int Y = dst_y0 + (int) (p / W), X = (int) (p % W);
157        const int repeats = OC * ft * 4 / C0;
158        const int ch = (oc * ft * 4 + (ft - 1) * 4 + (Y & 1) * 2 + (X & 1)) / repeats;
159        const int64_t sp = (int64_t) ((Y >> 1) - x0_y0) * (W >> 1) + (X >> 1);   // x0 holds the needed rows
160        v = v + x0[sp * C0 + ch];
161    }
162    dst[p * OC + oc] = v;
163}
164
165// Row softmax of s [n][n] in place with the scale applied first (ggml soft_max: max, exp(x - max), sum, x / sum).
166__global__ void softmax_rows_kernel(float* s, int n, float scale) {
167    __shared__ float red[256];
168    float* row = s + (int64_t) blockIdx.x * n;
169    float m = -INFINITY;
170    for (int j = threadIdx.x; j < n; j += 256) m = fmaxf(m, row[j] * scale);
171    red[threadIdx.x] = m;
172    __syncthreads();
173    for (int w = 128; w > 0; w >>= 1) {
174        if (threadIdx.x < w) red[threadIdx.x] = fmaxf(red[threadIdx.x], red[threadIdx.x + w]);
175        __syncthreads();
176    }
177    m = red[0];
178    __syncthreads();
179    float sum = 0.f;
180    for (int j = threadIdx.x; j < n; j += 256) {
181        const float e = expf(row[j] * scale - m);
182        row[j] = e;
183        sum += e;
184    }
185    red[threadIdx.x] = sum;
186    __syncthreads();
187    for (int w = 128; w > 0; w >>= 1) {
188        if (threadIdx.x < w) red[threadIdx.x] += red[threadIdx.x + w];
189        __syncthreads();
190    }
191    const float inv = 1.0f / red[0];
192    for (int j = threadIdx.x; j < n; j += 256) row[j] = row[j] * inv;
193}
194
195// ---------------------------------------------------------------------------------------------------------------
196// host side
197
198struct Pool {   // device buffers reused by size; peak = what was ever allocated at once
199    struct Blk { void* p; size_t n; bool used; };
200    std::vector<Blk> blks;
201    size_t live = 0, peak = 0;
202    void* get(size_t n, std::string& err) {
203        Blk* best = nullptr;
204        for (auto& b : blks)
205            if (!b.used && b.n >= n && (!best || b.n < best->n)) best = &b;
206        if (best) { best->used = true; return best->p; }
207        void* p = nullptr;
208        cudaError_t e = cudaMalloc(&p, n);
209        if (e != cudaSuccess) {   // give back the free blocks and try once more
210            for (auto it = blks.begin(); it != blks.end();) {
211                if (!it->used) { cudaFree(it->p); live -= it->n; it = blks.erase(it); } else ++it;
212            }
213            e = cudaMalloc(&p, n);
214            if (e != cudaSuccess) { err = std::string("wan_vae: out of device memory (") + std::to_string(n >> 20) + " MiB)"; return nullptr; }
215        }
216        blks.push_back({p, n, true});
217        live += n;
218        if (live > peak) peak = live;
219        return p;
220    }
221    void put(const void* p) {
222        for (auto& b : blks) if (b.p == p) { b.used = false; return; }
223    }
224    void clear() { for (auto& b : blks) cudaFree(b.p); blks.clear(); live = 0; }
225};
226
227// H rows (image rows y0 .. y0+H-1 of a picture Hi rows high; a whole tensor has y0 = 0, Hi = H) x W x C
228struct Tensor {
229    float* d = nullptr;
230    int H = 0, W = 0, C = 0, y0 = 0, Hi = 0;
231    int64_t P() const { return (int64_t) H * W; }
232};
233
234struct Conv {
235    int ic = 0, oc = 0, k = 0;
236    int shift = CONV_SHIFT;          // operand = input x 2^-shift (fixed per layer: conv_shift())
237    uint16_t* w = nullptr;
238    float* b = nullptr;
239    std::string name;
240};
241struct Norm { int c = 0; float* g = nullptr; };
242struct Resnet { Norm n1, n2; Conv c1, c2, sc; bool has_sc = false; };
243
244}  // namespace
245
246struct WanVae {
247    int device = 0;
248    cudaStream_t stream = nullptr;
249    cublasHandle_t blas = nullptr;
250    std::vector<void*> weights;
251    size_t weight_bytes = 0;
252    Conv post_quant, conv_in, qkv, proj, conv_out;
253    Norm attn_norm, norm_out;
254    Resnet mid0, mid1;
255    Resnet up[5][3];
256    Conv resample[5];
257    Pool pool;
258    uint16_t* gbuf = nullptr;   // [PB][Kmax] f16
259    float* abuf = nullptr;      // [PB][OCmax] f32
260    std::function<void(const char*, const float*, int, int, int)> dump;
261    bool range_on = false;      // test-only range statistics (wan_vae_set_range_stats)
262    unsigned int* range_dev = nullptr;
263    std::map<std::string, std::vector<unsigned long long>> range;   // per conv: exponent bins, zeros, max bits, shift
264    double open_ms[4] = {0, 0, 0, 0};                      // read, device setup, convert, upload (wan_vae_open_report)
265    int band_rows = 0;          // 0: STREAM_ROWS; other heights only for the identity test (wan_vae_set_band_rows)
266    int stream_mode = 1;        // 1 the row-band tail (always, coordinator 11-10); 0 the one-pass reference (tests)
267};
268
269namespace {
270
271const int UP_FT[5] = {2, 2, 2, 1, 1};          // DupUp3D temporal factor (temperal_upsample {T, T, T, F})
272const bool UP_HAS[5] = {true, true, true, true, false};
273
274// Opening: the file's data section is read once (in parallel parts), every weight is converted straight from it into
275// one host staging buffer (a list of jobs split over the image program's threads), and the buffer goes to the device
276// in ONE allocation and ONE copy.  The conversions are the per-value ones of convert.hpp: the same bytes for any
277// thread count (tools/image/gate/test_vae_convert.py).
278struct Job {
279    size_t src = 0, dst = 0, n = 0;   // byte offset in the data section, byte offset in the staging buffer, values
280    int kind = 0;                     // 0: conv weight bf16 -> f16 [oc][taps*ic]; 1: bf16 -> f32; 2: f32 copy
281    int oc = 0, ic = 0, taps = 0;
282    void** slot = nullptr;            // the device pointer to fill in
283};
284
285struct Loader {
286    std::string path;
287    StFile file;
288    std::unique_ptr<unsigned char[]> data;   // the data section
289    size_t data_size = 0;
290    int threads = 1;
291    std::vector<Job> jobs;
292    size_t staging = 0;               // bytes of the staging buffer so far
293    std::string plan(const std::string& name, int kind, const std::vector<int64_t>& want_dims_or_empty,
294                     std::vector<int64_t>& shape, void** slot) {
295        auto it = file.tensors.find(name);
296        if (it == file.tensors.end()) return "wan_vae: tensor " + name + " missing in " + path;
297        const auto& t = it->second;
298        size_t n = 1;
299        for (auto s : t.shape) n *= (size_t) s;
300        const bool bf16 = t.dtype == "BF16" && t.end - t.begin == n * 2;
301        const bool f32 = t.dtype == "F32" && t.end - t.begin == n * 4;
302        if (!bf16 && !(f32 && kind != 0))
303            return "wan_vae: tensor " + name + " has dtype " + t.dtype + (kind == 0 ? " (bf16 expected)" : " (bf16 or f32 expected)");
304        if (t.end > data_size) return "wan_vae: tensor " + name + " lies past the end of " + path;
305        (void) want_dims_or_empty;
306        shape = t.shape;
307        Job j;
308        j.src = t.begin;
309        j.n = n;
310        j.kind = kind == 0 ? 0 : (bf16 ? 1 : 2);
311        j.dst = (staging + 255) & ~(size_t) 255;
312        staging = j.dst + n * (kind == 0 ? 2 : 4);
313        j.slot = slot;
314        jobs.push_back(j);
315        return "";
316    }
317};
318
319// Run the conversion jobs into a staging buffer and upload it in one copy; fills every job's slot.
320std::string convert_and_upload(WanVae* v, Loader& L, double* convert_ms, double* upload_ms) {
321    using clk = std::chrono::steady_clock;
322    const auto t0 = clk::now();
323    std::unique_ptr<unsigned char[]> stage(new unsigned char[L.staging]);   // not zero-filled: every byte is written
324    // work items: a conv weight in parts of rows, the small vectors whole
325    struct Item { size_t job, b, e; };
326    std::vector<Item> items;
327    for (size_t k = 0; k < L.jobs.size(); ++k) {
328        const Job& j = L.jobs[k];
329        if (j.kind == 0) {
330            const size_t rows_per = std::max<size_t>(1, (size_t) 65536 / ((size_t) j.ic * j.taps));
331            for (size_t b = 0; b < (size_t) j.oc; b += rows_per) items.push_back({k, b, std::min<size_t>(j.oc, b + rows_per)});
332        } else {
333            items.push_back({k, 0, j.n});
334        }
335    }
336    const unsigned char* data = L.data.get();
337    parallel_ranges(items.size(), L.threads, [&](size_t ib, size_t ie) {
338        for (size_t it = ib; it < ie; ++it) {
339            const Job& j = L.jobs[items[it].job];
340            if (j.kind == 0)
341                bf16_conv_to_f16_rows(data + j.src, j.ic, j.taps, items[it].b, items[it].e, (uint16_t*) (stage.get() + j.dst));
342            else if (j.kind == 1)
343                bf16_to_f32_range(data + j.src, 0, j.n, (float*) (stage.get() + j.dst));
344            else
345                std::memcpy(stage.get() + j.dst, data + j.src, j.n * 4);
346        }
347    });
348    const auto t1 = clk::now();
349    void* d = nullptr;
350    VAE_CUDA(cudaMalloc(&d, L.staging));
351    v->weights.push_back(d);
352    v->weight_bytes += L.staging;
353    VAE_CUDA(cudaMemcpy(d, stage.get(), L.staging, cudaMemcpyHostToDevice));
354    for (const Job& j : L.jobs) *j.slot = (char*) d + j.dst;
355    const auto t2 = clk::now();
356    *convert_ms = std::chrono::duration<double, std::milli>(t1 - t0).count();
357    *upload_ms = std::chrono::duration<double, std::milli>(t2 - t1).count();
358    return "";
359}
360
361// The fixed operand shift of each convolution (input x 2^-shift -> f16; output x 2^shift, both exact): stable-
362// diffusion.cpp's 2^-7 everywhere, except the layers listed here.  Fixed per layer, never from the picture's data (a
363// data-dependent scale would differ between a band and the whole picture and break the byte-identity gate).
364// Chosen from the measured ranges (strata-vae-decode --stats over the 16 gate latents, 11-10, Spark; RESULTS-OWN-5):
365// every layer whose largest input came within 16x of the f16 maximum after 2^-7 gets at least 16x headroom.
366//   decoder.up_blocks.4.resnets.0.conv_shortcut: largest input 3.48e6 (1024 p4), 2.4x headroom at shift 7;
367//     shift 11 -> 38.5x.  Share of its nonzero inputs that are f16-subnormal: 0.08% at shift 7, 1.24% at shift 11
368//     (inputs below 2^-3 against a largest input of 3.48e6; their absolute error stays under 2^-14).
369//   Next closest: up_blocks.3.upsampler.resample.1 62.8x, up_blocks.3.resnets.0.conv_shortcut 113x: kept at 7.
370int conv_shift(const std::string& name) {
371    if (name == "decoder.up_blocks.4.resnets.0.conv_shortcut") return 11;
372    return CONV_SHIFT;
373}
374
375std::string load_conv(WanVae* v, Loader& L, const std::string& name, Conv& cv) {
376    (void) v;
377    std::vector<int64_t> sh, bs;
378    VAE_TRY(L.plan(name + ".weight", 0, {}, sh, (void**) &cv.w));
379    VAE_TRY(L.plan(name + ".bias", 1, {}, bs, (void**) &cv.b));
380    if (sh.size() != 4 || sh[2] != sh[3] || (sh[2] != 1 && sh[2] != 3) || bs.size() != 1 || bs[0] != sh[0] ||
381        sh[1] % 8 != 0)
382        return "wan_vae: " + name + ": unexpected shape";
383    cv.oc = (int) sh[0];
384    cv.name = name;
385    cv.shift = conv_shift(name);
386    cv.ic = (int) sh[1];
387    cv.k = (int) sh[2];
388    Job& wj = L.jobs[L.jobs.size() - 2];
389    wj.oc = cv.oc;
390    wj.ic = cv.ic;
391    wj.taps = cv.k * cv.k;
392    return "";
393}
394
395std::string load_norm(WanVae* v, Loader& L, const std::string& name, Norm& n) {
396    (void) v;
397    std::vector<int64_t> sh;
398    VAE_TRY(L.plan(name + ".gamma", 1, {}, sh, (void**) &n.g));
399    size_t c = 1;
400    for (auto s2 : sh) c *= (size_t) s2;
401    n.c = (int) c;
402    return "";
403}
404
405std::string load_resnet(WanVae* v, Loader& L, const std::string& p, Resnet& r) {
406    VAE_TRY(load_norm(v, L, p + ".norm1", r.n1));
407    VAE_TRY(load_conv(v, L, p + ".conv1", r.c1));
408    VAE_TRY(load_norm(v, L, p + ".norm2", r.n2));
409    VAE_TRY(load_conv(v, L, p + ".conv2", r.c2));
410    r.has_sc = L.file.tensors.count(p + ".conv_shortcut.weight") > 0;
411    if (r.has_sc) VAE_TRY(load_conv(v, L, p + ".conv_shortcut", r.sc));
412    return "";
413}
414
415std::string alloc_t(WanVae* v, Tensor& t, int H, int W, int C, int y0 = 0, int Hi = -1) {
416    std::string err;
417    t.H = H; t.W = W; t.C = C; t.y0 = y0; t.Hi = Hi < 0 ? H : Hi;
418    t.d = (float*) v->pool.get((size_t) H * W * C * sizeof(float), err);
419    return t.d ? "" : err;
420}
421void free_t(WanVae* v, Tensor& t) { if (t.d) v->pool.put(t.d); t.d = nullptr; }
422
423// dst (must be allocated, [H][W][oc]) = conv(src) with the gather mode, + res (may be dst itself), + DupUp(x0).
424std::string conv(WanVae* v, const Conv& cv, const Tensor& src, int mode, const Norm* nrm, Tensor& dst,
425                 const float* res, const Tensor* x0, int ft) {
426    if (src.C != cv.ic) return "wan_vae: conv input channels differ";
427    if (nrm && nrm->c != src.C) return "wan_vae: norm channels differ";
428    // the conv-input grid's image height (zero padding at its edges) and width; dst is a window of its rows
429    const int Hg = mode == G_UP2 ? src.Hi * 2 : src.Hi, W = mode == G_UP2 ? src.W * 2 : src.W;
430    if (dst.Hi != Hg || dst.W != W || dst.C != cv.oc || dst.y0 < 0 || dst.y0 + dst.H > Hg)
431        return "wan_vae: conv output shape differs";
432    if (x0 && (x0->y0 > dst.y0 / 2 || x0->y0 + x0->H < (dst.y0 + dst.H + 1) / 2)) return "wan_vae: DupUp rows missing";
433    const int64_t P = dst.P();
434    float* inv = nullptr;
435    std::string err;
436    if (mode == G_NORM || mode == G_NORM_SILU) {
437        inv = (float*) v->pool.get((size_t) src.P() * sizeof(float), err);
438        if (!inv) return err;
439        rms_inv_kernel<<<(unsigned) ((src.P() + 7) / 8), 256, 0, v->stream>>>(src.d, src.P(), src.C, inv);
440        VAE_CUDA(cudaGetLastError());
441    }
442    const int K = cv.k * cv.k * cv.ic;
443    const float one = 1.f, zero = 0.f;
444    const float scale = std::ldexp(1.0f, -cv.shift), unscale = std::ldexp(1.0f, cv.shift);   // exact powers of two
445    unsigned int* hist = v->range_on ? v->range_dev : nullptr;
446    if (hist) VAE_CUDA(cudaMemsetAsync(hist, 0, RANGE_BINS * sizeof(unsigned int), v->stream));
447    // GEMM blocks of PB pixels on the PICTURE's pixel grid (global pixel k*PB .. (k+1)*PB-1), also for a window of rows:
448    // every pixel then sits in the same row of a same-shape GEMM in the row bands as in the one-pass decode.  hipBLAS
449    // (R9700, 11-10) gives a row a different reduction order at a different row position of the call; cuBLAS did not.
450    const int64_t g0 = (int64_t) dst.y0 * W;   // the window's first pixel in the picture
451    for (int64_t p0 = (g0 / PB) * PB - g0; p0 < P; p0 += PB) {   // p0: the block's first pixel, window-local (<= 0)
452        const int64_t total = (int64_t) PB * cv.k * cv.k * (cv.ic / 8);
453        const unsigned blocks = (unsigned) ((total + 255) / 256);
454        switch (mode) {
455            case G_PLAIN: gather_kernel<G_PLAIN><<<blocks, 256, 0, v->stream>>>(src.d, src.H, src.W, src.C, Hg, W, cv.k, p0, P, inv, nullptr, v->gbuf, src.y0, dst.y0, scale, hist); break;
456            case G_NORM: gather_kernel<G_NORM><<<blocks, 256, 0, v->stream>>>(src.d, src.H, src.W, src.C, Hg, W, cv.k, p0, P, inv, nrm->g, v->gbuf, src.y0, dst.y0, scale, hist); break;
457            case G_NORM_SILU: gather_kernel<G_NORM_SILU><<<blocks, 256, 0, v->stream>>>(src.d, src.H, src.W, src.C, Hg, W, cv.k, p0, P, inv, nrm->g, v->gbuf, src.y0, dst.y0, scale, hist); break;
458            default: gather_kernel<G_UP2><<<blocks, 256, 0, v->stream>>>(src.d, src.H, src.W, src.C, Hg, W, cv.k, p0, P, inv, nullptr, v->gbuf, src.y0, dst.y0, scale, hist); break;
459        }
460        VAE_CUDA(cudaGetLastError());
461        VAE_BLAS(cublasGemmEx(v->blas, CUBLAS_OP_T, CUBLAS_OP_N, cv.oc, PB, K, &one, cv.w, CUDA_R_16F, K, v->gbuf,
462                              CUDA_R_16F, K, &zero, v->abuf, CUDA_R_32F, cv.oc, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT));
463        const int64_t lo = p0 < 0 ? -p0 : 0;                          // the block's rows inside the window
464        const int64_t nvalid = std::min<int64_t>(PB, P - p0) - lo;
465        const int64_t et = nvalid * cv.oc;
466        epilogue_kernel<<<(unsigned) ((et + 255) / 256), 256, 0, v->stream>>>(
467            v->abuf, cv.oc, p0, lo, nvalid, cv.b, res, dst.d, W, x0 ? x0->d : nullptr, x0 ? x0->C : 0, ft, dst.y0,
468            x0 ? x0->y0 : 0, unscale);
469        VAE_CUDA(cudaGetLastError());
470    }
471    if (inv) v->pool.put(inv);
472    if (hist) {
473        unsigned int h[RANGE_BINS];
474        VAE_CUDA(cudaMemcpyAsync(h, hist, sizeof(h), cudaMemcpyDeviceToHost, v->stream));
475        VAE_CUDA(cudaStreamSynchronize(v->stream));
476        auto& acc = v->range[cv.name];
477        acc.resize(RANGE_BINS + 1, 0);
478        for (int i = 0; i < 257; ++i) acc[i] += h[i];
479        acc[257] = std::max<unsigned long long>(acc[257], h[257]);
480        acc[258] = (unsigned long long) cv.shift;
481    }
482    return "";
483}
484
485// x -> resnet(x); x is consumed (its buffer becomes the output when the channels stay, else it is freed unless
486// keep_input: then the caller still owns it).
487std::string resnet(WanVae* v, const Resnet& r, Tensor& x, bool keep_input = false) {
488    Tensor h, t;
489    if (r.has_sc) {
490        VAE_TRY(alloc_t(v, h, x.H, x.W, r.sc.oc, x.y0, x.Hi));
491        VAE_TRY(conv(v, r.sc, x, G_PLAIN, nullptr, h, nullptr, nullptr, 0));
492    } else {
493        h = x;
494    }
495    VAE_TRY(alloc_t(v, t, x.H, x.W, r.c1.oc, x.y0, x.Hi));
496    VAE_TRY(conv(v, r.c1, x, G_NORM_SILU, &r.n1, t, nullptr, nullptr, 0));
497    VAE_TRY(conv(v, r.c2, t, G_NORM_SILU, &r.n2, h, h.d, nullptr, 0));   // in place on h
498    free_t(v, t);
499    if (r.has_sc && !keep_input) free_t(v, x);
500    x = h;
501    return "";
502}
503
504std::string attention(WanVae* v, Tensor& x) {
505    const int C = x.C;
506    const int64_t n = x.P();
507    Tensor qkv, o;
508    VAE_TRY(alloc_t(v, qkv, x.H, x.W, 3 * C));
509    VAE_TRY(conv(v, v->qkv, x, G_NORM, &v->attn_norm, qkv, nullptr, nullptr, 0));
510    std::string err;
511    float* s = (float*) v->pool.get((size_t) n * n * sizeof(float), err);
512    if (!s) return err;
513    const float one = 1.f, zero = 0.f;
514    // s (row-major [n][n], row i = query i) = Q K^T: column-major S^T = K * Q^T ... with ld 3C
515    VAE_BLAS(cublasSgemm(v->blas, CUBLAS_OP_T, CUBLAS_OP_N, (int) n, (int) n, C, &one, qkv.d + C, 3 * C, qkv.d, 3 * C,
516                         &zero, s, (int) n));
517    softmax_rows_kernel<<<(unsigned) n, 256, 0, v->stream>>>(s, (int) n, 1.0f / std::sqrt((float) C));
518    VAE_CUDA(cudaGetLastError());
519    VAE_TRY(alloc_t(v, o, x.H, x.W, C));
520    // o (row-major [n][C]) = A V: column-major O (C x n) = V (C x n, ld 3C) * A^T-view (n x n, ld n)
521    VAE_BLAS(cublasSgemm(v->blas, CUBLAS_OP_N, CUBLAS_OP_N, C, (int) n, (int) n, &one, qkv.d + 2 * C, 3 * C, s, (int) n,
522                         &zero, o.d, C));
523    v->pool.put(s);
524    free_t(v, qkv);
525    VAE_TRY(conv(v, v->proj, o, G_PLAIN, nullptr, x, x.d, nullptr, 0));       // proj + identity, in place on x
526    free_t(v, o);
527    return "";
528}
529
530std::string stage(WanVae* v, const char* name, const Tensor& t) {
531    if (!v->dump) return "";
532    std::vector<float> h((size_t) t.P() * t.C);
533    VAE_CUDA(cudaMemcpyAsync(h.data(), t.d, h.size() * 4, cudaMemcpyDeviceToHost, v->stream));
534    VAE_CUDA(cudaStreamSynchronize(v->stream));
535    v->dump(name, h.data(), t.H, t.W, t.C);
536    return "";
537}
538
539// The small-card path (owner decision 11-10, option A): block 3's upsample, block 4 and the head in bands of
540// STREAM_ROWS picture rows, each computed with STREAM_HALO extra rows above and below (block 4's six 3x3 convolutions
541// and conv_out each need one row more), from the complete block-3 tensors x (after its resnets) and x0 (its input).
542// Every kept pixel goes through the same operations on the same operands as in the one-pass decode (the GEMM bands
543// stay PB pixels), so the picture is the same bytes; only memory differs.  hwc: the picture, [HF][WF][4].
544constexpr int STREAM_ROWS = 128;
545constexpr int STREAM_HALO = 7;
546
547std::string stream_tail(WanVae* v, const Tensor& x, const Tensor& x0, float* hwc) {
548    const int H = x.Hi * 2, W = x.W * 2;
549    const int rows = v->band_rows > 0 ? v->band_rows : STREAM_ROWS;
550    for (int o0 = 0; o0 < H; o0 += rows) {
551        const int o1 = std::min(H, o0 + rows);
552        const int a = std::max(0, o0 - STREAM_HALO), b = std::min(H, o1 + STREAM_HALO);
553        Tensor u, o;
554        VAE_TRY(alloc_t(v, u, b - a, W, v->resample[3].oc, a, H));
555        VAE_TRY(conv(v, v->resample[3], x, G_UP2, nullptr, u, nullptr, &x0, UP_FT[3]));
556        for (int j = 0; j < 3; ++j) VAE_TRY(resnet(v, v->up[4][j], u));
557        VAE_TRY(alloc_t(v, o, b - a, W, v->conv_out.oc, a, H));
558        VAE_TRY(conv(v, v->conv_out, u, G_NORM_SILU, &v->norm_out, o, nullptr, nullptr, 0));
559        free_t(v, u);
560        VAE_CUDA(cudaMemcpyAsync(hwc + (size_t) o0 * W * 4, o.d + (size_t) (o0 - a) * W * 4,
561                                 (size_t) (o1 - o0) * W * 4 * sizeof(float), cudaMemcpyDeviceToHost, v->stream));
562        VAE_CUDA(cudaStreamSynchronize(v->stream));
563        free_t(v, o);
564    }
565    return "";
566}
567
568std::string decode_impl(WanVae* v, const float* latent, int h, int w, float* out, WanVaeStats* st) {
569    VAE_CUDA(cudaSetDevice(v->device));
570    cudaEvent_t e0, e1;
571    VAE_CUDA(cudaEventCreate(&e0));
572    VAE_CUDA(cudaEventCreate(&e1));
573    VAE_CUDA(cudaEventRecord(e0, v->stream));
574    Tensor z, x;
575    {
576        std::vector<float> hwc((size_t) h * w * Z_DIM);
577        for (int c = 0; c < Z_DIM; ++c)
578            for (int i = 0; i < h * w; ++i) hwc[(size_t) i * Z_DIM + c] = latent[(size_t) c * h * w + i];
579        VAE_TRY(alloc_t(v, z, h, w, Z_DIM));
580        VAE_CUDA(cudaMemcpyAsync(z.d, hwc.data(), hwc.size() * 4, cudaMemcpyHostToDevice, v->stream));
581        VAE_CUDA(cudaStreamSynchronize(v->stream));
582    }
583    Tensor y;
584    VAE_TRY(alloc_t(v, y, h, w, v->post_quant.oc));
585    VAE_TRY(conv(v, v->post_quant, z, G_PLAIN, nullptr, y, nullptr, nullptr, 0));
586    free_t(v, z);
587    VAE_TRY(alloc_t(v, x, h, w, v->conv_in.oc));
588    VAE_TRY(conv(v, v->conv_in, y, G_PLAIN, nullptr, x, nullptr, nullptr, 0));
589    free_t(v, y);
590    VAE_TRY(stage(v, "conv_in", x));
591    VAE_TRY(resnet(v, v->mid0, x));
592    VAE_TRY(attention(v, x));
593    VAE_TRY(stage(v, "mid_attn", x));
594    VAE_TRY(resnet(v, v->mid1, x));
595    VAE_TRY(stage(v, "mid", x));
596    const bool streamed = v->stream_mode == 1;
597    const int HF = 16 * h, WF = 16 * w;                 // the picture
598    std::vector<float> hwc((size_t) HF * WF * 4);
599    for (int i = 0; i < 5; ++i) {
600        Tensor x0;
601        // keep the block's input for the DupUp shortcut: when the first resnet changes the channels it writes a new
602        // tensor anyway, so the input itself is kept; otherwise (blocks 0, 1) it works in place and x0 is a copy
603        const bool alias = UP_HAS[i] && v->up[i][0].has_sc;
604        if (alias) {
605            x0 = x;
606        } else if (UP_HAS[i]) {
607            VAE_TRY(alloc_t(v, x0, x.H, x.W, x.C));
608            VAE_CUDA(cudaMemcpyAsync(x0.d, x.d, (size_t) x.P() * x.C * 4, cudaMemcpyDeviceToDevice, v->stream));
609        }
610        for (int j = 0; j < 3; ++j) VAE_TRY(resnet(v, v->up[i][j], x, alias && j == 0));
611        if (streamed && i == 3) {   // the rest of the picture in row bands (stream_tail), from block 3's upsample on
612            VAE_TRY(stream_tail(v, x, x0, hwc.data()));
613            free_t(v, x);
614            free_t(v, x0);
615            break;
616        }
617        if (UP_HAS[i]) {
618            Tensor u;
619            VAE_TRY(alloc_t(v, u, x.H * 2, x.W * 2, v->resample[i].oc));
620            VAE_TRY(conv(v, v->resample[i], x, G_UP2, nullptr, u, nullptr, &x0, UP_FT[i]));
621            free_t(v, x);
622            free_t(v, x0);
623            x = u;
624        }
625        const char* names[5] = {"up0", "up1", "up2", "up3", "up4"};
626        VAE_TRY(stage(v, names[i], x));
627    }
628    if (!streamed) {
629        Tensor o;
630        VAE_TRY(alloc_t(v, o, x.H, x.W, v->conv_out.oc));
631        VAE_TRY(conv(v, v->conv_out, x, G_NORM_SILU, &v->norm_out, o, nullptr, nullptr, 0));
632        free_t(v, x);
633        VAE_TRY(stage(v, "out", o));
634        VAE_CUDA(cudaMemcpyAsync(hwc.data(), o.d, hwc.size() * 4, cudaMemcpyDeviceToHost, v->stream));
635        free_t(v, o);
636    }
637    VAE_CUDA(cudaEventRecord(e1, v->stream));
638    VAE_CUDA(cudaEventSynchronize(e1));
639    if (streamed && v->dump) v->dump("out", hwc.data(), HF, WF, 4);
640    const int64_t P = (int64_t) HF * WF;
641    for (int c = 0; c < 4; ++c)
642        for (int64_t i = 0; i < P; ++i) out[(size_t) c * P + i] = hwc[(size_t) i * 4 + c];
643    float ms = 0;
644    VAE_CUDA(cudaEventElapsedTime(&ms, e0, e1));
645    cudaEventDestroy(e0);
646    cudaEventDestroy(e1);
647    for (float f : hwc)   // an operand outside the f16 range ends as inf or NaN: the caller falls back instead
648        if (!std::isfinite(f)) return "wan_vae: the picture has values that are not finite (an activation left the f16 range)";
649    if (st) {
650        st->decode_ms = ms;
651        st->weight_bytes = v->weight_bytes;
652        st->peak_bytes = v->weight_bytes + v->pool.peak;
653    }
654    return "";
655}
656
657std::string open_impl(WanVae* v, const std::string& path, int threads) {
658    Loader L;
659    L.path = path;
660    L.threads = threads;
661    using clk = std::chrono::steady_clock;
662    auto ms = [](clk::time_point a, clk::time_point b) { return std::chrono::duration<double, std::milli>(b - a).count(); };
663    const auto t0 = clk::now();
664    VAE_TRY(st_read_header(path, L.file));
665    VAE_TRY(st_read_all_parallel(path, L.file, L.data, L.data_size, threads));
666    const auto t1 = clk::now();
667    VAE_CUDA(cudaSetDevice(v->device));
668    VAE_CUDA(cudaStreamCreateWithFlags(&v->stream, cudaStreamNonBlocking));
669    VAE_BLAS(cublasCreate(&v->blas));
670    VAE_BLAS(cublasSetStream(v->blas, v->stream));
671    const auto t2 = clk::now();
672    VAE_TRY(load_conv(v, L, "post_quant_conv", v->post_quant));
673    VAE_TRY(load_conv(v, L, "decoder.conv_in", v->conv_in));
674    VAE_TRY(load_resnet(v, L, "decoder.mid_block.resnets.0", v->mid0));
675    VAE_TRY(load_norm(v, L, "decoder.mid_block.attentions.0.norm", v->attn_norm));
676    VAE_TRY(load_conv(v, L, "decoder.mid_block.attentions.0.to_qkv", v->qkv));
677    VAE_TRY(load_conv(v, L, "decoder.mid_block.attentions.0.proj", v->proj));
678    VAE_TRY(load_resnet(v, L, "decoder.mid_block.resnets.1", v->mid1));
679    for (int i = 0; i < 5; ++i) {
680        for (int j = 0; j < 3; ++j)
681            VAE_TRY(load_resnet(v, L, "decoder.up_blocks." + std::to_string(i) + ".resnets." + std::to_string(j), v->up[i][j]));
682        if (UP_HAS[i]) VAE_TRY(load_conv(v, L, "decoder.up_blocks." + std::to_string(i) + ".upsampler.resample.1", v->resample[i]));
683    }
684    VAE_TRY(load_norm(v, L, "decoder.norm_out", v->norm_out));
685    VAE_TRY(load_conv(v, L, "decoder.conv_out", v->conv_out));
686    VAE_TRY(convert_and_upload(v, L, &v->open_ms[2], &v->open_ms[3]));
687    v->open_ms[0] = ms(t0, t1);
688    v->open_ms[1] = ms(t1, t2);
689    if (v->post_quant.ic != Z_DIM || v->conv_in.ic != Z_DIM || v->conv_out.oc != 4)
690        return "wan_vae: " + path + " is not a Qwen-Image-2.1 VAE (latent channels / output channels differ)";
691    // the work buffers: the largest K and OC of any layer
692    int kmax = 0, ocmax = 0;
693    auto see = [&](const Conv& c) { kmax = std::max(kmax, c.k * c.k * c.ic); ocmax = std::max(ocmax, c.oc); };
694    see(v->post_quant); see(v->conv_in); see(v->qkv); see(v->proj); see(v->conv_out);
695    for (const Resnet* r : {&v->mid0, &v->mid1}) { see(r->c1); see(r->c2); if (r->has_sc) see(r->sc); }
696    for (int i = 0; i < 5; ++i) {
697        for (int j = 0; j < 3; ++j) { see(v->up[i][j].c1); see(v->up[i][j].c2); if (v->up[i][j].has_sc) see(v->up[i][j].sc); }
698        if (UP_HAS[i]) see(v->resample[i]);
699    }
700    void* d = nullptr;
701    VAE_CUDA(cudaMalloc(&d, (size_t) PB * kmax * 2));
702    v->weights.push_back(d);
703    v->gbuf = (uint16_t*) d;
704    VAE_CUDA(cudaMalloc(&d, (size_t) PB * ocmax * 4));
705    v->weights.push_back(d);
706    v->abuf = (float*) d;
707    v->weight_bytes += (size_t) PB * kmax * 2 + (size_t) PB * ocmax * 4;
708    return "";
709}
710
711}  // namespace
712
713WanVae* wan_vae_open(const std::string& path, int device, std::string* err, int threads) {
714    auto* v = new WanVae();
715    if (device < 0) {
716        if (cudaGetDevice(&device) != cudaSuccess) device = 0;
717    }
718    v->device = device;
719    std::string r = open_impl(v, path, threads);
720    if (!r.empty()) {
721        if (err) *err = r;
722        wan_vae_close(v);
723        return nullptr;
724    }
725    return v;
726}
727
728std::string wan_vae_decode(WanVae* v, const float* latent, int h, int w, float* out, WanVaeStats* stats) {
729    if (!v || !latent || !out || h <= 0 || w <= 0) return "wan_vae: bad arguments";
730    std::string r = decode_impl(v, latent, h, w, out, stats);
731    cudaStreamSynchronize(v->stream);
732    for (auto& b : v->pool.blks) b.used = false;   // after an error part-way, nothing stays held
733    return r;
734}
735
736void wan_vae_denormalize(float* latent, int h, int w) {
737    // wan_vae.hpp get_latents_mean_std, VERSION_QWEN_IMAGE_2_1 (64 channels); diffusion_to_vae_latents computes
738    // (latents * std) / scale_factor + mean, three float operations, scale_factor 1
739    static const float mean[64] = {
740        0.5126f, 0.7721f, -0.0631f, 1.3506f, -0.7855f, -2.1025f, -0.3458f, 1.3722f, 1.8873f, -1.7177f, -0.6510f, 0.2732f,
741        0.7562f, -0.6163f, -1.0277f, 3.8363f, 2.0210f, 0.0472f, 0.9320f, 2.0087f, 2.4954f, -0.1391f, -1.4249f, 1.8464f,
742        -0.5236f, 1.2826f, 3.7046f, -1.3035f, 2.7286f, -1.4518f, -1.9036f, -1.9955f, -0.0342f, -1.0265f, -0.7636f, 3.0555f,
743        0.0746f, -3.0751f, -0.1076f, 1.7376f, -1.0914f, -1.9435f, -0.2784f, -1.3680f, 0.4809f, -0.4433f, 0.3764f, 0.5729f,
744        -2.0595f, 1.0960f, -1.3260f, -2.0211f, -5.0179f, 0.5275f, 4.0162f, 1.8505f, 0.3026f, 1.9373f, 1.4937f, 0.2632f,
745        0.5547f, -1.7121f, -0.1562f, 0.0304f};
746    static const float stdv[64] = {
747        3.2001f, 3.2936f, 3.4321f, 3.0091f, 3.1061f, 4.0379f, 4.0705f, 3.7910f, 3.0785f, 3.6500f, 3.9308f, 3.0904f,
748        2.8778f, 3.7675f, 3.7320f, 5.0756f, 3.2864f, 4.0397f, 3.1317f, 4.0443f, 2.9249f, 3.9454f, 3.0988f, 4.2489f,
749        3.4896f, 3.8513f, 3.9323f, 3.4719f, 3.7498f, 4.2830f, 3.5694f, 4.2467f, 3.9037f, 3.2947f, 5.0770f, 3.5075f,
750        3.2700f, 3.4767f, 2.8063f, 5.1125f, 3.5327f, 4.7833f, 3.1286f, 4.1819f, 3.8527f, 3.8312f, 3.5605f, 4.3875f,
751        3.9624f, 4.0168f, 3.5643f, 4.0550f, 5.5614f, 4.2963f, 4.4080f, 3.4959f, 3.8747f, 3.7608f, 3.5735f, 3.1490f,
752        3.7662f, 3.6746f, 3.4563f, 3.8161f};
753    volatile float one = 1.0f;   // keep the three operations separate, as sd.cpp's Tensor operators are
754    for (int c = 0; c < 64; ++c)
755        for (int i = 0; i < h * w; ++i) {
756            float& x = latent[(size_t) c * h * w + i];
757            float a = x * stdv[c];
758            a = a / one;
759            x = a + mean[c];
760        }
761}
762
763void wan_vae_set_streaming(WanVae* v, bool on) {
764    if (v) v->stream_mode = on ? 1 : 0;
765}
766
767std::string wan_vae_open_report(WanVae* v) {
768    if (!v) return "";
769    char line[200];
770    std::snprintf(line, sizeof(line), "read %.1f ms, device setup %.1f ms, convert %.1f ms, upload %.1f ms",
771                  v->open_ms[0], v->open_ms[1], v->open_ms[2], v->open_ms[3]);
772    return line;
773}
774
775void wan_vae_set_band_rows(WanVae* v, int rows) {
776    if (v) v->band_rows = rows > 0 ? rows : 0;
777}
778
779std::string wan_vae_set_range_stats(WanVae* v, bool on) {
780    if (!v) return "wan_vae: bad arguments";
781    if (on && !v->range_dev) {
782        void* d = nullptr;
783        VAE_CUDA(cudaMalloc(&d, RANGE_BINS * sizeof(unsigned int)));
784        v->range_dev = (unsigned int*) d;
785    }
786    v->range_on = on;
787    return "";
788}
789
790std::string wan_vae_range_report(WanVae* v) {
791    // per convolution: "name shift max_input nonzero sub(s=7..12)": max_input = the largest |input| before the shift
792    // (exact); sub(s) = the share of nonzero inputs that would be f16 subnormal (|input| x 2^-s < 2^-14) at shift s
793    std::string out;
794    if (!v) return out;
795    char line[512];
796    for (const auto& kv : v->range) {
797        const auto& a = kv.second;
798        const int shift = (int) a[258];
799        unsigned int mb = (unsigned int) a[257];
800        float qmax;
801        std::memcpy(&qmax, &mb, 4);
802        const double xmax = std::ldexp((double) qmax, shift);
803        unsigned long long nz = 0;
804        for (int e = 0; e < 256; ++e) nz += a[e];
805        int n = std::snprintf(line, sizeof(line), "%s shift %d max_input %.6g nonzero %llu zeros %llu headroom_now %.3g",
806                              kv.first.c_str(), shift, xmax, nz, a[256], 65504.0 / (qmax > 0 ? qmax : 1e-30));
807        for (int s = 7; s <= 12; ++s) {
808            // input exponent ex = e - 127 + shift; subnormal at shift s when |input| < 2^(s - 14), i.e. ex < s - 14
809            unsigned long long sub = 0;
810            for (int e = 1; e < 256; ++e)
811                if (e - 127 + shift < s - 14) sub += a[e];
812            n += std::snprintf(line + n, sizeof(line) - n, " sub%d %.3g%%", s, nz ? 100.0 * sub / nz : 0.0);
813        }
814        out += line;
815        out += "\n";
816    }
817    return out;
818}
819
820void wan_vae_set_dump(WanVae* v, std::function<void(const char*, const float*, int, int, int)> dump) {
821    if (v) v->dump = std::move(dump);
822}
823
824void wan_vae_close(WanVae* v) {
825    if (!v) return;
826    if (v->stream) cudaStreamSynchronize(v->stream);
827    v->pool.clear();
828    for (void* p : v->weights) cudaFree(p);
829    if (v->range_dev) cudaFree(v->range_dev);
830    if (v->blas) cublasDestroy(v->blas);
831    if (v->stream) cudaStreamDestroy(v->stream);
832    delete v;
833}
834
835}  // namespace strata::image