Skip to content

Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

qwenimage: the VAE decoder on the device when the chain runs

JustVugg77619f377bc8
diff --git a/c/Makefile b/c/Makefile
index 4b86266f..83a32933 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -746,6 +746,8 @@ VK_SPV += shaders/chain_attn_flash.spv
# a diffusion step's attention, every query row over every key row (made on first use;
# qwenimage_chain.h)
VK_SPV += shaders/chain_attn_full.spv
+# Qwen-Image's VAE decoder: a band's 3x3 taps and the DupUp3D shortcut (made on first use)
+VK_SPV += shaders/chain_vae.spv
endif
# Optional AMD XDNA2 (Ryzen AI NPU) lane, Windows. Same opt-in shape as VK=1:
diff --git a/c/qwenimage.c b/c/qwenimage.c
index 141083e0..f6d41cc9 100644
--- a/c/qwenimage.c
+++ b/c/qwenimage.c
@@ -762,6 +762,19 @@ static void dit_step_free(DitStep *s){
#ifdef COLI_VULKAN
#include "qwenimage_chain.h" /* COLI_VK_CHAIN: every block of a step on the device */
+#ifdef QI_HAVE_VAE
+#include "qwenimage_vae_vk.h" /* and the VAE decoder after it */
+#endif
+#endif
+#ifdef QI_HAVE_VAE
+/* The VAE decode: on the device when the transformer's chain runs, else (or when the
+ * device's decode fails) the CPU's. */
+static int qi_vae_decode(QiVae *v, const float *z, int h, int w, uint8_t *rgba, float *out_f){
+#ifdef COLI_VULKAN
+ if (g_qic_on > 0 && !g_qic.failed && qvv_decode(v, z, h, w, rgba, out_f) == 0) return 0;
+#endif
+ return qiv_decode(v, z, h, w, rgba, out_f);
+}
#endif
static void dit_forward(Dit *d, const Prefix *p, DitStep *s, const float *lat, float t, float *out){
#ifdef COLI_VULKAN
@@ -1070,7 +1083,7 @@ static int engine_generate(Engine *e, const char *prompt, int width, int height,
emit_progress(pg, "decode", steps, steps, t0);
#ifdef QI_HAVE_VAE
if (!e->vae && !(e->vae = engine_vae(e, msg, msgn))) rc = -1;
- if (rc == 0 && qiv_decode(e->vae, lat, gh, gw, rgba, NULL) != 0) { snprintf(msg, msgn, "VAE decode failed"); rc = -1; }
+ if (rc == 0 && qi_vae_decode(e->vae, lat, gh, gw, rgba, NULL) != 0) { snprintf(msg, msgn, "VAE decode failed"); rc = -1; }
#else
/* no VAE compiled in: show the first three latent channels, stretched */
for (int y = 0; y < height; y++)
@@ -1387,7 +1400,7 @@ static int run_oracle(Engine *e, const char *refdir){
if (vae && fin) {
uint8_t *rgba = xmalloc((size_t)width * height * 4);
float *of = fmalloc((size_t)4 * width * height);
- qiv_decode(vae, fin, gh, gw, rgba, of);
+ qi_vae_decode(vae, fin, gh, gw, rgba, of);
float *img_ref = ref_tensor(&R, "vae_out", NULL);
if (img_ref) fails += cmp("VAE output (ref latents)", of, img_ref, (size_t)4 * width * height) > LOOSE;
st_tensor *rt = st_find(&R, "rgba");
@@ -1403,7 +1416,7 @@ static int run_oracle(Engine *e, const char *refdir){
}
const char *tag = getenv("QWENIMAGE_ORACLE_TAG");
char out[2200]; snprintf(out, sizeof out, "%s/oracle_c%s%s.png", refdir, tag ? "_" : "", tag ? tag : "");
- qiv_decode(vae, mine, gh, gw, rgba, NULL);
+ qi_vae_decode(vae, mine, gh, gw, rgba, NULL);
if (!write_png(out, rgba, width, height)) fprintf(stderr, "[oracle] our own chained image: %s\n", out);
/* PSNR of the RGB of our chained image against the reference's: the
* number that says what int8 weights or activations cost in pixels */
@@ -1434,6 +1447,9 @@ static void qi_vk_report(void){
#ifdef COLI_VULKAN
if (g_vk_ready) fprintf(stderr, "[VK] qwenimage: %llu matmuls on the GPU\n", coli_vk_matmul_calls());
qic_report();
+#ifdef QI_HAVE_VAE
+ if (g_qvv.decodes) fprintf(stderr, "[VK] qwenimage vae: %llu decodes on the device\n", g_qvv.decodes);
+#endif
#endif
}
diff --git a/c/qwenimage_vae.h b/c/qwenimage_vae.h
index 2739eac3..059c2702 100644
--- a/c/qwenimage_vae.h
+++ b/c/qwenimage_vae.h
@@ -66,11 +66,13 @@ typedef struct {
int cin, cout, k; /* k = 1 or 3 */
float *w, *b; /* w: [cout][kx][ky][cin] */
QiMat m;
+ void *vk; int bo; /* qwenimage_vae_vk.h: the device's copy of w, b's place in its parameters */
} QivConv;
typedef struct {
int cin, cout;
float *g1, *g2; /* RMS norm gammas, [cin] and [cout] */
+ int g1o, g2o; /* their places in the device's parameters (qwenimage_vae_vk.h) */
QivConv c1, c2, sc; /* sc only when cin != cout */
} QivRes;
@@ -92,6 +94,7 @@ typedef struct QiVae {
int nblk;
QivBlock blk[QIV_MAX_BLOCKS];
float *g_out;
+ int g_outo; /* its place in the device's parameters */
QivConv conv_out;
size_t wbytes; /* resident weight bytes */
void (*progress)(void *ud, int step, int steps);
@@ -530,6 +533,22 @@ out:
return rc;
}
+/* conv_out's [HW][OC] to the picture: torch.clamp(-1, 1), then postprocess
+ * ((x*0.5 + 0.5).clamp(0, 1), *255 in float32, numpy round (half to even), uint8;
+ * x*0.5 is exact, so an FMA here rounds exactly like torch's two ops). */
+static void qiv_post(const float *o, size_t HW, int OC, uint8_t *rgba, float *out_f){
+ #pragma omp parallel for schedule(static)
+ for (size_t p = 0; p < HW; p++)
+ for (int c = 0; c < 4; c++) {
+ float f = c < OC ? o[p * OC + c] : 1.f;
+ f = f < -1.f ? -1.f : f > 1.f ? 1.f : f;
+ if (c < OC && out_f) out_f[(size_t)c * HW + p] = f;
+ float u = f * 0.5f + 0.5f;
+ u = u < 0.f ? 0.f : u > 1.f ? 1.f : u;
+ if (rgba) rgba[p * 4 + c] = (uint8_t)nearbyintf(u * 255.f);
+ }
+}
+
/* z: normalized latents [h][w][z_dim] (the packed DiT output, token y*w + x).
* rgba: [scale*h][scale*w][4] uint8 top row first (alpha 255 if the model has 3
* output channels). out_f: optional [out_ch][scale*h][scale*w] in [-1, 1].
@@ -600,19 +619,7 @@ static int qiv_decode(QiVae *v, const float *z, int h, int w, uint8_t *rgba, flo
QivEpi ep; memset(&ep, 0, sizeof ep); ep.rel_x = 1;
if (!o || qiv_conv3(&v->conv_out, x, H, W, v->g_out, 0, o, &ep)) { free(o); goto fail; }
free(x); x = NULL;
- #pragma omp parallel for schedule(static)
- for (size_t p = 0; p < HW; p++)
- for (int c = 0; c < 4; c++) {
- float f = c < OC ? o[p * OC + c] : 1.f;
- /* torch.clamp(-1, 1), then postprocess: (x*0.5 + 0.5).clamp(0, 1),
- * *255 in float32, numpy round (half to even), uint8. x*0.5 is
- * exact, so an FMA here rounds exactly like torch's two ops. */
- f = f < -1.f ? -1.f : f > 1.f ? 1.f : f;
- if (c < OC && out_f) out_f[(size_t)c * HW + p] = f;
- float u = f * 0.5f + 0.5f;
- u = u < 0.f ? 0.f : u > 1.f ? 1.f : u;
- if (rgba) rgba[p * 4 + c] = (uint8_t)nearbyintf(u * 255.f);
- }
+ qiv_post(o, HW, OC, rgba, out_f);
free(o);
}
QIV_STAGE("conv_out");
diff --git a/c/qwenimage_vae_vk.h b/c/qwenimage_vae_vk.h
new file mode 100644
index 00000000..b5f9487d
--- /dev/null
+++ b/c/qwenimage_vae_vk.h
@@ -0,0 +1,224 @@
+/* qwenimage_vae_vk.h -- the VAE decoder of qwenimage_vae.h on the Vulkan chain
+ * (vk_chain.h). Included by qwenimage.c in a COLI_VULKAN build after both; it runs when
+ * the transformer's chain does (COLI_VK_CHAIN), and the CPU's qiv_decode otherwise or
+ * when anything here fails.
+ *
+ * The same arithmetic as qiv_decode, the maps channel-last on the device from conv_in to
+ * conv_out:
+ * - a 3x3 convolution is chain_vae.comp's taps of a band of output rows (zero padding,
+ * the nearest 2x upsample of an up block folded into the read) and one GEMM over
+ * them with the f32 weights qwenimage_vae.h already permuted to [cout][kx][ky][cin],
+ * then its bias (vkc_enc_bias);
+ * - the RMS norm + SiLU in front of a residual conv is an L2 norm times sqrt(C) by its
+ * gamma (chain_norm.comp) and a SiLU (chain_ew.comp's HC_LOW with fc 1);
+ * - a 1x1 shortcut conv is a GEMM and its bias; the DupUp3D shortcut of an up block is
+ * chain_vae.comp's gather of the block's input channels, added;
+ * - the mid block's single-head attention over every pixel (384 channels a head, past
+ * the chain's attention ops) runs on the CPU between the two mid resnets: the map
+ * comes down and goes back up (6 MB at 1024x1024);
+ * - z * std + mean and post_quant_conv (a 1x1 conv on the latent grid) run on the CPU
+ * before the upload, the clamp and the uint8 rounding (qiv_post) after the read-back.
+ * The device sums in other orders than the CPU (the norms in float trees, the GEMMs by
+ * tiles), so the pixels agree with the CPU's to rounding. */
+#include "vk_chain.h"
+
+#define QVV_TAPS ((size_t)64 << 20) /* floats of a band's taps (256 MB) */
+
+static struct {
+ int ok, failed;
+ VkcBuf *prm; /* the device convs' biases and the norms' gammas */
+ VkcBuf *dup[QIV_MAX_BLOCKS]; /* the up blocks' DupUp3D tables, int32 [cout][4] */
+ VkcBuf *q; /* a band's taps */
+ unsigned long long decodes;
+} g_qvv;
+
+static void qvv_off(const char *why) {
+ if (!g_qvv.failed) fprintf(stderr, "[VK] qwenimage vae: %s; the VAE decodes on the CPU\n", why);
+ g_qvv.failed = 1;
+}
+
+/* every conv the device runs, in the order their parameters are laid out */
+static int qvv_convs(QiVae *v, QivConv **cv) {
+ int n = 0;
+ cv[n++] = &v->conv_in;
+ for (int m = 0; m < 2; m++) { cv[n++] = &v->mid[m].c1; cv[n++] = &v->mid[m].c2; if (v->mid[m].cin != v->mid[m].cout) cv[n++] = &v->mid[m].sc; }
+ for (int i = 0; i < v->nblk; i++) {
+ QivBlock *b = &v->blk[i];
+ for (int j = 0; j < b->nres; j++) {
+ cv[n++] = &b->res[j].c1; cv[n++] = &b->res[j].c2;
+ if (b->res[j].cin != b->res[j].cout) cv[n++] = &b->res[j].sc;
+ }
+ if (b->up) cv[n++] = &b->upc;
+ }
+ cv[n++] = &v->conv_out;
+ return n;
+}
+
+static int qvv_setup(QiVae *v) {
+ QivConv *cv[2 + 3 * 2 + QIV_MAX_BLOCKS * (3 * QIV_MAX_RES + 1)];
+ int nc = qvv_convs(v, cv);
+ size_t n = 0;
+ for (int k = 0; k < nc; k++) { cv[k]->bo = (int)n; n += cv[k]->cout; }
+ for (int m = 0; m < 2; m++) { v->mid[m].g1o = (int)n; n += v->mid[m].cin; v->mid[m].g2o = (int)n; n += v->mid[m].cout; }
+ for (int i = 0; i < v->nblk; i++)
+ for (int j = 0; j < v->blk[i].nres; j++) {
+ QivRes *r = &v->blk[i].res[j];
+ r->g1o = (int)n; n += r->cin; r->g2o = (int)n; n += r->cout;
+ }
+ v->g_outo = (int)n; n += v->conv_out.cin;
+ float *a = malloc(n * sizeof(float));
+ if (!a) return 0;
+ for (int k = 0; k < nc; k++) memcpy(a + cv[k]->bo, cv[k]->b, (size_t)cv[k]->cout * sizeof(float));
+ for (int m = 0; m < 2; m++) {
+ memcpy(a + v->mid[m].g1o, v->mid[m].g1, (size_t)v->mid[m].cin * sizeof(float));
+ memcpy(a + v->mid[m].g2o, v->mid[m].g2, (size_t)v->mid[m].cout * sizeof(float));
+ }
+ for (int i = 0; i < v->nblk; i++)
+ for (int j = 0; j < v->blk[i].nres; j++) {
+ QivRes *r = &v->blk[i].res[j];
+ memcpy(a + r->g1o, r->g1, (size_t)r->cin * sizeof(float));
+ memcpy(a + r->g2o, r->g2, (size_t)r->cout * sizeof(float));
+ }
+ memcpy(a + v->g_outo, v->g_out, (size_t)v->conv_out.cin * sizeof(float));
+ g_qvv.prm = vkc_buf(n * sizeof(float), VKC_DEV);
+ int ok = g_qvv.prm && vkc_begin() && vkc_write(g_qvv.prm, 0, a, n * sizeof(float));
+ free(a);
+ for (int i = 0; ok && i < v->nblk; i++)
+ if (v->blk[i].up)
+ ok = (g_qvv.dup[i] = vkc_buf((size_t)v->blk[i].cout * 4 * sizeof(int), VKC_DEV)) &&
+ vkc_write(g_qvv.dup[i], 0, v->blk[i].dup, (size_t)v->blk[i].cout * 4 * sizeof(int));
+ ok = ok && vkc_submit(1);
+ for (int k = 0; ok && k < nc; k++)
+ ok = coli_vk_tensor_ensure((ColiVkTensor **)&cv[k]->vk, cv[k]->w, NULL, 10, cv[k]->cin * cv[k]->k * cv[k]->k,
+ cv[k]->cout, 0);
+ if (!ok) { qvv_off(vkc_lost() ? "the device was lost" : "the device refused its weights"); return 0; }
+ g_qvv.ok = 1;
+ return 1;
+}
+
+static int qvv_bias(VkcBuf *y, size_t yo, int rows, const QivConv *c) {
+ VkcEncBias b = {1, rows * c->cout, c->cout, (int)yo, c->cout, c->bo, 0};
+ return vkc_enc_bias(y, g_qvv.prm, &b);
+}
+/* t = SiLU(RMS norm of x by the gamma at go): x * sqrt(C) * gamma / |x|, then SiLU */
+static int qvv_pre(VkcBuf *x, VkcBuf *t, size_t HW, int C, int go) {
+ VkcNorm nn = {(int)HW, C, 1, 0, C, 0, 0, C, 0, go, 0, VKC_NORM_L2, 1e-24f, sqrtf((float)C)};
+ VkcEw si = {VKC_EW_HC_LOW, (int)(HW * C), C, 1, 0, 0, 0, 0, 0, 0, 0, 1.f};
+ return vkc_norm(x, g_qvv.prm, t, &nn) && vkc_ew(t, t, NULL, NULL, NULL, &si);
+}
+/* y = conv3x3(x) + bias over an Ho x Wo map (x H x W, upsampled 2x first with up), in
+ * bands of output rows; a submission a band */
+static int qvv_conv3(const QivConv *c, VkcBuf *x, int H, int W, int up, VkcBuf *y) {
+ int C = c->cin, Co = c->cout, Ho = H << up, Wo = W << up;
+ size_t per_row = (size_t)Wo * 9 * C;
+ int band = (int)(QVV_TAPS / per_row);
+ if (band > 65535 / Wo) band = 65535 / Wo; /* vkc_matmul's rows a call */
+ if (band < 1) band = 1;
+ if (band > Ho) band = Ho;
+ if (!vkc_reserve(&g_qvv.q, (size_t)band * per_row * sizeof(float), VKC_DEV)) return 0;
+ int ok = 1;
+ for (int y0 = 0; ok && y0 < Ho; y0 += band) {
+ int nb = Ho - y0 < band ? Ho - y0 : band;
+ VkcVae p = {0, C, H, W, up, Ho, Wo, y0, (int)((size_t)nb * per_row), 0, 0, Co, 0};
+ ok = vkc_vae(x, g_qvv.q, NULL, &p) &&
+ vkc_matmul((ColiVkTensor *)c->vk, g_qvv.q, 0, y, (size_t)y0 * Wo * Co, nb * Wo) &&
+ qvv_bias(y, (size_t)y0 * Wo * Co, nb * Wo, c) && vkc_submit(0) && vkc_begin();
+ }
+ return ok;
+}
+static VkcBuf *qvv_map(size_t floats) { return vkc_buf(floats * sizeof(float), VKC_DEV); }
+/* one residual block; x is kept (the caller frees it), the result is new */
+static VkcBuf *qvv_resnet(const QivRes *r, VkcBuf *x, int H, int W) {
+ size_t HW = (size_t)H * W;
+ VkcBuf *pa = qvv_map(HW * r->cin), *t = qvv_map(HW * r->cout), *pb = qvv_map(HW * r->cout), *y = qvv_map(HW * r->cout);
+ VkcBuf *s = r->cin != r->cout ? qvv_map(HW * r->cout) : NULL;
+ int ok = pa && t && pb && y && (r->cin == r->cout || s) &&
+ qvv_pre(x, pa, HW, r->cin, r->g1o) && qvv_conv3(&r->c1, pa, H, W, 0, t) &&
+ qvv_pre(t, pb, HW, r->cout, r->g2o) && qvv_conv3(&r->c2, pb, H, W, 0, y);
+ for (size_t p0 = 0; ok && s && p0 < HW; p0 += 32768) { /* the 1x1 shortcut of x, 32768 pixels a GEMM */
+ int np = HW - p0 < 32768 ? (int)(HW - p0) : 32768;
+ ok = vkc_matmul((ColiVkTensor *)r->sc.vk, x, p0 * r->cin, s, p0 * r->cout, np) && qvv_bias(s, p0 * r->cout, np, &r->sc);
+ }
+ VkcEw add = {VKC_EW_ADD, (int)(HW * r->cout), r->cout, 1, 0, 0, 0, 0, 0, 0, 0, 1.f};
+ ok = ok && vkc_ew(y, y, s ? s : x, NULL, NULL, &add) && vkc_submit(0) && vkc_begin();
+ vkc_free(pa); vkc_free(t); vkc_free(pb); vkc_free(s);
+ if (!ok) { vkc_free(y); return NULL; }
+ return y;
+}
+
+/* qiv_decode on the device: 0, or -1 (nothing written; the CPU decodes) */
+static int qvv_decode(QiVae *v, const float *z, int h, int w, uint8_t *rgba, float *out_f) {
+ if (g_qvv.failed || vkc_lost() || !vkc_vae_ready() || !v || !z || h <= 0 || w <= 0) return -1;
+ if (!g_qvv.ok && !qvv_setup(v)) return -1;
+ const int prof = getenv("QIV_PROFILE") != NULL, Z = v->z_dim, steps = 3 + v->nblk;
+ int step = 0, H = h, W = w;
+ size_t HW = (size_t)H * W;
+ double t0 = qiv_now(), tl = t0;
+#define QVV_STAGE(name) do { double tn = qiv_now(); \
+ if (prof) fprintf(stderr, "[vae vk] %-10s %4dx%-4d %7.3f s\n", name, H, W, tn - tl); tl = tn; \
+ if (v->progress) v->progress(v->progress_ud, ++step, steps); } while (0)
+ float *a = qiv_alloc(HW * Z), *b = qiv_alloc(HW * Z), *host = NULL;
+ VkcBuf *x = NULL, *bb = NULL, *nx = NULL;
+ int ok = a && b;
+ if (ok) { /* z * std + mean and post_quant_conv on the CPU, as qiv_decode */
+ for (size_t p = 0; p < HW; p++)
+ for (int c = 0; c < Z; c++) a[p * Z + c] = z[p * Z + c] * v->std[c] + v->mean[c];
+ qi_gemm(b, a, (int)HW, &v->pqc.m, v->pqc.b);
+ }
+ ok = ok && (bb = qvv_map(HW * Z)) && (x = qvv_map(HW * v->conv_in.cout)) && vkc_begin() &&
+ vkc_write(bb, 0, b, HW * Z * sizeof(float)) && qvv_conv3(&v->conv_in, bb, H, W, 0, x);
+ free(a); free(b); a = b = NULL;
+ vkc_free(bb); bb = NULL;
+ if (ok) QVV_STAGE("conv_in");
+ /* mid: a resnet, the attention on the CPU, a resnet */
+ ok = ok && (nx = qvv_resnet(&v->mid[0], x, H, W));
+ if (ok) { vkc_free(x); x = nx; nx = NULL; }
+ ok = ok && (host = qiv_alloc(HW * v->mid[0].cout)) && vkc_submit(1) &&
+ vkc_read(x, 0, host, HW * v->mid[0].cout * sizeof(float)) && qiv_attention(v, host, (int)HW) == 0 &&
+ vkc_begin() && vkc_write(x, 0, host, HW * v->mid[0].cout * sizeof(float));
+ free(host); host = NULL;
+ ok = ok && (nx = qvv_resnet(&v->mid[1], x, H, W));
+ if (ok) { vkc_free(x); x = nx; nx = NULL; QVV_STAGE("mid"); }
+ for (int i = 0; ok && i < v->nblk; i++) {
+ const QivBlock *bk = &v->blk[i];
+ VkcBuf *xin = x, *cur = x; /* xin: the block's input, the DupUp3D shortcut's source */
+ for (int j = 0; ok && j < bk->nres; j++) {
+ ok = (nx = qvv_resnet(&bk->res[j], cur, H, W)) != NULL;
+ if (ok) { if (cur != xin) vkc_free(cur); cur = nx; nx = NULL; }
+ }
+ if (ok && bk->up) {
+ size_t HW4 = HW * 4;
+ VkcBuf *y = qvv_map(HW4 * bk->cout);
+ VkcVae p = {1, bk->cout, H, W, 1, 2 * H, 2 * W, 0, (int)(HW4 * bk->cout), 0, 0, bk->cout, bk->cin};
+ ok = y && qvv_conv3(&bk->upc, cur, H, W, 1, y) && vkc_vae(xin, y, g_qvv.dup[i], &p) && vkc_submit(0) && vkc_begin();
+ if (cur != xin) vkc_free(cur);
+ vkc_free(xin);
+ x = y;
+ H *= 2; W *= 2; HW = (size_t)H * W;
+ } else if (ok) {
+ if (xin != cur) vkc_free(xin);
+ x = cur;
+ } else {
+ if (cur != xin) vkc_free(cur);
+ x = xin;
+ }
+ if (ok) { char nm[16]; snprintf(nm, sizeof nm, "block%d", i); QVV_STAGE(nm); }
+ }
+ const int OC = v->out_ch;
+ VkcBuf *pre = NULL, *o = NULL, *od = NULL;
+ ok = ok && (pre = qvv_map(HW * v->conv_out.cin)) && (o = qvv_map(HW * OC)) &&
+ (od = vkc_buf(HW * OC * sizeof(float), VKC_DOWN)) && qvv_pre(x, pre, HW, v->conv_out.cin, v->g_outo) &&
+ qvv_conv3(&v->conv_out, pre, H, W, 0, o) && vkc_copy(od, 0, o, 0, HW * OC) && vkc_submit(1);
+ if (ok) qiv_post((const float *)vkc_ptr(od), HW, OC, rgba, out_f);
+ vkc_free(pre); vkc_free(o); vkc_free(od); vkc_free(x);
+ if (!ok) {
+ if (vkc_lost()) qvv_off("the device was lost");
+ else qvv_off("a step of the decode failed (the device's memory, or a shape its ops do not take)");
+ return -1;
+ }
+ QVV_STAGE("conv_out");
+ if (prof) fprintf(stderr, "[vae vk] total %.3f s\n", qiv_now() - t0);
+#undef QVV_STAGE
+ g_qvv.decodes++;
+ return 0;
+}
diff --git a/c/shaders/chain_vae.comp b/c/shaders/chain_vae.comp
new file mode 100644
index 00000000..a3061aaf
--- /dev/null
+++ b/c/shaders/chain_vae.comp
@@ -0,0 +1,44 @@
+#version 450
+// Qwen-Image's VAE decoder on the chain (vk_chain.c, vkc_vae_*; qwenimage_vae_vk.h): the
+// two steps of its convolutions that are not a GEMM. Maps are channel-last, [H][W][C].
+// One thread per output element. The push constants: v[0] the mode, then
+// C, H, W, up, Ho, Wo, y0, n, x_off, o_off, Co, dupC.
+//
+// mode 0, the 3x3 taps of a band of output rows (an im2col for vkc_matmul): output pixel
+// p (row y0 + p / Wo, column p % Wo of the Ho x Wo map) gets its nine taps as 9*C
+// floats ordered [kx][ky][c], the order qwenimage_vae.h permutes the weights to:
+// o[o_off + p*9C + kx*3C + ky*C + c] = x[x_off + ((sy >> up)*W + (sx >> up))*C + c],
+// sy = row + ky - 1, sx = column + kx - 1, zero outside the map (the conv's padding);
+// up 1 reads x (H x W) nearest-upsampled to Ho x Wo = 2H x 2W.
+// mode 1, the DupUp3D shortcut of an upsampling block, added: for output pixel p of the
+// band and channel o < Co, o[o_off + p*Co + o] += x[x_off + src*dupC + tab[o*4 + s]],
+// src = (row >> 1)*(Wo >> 1) + (column >> 1), s = (row & 1)*2 + (column & 1).
+layout(local_size_x = 256) in;
+
+layout(std430, binding = 0) readonly buffer XB { float x[]; };
+layout(std430, binding = 1) buffer OB { float o[]; };
+layout(std430, binding = 2) readonly buffer TB { int tab[]; };
+layout(push_constant) uniform P {
+ int mode, C, H, W, up, Ho, Wo, y0, n, x_off, o_off, Co, dupC;
+} p;
+
+void main() {
+ int i = int(gl_GlobalInvocationID.x + gl_GlobalInvocationID.y * gl_NumWorkGroups.x * 256u);
+ if (i >= p.n) return;
+ if (p.mode == 0) {
+ int C3 = 3 * p.C, C9 = 9 * p.C;
+ int px = i / C9, rem = i - px * C9;
+ int kx = rem / C3, r2 = rem - kx * C3, ky = r2 / p.C, c = r2 - ky * p.C;
+ int row = p.y0 + px / p.Wo, col = px - (px / p.Wo) * p.Wo;
+ int sy = row + ky - 1, sx = col + kx - 1;
+ float v = 0.0;
+ if (sy >= 0 && sy < p.Ho && sx >= 0 && sx < p.Wo)
+ v = x[p.x_off + ((sy >> p.up) * p.W + (sx >> p.up)) * p.C + c];
+ o[p.o_off + i] = v;
+ } else {
+ int px = i / p.Co, oc = i - px * p.Co;
+ int row = p.y0 + px / p.Wo, col = px - (px / p.Wo) * p.Wo;
+ int src = (row >> 1) * (p.Wo >> 1) + (col >> 1), s = (row & 1) * 2 + (col & 1);
+ o[p.o_off + i] += x[p.x_off + src * p.dupC + tab[oc * 4 + s]];
+ }
+}
diff --git a/c/shaders/chain_vae.spv b/c/shaders/chain_vae.spv
new file mode 100644
index 00000000..ceada18c
Binary files /dev/null and b/c/shaders/chain_vae.spv differ
diff --git a/c/tests/test_vk_chain.c b/c/tests/test_vk_chain.c
index 15b0e133..f4f83912 100644
--- a/c/tests/test_vk_chain.c
+++ b/c/tests/test_vk_chain.c
@@ -269,6 +269,40 @@ static void test_attn_hk(int S, int pos_base, int H, int KVH, int hd, int use_li
}
static void test_attn(int S, int pos_base, int hd, int use_list) { test_attn_hk(S, pos_base, 4, 2, hd, use_list); }
+/* chain_vae.comp (Qwen-Image's VAE): a band's 3x3 taps, with and without the 2x upsample,
+ * and the DupUp3D shortcut added; both are copies, so the bytes must be the CPU's. */
+static void test_vae_ops(int H, int W, int C, int u2, int y0, int nb) {
+ int Ho = H << u2, Wo = W << u2, C9 = 9 * C;
+ size_t xn = (size_t)H * W * C, qn = (size_t)nb * Wo * C9;
+ float *x = fvec(xn + 5, 1.f), *ref = malloc(qn * sizeof *ref);
+ for (int px = 0; px < nb * Wo; px++)
+ for (int kx = 0; kx < 3; kx++) for (int ky = 0; ky < 3; ky++) for (int c = 0; c < C; c++) {
+ int row = y0 + px / Wo, col = px % Wo, sy = row + ky - 1, sx = col + kx - 1;
+ ref[(size_t)px * C9 + kx * 3 * C + ky * C + c] =
+ sy >= 0 && sy < Ho && sx >= 0 && sx < Wo ? x[5 + ((size_t)(sy >> u2) * W + (sx >> u2)) * C + c] : 0.f;
+ }
+ VkcBuf *xb = up(x, xn + 5), *qb = vkc_buf((qn + 3) * 4, VKC_DOWN);
+ VkcVae p = {0, C, H, W, u2, Ho, Wo, y0, (int)qn, 5, 3, 0, 0};
+ vkc_begin(); int ok = vkc_vae(xb, qb, NULL, &p); ok = vkc_submit(1) && ok;
+ CHECK(ok && memcmp((float *)vkc_ptr(qb) + 3, ref, qn * 4) == 0, "vae taps H %d W %d C %d up %d rows %d+%d", H, W, C, u2, y0, nb);
+ /* DupUp3D: the half-size map x (C channels) into a 2H x 2W map of Co channels */
+ int Co = 4, *tab = malloc((size_t)Co * 4 * sizeof *tab);
+ for (int i = 0; i < Co * 4; i++) tab[i] = (i * 7 + 3) % C;
+ size_t yn = (size_t)(2 * H) * (2 * W) * Co;
+ float *y = fvec(yn, 1.f), *yr = malloc(yn * sizeof *yr);
+ for (int px = 0; px < 4 * H * W; px++) for (int o = 0; o < Co; o++) {
+ int row = px / (2 * W), col = px % (2 * W), src = (row >> 1) * W + (col >> 1), sub = (row & 1) * 2 + (col & 1);
+ yr[(size_t)px * Co + o] = y[(size_t)px * Co + o] + x[5 + (size_t)src * C + tab[o * 4 + sub]];
+ }
+ VkcBuf *yb = up(y, yn), *tb = vkc_buf((size_t)Co * 4 * sizeof(int), VKC_DEV);
+ VkcVae d = {1, C, H, W, 1, 2 * H, 2 * W, 0, (int)yn, 5, 0, Co, C};
+ vkc_begin(); ok = vkc_write(tb, 0, tab, (size_t)Co * 4 * sizeof(int)) && vkc_vae(xb, yb, tb, &d); ok = vkc_submit(1) && ok;
+ float *got = down(yb, 0, yn);
+ CHECK(ok && memcmp(got, yr, yn * 4) == 0, "vae dup H %d W %d C %d", H, W, C);
+ vkc_free(xb); vkc_free(qb); vkc_free(yb); vkc_free(tb);
+ free(x); free(ref); free(tab); free(y); free(yr); free(got);
+}
+
/* GATE_ADD (Qwen-Image's gated residual): y = a + e[col] * b, a gate per column. */
static void test_ew_gate(void) {
int R = 5, D = 70;
@@ -2733,6 +2767,8 @@ int main(int argc, char **argv) {
test_attn_full(70, 129, 2, 64); test_attn_full(1, 300, 4, 128);
printf("attn full done\n");
test_ew_gate();
+ test_vae_ops(5, 7, 3, 0, 0, 5); test_vae_ops(5, 7, 3, 1, 3, 4); test_vae_ops(4, 4, 16, 1, 0, 8);
+ printf("vae ops done\n");
VkcStats st; vkc_stats(&st);
printf("chain: %llu frames, %llu ops, %llu matmuls (%llu GEMM), %llu barriers\n", st.frames, st.ops, st.matmuls, st.gemms, st.barriers);
vkc_shutdown();
diff --git a/c/tests/vulkan_engines.sh b/c/tests/vulkan_engines.sh
index 793cd578..93c15093 100755
--- a/c/tests/vulkan_engines.sh
+++ b/c/tests/vulkan_engines.sh
@@ -907,7 +907,10 @@ for k in c:
print(f"OK {os.environ['TAG']}: {len(c)} stages match the CPU run")
QIPY
}
- for bits in 8 16 32; do qi_chain "qwenimage chain bits=$bits" $bits; done
+ for bits in 8 16 32; do
+ qi_chain "qwenimage chain bits=$bits" $bits
+ grep -qa 'qwenimage vae: [0-9]* decodes on the device' qi-vk.log || { cat qi-vk.log; fail "qwenimage chain bits=$bits: the VAE did not decode on the device"; }
+ done
qi_chain "qwenimage chain, the attention in slices" 32 COLI_VK_ATTN_SLICE=60000
grep -qa 'qwenimage chain: [0-9]* steps' qi-vk.log || { cat qi-vk.log; fail "qwenimage chain, slices: no step on the device"; }
qi_chain "qwenimage chain, the device lost" 32 COLI_VK_CHAIN_FAULT=9
@@ -915,6 +918,7 @@ QIPY
COLI_VULKAN=1 COLI_VK_CHAIN=1 COLI_IMG_BITS=8 COLI_IMG_ACT8=0 ./qwenimage --model qwenimage_tiny --prompt "a red fox in the snow" \
--width 256 --height 256 --steps 2 --seed 1 --out qi-vk.png 2> qi-vk-gen.err
grep -qa 'qwenimage chain: [0-9]* steps' qi-vk-gen.err || { cat qi-vk-gen.err; fail "qwenimage chain picture: the chain never ran"; }
+ grep -qa 'qwenimage vae: 1 decodes on the device' qi-vk-gen.err || { cat qi-vk-gen.err; fail "qwenimage chain picture: the VAE did not decode on the device"; }
$PY - <<'QIPY'
import sys; sys.path.insert(0, ".")
import image_engine as e
diff --git a/c/vk_chain.c b/c/vk_chain.c
index 7edd6f5a..3f8db4f9 100644
--- a/c/vk_chain.c
+++ b/c/vk_chain.c
@@ -1424,6 +1424,30 @@ int vkc_attn_full_ready(void) {
return KF.mod != VK_NULL_HANDLE;
}
+/* chain_vae.comp (Qwen-Image's VAE: a band's 3x3 taps, the DupUp3D shortcut): made on first use */
+static struct { VkShaderModule mod; VkPipeline pipe; int tried; } g_kva[2];
+#define KVA (g_kva[g_kd])
+static void kva_shutdown(void) {
+ if (KVA.pipe) vkDestroyPipeline(KC.dev, KVA.pipe, NULL);
+ if (KVA.mod) vkDestroyShaderModule(KC.dev, KVA.mod, NULL);
+ memset(&KVA, 0, sizeof KVA);
+}
+int vkc_vae_ready(void) {
+ if (!vkc_ready()) return 0;
+ if (!KVA.pipe && !KVA.tried) {
+ KVA.tried = 1;
+ if ((KVA.mod = load_module(KC.core.spv_path, "chain_vae.spv"))) KVA.pipe = make_pipe(KVA.mod, NULL);
+ }
+ return KVA.pipe != VK_NULL_HANDLE;
+}
+int vkc_vae(VkcBuf *x, VkcBuf *o, VkcBuf *tab, const VkcVae *p) {
+ if (p->n < 1 || !vkc_vae_ready()) return 0;
+ KC.kind = PK_EW;
+ VkcBind bd[3] = {B(x, 0), B(o, 1), B(p->mode == 1 ? tab : NULL, 0)};
+ uint32_t gx, gy; grid(((uint64_t)p->n + 255) / 256, &gx, &gy);
+ return record(KVA.pipe, bd, 3, p, sizeof *p, gx, gy, 1);
+}
+
static VkPipeline ke_pipe(void) {
if (KE.pipe || KE.tried || !vkc_ready()) return KE.pipe;
KE.tried = 1;
@@ -1719,6 +1743,7 @@ void vkc_shutdown(void) {
kab_shutdown();
ke_shutdown();
kf_shutdown();
+ kva_shutdown();
for (int i = 0; i < P_NPIPE; i++) {
if (KC.pipe[i]) vkDestroyPipeline(KC.dev, KC.pipe[i], NULL);
if (KC.mod[i]) vkDestroyShaderModule(KC.dev, KC.mod[i], NULL);
diff --git a/c/vk_chain.h b/c/vk_chain.h
index 99ab02c2..08815198 100644
--- a/c/vk_chain.h
+++ b/c/vk_chain.h
@@ -687,6 +687,16 @@ typedef struct { int S, T, H, hd, q_off, q_row, k_off, v_off, kv_row, o_off, o_r
int vkc_attn_full(VkcBuf *qkv, VkcBuf *o, const VkcAttnFull *p);
int vkc_attn_full_ready(void);
+/* chain_vae.comp: Qwen-Image's VAE decoder (qwenimage_vae_vk.h), the two steps of its
+ * convolutions that are not a GEMM; maps channel-last [H][W][C]. mode 0: the 3x3 taps of
+ * output rows y0.. (n = pixels x 9C floats at o_off, [kx][ky][c] a pixel, zero outside the
+ * Ho x Wo map; up 1: x is H x W, nearest-upsampled 2x); mode 1: o[o_off + p*Co + c] +=
+ * the DupUp3D shortcut's input channel tab[c*4 + sub-pixel] of the half-size map x (dupC
+ * channels), n = pixels x Co. Made on first use. */
+typedef struct { int mode, C, H, W, up, Ho, Wo, y0, n, x_off, o_off, Co, dupC; } VkcVae;
+int vkc_vae(VkcBuf *x, VkcBuf *o, VkcBuf *tab, const VkcVae *p);
+int vkc_vae_ready(void);
+
/* counters, for the engines' [VK] lines */
typedef struct {
unsigned long long frames, waits, ops, matmuls, gemms, barriers, bytes_up, bytes_down;
diff --git a/docs/qwen-image.md b/docs/qwen-image.md
index 0b4800b1..7a9b5deb 100644
--- a/docs/qwen-image.md
+++ b/docs/qwen-image.md
@@ -272,8 +272,11 @@ per step. Without the chain (`COLI_VK_CHAIN=0`, or a device that refuses the
chain's buffers) the matrices run there one by one and the attention on the CPU,
as before. The weights keep the storage `COLI_IMG_BITS` gave them (int8 by default,
bf16 or f32) and the activations stay f32, so `COLI_IMG_ACT8` does not apply on the
-device and the result is the CPU's `COLI_IMG_ACT8=0` run up to summation order. The
-text encoder and the VAE run on the CPU.
+device and the result is the CPU's `COLI_IMG_ACT8=0` run up to summation order. When
+the chain runs, the VAE decodes on the device too (`qwenimage_vae_vk.h`: its 3x3
+convolutions as a band's taps and one GEMM, the norms, the shortcuts; the mid block's
+attention over every pixel on the CPU), with the CPU's decode as the fallback. The
+text encoder runs on the CPU.
Measured on a Radeon 780M (an integrated GPU sharing the RAM of the 8-core Zen 4
above), 8 steps:
@@ -282,10 +285,12 @@ above), 8 steps:
|---|---|---|---|
| CPU | 11.6 s | 67 s | 1 min 52 s |
| GPU, the matrices one by one | 11.8 s | 63 s | |
-| GPU, the chain | 5.4 s | 39 s | 62 s |
+| GPU, the chain | 5.4 s | 38 s | 61 s |
-The image's time with the chain: 11 s to load and encode the prompt, 43 s of
-denoising, 8 s of VAE. Loading went from 34 s to 7.5 s in this release: four
+The image's time with the chain: 11 s to load and encode the prompt, 42 s of
+denoising, 7.5 s of VAE (6.1 s of it on the device; 8.0 s on the CPU). At 1024x1024
+the VAE takes 24 s on the 780M against the CPU's 28 to 30: an integrated GPU's f32
+products gain little there, a discrete card's more. Loading went from 34 s to 7.5 s in this release: four
layers at once, each matrix quantized straight from its bf16 rows
(`COLI_IMG_LOAD_THREADS` sets how many; each holds one matrix's bf16 bytes, up to
about 140 MB, while it quantizes). On a 1024x1024 step the 780M spends half the