Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
qwen-image: live previews, and int8 DiT activations by default where VNNI exists
JustVugga0607739532e
diff --git a/c/Makefile b/c/Makefileindex 117e6e29..9ae57efd 100644--- a/c/Makefile+++ b/c/Makefile@@ -1194,7 +1194,7 @@ ifneq ($(EXE),).PHONY: qwenimageqwenimage: qwenimage$(EXE)endif-qwenimage$(EXE): qwenimage.c qi_gemm.h qwenimage_vae.h st.h json.h tok.h tok_unicode.h tok_unicode_o200k.h tok_unicode_deepseek.h qwen38_nfc.h qwen38_nfc_tables.h serve_poll.h compat.h .build-config+qwenimage$(EXE): qwenimage.c qi_gemm.h qwenimage_vae.h qwenimage_preview.h st.h json.h tok.h tok_unicode.h tok_unicode_o200k.h tok_unicode_deepseek.h qwen38_nfc.h qwen38_nfc_tables.h serve_poll.h compat.h .build-config$(CC) $(CFLAGS) qwenimage.c -o qwenimage$(EXE) $(LDFLAGS)test_qi_gemm$(EXE): tests/test_qi_gemm.c qi_gemm.hdiff --git a/c/qwenimage.c b/c/qwenimage.cindex 18ef2713..deaec571 100644--- a/c/qwenimage.c+++ b/c/qwenimage.c@@ -91,7 +91,7 @@ static int jbool(jval *o, const char *k, int def){/* ---- weights ------------------------------------------------------------ */static int g_bits = 8; /* COLI_IMG_BITS: storage of the big matrices */-static int g_act8 = 0; /* COLI_IMG_ACT8=1: int8 activations on the int8 matrices (VNNI) */+static int g_act8 = 1; /* COLI_IMG_ACT8=0 turns off the int8 activations of the DiT blocks (VNNI) *//* act8: this matrix may take int8 activations (COLI_IMG_ACT8). Only the DiT's* block matrices do. Measured on the real model: the text encoder's hidden@@ -815,7 +815,34 @@ typedef struct {char *last_prompt; Prefix prefix;} Engine;-typedef struct { const char *id; int (*cancelled)(const char *id); } Progress;+typedef struct { const char *id; int (*cancelled)(const char *id); int preview; } Progress;++#include "qwenimage_preview.h" /* QI_PREVIEW_RGB: the fitted latent -> RGB map */++/* The picture as it stands after a step: the flow-matching estimate of the clean+ * latent (x0 = x_t - sigma * v) through a linear latent -> RGB map, one pixel per+ * latent pixel. 64x3 multiply-adds per token: free next to a DiT step. */+static void emit_preview(const Progress *pg, int step, const float *lat, const float *v, float sigma,+ int gh, int gw, int C){+ if (!pg || !pg->id || !pg->preview || C != 64) return;+ size_t n = (size_t)gh * gw * 3;+ uint8_t *rgb = xmalloc(n);+ for (int t = 0; t < gh * gw; t++) {+ const float *x = lat + (int64_t)t * C, *u = v + (int64_t)t * C;+ for (int c = 0; c < 3; c++) {+ float a = QI_PREVIEW_RGB[64][c];+ for (int k = 0; k < 64; k++) a += (x[k] - sigma * u[k]) * QI_PREVIEW_RGB[k][c];+ a = a * 255.f + 0.5f;+ rgb[t * 3 + c] = a < 0 ? 0 : a > 255 ? 255 : (uint8_t)a;+ }+ }+ printf("PREVIEW {\"id\":\"%s\",\"step\":%d,\"width\":%d,\"height\":%d,\"channels\":3,\"bytes\":%zu}\n",+ pg->id, step, gw, gh, n);+ fwrite(rgb, 1, n, stdout);+ putchar('\n');+ fflush(stdout);+ free(rgb);+}static void emit_progress(const Progress *pg, const char *stage, int step, int steps, double t0){if (!pg || !pg->id) return;@@ -884,6 +911,7 @@ static int engine_generate(Engine *e, const char *prompt, int width, int height,double ts0 = now_s();g_t_lin = g_t_att = 0;dit_forward(&e->dit, &e->prefix, &s, lat, ts[i], np);+ emit_preview(pg, i + 1, lat, np, sig[i], gh, gw, C);float dt = sig[i + 1] - sig[i];for (int64_t k = 0; k < (int64_t)N * C; k++) lat[k] += dt * np[k];double tstep = now_s() - ts0;@@ -1003,7 +1031,7 @@ static int serve_loop(Engine *e, int dw, int dh, int dsteps){g_cancel_pending = 0;uint8_t *rgba = xmalloc((size_t)w * h * 4);double tm[3];- Progress pg = { id, serve_cancelled };+ Progress pg = { id, serve_cancelled, (int)jnum(j, "preview", 0) };if (engine_generate(e, prompt, w, h, steps, seed, rgba, tm, &pg, msg, sizeof msg)) send_error(id, msg);else {printf("IMAGE {\"id\":\""); json_escape_out(id);@@ -1201,7 +1229,7 @@ static void usage(void){" qwenimage --model DIR --serve\n"" qwenimage --model DIR --ref REFDIR\n""env: COLI_IMG_BITS=8|16|32 weight storage (default 8: int8 rows)\n"- " COLI_IMG_ACT8=1 int8 activations in the DiT blocks (VNNI, about 2x on the step; 30.1 dB vs 35.6)\n"+ " COLI_IMG_ACT8=0 f32 activations in the DiT (default where VNNI exists: int8, about 2x per step)\n"" COLI_IMG_TE=resident|stage keep the text encoder loaded between prompts (serve default: resident)\n");}@@ -1231,11 +1259,15 @@ int main(int argc, char **argv){if (!model || (!serve && !ref && !getenv("QWENIMAGE_PRINT_TOKENS") && (!prompt || !out))) { usage(); return 2; }const char *b = getenv("COLI_IMG_BITS");if (b && *b) { g_bits = atoi(b); if (g_bits != 8 && g_bits != 16 && g_bits != 32) { usage(); return 2; } }+ /* On by default where VNNI exists: measured 2x on the step (768x512: 34.3 -> 18.3 s+ * per step on 8 Zen 4 cores) with pictures that cannot be told apart by eye+ * (fox and neon-sign prompts; 30.1 dB against the f32 reference, 35.6 without). */const char *a8 = getenv("COLI_IMG_ACT8");- g_act8 = a8 && *a8 == '1';+ g_act8 = !(a8 && *a8 == '0');g_prof = getenv("QWENIMAGE_PROF") != NULL;#ifndef QI_HAVE_VNNI- if (g_act8) { fprintf(stderr, "[qwenimage] COLI_IMG_ACT8 needs VNNI; this build has none, staying on f32 activations\n"); g_act8 = 0; }+ if (g_act8 && a8 && *a8 == '1') fprintf(stderr, "[qwenimage] COLI_IMG_ACT8 needs VNNI; this build has none, staying on f32 activations\n");+ g_act8 = 0;#endifif (!seed_set && !serve && !ref) seed = (uint64_t)time(NULL);static Engine e;diff --git a/c/qwenimage_preview.h b/c/qwenimage_preview.hnew file mode 100644index 00000000..54389b9d--- /dev/null+++ b/c/qwenimage_preview.h@@ -0,0 +1,79 @@+/* qwenimage_preview.h -- the latent -> RGB map of the live previews.+ *+ * One linear map from the 64 normalized latent channels of Qwen-Image-2.1 (plus+ * a bias, row 64) to the mean RGB of the latent pixel's 16x16 tile, in [0, 1].+ * Fitted by tools/qwenimage_fit_preview.py on the real VAE encoder over six+ * images (a photo of a cat, a test card, two foxes, a neon street at night, a+ * colour wheel). Held out one at a time, the RMS error per channel was 13 to 33+ * of 255 on ordinary pictures and 52 on the night scene: a preview, not the+ * image, which comes from the VAE at the end. */+#ifndef COLIBRI_QWENIMAGE_PREVIEW_H+#define COLIBRI_QWENIMAGE_PREVIEW_H+static const float QI_PREVIEW_RGB[65][3] = {+ {-0.000162f, 0.007304f, 0.016449f},+ {-0.023798f, 0.003098f, -0.015584f},+ {0.040925f, 0.015906f, -0.017933f},+ {0.030847f, 0.048854f, 0.011990f},+ {-0.004273f, 0.021853f, 0.002103f},+ {-0.002533f, 0.016935f, 0.013194f},+ {0.014251f, 0.011290f, -0.005530f},+ {-0.005634f, -0.046089f, -0.004886f},+ {0.008517f, -0.013905f, -0.010344f},+ {-0.047933f, 0.013475f, 0.032792f},+ {-0.018821f, -0.010070f, -0.007883f},+ {-0.007563f, 0.008810f, 0.010754f},+ {0.005722f, -0.029842f, -0.006200f},+ {-0.015920f, -0.027919f, -0.047562f},+ {0.015827f, 0.014994f, 0.009677f},+ {0.038689f, 0.024671f, 0.033631f},+ {0.026767f, 0.015371f, 0.020238f},+ {-0.007613f, -0.013988f, 0.004844f},+ {-0.003757f, 0.009013f, 0.000950f},+ {0.007186f, -0.013881f, -0.003376f},+ {0.009847f, 0.002135f, 0.015971f},+ {0.001250f, 0.011035f, 0.013640f},+ {0.013445f, 0.008677f, 0.028105f},+ {0.000957f, 0.009628f, 0.027064f},+ {-0.047716f, -0.017486f, 0.004429f},+ {-0.026926f, -0.022445f, 0.008302f},+ {-0.002730f, -0.000335f, -0.008732f},+ {-0.018194f, -0.014382f, -0.026248f},+ {0.008141f, -0.013082f, -0.002909f},+ {0.007258f, 0.018187f, 0.021778f},+ {-0.001354f, 0.003045f, 0.002348f},+ {0.005817f, -0.008618f, -0.006669f},+ {0.015531f, -0.004067f, -0.003251f},+ {-0.005029f, 0.006622f, -0.027742f},+ {0.008663f, 0.060584f, 0.062884f},+ {-0.004457f, -0.008098f, -0.026956f},+ {-0.014145f, 0.004375f, -0.005057f},+ {0.002530f, 0.001928f, -0.000307f},+ {-0.017628f, -0.012111f, 0.007016f},+ {-0.007397f, -0.040340f, 0.000047f},+ {-0.003694f, 0.005903f, -0.025010f},+ {0.082737f, 0.019231f, 0.029273f},+ {-0.011456f, -0.005718f, -0.006880f},+ {0.023613f, 0.017443f, 0.004153f},+ {-0.006679f, -0.020114f, -0.018899f},+ {0.027505f, -0.006793f, 0.005784f},+ {0.007613f, -0.013551f, -0.048627f},+ {-0.074491f, -0.018776f, -0.039472f},+ {0.001864f, -0.019908f, -0.000012f},+ {0.017660f, 0.059504f, 0.016122f},+ {-0.023709f, 0.004954f, -0.025340f},+ {0.006790f, -0.016079f, -0.012522f},+ {0.005409f, -0.017264f, 0.009443f},+ {0.030589f, -0.035789f, -0.055619f},+ {0.005542f, -0.008499f, -0.011957f},+ {-0.015744f, 0.015918f, -0.005303f},+ {-0.023556f, 0.000347f, -0.019940f},+ {-0.002043f, -0.017813f, -0.019266f},+ {0.006739f, -0.001820f, -0.005029f},+ {0.000393f, 0.002469f, 0.023242f},+ {0.016665f, -0.010279f, -0.012886f},+ {-0.008567f, -0.018800f, -0.023963f},+ {-0.004872f, -0.017309f, -0.007768f},+ {-0.017299f, 0.003615f, -0.025075f},+ {0.520193f, 0.476208f, 0.411574f},+};+#endifdiff --git a/c/tools/qwenimage_fit_preview.py b/c/tools/qwenimage_fit_preview.pynew file mode 100644index 00000000..1deac5ee--- /dev/null+++ b/c/tools/qwenimage_fit_preview.py@@ -0,0 +1,53 @@+"""Fit the latent -> RGB map the engine uses for its live previews.++Qwen-Image-2.1's 64 normalized latent channels at one latent pixel say roughly+what colour its 16x16 pixel tile will be. A least-squares linear map from those+64 values to the tile's mean RGB is enough to show the picture forming while the+DiT runs, at a cost of 64x3 multiply-adds per latent pixel.++The fit uses the real VAE encoder on a few varied images (pipeline encoding:+RGBA in [-1, 1], latent_dist mode, (z - mean) / std), holds one image out, and+prints the C table. Run with the diffusers venv:+ python fit_preview.py VAE_DIR img1 img2 ... """+import sys+import numpy as np+import torch+from PIL import Image+from diffusers import AutoencoderKLQwenImage21++vae_dir, paths = sys.argv[1], sys.argv[2:]+vae = AutoencoderKLQwenImage21.from_pretrained(vae_dir, torch_dtype=torch.float32).eval()+mean = torch.tensor(vae.config.latents_mean).view(1, -1, 1, 1, 1)+std = torch.tensor(vae.config.latents_std).view(1, -1, 1, 1, 1)+++def samples(path, side=512):+ img = Image.open(path).convert("RGBA").resize((side, side), Image.BICUBIC)+ a = np.asarray(img, dtype=np.float32) / 255.0+ x = torch.from_numpy(a * 2 - 1).permute(2, 0, 1)[None, :, None] # [1,4,1,H,W]+ with torch.no_grad():+ z = vae.encode(x).latent_dist.mode()+ z = ((z - mean) / std)[0, :, 0] # [64,h,w]+ h, w = z.shape[1:]+ X = z.permute(1, 2, 0).reshape(h * w, -1).numpy()+ tiles = a[..., :3].reshape(h, 16, w, 16, 3).mean(axis=(1, 3)).reshape(h * w, 3)+ return X, tiles+++data = [samples(p) for p in paths]+for held in range(len(data)):+ Xs = np.concatenate([d[0] for i, d in enumerate(data) if i != held])+ Ys = np.concatenate([d[1] for i, d in enumerate(data) if i != held])+ A = np.hstack([Xs, np.ones((len(Xs), 1))])+ W = np.linalg.solve(A.T @ A + 1e-2 * np.eye(A.shape[1]), A.T @ Ys)+ X, Y = data[held]+ P = np.hstack([X, np.ones((len(X), 1))]) @ W+ err = np.sqrt(((np.clip(P, 0, 1) - Y) ** 2).mean()) * 255+ print(f"held out {paths[held]}: RMS error {err:.1f} / 255 per channel")+Xs = np.concatenate([d[0] for d in data]); Ys = np.concatenate([d[1] for d in data])+A = np.hstack([Xs, np.ones((len(Xs), 1))])+W = np.linalg.solve(A.T @ A + 1e-2 * np.eye(A.shape[1]), A.T @ Ys)+print("static const float QI_PREVIEW_RGB[65][3] = {")+for r in W:+ print(" {%.6ff, %.6ff, %.6ff}," % tuple(r))+print("};")