mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-05 07:48:45 +00:00
Image generation, VAE decoder: f16 headroom for the block-4 shortcut (fixed shift 11), GEMM blocks on the picture's pixel grid (row bands byte-identical on HIP too), and no broken picture on a non-finite value
Operand range (strata-vae-decode --stats over the 16 gate latents, merged per convolution): the only layer within 16x of the f16 maximum under stable-diffusion.cpp's 2^-7 is up_blocks.4.resnets.0.conv_shortcut (largest input 3.48e6, 2.4x headroom); it gets the fixed shift 11 (38.5x). The shift is a constant per layer (conv_shift()), never from the picture's data; vae_ref.py carries the same table and a test checks they agree. Next closest layers: 62.8x and 113x, kept at 7. The row bands were not byte-identical on HIP (R9700: 8 of 16 differed; hipBLAS gives a row another reduction order at another row position of the call). Every convolution now runs its GEMM blocks on the picture's pixel grid, also in a row window (rows outside the window are zero and dropped), so a pixel sits in the same row of a same-shape call in both paths. wan_vae_set_band_rows / --band-rows: vae_identity.py also checks band heights 48 and 100. A picture with a non-finite value is an error (the sd-cli hook then logs "...; using stable-diffusion.cpp's decoder, which may fail the same way", the approved line). Test-only: wan_vae_set_range_stats / wan_vae_range_report. Gates: identity (bands of 128, 48 and 100 rows against one pass, bands run to run) PASS 16 of 16 on CUDA (dgxspark-20261110-1832-ea13) and on HIP (p620-20261110-1832-6e66). Against sd.cpp's CUDA pictures, PSNR worst / mean: CUDA 56.80 / 57.72, 56.20 / 57.50, 57.02 / 57.37 dB at 512, 1024, 1536x1024 (vae_same_tiling pass); HIP 56.81 / 57.71, 56.21 / 57.50, 57.02 / 57.37 dB. Against the previous commit's pictures 79.4-81.2 dB (max 1). Stress, 1024 p4's latent x2 / x4: ours finite, 65.36 / 63.99 dB from the numpy f32 reference (sd.cpp's decoder 53.91 / 49.59 dB); the shortcut's headroom 113x / 133x. Decode (bands) CUDA 0.46-0.48 / 1.03-1.08 / 1.46-1.50 s, HIP 0.82-0.84 / 1.19-1.23 / 1.49-1.50 s. CPU tests 98 passed with the other image tests (boston-20261110-1837-287a).
This commit is contained in:
1 parent
e09b23383e
commit
cab47f3d2c
8 files changed
+188
-34
No files matched your search
@@ -41,6 +41,15 @@ void wan_vae_denormalize(float* latent, int h, int w);
|
||||
// off only for the one-pass reference that the byte-identity test compares against.
|
||||
void wan_vae_set_streaming(WanVae* vae, bool on);
|
||||
|
||||
// Test hook: the row bands `rows` picture rows high instead of the default (0 = default). The picture must not
|
||||
// change with it (tools/image/gate/vae_identity.py checks two other heights against the one-pass decode).
|
||||
void wan_vae_set_band_rows(WanVae* vae, int rows);
|
||||
|
||||
// Test hooks for the operand ranges: collect, per convolution, the exponents and the largest of its inputs during the
|
||||
// next decodes (it does not change any value), and the report (one line per convolution, see wan_vae.cu).
|
||||
std::string wan_vae_set_range_stats(WanVae* vae, bool on);
|
||||
std::string wan_vae_range_report(WanVae* vae);
|
||||
|
||||
// Test hook: called with each stage's output (host copy, pixel-major [H][W][C]) during the next decodes; names as in
|
||||
// tools/image/gate/vae_ref.py (conv_in, mid_attn, mid, up0..up4, out). An empty function turns it off.
|
||||
void wan_vae_set_dump(WanVae* vae, std::function<void(const char*, const float*, int, int, int)> dump);
|
||||
|
||||
+119
-20
@@ -40,8 +40,8 @@ namespace strata::image {
|
||||
namespace {
|
||||
|
||||
constexpr int PB = 8192; // pixels per GEMM band (fixed: see the file comment)
|
||||
constexpr float CONV_SCALE = 0.0078125f; // 2^-7, wan_vae.hpp "Keep large VAE activations within the FP16 range"
|
||||
constexpr float CONV_UNSCALE = 128.0f;
|
||||
constexpr int CONV_SHIFT = 7; // inputs x 2^-7: wan_vae.hpp "Keep large VAE activations within the FP16 range"
|
||||
constexpr int RANGE_BINS = 258; // range statistics: 256 float exponents of |scaled input|, zeros, max bits
|
||||
constexpr float RMS_EPS = 1e-12f;
|
||||
constexpr int Z_DIM = 64;
|
||||
|
||||
@@ -92,7 +92,8 @@ template <int MODE>
|
||||
// own edges; a row outside the window is read as zero too, and the rows that depend on it are never used.
|
||||
__global__ void gather_kernel(const float* __restrict__ src, int Hs, int Ws, int C, int H, int W, int k,
|
||||
int64_t p0, int64_t P, const float* __restrict__ inv, const float* __restrict__ gamma,
|
||||
uint16_t* __restrict__ out, int src_y0, int dst_y0) {
|
||||
uint16_t* __restrict__ out, int src_y0, int dst_y0, float scale,
|
||||
unsigned int* __restrict__ hist) {
|
||||
const int taps = k * k, c8n = C >> 3;
|
||||
const int64_t total = (int64_t) PB * taps * c8n;
|
||||
const int64_t t = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
|
||||
@@ -103,7 +104,7 @@ __global__ void gather_kernel(const float* __restrict__ src, int Hs, int Ws, int
|
||||
const int64_t pl = rest / taps;
|
||||
const int64_t p = p0 + pl;
|
||||
uint16_t h[8] = {0, 0, 0, 0, 0, 0, 0, 0};
|
||||
if (p < P) {
|
||||
if (p >= 0 && p < P) { // rows outside the window (a band's GEMM block reaching past it) stay zero
|
||||
const int y = dst_y0 + (int) (p / W), xq = (int) (p % W);
|
||||
const int yy = y + tap / k - k / 2, xx = xq + tap % k - k / 2;
|
||||
const int ly = (MODE == G_UP2 ? (yy >> 1) : yy) - src_y0;
|
||||
@@ -119,7 +120,12 @@ __global__ void gather_kernel(const float* __restrict__ src, int Hs, int Ws, int
|
||||
float q = v[i];
|
||||
if (MODE == G_NORM || MODE == G_NORM_SILU) q = (q * r) * gamma[c8 * 8 + i];
|
||||
if (MODE == G_NORM_SILU) q = q / (1.0f + expf(-q));
|
||||
q = q * CONV_SCALE;
|
||||
q = q * scale; // an exact power of two (the layer's fixed shift)
|
||||
if (hist) { // test-only range statistics (wan_vae_set_range_stats)
|
||||
const unsigned int b = __float_as_uint(q) & 0x7FFFFFFFu;
|
||||
atomicAdd(&hist[b ? (b >> 23) : 256], 1u);
|
||||
atomicMax(&hist[257], b);
|
||||
}
|
||||
h[i] = strata::kernels::f16_from_f32(q);
|
||||
}
|
||||
}
|
||||
@@ -134,14 +140,14 @@ __global__ void gather_kernel(const float* __restrict__ src, int Hs, int Ws, int
|
||||
|
||||
// dst[p][oc] = ((acc * 2^7 + bias) + res) + dup; dup = the DupUp3D shortcut of x0 [Hs][Ws][C0] for an output of
|
||||
// [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.
|
||||
__global__ void epilogue_kernel(const float* __restrict__ acc, int OC, int64_t p0, int64_t nvalid,
|
||||
__global__ void epilogue_kernel(const float* __restrict__ acc, int OC, int64_t p0, int64_t pl_lo, int64_t nvalid,
|
||||
const float* __restrict__ bias, const float* res, float* dst, int W,
|
||||
const float* __restrict__ x0, int C0, int ft, int dst_y0, int x0_y0) {
|
||||
const float* __restrict__ x0, int C0, int ft, int dst_y0, int x0_y0, float unscale) {
|
||||
const int64_t t = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (t >= nvalid * OC) return;
|
||||
const int oc = (int) (t % OC);
|
||||
const int64_t pl = t / OC, p = p0 + pl;
|
||||
float v = acc[pl * OC + oc] * CONV_UNSCALE;
|
||||
const int64_t pl = pl_lo + t / OC, p = p0 + pl;
|
||||
float v = acc[pl * OC + oc] * unscale;
|
||||
v = v + bias[oc];
|
||||
if (res) v = v + res[p * OC + oc];
|
||||
if (x0) {
|
||||
@@ -223,7 +229,13 @@ struct Tensor {
|
||||
int64_t P() const { return (int64_t) H * W; }
|
||||
};
|
||||
|
||||
struct Conv { int ic = 0, oc = 0, k = 0; uint16_t* w = nullptr; float* b = nullptr; };
|
||||
struct Conv {
|
||||
int ic = 0, oc = 0, k = 0;
|
||||
int shift = CONV_SHIFT; // operand = input x 2^-shift (fixed per layer: conv_shift())
|
||||
uint16_t* w = nullptr;
|
||||
float* b = nullptr;
|
||||
std::string name;
|
||||
};
|
||||
struct Norm { int c = 0; float* g = nullptr; };
|
||||
struct Resnet { Norm n1, n2; Conv c1, c2, sc; bool has_sc = false; };
|
||||
|
||||
@@ -244,6 +256,10 @@ struct WanVae {
|
||||
uint16_t* gbuf = nullptr; // [PB][Kmax] f16
|
||||
float* abuf = nullptr; // [PB][OCmax] f32
|
||||
std::function<void(const char*, const float*, int, int, int)> dump;
|
||||
bool range_on = false; // test-only range statistics (wan_vae_set_range_stats)
|
||||
unsigned int* range_dev = nullptr;
|
||||
std::map<std::string, std::vector<unsigned long long>> range; // per conv: exponent bins, zeros, max bits, shift
|
||||
int band_rows = 0; // 0: STREAM_ROWS; other heights only for the identity test (wan_vae_set_band_rows)
|
||||
int stream_mode = 1; // 1 the row-band tail (always, coordinator 11-10); 0 the one-pass reference (tests)
|
||||
};
|
||||
|
||||
@@ -284,6 +300,20 @@ struct Loader {
|
||||
}
|
||||
};
|
||||
|
||||
// The fixed operand shift of each convolution (input x 2^-shift -> f16; output x 2^shift, both exact): stable-
|
||||
// diffusion.cpp's 2^-7 everywhere, except the layers listed here. Fixed per layer, never from the picture's data (a
|
||||
// data-dependent scale would differ between a band and the whole picture and break the byte-identity gate).
|
||||
// Chosen from the measured ranges (strata-vae-decode --stats over the 16 gate latents, 11-10, Spark; RESULTS-OWN-5):
|
||||
// every layer whose largest input came within 16x of the f16 maximum after 2^-7 gets at least 16x headroom.
|
||||
// decoder.up_blocks.4.resnets.0.conv_shortcut: largest input 3.48e6 (1024 p4), 2.4x headroom at shift 7;
|
||||
// shift 11 -> 38.5x. Share of its nonzero inputs that are f16-subnormal: 0.08% at shift 7, 1.24% at shift 11
|
||||
// (inputs below 2^-3 against a largest input of 3.48e6; their absolute error stays under 2^-14).
|
||||
// Next closest: up_blocks.3.upsampler.resample.1 62.8x, up_blocks.3.resnets.0.conv_shortcut 113x: kept at 7.
|
||||
int conv_shift(const std::string& name) {
|
||||
if (name == "decoder.up_blocks.4.resnets.0.conv_shortcut") return 11;
|
||||
return CONV_SHIFT;
|
||||
}
|
||||
|
||||
std::string load_conv(WanVae* v, Loader& L, const std::string& name, Conv& cv) {
|
||||
std::vector<float> w, b;
|
||||
std::vector<int64_t> sh;
|
||||
@@ -292,6 +322,8 @@ std::string load_conv(WanVae* v, Loader& L, const std::string& name, Conv& cv) {
|
||||
if (sh.size() != 4 || sh[2] != sh[3] || (sh[2] != 1 && sh[2] != 3) || (int64_t) b.size() != sh[0] || sh[1] % 8 != 0)
|
||||
return "wan_vae: " + name + ": unexpected shape";
|
||||
cv.oc = (int) sh[0];
|
||||
cv.name = name;
|
||||
cv.shift = conv_shift(name);
|
||||
cv.ic = (int) sh[1];
|
||||
cv.k = (int) sh[2];
|
||||
const int taps = cv.k * cv.k, K = taps * cv.ic;
|
||||
@@ -357,26 +389,44 @@ std::string conv(WanVae* v, const Conv& cv, const Tensor& src, int mode, const N
|
||||
}
|
||||
const int K = cv.k * cv.k * cv.ic;
|
||||
const float one = 1.f, zero = 0.f;
|
||||
for (int64_t p0 = 0; p0 < P; p0 += PB) {
|
||||
const float scale = std::ldexp(1.0f, -cv.shift), unscale = std::ldexp(1.0f, cv.shift); // exact powers of two
|
||||
unsigned int* hist = v->range_on ? v->range_dev : nullptr;
|
||||
if (hist) VAE_CUDA(cudaMemsetAsync(hist, 0, RANGE_BINS * sizeof(unsigned int), v->stream));
|
||||
// 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:
|
||||
// every pixel then sits in the same row of a same-shape GEMM in the row bands as in the one-pass decode. hipBLAS
|
||||
// (R9700, 11-10) gives a row a different reduction order at a different row position of the call; cuBLAS did not.
|
||||
const int64_t g0 = (int64_t) dst.y0 * W; // the window's first pixel in the picture
|
||||
for (int64_t p0 = (g0 / PB) * PB - g0; p0 < P; p0 += PB) { // p0: the block's first pixel, window-local (<= 0)
|
||||
const int64_t total = (int64_t) PB * cv.k * cv.k * (cv.ic / 8);
|
||||
const unsigned blocks = (unsigned) ((total + 255) / 256);
|
||||
switch (mode) {
|
||||
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); break;
|
||||
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); break;
|
||||
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); break;
|
||||
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); break;
|
||||
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;
|
||||
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;
|
||||
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;
|
||||
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;
|
||||
}
|
||||
VAE_CUDA(cudaGetLastError());
|
||||
VAE_BLAS(cublasGemmEx(v->blas, CUBLAS_OP_T, CUBLAS_OP_N, cv.oc, PB, K, &one, cv.w, CUDA_R_16F, K, v->gbuf,
|
||||
CUDA_R_16F, K, &zero, v->abuf, CUDA_R_32F, cv.oc, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT));
|
||||
const int64_t nvalid = (P - p0) < PB ? (P - p0) : PB;
|
||||
const int64_t lo = p0 < 0 ? -p0 : 0; // the block's rows inside the window
|
||||
const int64_t nvalid = std::min<int64_t>(PB, P - p0) - lo;
|
||||
const int64_t et = nvalid * cv.oc;
|
||||
epilogue_kernel<<<(unsigned) ((et + 255) / 256), 256, 0, v->stream>>>(
|
||||
v->abuf, cv.oc, p0, nvalid, cv.b, res, dst.d, W, x0 ? x0->d : nullptr, x0 ? x0->C : 0, ft, dst.y0,
|
||||
x0 ? x0->y0 : 0);
|
||||
v->abuf, cv.oc, p0, lo, nvalid, cv.b, res, dst.d, W, x0 ? x0->d : nullptr, x0 ? x0->C : 0, ft, dst.y0,
|
||||
x0 ? x0->y0 : 0, unscale);
|
||||
VAE_CUDA(cudaGetLastError());
|
||||
}
|
||||
if (inv) v->pool.put(inv);
|
||||
if (hist) {
|
||||
unsigned int h[RANGE_BINS];
|
||||
VAE_CUDA(cudaMemcpyAsync(h, hist, sizeof(h), cudaMemcpyDeviceToHost, v->stream));
|
||||
VAE_CUDA(cudaStreamSynchronize(v->stream));
|
||||
auto& acc = v->range[cv.name];
|
||||
acc.resize(RANGE_BINS + 1, 0);
|
||||
for (int i = 0; i < 257; ++i) acc[i] += h[i];
|
||||
acc[257] = std::max<unsigned long long>(acc[257], h[257]);
|
||||
acc[258] = (unsigned long long) cv.shift;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
@@ -444,8 +494,9 @@ constexpr int STREAM_HALO = 7;
|
||||
|
||||
std::string stream_tail(WanVae* v, const Tensor& x, const Tensor& x0, float* hwc) {
|
||||
const int H = x.Hi * 2, W = x.W * 2;
|
||||
for (int o0 = 0; o0 < H; o0 += STREAM_ROWS) {
|
||||
const int o1 = std::min(H, o0 + STREAM_ROWS);
|
||||
const int rows = v->band_rows > 0 ? v->band_rows : STREAM_ROWS;
|
||||
for (int o0 = 0; o0 < H; o0 += rows) {
|
||||
const int o1 = std::min(H, o0 + rows);
|
||||
const int a = std::max(0, o0 - STREAM_HALO), b = std::min(H, o1 + STREAM_HALO);
|
||||
Tensor u, o;
|
||||
VAE_TRY(alloc_t(v, u, b - a, W, v->resample[3].oc, a, H));
|
||||
@@ -541,6 +592,8 @@ std::string decode_impl(WanVae* v, const float* latent, int h, int w, float* out
|
||||
VAE_CUDA(cudaEventElapsedTime(&ms, e0, e1));
|
||||
cudaEventDestroy(e0);
|
||||
cudaEventDestroy(e1);
|
||||
for (float f : hwc) // an operand outside the f16 range ends as inf or NaN: the caller falls back instead
|
||||
if (!std::isfinite(f)) return "wan_vae: the picture has values that are not finite (an activation left the f16 range)";
|
||||
if (st) {
|
||||
st->decode_ms = ms;
|
||||
st->weight_bytes = v->weight_bytes;
|
||||
@@ -649,6 +702,51 @@ void wan_vae_set_streaming(WanVae* v, bool on) {
|
||||
if (v) v->stream_mode = on ? 1 : 0;
|
||||
}
|
||||
|
||||
void wan_vae_set_band_rows(WanVae* v, int rows) {
|
||||
if (v) v->band_rows = rows > 0 ? rows : 0;
|
||||
}
|
||||
|
||||
std::string wan_vae_set_range_stats(WanVae* v, bool on) {
|
||||
if (!v) return "wan_vae: bad arguments";
|
||||
if (on && !v->range_dev) {
|
||||
void* d = nullptr;
|
||||
VAE_CUDA(cudaMalloc(&d, RANGE_BINS * sizeof(unsigned int)));
|
||||
v->range_dev = (unsigned int*) d;
|
||||
}
|
||||
v->range_on = on;
|
||||
return "";
|
||||
}
|
||||
|
||||
std::string wan_vae_range_report(WanVae* v) {
|
||||
// per convolution: "name shift max_input nonzero sub(s=7..12)": max_input = the largest |input| before the shift
|
||||
// (exact); sub(s) = the share of nonzero inputs that would be f16 subnormal (|input| x 2^-s < 2^-14) at shift s
|
||||
std::string out;
|
||||
if (!v) return out;
|
||||
char line[512];
|
||||
for (const auto& kv : v->range) {
|
||||
const auto& a = kv.second;
|
||||
const int shift = (int) a[258];
|
||||
unsigned int mb = (unsigned int) a[257];
|
||||
float qmax;
|
||||
std::memcpy(&qmax, &mb, 4);
|
||||
const double xmax = std::ldexp((double) qmax, shift);
|
||||
unsigned long long nz = 0;
|
||||
for (int e = 0; e < 256; ++e) nz += a[e];
|
||||
int n = std::snprintf(line, sizeof(line), "%s shift %d max_input %.6g nonzero %llu zeros %llu headroom_now %.3g",
|
||||
kv.first.c_str(), shift, xmax, nz, a[256], 65504.0 / (qmax > 0 ? qmax : 1e-30));
|
||||
for (int s = 7; s <= 12; ++s) {
|
||||
// input exponent ex = e - 127 + shift; subnormal at shift s when |input| < 2^(s - 14), i.e. ex < s - 14
|
||||
unsigned long long sub = 0;
|
||||
for (int e = 1; e < 256; ++e)
|
||||
if (e - 127 + shift < s - 14) sub += a[e];
|
||||
n += std::snprintf(line + n, sizeof(line) - n, " sub%d %.3g%%", s, nz ? 100.0 * sub / nz : 0.0);
|
||||
}
|
||||
out += line;
|
||||
out += "\n";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void wan_vae_set_dump(WanVae* v, std::function<void(const char*, const float*, int, int, int)> dump) {
|
||||
if (v) v->dump = std::move(dump);
|
||||
}
|
||||
@@ -658,6 +756,7 @@ void wan_vae_close(WanVae* v) {
|
||||
if (v->stream) cudaStreamSynchronize(v->stream);
|
||||
v->pool.clear();
|
||||
for (void* p : v->weights) cudaFree(p);
|
||||
if (v->range_dev) cudaFree(v->range_dev);
|
||||
if (v->blas) cublasDestroy(v->blas);
|
||||
if (v->stream) cudaStreamDestroy(v->stream);
|
||||
delete v;
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
// src/image/vae/wan_vae_decode_main.cpp - test program for Strata's VAE decoder (OWN-5 gate harness).
|
||||
//
|
||||
// strata-vae-decode <vae.safetensors> <latent.bin> <out.f32> [--dump DIR] [--repeat N] [--device D] [--stream on|off]
|
||||
// strata-vae-decode <vae.safetensors> <latent.bin> <out.f32> [--dump DIR] [--repeat N] [--device D] [--stream on|off] [--band-rows N] [--stats FILE]
|
||||
//
|
||||
// latent.bin: the diffusion-space latent as run_set.py --dump writes it (float32 planar [64][h][w], latent.shape beside
|
||||
// it says "w h 64 1"); it is denormalized like sd.cpp's decode_first_stage does, then decoded. out.f32: float32
|
||||
// planar [4][16h][16w] (before sd.cpp's 0-1 scaling; tools/image/gate/vae_ref.py --png makes the picture).
|
||||
// --dump DIR writes every stage as DIR/<name>.f32 (pixel-major [H][W][C]) with DIR/<name>.shape "H W C".
|
||||
// --band-rows N: the row bands N picture rows high instead of the default (the identity test only).
|
||||
// --stats FILE: the operand range report of the decode (wan_vae_range_report) into FILE.
|
||||
// --stream off: the one-pass reference decode (the product always uses the row bands; same bytes, more memory).
|
||||
// --repeat N decodes N times and checks that every run gives the same bytes (run to run), printing each time.
|
||||
// Prints one line per run: "decode <ms> ms, peak <MiB> MiB (weights+work <MiB>)".
|
||||
@@ -35,13 +37,15 @@ int main(int argc, char** argv) {
|
||||
std::fprintf(stderr, "usage: strata-vae-decode <vae.safetensors> <latent.bin> <out.f32> [--dump DIR] [--repeat N] [--device D]\n");
|
||||
return 2;
|
||||
}
|
||||
std::string vae = argv[1], lat = argv[2], outp = argv[3], dump_dir;
|
||||
int repeat = 1, device = -1, stream = 1;
|
||||
std::string vae = argv[1], lat = argv[2], outp = argv[3], dump_dir, stats_path;
|
||||
int repeat = 1, device = -1, stream = 1, band_rows = 0;
|
||||
for (int i = 4; i + 1 < argc; i += 2) {
|
||||
if (!std::strcmp(argv[i], "--dump")) dump_dir = argv[i + 1];
|
||||
else if (!std::strcmp(argv[i], "--repeat")) repeat = std::atoi(argv[i + 1]);
|
||||
else if (!std::strcmp(argv[i], "--device")) device = std::atoi(argv[i + 1]);
|
||||
else if (!std::strcmp(argv[i], "--stream")) stream = !std::strcmp(argv[i + 1], "on");
|
||||
else if (!std::strcmp(argv[i], "--stats")) stats_path = argv[i + 1];
|
||||
else if (!std::strcmp(argv[i], "--band-rows")) band_rows = std::atoi(argv[i + 1]);
|
||||
}
|
||||
std::string shp = lat.substr(0, lat.size() - 4) + ".shape";
|
||||
std::ifstream sf(shp);
|
||||
@@ -65,6 +69,8 @@ int main(int argc, char** argv) {
|
||||
}
|
||||
std::printf("open %.1f ms\n", std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t_open).count());
|
||||
wan_vae_set_streaming(v, stream != 0);
|
||||
if (band_rows > 0) wan_vae_set_band_rows(v, band_rows);
|
||||
if (!stats_path.empty()) wan_vae_set_range_stats(v, true);
|
||||
if (!dump_dir.empty()) {
|
||||
wan_vae_set_dump(v, [&](const char* name, const float* data, int H, int W, int C) {
|
||||
std::string b = dump_dir + "/" + name;
|
||||
@@ -97,6 +103,9 @@ int main(int argc, char** argv) {
|
||||
if (!f || std::fwrite(first.data(), 4, n_out, f) != n_out) rc = 6;
|
||||
if (f) std::fclose(f);
|
||||
}
|
||||
if (!stats_path.empty()) { // the range report of all runs, one line per convolution
|
||||
if (FILE* f = std::fopen(stats_path.c_str(), "w")) { std::fputs(wan_vae_range_report(v).c_str(), f); std::fclose(f); }
|
||||
}
|
||||
wan_vae_close(v);
|
||||
return rc;
|
||||
}
|
||||
@@ -69,6 +69,17 @@ class Pieces(unittest.TestCase):
|
||||
with self.assertRaises(OverflowError):
|
||||
dec.conv("c", np.full((1, 1, 1), 70000.0 * 128, np.float32))
|
||||
|
||||
def test_shift_table_matches_the_decoder(self):
|
||||
"""vae_ref's CONV_SHIFTS is the table of src/image/vae/wan_vae.cu conv_shift(), so "f16op" models our operands."""
|
||||
import re
|
||||
cu = (Path(__file__).resolve().parents[3] / "src" / "image" / "vae" / "wan_vae.cu").read_text(encoding="utf-8")
|
||||
body = cu[cu.index("int conv_shift(const std::string& name) {"):]
|
||||
body = body[:body.index("\n}\n")]
|
||||
table = {m.group(1): int(m.group(2)) for m in re.finditer(r'if \(name == "([^"]+)"\) return (\d+);', body)}
|
||||
self.assertEqual(table, V.CONV_SHIFTS)
|
||||
self.assertIn("return CONV_SHIFT;", body)
|
||||
self.assertIn("constexpr int CONV_SHIFT = 7;", cu)
|
||||
|
||||
def test_bf16_reader(self):
|
||||
vals = np.array([1.0, -2.5, 0.15625], np.float32)
|
||||
raw = (vals.view(np.uint32) >> 16).astype(np.uint16).tobytes()
|
||||
|
||||
@@ -4,8 +4,9 @@ the one-pass reference decode, byte for byte, for every fixed latent of the stag
|
||||
python -I -B vae_identity.py <strata-vae-decode> <vae.safetensors> <pics root> <latent tag> [<latent tag> ...]
|
||||
|
||||
For each <pics root>/<tag>/dump_<name>/latent.bin: decode with --stream off (one pass) and --stream on --repeat 2
|
||||
(row bands, twice in one process); prints the peak memory and time of both and IDENTICAL / DIFFERENT; exit 1 if any
|
||||
pair differs (gate: all identical at 512, 1024 and 1536x1024)."""
|
||||
(row bands, twice in one process), and with two other band heights (--band-rows 48 and 100: other positions of the
|
||||
pixels in their GEMM blocks than the default 128 rows); prints the peak memory and time and IDENTICAL / DIFFERENT;
|
||||
exit 1 if anything differs (gate: all identical at 512, 1024 and 1536x1024, on CUDA and on HIP)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
@@ -14,6 +15,7 @@ import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
OTHER_BAND_ROWS = (48, 100)
|
||||
LINE = re.compile(r"decode (\d+)x(\d+) run (\d+): ([\d.]+) ms, peak (\d+) MiB(?:.*(identical|DIFFERS))?")
|
||||
|
||||
|
||||
@@ -41,12 +43,20 @@ def main(argv) -> int:
|
||||
bad += 1
|
||||
print(f"{name}: FAILED rc {rc1}/{rc2} {(e1 + e2).strip()[-300:]}")
|
||||
continue
|
||||
same = one.read_bytes() == band.read_bytes()
|
||||
ref = one.read_bytes()
|
||||
same = ref == band.read_bytes()
|
||||
others = []
|
||||
for rows in OTHER_BAND_ROWS:
|
||||
rc3, r3, e3 = run(exe, vae, d / "latent.bin", band, ["--stream", "on", "--band-rows", str(rows)])
|
||||
ok = rc3 == 0 and bool(r3) and band.read_bytes() == ref
|
||||
others.append(f"{rows} rows {'IDENTICAL' if ok else 'DIFFERENT'}")
|
||||
same = same and ok
|
||||
rtr = all(g[5] == "identical" for g in r2[1:])
|
||||
bad += (not same) or (not rtr)
|
||||
print(f"{name} {r1[0][0]}x{r1[0][1]}: one pass {float(r1[0][3]):.0f} ms peak {r1[0][4]} MiB, "
|
||||
f"bands {float(r2[0][3]):.0f} ms peak {r2[0][4]} MiB: "
|
||||
f"{'IDENTICAL' if same else 'DIFFERENT'}, bands run to run {'identical' if rtr else 'DIFFERENT'}")
|
||||
f"{'IDENTICAL' if same else 'DIFFERENT'} ({', '.join(others)}), bands run to run "
|
||||
f"{'identical' if rtr else 'DIFFERENT'}")
|
||||
print(f"VAE-IDENTITY {'PASS' if bad == 0 else 'FAIL'}: {n - bad} of {n}")
|
||||
return 0 if bad == 0 else 1
|
||||
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
stable-diffusion.cpp 2988060 runs it for one picture (src/model/vae/wan_vae.hpp, VERSION_QWEN_IMAGE_2_1, 2D weights).
|
||||
|
||||
It is the oracle for our own GPU decoder (src/image/vae): the per-stage values, the activation ranges (what must fit
|
||||
the f16 operands), and the f32 picture our decode is measured against besides sd.cpp's own.
|
||||
the f16 operands), and the f32 picture our decode is measured against besides sd.cpp's own. "f16op" uses our decoder's per-layer operand
|
||||
shifts (CONV_SHIFTS; shifts=False for sd.cpp's 2^-7 everywhere).
|
||||
|
||||
The decoder, pixel-major (HWC, float32): latent (64 ch) -> post_quant_conv 1x1 -> conv_in 3x3 (1152) -> mid block
|
||||
(resnet, attention, resnet) -> up_blocks 0..4 (1152, 1152, 576, 288, 144 channels; 3 resnets each; blocks 0-3 end in
|
||||
@@ -50,6 +51,8 @@ LATENT_STD = [3.2001, 3.2936, 3.4321, 3.0091, 3.1061, 4.0379, 4.0705, 3.7910,
|
||||
3.8747, 3.7608, 3.5735, 3.1490, 3.7662, 3.6746, 3.4563, 3.8161]
|
||||
|
||||
CONV_SCALE = np.float32(1.0 / 128.0) # wan_vae.hpp: "Keep large VAE activations within the FP16 convolution range"
|
||||
# Strata's decoder (src/image/vae/wan_vae.cu conv_shift) uses other fixed shifts for these layers (f16 headroom)
|
||||
CONV_SHIFTS = {"decoder.up_blocks.4.resnets.0.conv_shortcut": 11}
|
||||
F16_MAX = 65504.0
|
||||
# up block i: (in, out, DupUp factor_t, has upsampler); wan_vae.hpp temperal_upsample {true, true, true, false}
|
||||
UP_BLOCKS = [(1152, 1152, 2, True), (1152, 1152, 2, True), (1152, 576, 2, True), (576, 288, 1, True), (288, 144, 1, False)]
|
||||
@@ -84,9 +87,11 @@ def load_safetensors(path, prefix="") -> dict:
|
||||
|
||||
|
||||
class Decoder:
|
||||
def __init__(self, weights: dict, mode: str = "f32", stats: bool = False):
|
||||
def __init__(self, weights: dict, mode: str = "f32", stats: bool = False, shifts: bool = True):
|
||||
"""shifts: Strata's per-layer operand shifts (CONV_SHIFTS); False = sd.cpp's 2^-7 everywhere ("f16op" only
|
||||
differs; in "f32" a power-of-two scale is exact)."""
|
||||
assert mode in ("f32", "f16op")
|
||||
self.w, self.mode = weights, mode
|
||||
self.w, self.mode, self.shifts = weights, mode, shifts
|
||||
self.stats = {} if stats else None
|
||||
self.cache = {}
|
||||
|
||||
@@ -110,11 +115,12 @@ class Decoder:
|
||||
"""3x3 (pad 1) or 1x1 conv of x [H, W, IC] -> [H, W, OC]; the input scaled by 2^-7 like sd.cpp."""
|
||||
wm, k, bias = self._conv_w(name)
|
||||
H, W, C = x.shape
|
||||
xs = x * CONV_SCALE
|
||||
scale = np.float32(2.0 ** -CONV_SHIFTS.get(name, 7)) if self.shifts else CONV_SCALE
|
||||
xs = x * scale
|
||||
self._note(name + ":in_scaled", xs)
|
||||
if self.mode == "f16op":
|
||||
if np.abs(xs).max() > F16_MAX:
|
||||
raise OverflowError(f"{name}: conv input exceeds the f16 range after the 2^-7 scale")
|
||||
raise OverflowError(f"{name}: conv input exceeds the f16 range after its scale")
|
||||
xs = xs.astype(np.float16).astype(np.float32)
|
||||
oc = wm.shape[1]
|
||||
out = np.empty((H, W, oc), dtype=np.float32)
|
||||
@@ -128,7 +134,7 @@ class Decoder:
|
||||
y1 = min(H, y0 + step)
|
||||
cols = np.concatenate([pad[y0 + dy:y1 + dy, dx:dx + W] for dy in range(3) for dx in range(3)], axis=2)
|
||||
out[y0:y1] = (cols.reshape(-1, 9 * C).astype(np.float64) @ wm).reshape(y1 - y0, W, oc)
|
||||
out = out / CONV_SCALE # x 2^7: exact
|
||||
out = out / scale # x 2^shift: exact
|
||||
out += bias
|
||||
return out
|
||||
|
||||
|
||||
@@ -71,7 +71,12 @@ DECODE_NEW = """ auto latents = first_stage_model->diffu
|
||||
strata_stats.peak_bytes / 1048576.0);
|
||||
return decoded;
|
||||
}
|
||||
LOG_WARN("strata VAE decoder: %s; using stable-diffusion.cpp's decoder", strata_err.c_str());
|
||||
if (strata_err.find("not finite") != std::string::npos) { // sd.cpp's decoder has the same f16 operands
|
||||
LOG_WARN("strata VAE decoder: %s; using stable-diffusion.cpp's decoder, which may fail the same way",
|
||||
strata_err.c_str());
|
||||
} else {
|
||||
LOG_WARN("strata VAE decoder: %s; using stable-diffusion.cpp's decoder", strata_err.c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -79,6 +79,11 @@ class Apply(unittest.TestCase):
|
||||
# the fallback: the reason goes into the warning, then stable-diffusion.cpp's decoder runs (no return)
|
||||
self.assertEqual(eng.count('LOG_WARN("strata VAE decoder: %s; using stable-diffusion.cpp\'s decoder", '
|
||||
'strata_err.c_str());'), 2)
|
||||
# a non-finite picture: the warning says that sd.cpp's decoder (the same f16 operands) may fail the same way
|
||||
self.assertIn('if (strata_err.find("not finite") != std::string::npos)', eng)
|
||||
self.assertIn("using stable-diffusion.cpp's decoder, which may fail the same way", eng)
|
||||
cu = (ROOT / "src" / "image" / "vae" / "wan_vae.cu").read_text(encoding="utf-8")
|
||||
self.assertIn('"wan_vae: the picture has values that are not finite', cu) # the reason the hook looks for
|
||||
self.assertLess(eng.index("return decoded;"), eng.rindex("LOG_WARN"))
|
||||
self.assertLess(eng.rindex("LOG_WARN"), eng.index("auto tiling_params"))
|
||||
self.assertIn("add_library(strata_vae STATIC", cm)
|
||||
|
||||
Reference in new issue
Block a user