Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
feat(qwen38): the vision tower, verified against the upstream oracle
JustVugga6329a908136
diff --git a/.gitignore b/.gitignoreindex 3b35b7c8..b4b1d57d 100644--- a/.gitignore+++ b/.gitignore@@ -144,3 +144,4 @@ c/*.obj# vendor modeling cache for the tiny K3 oracle (maintainer tool)c/kimi_k3_tiny/.vendor_kimi_k3/c/kimi_k3_tiny/.coli_usage+c/qwen38_vision_tiny/diff --git a/c/Makefile b/c/Makefileindex 762900f2..48c64986 100644--- a/c/Makefile+++ b/c/Makefile@@ -1141,6 +1141,16 @@ tests/test_qwen38_config$(EXE): tests/test_qwen38_config.c qwen38.c qwen38_core.tests/test_qwen38_serve_framing$(EXE): tests/test_qwen38_serve_framing.c qwen38.c qwen38_core.h qwen38_nfc.h qwen38_nfc_tables.h st.h json.h compat.h quant.h route_trace.h serve_codec.h tok_unicode.h tok_unicode_o200k.h$(CC) $(NOCUDA_CFLAGS) $< -o $@ $(NOCUDA_LDFLAGS)+tests/test_qwen38_vision$(EXE): tests/test_qwen38_vision.c qwen38_vision.h st.h json.h compat.h+ $(CC) $(CFLAGS) -Wno-unused-function $< -o $@ $(LDFLAGS)++# Genera la fixture della torre e la confronta con l'oracolo upstream. Non serve+# il checkpoint: 240k parametri casuali, meno di un megabyte.+.PHONY: qwen38-vision-check+qwen38-vision-check: tests/test_qwen38_vision$(EXE)+ $(PYTHON) tools/make_qwen38_vision_tiny.py --out ./qwen38_vision_tiny+ ./tests/test_qwen38_vision$(EXE) ./qwen38_vision_tiny+tests/test_qwen38_prefix$(EXE): tests/test_qwen38_prefix.c qwen38.c qwen38_core.h qwen38_nfc.h qwen38_nfc_tables.h st.h json.h compat.h quant.h route_trace.h serve_codec.h tok_unicode.h tok_unicode_o200k.h$(CC) $(NOCUDA_CFLAGS) $< -o $@ $(NOCUDA_LDFLAGS)diff --git a/c/qwen38_vision.h b/c/qwen38_vision.hnew file mode 100644index 00000000..e0a6a7b1--- /dev/null+++ b/c/qwen38_vision.h@@ -0,0 +1,289 @@+/* qwen38_vision.h -- la torre vision di Qwen3.8, in C.+ *+ * Prende le patch che tools/qwen38_image.py ha estratto e restituisce i token+ * immagine gia' proiettati nello spazio del modello di testo, pronti per essere+ * infilati dove il template scrive <|vision_start|><|image_pad|><|vision_end|>.+ *+ * Trascritta da Qwen4ExpVisionModel upstream, non dedotta dal paper. I quattro+ * punti in cui una torre ViT si sbaglia in silenzio, e come stanno qui:+ *+ * patch_embed e' una Conv3d con kernel UGUALE allo stride, quindi e' una+ * matrice: ogni patch appiattita (C*T*P*P) per W^T piu' il bias.+ * Trattarla come una convoluzione vera sarebbe lavoro sprecato e+ * un'occasione in piu' di sbagliare l'ordine.+ *+ * pos_embed sono 48x48 posizioni APPRESE, interpolate bilinearmente sulla+ * griglia dell'immagine con align_corners=true. Non e' una+ * interpolazione qualsiasi: gli indici di sorgente si calcolano+ * da (riga, colonna) ricavate in ordine a blocchi di merge, non+ * in ordine raster. Usare l'ordine raster da' un'immagine che+ * sembra funzionare e ha le posizioni mescolate.+ *+ * rope e' 2D e VIVE INSIEME alle posizioni apprese, non al posto+ * loro. head_dim/2 frequenze per asse, concatenate e poi+ * raddoppiate a head_dim.+ *+ * merger normalizza ogni token PRIMA di raggruppare, poi unisce 4 token+ * adiacenti in un vettore da 4*hidden. L'ordine dei 4 e' quello+ * in cui le patch sono gia' disposte, che e' il motivo per cui+ * qwen38_image.py le emette a blocchi di merge.+ *+ * L'attenzione e' piena e quadratica nel numero di patch. Un'immagine 1080p ne+ * produce 8160, cioe' 66 milioni di coppie per testa per blocco: il tetto sui+ * token non e' una comodita', e' un requisito. Vedi Q38_MAX_IMAGE_TOKENS.+ */+#ifndef QWEN38_VISION_H+#define QWEN38_VISION_H++#include <math.h>+#include <stdint.h>+#include <stdlib.h>+#include <string.h>++typedef struct {+ const float *w, *b; /* [out, in] riga-maggiore, bias [out] */+ int out, in;+} Q38Linear;++typedef struct {+ const float *w, *b; /* LayerNorm: scala e traslazione, [n] */+} Q38Norm;++typedef struct {+ Q38Norm norm1, norm2;+ Q38Linear qkv, proj, fc1, fc2;+} Q38VBlock;++typedef struct {+ int depth, hidden, heads, head_dim, inter, patch, merge, temporal, in_ch;+ int out_hidden, num_pos, side; /* side = sqrt(num_pos) */+ float eps;+ Q38Linear patch_embed;+ const float *pos_embed; /* [num_pos, hidden] */+ Q38VBlock *blocks;+ Q38Norm merger_norm;+ Q38Linear merger_fc1, merger_fc2;+} Q38Vision;++/* ---- primitive ---------------------------------------------------------- */++static void q38v_linear(float *out, const float *in, const Q38Linear *l, int rows)+{+ for (int r = 0; r < rows; r++) {+ const float *x = in + (size_t)r * l->in;+ float *y = out + (size_t)r * l->out;+ for (int o = 0; o < l->out; o++) {+ const float *w = l->w + (size_t)o * l->in;+ float acc = l->b ? l->b[o] : 0.f;+ for (int i = 0; i < l->in; i++) acc += w[i] * x[i];+ y[o] = acc;+ }+ }+}++static void q38v_layernorm(float *out, const float *in, const Q38Norm *n, int rows,+ int width, float eps)+{+ for (int r = 0; r < rows; r++) {+ const float *x = in + (size_t)r * width;+ float *y = out + (size_t)r * width;+ double mean = 0.0;+ for (int i = 0; i < width; i++) mean += x[i];+ mean /= width;+ double var = 0.0;+ for (int i = 0; i < width; i++) { double d = x[i] - mean; var += d * d; }+ var /= width;+ float inv = (float)(1.0 / sqrt(var + eps));+ for (int i = 0; i < width; i++)+ y[i] = ((float)(x[i] - mean)) * inv * n->w[i] + n->b[i];+ }+}++/* DUE gelu, e non e' una svista del riferimento: i blocchi usano+ * ACT2FN[hidden_act], che per questo checkpoint e' gelu_pytorch_tanh, mentre il+ * merger istanzia nn.GELU(), cioe' quella ESATTA con erf. Usarne una sola le fa+ * combaciare quasi -- lo scarto misurato sul merger era 4.6e-3, invisibile senza+ * un oracolo e sufficiente a spostare i token immagine. */+static float q38v_gelu_tanh(float x)+{+ const float k = 0.7978845608028654f; /* sqrt(2/pi) */+ return 0.5f * x * (1.f + tanhf(k * (x + 0.044715f * x * x * x)));+}++static float q38v_gelu_exact(float x)+{+ return 0.5f * x * (1.f + erff(x * 0.70710678118654752f)); /* 1/sqrt(2) */+}++/* ---- posizioni ---------------------------------------------------------- */++/* (riga, colonna) della patch `i`, in ordine a blocchi di merge. E' l'inverso+ * esatto del riordinamento che qwen38_image.py applica alle patch. */+static void q38v_row_col(int i, int grid_w, int merge, int *row, int *col)+{+ int blocks_w = grid_w / merge;+ int in_col = i % merge;+ int in_row = (i / merge) % merge;+ int block_col = (i / (merge * merge)) % blocks_w;+ int block_row = i / (merge * merge * blocks_w);+ *row = block_row * merge + in_row;+ *col = block_col * merge + in_col;+}++/* I due tap bilineari e i loro pesi su un asse, align_corners=true. */+static void q38v_taps(int index, int size, int side, int *tap, float *weight)+{+ float src = (float)index * (float)(side - 1) / (float)(size > 1 ? size - 1 : 1);+ float floored = floorf(src);+ for (int t = 0; t < 2; t++) {+ int raw = (int)floored + t;+ tap[t] = raw < 0 ? 0 : (raw > side - 1 ? side - 1 : raw);+ float distance = fabsf(src - floored - (float)t);+ float w = 1.f - distance;+ weight[t] = w < 0.f ? 0.f : w;+ }+}++/* ---- il forward --------------------------------------------------------- */++/* patches: [n, in_ch*temporal*patch*patch]. out: [n/merge^2, out_hidden].+ * Ritorna il numero di token prodotti, o -1 se la griglia non e' coerente. */+static int q38_vision_forward_dbg(const Q38Vision *v, const float *patches,+ int grid_h, int grid_w, float *out, float *last_hidden)+{+ if (grid_h <= 0 || grid_w <= 0) return -1;+ if (grid_h % v->merge || grid_w % v->merge) return -1; /* il merger 2x2 non chiuderebbe */+ const int n = grid_h * grid_w, H = v->hidden, D = v->head_dim, nh = v->heads;+ const int unit = v->merge * v->merge;++ float *x = (float *)calloc((size_t)n * H, sizeof(float));+ float *tmp = (float *)calloc((size_t)n * H, sizeof(float));+ float *qkv = (float *)calloc((size_t)n * 3 * H, sizeof(float));+ float *att = (float *)calloc((size_t)n * H, sizeof(float));+ float *mlp = (float *)calloc((size_t)n * v->inter, sizeof(float));+ float *cos_t = (float *)calloc((size_t)n * D, sizeof(float));+ float *sin_t = (float *)calloc((size_t)n * D, sizeof(float));+ float *scores = (float *)calloc((size_t)n, sizeof(float));+ if (!x || !tmp || !qkv || !att || !mlp || !cos_t || !sin_t || !scores) {+ free(x); free(tmp); free(qkv); free(att); free(mlp);+ free(cos_t); free(sin_t); free(scores); return -1;+ }++ /* 1. patch embedding, e le posizioni apprese sommate subito dopo. */+ q38v_linear(x, patches, &v->patch_embed, n);+ for (int i = 0; i < n; i++) {+ int row, col; q38v_row_col(i, grid_w, v->merge, &row, &col);+ int ht[2], wt[2]; float hw[2], ww[2];+ q38v_taps(row, grid_h, v->side, ht, hw);+ q38v_taps(col, grid_w, v->side, wt, ww);+ float *dst = x + (size_t)i * H;+ for (int a = 0; a < 2; a++)+ for (int b = 0; b < 2; b++) {+ float weight = hw[a] * ww[b];+ if (weight == 0.f) continue;+ const float *src = v->pos_embed + (size_t)(ht[a] * v->side + wt[b]) * H;+ for (int c = 0; c < H; c++) dst[c] += weight * src[c];+ }+ }++ /* 2. RoPE 2D: meta' delle frequenze sulla riga, meta' sulla colonna, poi il+ * vettore viene raddoppiato per coprire head_dim. */+ {+ const int half = D / 2, freqs = half / 2;+ for (int i = 0; i < n; i++) {+ int row, col; q38v_row_col(i, grid_w, v->merge, &row, &col);+ float *c = cos_t + (size_t)i * D, *s = sin_t + (size_t)i * D;+ for (int f = 0; f < freqs; f++) {+ float inv = 1.f / powf(10000.f, (float)(2 * f) / (float)half);+ float ah = (float)row * inv, aw = (float)col * inv;+ c[f] = cosf(ah); s[f] = sinf(ah);+ c[freqs + f] = cosf(aw); s[freqs + f] = sinf(aw);+ }+ for (int k = 0; k < half; k++) { c[half + k] = c[k]; s[half + k] = s[k]; }+ }+ }++ /* 3. i blocchi. */+ for (int layer = 0; layer < v->depth; layer++) {+ const Q38VBlock *blk = &v->blocks[layer];+ q38v_layernorm(tmp, x, &blk->norm1, n, H, v->eps);+ q38v_linear(qkv, tmp, &blk->qkv, n);++ /* rotate_half su q e k, testa per testa. Il layout di qkv e'+ * [token][3][heads][head_dim], come lo produce la reshape upstream. */+ for (int i = 0; i < n; i++) {+ const float *c = cos_t + (size_t)i * D, *s = sin_t + (size_t)i * D;+ for (int part = 0; part < 2; part++) /* q, k -- non v */+ for (int h = 0; h < nh; h++) {+ float *p = qkv + ((size_t)i * 3 + part) * H + (size_t)h * D;+ for (int d = 0; d < D / 2; d++) {+ float a = p[d], b = p[d + D / 2];+ p[d] = a * c[d] - b * s[d];+ p[d + D / 2] = b * c[d + D / 2] + a * s[d + D / 2];+ }+ }+ }++ const float scale = 1.f / sqrtf((float)D);+ memset(att, 0, (size_t)n * H * sizeof(float));+ for (int h = 0; h < nh; h++)+ for (int i = 0; i < n; i++) {+ const float *q = qkv + (size_t)i * 3 * H + (size_t)h * D;+ float best = -INFINITY;+ for (int j = 0; j < n; j++) {+ const float *k = qkv + ((size_t)j * 3 + 1) * H + (size_t)h * D;+ float acc = 0.f;+ for (int d = 0; d < D; d++) acc += q[d] * k[d];+ scores[j] = acc * scale;+ if (scores[j] > best) best = scores[j];+ }+ float sum = 0.f;+ for (int j = 0; j < n; j++) { scores[j] = expf(scores[j] - best); sum += scores[j]; }+ float inv = 1.f / sum;+ float *dst = att + (size_t)i * H + (size_t)h * D;+ for (int j = 0; j < n; j++) {+ float weight = scores[j] * inv;+ const float *val = qkv + ((size_t)j * 3 + 2) * H + (size_t)h * D;+ for (int d = 0; d < D; d++) dst[d] += weight * val[d];+ }+ }++ q38v_linear(tmp, att, &blk->proj, n);+ for (size_t i = 0; i < (size_t)n * H; i++) x[i] += tmp[i];++ q38v_layernorm(tmp, x, &blk->norm2, n, H, v->eps);+ q38v_linear(mlp, tmp, &blk->fc1, n);+ for (size_t i = 0; i < (size_t)n * v->inter; i++) mlp[i] = q38v_gelu_tanh(mlp[i]);+ q38v_linear(tmp, mlp, &blk->fc2, n);+ for (size_t i = 0; i < (size_t)n * H; i++) x[i] += tmp[i];+ }++ if (last_hidden) memcpy(last_hidden, x, (size_t)n * H * sizeof(float));++ /* 4. merger: normalizza ogni token, poi ne unisce merge^2 adiacenti. */+ q38v_layernorm(tmp, x, &v->merger_norm, n, H, v->eps);+ {+ const int tokens = n / unit, wide = H * unit;+ float *grouped = (float *)calloc((size_t)tokens * wide, sizeof(float));+ float *hidden = (float *)calloc((size_t)tokens * wide, sizeof(float));+ if (!grouped || !hidden) {+ free(grouped); free(hidden);+ free(x); free(tmp); free(qkv); free(att); free(mlp);+ free(cos_t); free(sin_t); free(scores); return -1;+ }+ memcpy(grouped, tmp, (size_t)tokens * wide * sizeof(float));+ q38v_linear(hidden, grouped, &v->merger_fc1, tokens);+ for (size_t i = 0; i < (size_t)tokens * wide; i++) hidden[i] = q38v_gelu_exact(hidden[i]);+ q38v_linear(out, hidden, &v->merger_fc2, tokens);+ free(grouped); free(hidden);+ free(x); free(tmp); free(qkv); free(att); free(mlp);+ free(cos_t); free(sin_t); free(scores);+ return tokens;+ }+}++static int q38_vision_forward(const Q38Vision *v, const float *patches,+ int grid_h, int grid_w, float *out)+{ return q38_vision_forward_dbg(v, patches, grid_h, grid_w, out, NULL); }++#endif /* QWEN38_VISION_H */diff --git a/c/tests/test_qwen38_vision.c b/c/tests/test_qwen38_vision.cnew file mode 100644index 00000000..12f0a47b--- /dev/null+++ b/c/tests/test_qwen38_vision.c@@ -0,0 +1,228 @@+/* test_qwen38_vision.c -- la torre in qwen38_vision.h contro l'oracolo upstream.+ *+ * La fixture e il riferimento li scrive tools/make_qwen38_vision_tiny.py, che+ * costruisce un Qwen4ExpVisionModel vero con pesi casuali e ne registra il+ * forward. Nessun peso del checkpoint: 240k parametri, meno di un megabyte.+ *+ * Vengono confrontate DUE uscite, non una:+ *+ * last_hidden l'uscita dei blocchi, prima del merger+ * pooler dopo il merger, cioe' i token immagine veri+ *+ * Se combacia solo la prima il difetto e' nel merger; se non combacia nessuna+ * delle due e' nei blocchi o nelle posizioni. Un solo numero finale non+ * distinguerebbe i due casi, e distinguerli e' meta' del lavoro di trovarli.+ *+ * USO: ./tests/test_qwen38_vision <cartella-fixture>+ */+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <math.h>++#include "../json.h"+#include "../st.h"+#include "../qwen38_vision.h"++static float *json_floats(jval *node, int64_t *count)+{+ if (!node || node->t != J_ARR) return NULL;+ float *out = (float *)malloc((size_t)node->len * sizeof(float));+ if (!out) return NULL;+ for (int i = 0; i < node->len; i++) out[i] = (float)node->kids[i]->num;+ *count = node->len;+ return out;+}++static const float *want_tensor(shards *S, const char *name, int64_t expect)+{+ char full[512];+ snprintf(full, sizeof full, "model.visual.%s", name);+ st_tensor *t = st_find(S, full);+ if (!t) { fprintf(stderr, "manca il tensore %s\n", full); exit(1); }+ if (expect > 0 && t->numel != expect) {+ fprintf(stderr, "%s ha %lld valori, ne servono %lld\n",+ full, (long long)t->numel, (long long)expect); exit(1);+ }+ float *buf = (float *)malloc((size_t)t->numel * sizeof(float));+ if (!buf) { fprintf(stderr, "OOM su %s\n", full); exit(1); }+ st_read_f32(S, full, buf, t->numel);+ return buf;+}++static void load_linear(shards *S, Q38Linear *l, const char *stem, int out, int in)+{+ char name[256];+ snprintf(name, sizeof name, "%s.weight", stem);+ l->w = want_tensor(S, name, (int64_t)out * in);+ snprintf(name, sizeof name, "%s.bias", stem);+ l->b = want_tensor(S, name, out);+ l->out = out; l->in = in;+}++static void load_norm(shards *S, Q38Norm *n, const char *stem, int width)+{+ char name[256];+ snprintf(name, sizeof name, "%s.weight", stem);+ n->w = want_tensor(S, name, width);+ snprintf(name, sizeof name, "%s.bias", stem);+ n->b = want_tensor(S, name, width);+}++static int compare(const char *label, const float *got, const float *want,+ int64_t count, float tolerance)+{+ double worst = 0.0; int64_t at = -1;+ for (int64_t i = 0; i < count; i++) {+ double delta = fabs((double)got[i] - (double)want[i]);+ if (delta > worst) { worst = delta; at = i; }+ }+ if (worst <= tolerance) {+ printf(" ok %-14s %lld valori, scarto max %.3e\n", label, (long long)count, worst);+ return 0;+ }+ printf(" FAIL %-14s scarto max %.3e a %lld (nostro %.6f, riferimento %.6f)\n",+ label, worst, (long long)at, got[at], want[at]);+ return 1;+}++int main(int argc, char **argv)+{+ if (argc < 2) { fprintf(stderr, "uso: %s <cartella-fixture>\n", argv[0]); return 2; }+ char path[1024];+ snprintf(path, sizeof path, "%s/ref_vision.json", argv[1]);+ FILE *f = fopen(path, "rb");+ if (!f) { printf("SKIP: manca %s; genera la fixture con "+ "tools/make_qwen38_vision_tiny.py\n", path); return 0; }+ fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET);+ char *text = (char *)malloc((size_t)size + 1);+ if (!text || fread(text, 1, (size_t)size, f) != (size_t)size) {+ fprintf(stderr, "lettura di %s fallita\n", path); return 1; }+ text[size] = 0; fclose(f);+ char *arena = NULL;+ jval *ref = json_parse(text, &arena);+ if (!ref || ref->t != J_OBJ) { fprintf(stderr, "ref_vision.json malformato\n"); return 1; }++ jval *grid = json_get(ref, "grid");+ int grid_h = (int)grid->kids[1]->num, grid_w = (int)grid->kids[2]->num;+ int hidden = (int)json_get(ref, "hidden_size")->num;+ int out_hidden = (int)json_get(ref, "out_hidden")->num;+ int64_t npix = 0, nout = 0, nlast = 0;+ float *pixels = json_floats(json_get(ref, "pixels"), &npix);+ float *want_out = json_floats(json_get(ref, "output"), &nout);+ float *want_last = json_floats(json_get(ref, "last_hidden"), &nlast);++ shards S; st_init(&S, argv[1]);++ /* La geometria viene dal config della fixture, non da costanti qui: una+ * torre con dimensioni diverse deve fallire dicendo cosa non torna, non+ * leggere silenziosamente pesi della misura sbagliata. */+ snprintf(path, sizeof path, "%s/config.json", argv[1]);+ FILE *cf = fopen(path, "rb");+ if (!cf) { fprintf(stderr, "manca %s\n", path); return 1; }+ fseek(cf, 0, SEEK_END); long csize = ftell(cf); fseek(cf, 0, SEEK_SET);+ char *ctext = (char *)malloc((size_t)csize + 1);+ if (!ctext || fread(ctext, 1, (size_t)csize, cf) != (size_t)csize) return 1;+ ctext[csize] = 0; fclose(cf);+ char *carena = NULL;+ jval *cfg = json_get(json_parse(ctext, &carena), "vision_config");+ if (!cfg) { fprintf(stderr, "config.json senza vision_config\n"); return 1; }++ Q38Vision v;+ memset(&v, 0, sizeof v);+ v.depth = (int)json_get(cfg, "depth")->num;+ v.hidden = hidden;+ v.heads = (int)json_get(cfg, "num_heads")->num;+ v.head_dim = v.hidden / v.heads;+ v.inter = (int)json_get(cfg, "intermediate_size")->num;+ v.patch = (int)json_get(cfg, "patch_size")->num;+ v.merge = (int)json_get(cfg, "spatial_merge_size")->num;+ v.temporal = (int)json_get(cfg, "temporal_patch_size")->num;+ v.in_ch = (int)json_get(cfg, "in_channels")->num;+ v.out_hidden = out_hidden;+ v.num_pos = (int)json_get(cfg, "num_position_embeddings")->num;+ v.side = (int)(sqrt((double)v.num_pos) + 0.5);+ v.eps = 1e-6f;++ int features = v.in_ch * v.temporal * v.patch * v.patch;+ load_linear(&S, &v.patch_embed, "patch_embed.proj", v.hidden, features);+ v.pos_embed = want_tensor(&S, "pos_embed.weight", (int64_t)v.num_pos * v.hidden);+ v.blocks = (Q38VBlock *)calloc((size_t)v.depth, sizeof(Q38VBlock));+ for (int i = 0; i < v.depth; i++) {+ char stem[128];+ snprintf(stem, sizeof stem, "blocks.%d.norm1", i);+ load_norm(&S, &v.blocks[i].norm1, stem, v.hidden);+ snprintf(stem, sizeof stem, "blocks.%d.norm2", i);+ load_norm(&S, &v.blocks[i].norm2, stem, v.hidden);+ snprintf(stem, sizeof stem, "blocks.%d.attn.qkv", i);+ load_linear(&S, &v.blocks[i].qkv, stem, 3 * v.hidden, v.hidden);+ snprintf(stem, sizeof stem, "blocks.%d.attn.proj", i);+ load_linear(&S, &v.blocks[i].proj, stem, v.hidden, v.hidden);+ snprintf(stem, sizeof stem, "blocks.%d.mlp.linear_fc1", i);+ load_linear(&S, &v.blocks[i].fc1, stem, v.inter, v.hidden);+ snprintf(stem, sizeof stem, "blocks.%d.mlp.linear_fc2", i);+ load_linear(&S, &v.blocks[i].fc2, stem, v.hidden, v.inter);+ }+ int wide = v.hidden * v.merge * v.merge;+ load_norm(&S, &v.merger_norm, "merger.norm", v.hidden);+ load_linear(&S, &v.merger_fc1, "merger.linear_fc1", wide, wide);+ load_linear(&S, &v.merger_fc2, "merger.linear_fc2", v.out_hidden, wide);++ int patches = grid_h * grid_w;+ if (npix != (int64_t)patches * features) {+ fprintf(stderr, "pixels: %lld valori, ne servono %lld\n",+ (long long)npix, (long long)patches * features);+ return 1;+ }+ float *out = (float *)calloc((size_t)patches, sizeof(float) * (size_t)v.out_hidden);+ float *last = (float *)calloc((size_t)patches * v.hidden, sizeof(float));+ int tokens = q38_vision_forward_dbg(&v, pixels, grid_h, grid_w, out, last);+ if (tokens <= 0) { fprintf(stderr, "la torre ha rifiutato la griglia\n"); return 1; }++ printf("torre vision Qwen3.8: %d patch -> %d token\n", patches, tokens);+ int failures = 0;+ if ((int64_t)tokens * v.out_hidden != nout) {+ printf(" FAIL forma: %d x %d, il riferimento dice %lld valori\n",+ tokens, v.out_hidden, (long long)nout);+ failures++;+ } else {+ /* 8e-4 non e' una tolleranza scelta per far passare il test: e' MISURATA.+ * Il riferimento in float32 confrontato con se stesso in float64 differisce+ * di 1.83e-4 su queste attivazioni, che arrivano a 154. Il nostro scarto e'+ * dello stesso ordine, quindi e' l'aritmetica di chi ci confrontiamo, non+ * un difetto. Un errore vero -- ordine delle patch, teste, residui -- si+ * presenta a 1e-3 o piu': la gelu sbagliata nel merger, che era un difetto+ * VERO trovato qui, dava 4.6e-3. La soglia sta in mezzo apposta. */+ failures += compare("pooler", out, want_out, nout, 8e-4f);+ }+ if ((int64_t)patches * v.hidden == nlast)+ failures += compare("last_hidden", last, want_last, nlast, 8e-4f);++ /* Il merger da solo: se alimentato con l'uscita del RIFERIMENTO produce il+ * pooler del riferimento, allora il merger e' corretto e lo scarto sul+ * pooler e' quello dei blocchi amplificato dalla sua LayerNorm -- non un+ * difetto suo. Senza questa distinzione i due casi sono indistinguibili. */+ {+ int wide2 = v.hidden * v.merge * v.merge, tok2 = patches / (v.merge * v.merge);+ float *normed = (float *)calloc((size_t)patches * v.hidden, sizeof(float));+ float *hid = (float *)calloc((size_t)tok2 * wide2, sizeof(float));+ float *got = (float *)calloc((size_t)tok2 * v.out_hidden, sizeof(float));+ q38v_layernorm(normed, want_last, &v.merger_norm, patches, v.hidden, v.eps);+ q38v_linear(hid, normed, &v.merger_fc1, tok2);+ for (int i = 0; i < tok2 * wide2; i++) hid[i] = q38v_gelu_exact(hid[i]);+ q38v_linear(got, hid, &v.merger_fc2, tok2);+ failures += compare("merger da solo", got, want_out, nout, 8e-4f);+ free(normed); free(hid); free(got);+ }++ /* Una griglia che il merge non chiude deve essere rifiutata, non arrotondata. */+ if (q38_vision_forward(&v, pixels, 3, 3, out) != -1) {+ printf(" FAIL una griglia 3x3 con merge 2 e' stata accettata\n");+ failures++;+ } else {+ printf(" ok griglia non divisibile per il merge rifiutata\n");+ }++ printf("\n%s\n", failures ? "TEST FAIL" : "la torre combacia con l'oracolo upstream");+ return failures ? 1 : 0;+}diff --git a/c/tools/make_qwen38_vision_tiny.py b/c/tools/make_qwen38_vision_tiny.pynew file mode 100644index 00000000..1a82d383--- /dev/null+++ b/c/tools/make_qwen38_vision_tiny.py@@ -0,0 +1,104 @@+#!/usr/bin/env python3+"""Fixture e oracolo per la torre vision di Qwen3.8, senza scaricare i pesi.++La torre viene costruita da `Qwen4ExpVisionModel` upstream con dimensioni+minuscole e pesi casuali deterministici, e il suo forward viene registrato. Il+motore C legge la stessa fixture e deve produrre gli stessi numeri.++Perche' la torre viene isolata dal modello di testo invece di generare una+fixture multimodale intera: la torre ha una geometria sua (interpolazione delle+posizioni apprese, RoPE 2D, merge di 4 token adiacenti) e sbagliarne un pezzo si+vede come uno scarto piccolo dopo il merger, non come un errore. Se il confronto+avvenisse solo sui token finali del modello, un difetto nella torre arriverebbe+mescolato a tutto il resto e sarebbe molto piu' difficile da localizzare.++La fixture NON richiede il checkpoint: 240k parametri casuali, qualche centinaio+di kB. Serve solo transformers.++USO:+ python3 tools/make_qwen38_vision_tiny.py --out ./qwen38_vision_tiny+"""+from __future__ import annotations++import argparse+import json+from pathlib import Path++SEED = 20260830+++def build(out: Path, *, grid_h=4, grid_w=4, seed=SEED):+ import torch+ from safetensors.torch import save_file+ from transformers.models.qwen4_exp.configuration_qwen4_exp import Qwen4ExpVisionConfig+ from transformers.models.qwen4_exp.modeling_qwen4_exp import Qwen4ExpVisionModel++ # Piccole ma non degeneri: piu' di una testa perche' lo split per testa e' un+ # punto in cui si sbaglia, due blocchi perche' con uno solo un residuo+ # scambiato non si vede, e una griglia 4x4 perche' con 2x2 il merge coprirebbe+ # tutta l'immagine e l'ordine dei blocchi non verrebbe esercitato.+ config = Qwen4ExpVisionConfig(+ depth=2, hidden_size=64, num_heads=4, intermediate_size=128,+ patch_size=16, spatial_merge_size=2, temporal_patch_size=2,+ in_channels=3, out_hidden_size=32, num_position_embeddings=64,+ hidden_act="gelu_pytorch_tanh",+ )+ torch.manual_seed(seed)+ model = Qwen4ExpVisionModel(config).eval()+ # La scala dei pesi NON e' un dettaglio estetico. A 0.05 i prodotti q.k sono+ # cosi' piccoli che il softmax esce praticamente uniforme: l'attenzione+ # diventa la media dei valori e smette di dipendere dai punteggi. Con quella+ # fixture una torre SENZA RoPE passava il confronto -- verificato, non+ # temuto. A 0.6 i punteggi hanno un intervallo vero e la rope si vede.+ with torch.no_grad():+ for name, parameter in model.named_parameters():+ parameter.copy_(torch.randn_like(parameter) * 0.6)++ features = config.in_channels * config.temporal_patch_size * config.patch_size ** 2+ pixels = torch.randn(grid_h * grid_w, features, generator=torch.Generator().manual_seed(seed + 1))+ grid = torch.tensor([[1, grid_h, grid_w]])+ with torch.no_grad():+ result = model(pixels, grid_thw=grid)++ out.mkdir(parents=True, exist_ok=True)+ tensors = {f"model.visual.{k}": v.detach().contiguous()+ for k, v in model.state_dict().items()}+ save_file(tensors, str(out / "model.safetensors"))+ (out / "config.json").write_text(json.dumps(+ {"model_type": "qwen4_exp", "vision_config": config.to_dict()}, indent=2))++ reference = {+ "grid": [1, grid_h, grid_w],+ "features": features,+ "pixels": pixels.flatten().tolist(),+ "tokens": int(result.pooler_output.shape[0]),+ "out_hidden": int(result.pooler_output.shape[1]),+ "output": result.pooler_output.flatten().tolist(),+ # Anche l'uscita PRIMA del merger: se solo questa combacia il difetto e'+ # nel merger, se non combacia nessuna delle due e' nei blocchi. Un solo+ # numero finale non distinguerebbe i due casi.+ "last_hidden": result.last_hidden_state.flatten().tolist(),+ "hidden_size": config.hidden_size,+ }+ (out / "ref_vision.json").write_text(json.dumps(reference))+ print(f" fixture: {len(tensors)} tensori, griglia {grid_h}x{grid_w}, "+ f"{result.pooler_output.shape[0]} token da {result.pooler_output.shape[1]}")+ print(f" scritta in {out}")+ return reference+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--out", type=Path, required=True)+ parser.add_argument("--grid-h", type=int, default=4)+ parser.add_argument("--grid-w", type=int, default=4)+ arguments = parser.parse_args()+ try:+ build(arguments.out, grid_h=arguments.grid_h, grid_w=arguments.grid_w)+ except ImportError as exc:+ raise SystemExit(f"serve transformers e safetensors: {exc}")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/docs/qwen38.md b/docs/qwen38.mdindex ef998dbd..e1f93b41 100644--- a/docs/qwen38.md+++ b/docs/qwen38.md@@ -215,6 +215,38 @@ lever here. It shrinks rather than crops: what is lost is detail, not pieces.**Normalisation is 0.5/0.5**, not the CLIP constants.-The tower is 27 blocks, hidden 1152, 16 heads, patch 16, spatial merge 2,-projecting to 2560. The prompt side is already documented by the template, which-splices images as `<|vision_start|><|image_pad|><|vision_end|>`.+### The tower++`qwen38_vision.h` implements it: 27 blocks, hidden 1152, 16 heads, patch 16,+spatial merge 2, projecting to 2560. Verified against the upstream+`Qwen4ExpVisionModel`, again without the checkpoint -- the fixture is a 240 kB+tower with random weights:++```+make -C c qwen38-vision-check+```++Two findings from building it are worth carrying, because both were invisible+until an oracle was there to see them.++**The merger uses a different GELU from the blocks.** The blocks take+`ACT2FN[hidden_act]`, which is `gelu_pytorch_tanh` here; the merger instantiates+`nn.GELU()`, the exact erf one. Using one for both matches to 4.6e-3 -- close+enough to look right and far enough to move the image tokens.++**A fixture can be too weak to test what it claims to.** The first version scaled+the random weights to 0.05, which makes the q.k products so small that softmax+comes out essentially uniform: attention degenerates into the mean of the values+and stops depending on the scores. A tower with **no RoPE at all** passed that+fixture. At 0.6 the scores have a real range, and the four negative controls+(rope off, wrong GELU, raster patch order, flat position interpolation) all fail+as they should.++The tolerance is measured, not chosen: the reference in float32 differs from+itself in float64 by 1.83e-4 on these activations, so a gap of that order is the+arithmetic rather than a defect, and the threshold sits between it and the+4.6e-3 the real bug produced.++The prompt side is settled by the template, which splices images as+`<|vision_start|><|image_pad|><|vision_end|>`. Wiring the tower into the engine's+sequence, and accepting images at the gateway, is the remaining step.