Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
feat(deepseek-v41): engine, CPU reference and container tools
JustVuggf29782e68e80
diff --git a/c/deepseek_v41.c b/c/deepseek_v41.cnew file mode 100644index 00000000..7f01af7e--- /dev/null+++ b/c/deepseek_v41.c@@ -0,0 +1,2242 @@+/* deepseek_v41.c — DeepSeek-V4.1-Flash on a machine that cannot hold it.+ *+ * 552B parameters, 510 GB on disk, and the shape of it is why this engine exists:+ *+ * engram 203 GB two n-gram memories (384M rows x 264 B) read by hash: at most+ * (max_ngram-1) * n_heads rows per layer per token, so ~13 KB of+ * random reads for 40% of the model. Streaming is not a compromise+ * here, it is the only sane way to serve it.+ * experts 289 GB 15,360 fp4 experts of 18.8 MB; 6 of 384 routed per layer, so+ * 4.5 GB per token, cached in RAM by the same LRU as every other+ * family here (GLM-5.2 reads 12.7 GB per token for comparison).+ * dense 18 GB attention, gates, norms, hyper-connection mixers: resident.+ *+ * No conversion step: the released checkpoint is already fp8 (dense, 32x32 ue8m0+ * block scales) and fp4 (experts, ue8m0 per 32-column group), and the fp4 layout is+ * byte-identical to the mxfp4 colibri already reads for Kimi K3, so quant.h's+ * matmul_mxfp4 is the expert kernel. What the container does need is a sidecar the+ * engine cannot compute (tools/prepare_dsv41.py): the engram bucket primes (sympy),+ * the hash multipliers (numpy PCG64) and the compressed-token map (the tokenizer's+ * normalizer). Those are tables, not weights.+ *+ * Mechanisms, each mirroring a named piece of the vendor's inference/model.py:+ * hyper-connections hc_mult parallel residual streams, mixed through a+ * doubly-stochastic matrix (Sinkhorn) — hyper_connections.h,+ * shared with DeepSeek V4 and GLM-5.3-Flash+ * sliding window every layer attends a ring of `window_size` raw KV, MQA:+ * one KV vector per position for all heads+ * compressed KV kv_source_layers pool `compress_ratio` tokens into one+ * latent with a softmax gate and publish it; the layers+ * between them read that same cache+ * DSA indexer index_source_layers score compressed positions and keep+ * index_topk of them, two-level when a candidate source is+ * configured+ * engram n-gram hash lookups gated into the residual stream+ * MoE sqrtsoftplus scores, noaux_tc bias picks but does not+ * scale, one shared expert every token pays+ *+ * The reference this engine is held to is tools/dsv41_ref.py (torch, CPU): the+ * vendor's own forward runs on tilelang GPU kernels and cannot be an oracle here.+ */+#define _GNU_SOURCE+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <stdint.h>+#include <math.h>+#include <errno.h>+#include <time.h>+#include <stdarg.h>+#include <sys/resource.h>+#ifdef _OPENMP+#include <omp.h>+#endif++#include "cli_args.h"+#include "compat.h"+#include "json.h"+#include "st.h"+#include "quant.h"+#include "hyper_connections.h"+#include "tok.h"+#include "serve_codec.h"+#include "serve_poll.h"++#define V41_MAX_LAYERS 64+#define V41_MAX_ENGRAM 4+#define V41_MAX_NGRAM 8+#define V41_MAX_EHEADS 16++/* ---------------------------------------------------------------- config ---- */++typedef struct {+ int vocab, dim, n_layers, n_heads, head_dim, rope_dim;+ int q_lora, o_lora, o_groups;+ int moe_inter, n_routed, n_activated, n_shared;+ int norm_topk_prob;+ float route_scale, gate_temp, swiglu_limit, norm_eps;+ int window;+ int compress_ratio[V41_MAX_LAYERS];+ int kv_source[V41_MAX_LAYERS]; /* 1 = this layer owns a compressed KV cache */+ int index_source[V41_MAX_LAYERS]; /* 1 = this layer runs its own indexer */+ int index_owner[V41_MAX_LAYERS]; /* which kv_source layer's caches it reads */+ float compress_rope_theta, rope_theta, rope_factor;+ int original_seq_len, beta_fast, beta_slow;+ int index_n_heads, index_head_dim, index_topk;+ int candidate_source, candidate_topk_blocks, candidate_block_size;+ int hc_mult, hc_iters;+ float hc_eps;+ int max_positions;+ /* engram */+ int n_engram, engram_layer[V41_MAX_ENGRAM];+ int64_t engram_rows[V41_MAX_ENGRAM];+ int engram_max_ngram, engram_heads, engram_head_dim, engram_pad_id;+ int engram_cols; /* (max_ngram - 1) * heads */+ /* vision (VL). vision_layers == 0 means a text-only container. */+ int vision_layers, vision_dim, vision_heads, vision_inter, vision_patch;+ int vision_ratio, vision_max_tokens, image_token_id;+ float vision_rope_theta;+} Cfg;++static double jnum(jval *o, const char *key, double fallback) {+ jval *v = o ? json_get(o, key) : NULL;+ return (v && v->t == J_NUM) ? v->num : fallback;+}++static int jints(jval *o, const char *key, int *out, int cap) {+ jval *v = o ? json_get(o, key) : NULL;+ if (!v || v->t != J_ARR) return 0;+ int n = v->len < cap ? v->len : cap;+ for (int i = 0; i < n; i++) out[i] = (int)v->kids[i]->num;+ return n;+}++/* The released config nests everything the text model needs under `text_config`;+ * the tiny fixture does the same, so one reader serves both. */+static void cfg_load(Cfg *c, const char *snap) {+ char path[1024];+ snprintf(path, sizeof(path), "%s/config.json", snap);+ FILE *f = fopen(path, "rb");+ if (!f) { fprintf(stderr, "[cfg] %s: %s\n", path, strerror(errno)); exit(1); }+ fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET);+ char *text = malloc((size_t)size + 1);+ if (!text || fread(text, 1, (size_t)size, f) != (size_t)size) {+ fprintf(stderr, "[cfg] short read on %s\n", path); exit(1); }+ text[size] = 0; fclose(f);+ char *arena = NULL;+ jval *root = json_parse(text, &arena);+ if (!root) { fprintf(stderr, "[cfg] %s is not valid JSON\n", path); exit(1); }+ jval *t = json_get(root, "text_config");+ if (!t) t = root; /* a flat config is accepted: the fields are the same */++ memset(c, 0, sizeof(*c));+ c->vocab = (int)jnum(t, "vocab_size", 0);+ c->dim = (int)jnum(t, "dim", jnum(t, "hidden_size", 0));+ c->n_layers = (int)jnum(t, "n_layers", jnum(t, "num_hidden_layers", 0));+ c->n_heads = (int)jnum(t, "n_heads", jnum(t, "num_attention_heads", 0));+ c->head_dim = (int)jnum(t, "head_dim", 0);+ c->rope_dim = (int)jnum(t, "rope_head_dim", jnum(t, "qk_rope_head_dim", 0));+ c->q_lora = (int)jnum(t, "q_lora_rank", 0);+ c->o_lora = (int)jnum(t, "o_lora_rank", 0);+ c->o_groups = (int)jnum(t, "o_groups", 1);+ c->moe_inter = (int)jnum(t, "moe_inter_dim", jnum(t, "moe_intermediate_size", 0));+ c->n_routed = (int)jnum(t, "n_routed_experts", 0);+ c->n_activated= (int)jnum(t, "n_activated_experts", jnum(t, "num_experts_per_tok", 0));+ c->n_shared = (int)jnum(t, "n_shared_experts", 1);+ c->norm_topk_prob = (int)jnum(t, "norm_topk_prob", 1);+ c->route_scale= (float)jnum(t, "route_scale", jnum(t, "routed_scaling_factor", 1.0));+ c->gate_temp = (float)jnum(t, "gate_temp", 1.0);+ c->swiglu_limit = (float)jnum(t, "swiglu_limit", 0.0);+ c->norm_eps = (float)jnum(t, "norm_eps", jnum(t, "rms_norm_eps", 1e-6));+ c->window = (int)jnum(t, "window_size", jnum(t, "sliding_window", 128));+ c->compress_rope_theta = (float)jnum(t, "compress_rope_theta", 40000.0);+ c->rope_theta = (float)jnum(t, "rope_theta", 10000.0);+ c->rope_factor= (float)jnum(t, "rope_factor", 1.0);+ c->original_seq_len = (int)jnum(t, "original_seq_len", 0);+ c->beta_fast = (int)jnum(t, "beta_fast", 32);+ c->beta_slow = (int)jnum(t, "beta_slow", 1);+ c->index_n_heads = (int)jnum(t, "index_n_heads", 0);+ c->index_head_dim= (int)jnum(t, "index_head_dim", 0);+ c->index_topk = (int)jnum(t, "index_topk", 0);+ c->candidate_source = (int)jnum(t, "candidate_source_layer",+ jnum(t, "candidate_source_layer_id", -1));+ c->candidate_topk_blocks = (int)jnum(t, "candidate_topk_blocks", 0);+ c->candidate_block_size = (int)jnum(t, "candidate_block_size", 0);+ c->hc_mult = (int)jnum(t, "hc_mult", 1);+ c->hc_iters = (int)jnum(t, "hc_sinkhorn_iters", 20);+ c->hc_eps = (float)jnum(t, "hc_eps", 1e-6);+ c->max_positions = (int)jnum(t, "max_seq_len", jnum(t, "max_position_embeddings", 4096));+ /* YaRN, as the vendor spells it: rope_scaling.factor when present */+ jval *scaling = json_get(t, "rope_scaling");+ if (scaling && scaling->t == J_OBJ) {+ c->rope_factor = (float)jnum(scaling, "factor", c->rope_factor);+ c->beta_fast = (int)jnum(scaling, "beta_fast", c->beta_fast);+ c->beta_slow = (int)jnum(scaling, "beta_slow", c->beta_slow);+ c->original_seq_len = (int)jnum(scaling, "original_max_position_embeddings",+ c->original_seq_len);+ }++ if (c->n_layers < 1 || c->n_layers > V41_MAX_LAYERS) {+ fprintf(stderr, "[cfg] n_layers %d out of range\n", c->n_layers); exit(1); }+ int ratios[V41_MAX_LAYERS] = {0};+ int nr = jints(t, "compress_ratios", ratios, V41_MAX_LAYERS);+ if (nr < c->n_layers) {+ fprintf(stderr, "[cfg] compress_ratios has %d entries for %d layers\n",+ nr, c->n_layers); exit(1); }+ for (int i = 0; i < c->n_layers; i++) c->compress_ratio[i] = ratios[i];+ int src[V41_MAX_LAYERS];+ int n = jints(t, "kv_source_layers", src, V41_MAX_LAYERS);+ if (!n) n = jints(t, "kv_source_layer_ids", src, V41_MAX_LAYERS);+ for (int i = 0; i < n; i++) if (src[i] >= 0 && src[i] < c->n_layers) c->kv_source[src[i]] = 1;+ n = jints(t, "index_source_layers", src, V41_MAX_LAYERS);+ if (!n) n = jints(t, "index_source_layer_ids", src, V41_MAX_LAYERS);+ for (int i = 0; i < n; i++) if (src[i] >= 0 && src[i] < c->n_layers) c->index_source[src[i]] = 1;+ /* Who owns the caches a layer reads: the nearest kv_source at or before it.+ * The vendor keeps this implicit in a module-level object that the source+ * writes and everyone after reads; making it explicit here means a layer can+ * be served without replaying the ones before it. */+ int owner = -1;+ for (int i = 0; i < c->n_layers; i++) {+ if (c->kv_source[i]) owner = i;+ c->index_owner[i] = owner;+ }+ jval *vision = json_get(root, "vision_config");+ if (vision && vision->t == J_OBJ) {+ c->vision_layers = (int)jnum(vision, "num_hidden_layers", 0);+ c->vision_dim = (int)jnum(vision, "hidden_size", 0);+ c->vision_heads = (int)jnum(vision, "num_attention_heads", 0);+ c->vision_inter = (int)jnum(vision, "intermediate_size", 0);+ c->vision_patch = (int)jnum(vision, "patch_size", 0);+ c->vision_ratio = (int)jnum(vision, "downsample_ratio", 1);+ c->vision_max_tokens = (int)jnum(vision, "max_image_tokens", 0);+ c->vision_rope_theta = (float)jnum(vision, "rope_theta", 10000.0);+ }+ c->image_token_id = (int)jnum(root, "image_token_id", -1);+ json_free(root); free(arena); free(text);+}++/* ------------------------------------------------------- weights in RAM ---- */++/* The dense trunk stays in the checkpoint's own formats: dequantizing fp8 to f32 at+ * load would turn 18 GB into 72 GB, which is the whole point of not doing it. Each+ * kernel below decodes as it multiplies. */+typedef struct { uint8_t *q; uint8_t *s; int O, I; } W8; /* e4m3 + 32x32 ue8m0 */+typedef struct { uint16_t *w; int O, I; } WB; /* bf16 */+typedef struct { float *w; int64_t n; } WF; /* f32 */++#define FP8_TILE 32++/* V41_TRACE=1 prints a checksum of the tensors the reference prints too, so a+ * divergence is located by diffing two columns rather than by reading two forwards. */+static int g_trace = 0;+static void trace(const char *name, int layer, const float *v, int n) {+ if (!g_trace) return;+ double sum = 0.0;+ for (int i = 0; i < n; i++) sum += v[i];+ fprintf(stderr, "T %-10s L%-2d n=%-5d sum=%+.6f [%+.6f %+.6f %+.6f]\n",+ name, layer, n, sum, v[0], n > 1 ? v[1] : 0.0f, n > 2 ? v[2] : 0.0f);+}++static double rss_gb(void) {+ struct rusage usage;+ getrusage(RUSAGE_SELF, &usage);+#ifdef __APPLE__+ return usage.ru_maxrss / 1e9;+#else+ return usage.ru_maxrss / 1e6;+#endif+}++static double now_s(void) {+ struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t);+ return t.tv_sec + t.tv_nsec * 1e-9;+}++static void *xmalloc(size_t bytes, const char *what) {+ void *p = malloc(bytes ? bytes : 1);+ if (!p) { fprintf(stderr, "OOM allocating %s (%zu bytes)\n", what, bytes); exit(1); }+ return p;+}++static void w8_load(shards *S, W8 *w, const char *name, int O, int I) {+ char scale_name[512];+ snprintf(scale_name, sizeof(scale_name), "%.*s.scale",+ (int)(strlen(name) - strlen(".weight")), name);+ st_tensor *t = st_find(S, name);+ if (!t) { fprintf(stderr, "%s: missing\n", name); exit(1); }+ if (t->nbytes != (int64_t)O * I) {+ fprintf(stderr, "%s: %lld bytes, expected %lld for [%d, %d] fp8\n",+ name, (long long)t->nbytes, (long long)O * I, O, I); exit(1); }+ int tiles = ((O + FP8_TILE - 1) / FP8_TILE) * ((I + FP8_TILE - 1) / FP8_TILE);+ w->O = O; w->I = I;+ w->q = xmalloc((size_t)O * I, name);+ w->s = xmalloc((size_t)tiles, scale_name);+ st_read_raw_cap(S, name, w->q, (int64_t)O * I, 0);+ st_read_raw_cap(S, scale_name, w->s, tiles, 0);+}++static void wb_load(shards *S, WB *w, const char *name, int O, int I) {+ st_tensor *t = st_find(S, name);+ if (!t) { fprintf(stderr, "%s: missing\n", name); exit(1); }+ if (t->nbytes != (int64_t)O * I * 2) {+ fprintf(stderr, "%s: %lld bytes, expected %lld for [%d, %d] bf16\n",+ name, (long long)t->nbytes, (long long)O * I * 2, O, I); exit(1); }+ w->O = O; w->I = I;+ w->w = xmalloc((size_t)O * I * 2, name);+ st_read_raw_cap(S, name, w->w, (int64_t)O * I * 2, 0);+}++static void wf_load(shards *S, WF *w, const char *name, int64_t n) {+ w->n = n;+ w->w = xmalloc((size_t)n * sizeof(float), name);+ /* st_read_f32 widens bf16/f16 as well, so a checkpoint that stores one of these+ * small tensors in bf16 rather than f32 still loads. */+ if (st_read_f32(S, name, w->w, 0) != n) {+ fprintf(stderr, "%s: expected %lld floats\n", name, (long long)n); exit(1); }+}++/* 2^(byte - 127) without a call: ue8m0 is a bare exponent, so the byte lands straight+ * in an IEEE exponent field. byte 0 and 255 (denormal / inf) never occur in a real+ * checkpoint and decode to +0 and +inf here, matching quant.h's mxfp4 path. */+static inline float ue8m0(uint8_t byte) {+ union { uint32_t u; float f; } value;+ value.u = (uint32_t)byte << 23;+ return value.f;+}++/* y[O] = W [O, I] x[I], W in e4m3 with one ue8m0 scale per 32x32 tile. */+static void mv8(float *y, const W8 *w, const float *x) {+ int I = w->I, tiles_i = (I + FP8_TILE - 1) / FP8_TILE;+ #pragma omp parallel for schedule(static)+ for (int o = 0; o < w->O; o++) {+ const uint8_t *row = w->q + (size_t)o * I;+ const uint8_t *scale = w->s + (size_t)(o / FP8_TILE) * tiles_i;+ float sum = 0.0f;+ for (int base = 0; base < I; base += FP8_TILE) {+ int width = I - base < FP8_TILE ? I - base : FP8_TILE;+ float tile = ue8m0(scale[base / FP8_TILE]);+ float part = 0.0f;+ for (int i = 0; i < width; i++) part += e4m3_decode(row[base + i]) * x[base + i];+ sum += part * tile;+ }+ y[o] = sum;+ }+}++static void mvb(float *y, const WB *w, const float *x) {+ int I = w->I;+ #pragma omp parallel for schedule(static)+ for (int o = 0; o < w->O; o++) {+ const uint16_t *row = w->w + (size_t)o * I;+ float sum = 0.0f;+ for (int i = 0; i < I; i++) sum += bf16_to_f32(row[i]) * x[i];+ y[o] = sum;+ }+}++/* ------------------------------------------------------------- engram ------ */++/* One n-gram memory. The table itself never enters RAM: `lookup` reads the row it+ * needs (head_dim bytes of e4m3 plus head_dim/32 scale bytes) and keeps it in a small+ * LRU, because n-gram traffic is Zipfian -- the common 2-grams repeat constantly. */+typedef struct {+ int fd_w, fd_s;+ int64_t off_w, off_s, rows;+ /* row cache: open addressing on the row id, LRU by a clock */+ int cap, mask;+ int64_t *key; /* row id, -1 for empty */+ uint64_t *used;+ float *value; /* cap x head_dim */+ uint64_t clock, hits, misses;+} EngramTable;++typedef struct {+ int active;+ int max_ngram, heads, head_dim, cols, pad_id;+ int64_t primes[V41_MAX_ENGRAM][V41_MAX_NGRAM][V41_MAX_EHEADS];+ int64_t offsets[V41_MAX_ENGRAM][V41_MAX_NGRAM * V41_MAX_EHEADS];+ int64_t multipliers[V41_MAX_ENGRAM][V41_MAX_NGRAM];+ int layer_of[V41_MAX_ENGRAM];+ int n_layers;+ int32_t *token_map;+ int token_map_len;+ EngramTable table[V41_MAX_ENGRAM];+ /* compressed ids of every position seen so far: the n-gram of a position looks+ * back over these, and an image position is DEAD (-1) so no n-gram spans it */+ int32_t *history;+ int history_len, history_cap;+} Engram;++#define ENGRAM_DEAD (-1)++static void engram_load_sidecar(Engram *e, const char *snap) {+ char path[1024];+ snprintf(path, sizeof(path), "%s/dsv41_engram.json", snap);+ FILE *f = fopen(path, "rb");+ if (!f) { e->active = 0; return; } /* a text-only container without engram is legal */+ fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET);+ char *text = xmalloc((size_t)size + 1, "engram sidecar");+ if (fread(text, 1, (size_t)size, f) != (size_t)size) {+ fprintf(stderr, "[engram] short read on %s\n", path); exit(1); }+ text[size] = 0; fclose(f);+ char *arena = NULL;+ jval *root = json_parse(text, &arena);+ if (!root) { fprintf(stderr, "[engram] %s is not valid JSON\n", path); exit(1); }++ e->max_ngram = (int)jnum(root, "max_ngram_size", 0);+ e->heads = (int)jnum(root, "n_heads", 0);+ e->head_dim = (int)jnum(root, "head_dim", 0);+ e->pad_id = (int)jnum(root, "pad_id", 0);+ e->cols = (e->max_ngram - 1) * e->heads;+ if (e->max_ngram > V41_MAX_NGRAM || e->heads > V41_MAX_EHEADS) {+ fprintf(stderr, "[engram] layout %dx%d exceeds the compiled maximum\n",+ e->max_ngram, e->heads); exit(1); }+ jval *ids = json_get(root, "layer_ids");+ e->n_layers = ids && ids->t == J_ARR ? ids->len : 0;+ if (e->n_layers > V41_MAX_ENGRAM) {+ fprintf(stderr, "[engram] %d tables exceed the compiled maximum\n", e->n_layers); exit(1); }+ for (int i = 0; i < e->n_layers; i++) e->layer_of[i] = (int)ids->kids[i]->num;+ jval *primes = json_get(root, "primes");+ jval *offsets = json_get(root, "offsets");+ jval *multipliers = json_get(root, "multipliers");+ if (!primes || !offsets || !multipliers) {+ fprintf(stderr, "[engram] sidecar lacks primes/offsets/multipliers\n"); exit(1); }+ for (int layer = 0; layer < e->n_layers; layer++) {+ jval *rows = primes->kids[layer];+ for (int n = 0; n < rows->len && n < V41_MAX_NGRAM; n++)+ for (int h = 0; h < rows->kids[n]->len && h < V41_MAX_EHEADS; h++)+ e->primes[layer][n][h] = (int64_t)rows->kids[n]->kids[h]->num;+ jval *off = offsets->kids[layer];+ for (int i = 0; i < off->len && i < V41_MAX_NGRAM * V41_MAX_EHEADS; i++)+ e->offsets[layer][i] = (int64_t)off->kids[i]->num;+ jval *mult = multipliers->kids[layer];+ for (int i = 0; i < mult->len && i < V41_MAX_NGRAM; i++) {+ /* Decimal strings on purpose. The multipliers run to int64 / compressed+ * vocabulary, which is past the 53 bits a double keeps exactly; read as a+ * number, a rounded multiplier would hash every n-gram into a different --+ * and perfectly valid-looking -- row. Refuse rather than round. */+ jval *entry = mult->kids[i];+ if (entry->t != J_STR) {+ fprintf(stderr, "[engram] multipliers must be decimal strings; this "+ "sidecar stores them as JSON numbers, which cannot hold "+ "them exactly. Regenerate it with tools/prepare_dsv41.py\n");+ exit(1);+ }+ errno = 0;+ char *end = NULL;+ long long value = strtoll(entry->str, &end, 10);+ if (errno || !end || *end) {+ fprintf(stderr, "[engram] multiplier %s is not an integer\n", entry->str);+ exit(1);+ }+ e->multipliers[layer][i] = (int64_t)value;+ }+ }+ jval *map = json_get(root, "token_map");+ if (!map || map->t != J_ARR) { fprintf(stderr, "[engram] sidecar lacks token_map\n"); exit(1); }+ e->token_map_len = map->len;+ e->token_map = xmalloc((size_t)map->len * sizeof(int32_t), "engram token map");+ for (int i = 0; i < map->len; i++) e->token_map[i] = (int32_t)map->kids[i]->num;+ e->active = 1;+ json_free(root); free(arena); free(text);+}++static void engram_table_open(EngramTable *t, shards *S, int layer, int head_dim, int cache_rows) {+ char name[256];+ snprintf(name, sizeof(name), "layers.%d.engram.embed.weight", layer);+ st_tensor *w = st_find(S, name);+ snprintf(name, sizeof(name), "layers.%d.engram.embed.scale", layer);+ st_tensor *s = st_find(S, name);+ if (!w || !s) { fprintf(stderr, "[engram] layer %d has no table\n", layer); exit(1); }+ t->fd_w = w->fd; t->off_w = w->off;+ t->fd_s = s->fd; t->off_s = s->off;+ t->rows = w->nbytes / head_dim;+ int cap = 1;+ while (cap < cache_rows) cap <<= 1;+ t->cap = cap; t->mask = cap - 1;+ t->key = xmalloc((size_t)cap * sizeof(int64_t), "engram row keys");+ t->used = xmalloc((size_t)cap * sizeof(uint64_t), "engram row clocks");+ t->value = xmalloc((size_t)cap * head_dim * sizeof(float), "engram row cache");+ for (int i = 0; i < cap; i++) { t->key[i] = -1; t->used[i] = 0; }+ t->clock = t->hits = t->misses = 0;+}++/* The row for `id`, dequantized. Reads through a direct-mapped-with-probe cache: on a+ * miss the row and its scales are one pread each, 264 bytes for the released table. */+static const float *engram_row(EngramTable *t, int64_t id, int head_dim) {+ int groups = head_dim / 32;+ int slot = (int)((uint64_t)(id * 0x9E3779B97F4A7C15ull) >> 40) & t->mask;+ int victim = slot;+ for (int probe = 0; probe < 4; probe++) {+ int at = (slot + probe) & t->mask;+ if (t->key[at] == id) { t->used[at] = ++t->clock; t->hits++;+ return t->value + (size_t)at * head_dim; }+ if (t->key[at] == -1) { victim = at; goto fill; }+ if (t->used[at] < t->used[victim]) victim = at;+ }+fill:+ t->misses++;+ {+ uint8_t bytes[512], scales[64];+ if (head_dim > (int)sizeof(bytes) || groups > (int)sizeof(scales)) {+ fprintf(stderr, "[engram] head_dim %d exceeds the row buffer\n", head_dim); exit(1); }+ st_pread_full(t->fd_w, bytes, head_dim, t->off_w + id * head_dim, "engram row");+ st_pread_full(t->fd_s, scales, groups, t->off_s + id * groups, "engram scale");+ float *out = t->value + (size_t)victim * head_dim;+ for (int g = 0; g < groups; g++) {+ float scale = ue8m0(scales[g]);+ for (int i = 0; i < 32; i++) out[g * 32 + i] = e4m3_decode(bytes[g * 32 + i]) * scale;+ }+ t->key[victim] = id; t->used[victim] = ++t->clock;+ return out;+ }+}++/* engram.py NgramHashState: the ids of the n-grams ending at `pos`, for one table.+ * `out` receives `cols` row ids. */+static void engram_hash(const Engram *e, int table, int pos, int64_t *out) {+ int64_t tokens[V41_MAX_NGRAM];+ int blocked = 0;+ for (int shift = 0; shift < e->max_ngram; shift++) {+ int at = pos - shift;+ int32_t source = at >= 0 ? e->history[at] : ENGRAM_DEAD;+ if (at < 0 || source == ENGRAM_DEAD) blocked = 1;+ tokens[shift] = blocked ? e->pad_id : source;+ }+ /* XOR the multiplied ids one lookback at a time: after step i the running value is+ * the hash of the (i+1)-gram, and each lands in its own prime-sized bucket range.+ * int64 throughout -- the multipliers are chosen so id * multiplier cannot wrap. */+ int64_t rolling = tokens[0] * e->multipliers[table][0];+ int col = 0;+ for (int i = 1; i < e->max_ngram; i++) {+ rolling ^= tokens[i] * e->multipliers[table][i];+ for (int h = 0; h < e->heads; h++, col++) {+ int64_t prime = e->primes[table][i - 1][h];+ int64_t bucket = prime > 0 ? rolling % prime : 0;+ if (bucket < 0) bucket += prime; /* C99 truncates toward zero */+ out[col] = bucket + e->offsets[table][col];+ }+ }+}++/* `image` may be NULL (all text) or one byte per token: an image position is DEAD, so+ * no n-gram spans it -- model.py passes ~image_mask as the engram's token_mask for the+ * same reason. */+static void engram_push(Engram *e, const int *ids, int n, const uint8_t *image) {+ if (e->history_len + n > e->history_cap) {+ int cap = e->history_cap ? e->history_cap : 1024;+ while (cap < e->history_len + n) cap *= 2;+ e->history = realloc(e->history, (size_t)cap * sizeof(int32_t));+ if (!e->history) { fprintf(stderr, "OOM growing the engram history\n"); exit(1); }+ e->history_cap = cap;+ }+ for (int i = 0; i < n; i++) {+ int id = ids[i];+ int32_t compressed = ENGRAM_DEAD;+ if (!(image && image[i]) && id >= 0 && id < e->token_map_len)+ compressed = e->token_map[id];+ e->history[e->history_len++] = compressed;+ }+}++/* -------------------------------------------------------------- model ------ */++/* One routed expert, resident in a cache slot. The three matrices keep the+ * checkpoint's fp4 packing and their ue8m0 group scales: quant.h's matmul_mxfp4+ * consumes exactly this, so nothing is unpacked on the way in. */+typedef struct {+ int eid;+ uint8_t *w1, *w3, *w2; /* packed nibbles */+ uint8_t *s1, *s3, *s2; /* ue8m0, one byte per 32-column group */+ uint64_t used;+} Slot;++typedef struct { Slot *slot; int n, cap; } LCache;++typedef struct {+ W8 wq_a, wq_b, wkv, wo_a, wo_b;+ WF q_norm, kv_norm, attn_sink, attn_norm, ffn_norm;+ WF hc_attn_fn, hc_ffn_fn, hc_attn_base, hc_ffn_base, hc_attn_scale, hc_ffn_scale;+ WB comp_wkv, comp_wgate;+ WF comp_norm;+ W8 idx_wq_b;+ WB idx_wk, idx_wproj;+ WF idx_knorm;+ WB gate_w;+ WF gate_bias;+ W8 sh_w1, sh_w3, sh_w2;+ /* engram (only on engram layers) */+ W8 eng_wkv;+ WF eng_q, eng_k;+ int engram_index; /* which table, -1 when this layer has none */+ /* per-layer state */+ float *window; /* [window_size, head_dim] ring of raw KV */+ float *ckv; /* [max_pos/ratio, head_dim] compressed KV (owners) */+ float *ikey; /* [max_pos/ratio, index_head_dim] index keys (owners) */+ float *cstate_kv, *cstate_score; /* compressor group still filling */+} Layer;++typedef struct {+ Cfg c;+ shards S;+ Engram engram;+ Layer *L;+ WB embed, head;+ WF norm;+ LCache *cache;+ int ecap; /* expert slots per layer */+ uint64_t clock, hits, miss;+ double t_disk, t_expert, t_attn, t_engram;+ uint64_t forwards, expert_bytes;+ /* rope tables: [max_pos, rope_dim/2] cos/sin pairs, one per theta in use */+ float *rope_window, *rope_compress;+ int pos; /* positions consumed so far */+ /* candidate mask published by the candidate source layer, one row per query */+ uint8_t *candidates;+ int candidate_width;+ /* What an index source publishes for the layers after it (model.py's+ * shared_attn.topk_idxs): the compressed positions each query keeps, already+ * shifted by the window offset. A layer that compresses but does not index reads+ * this instead of scoring again -- that is the whole point of index_source_layers+ * being a subset. Persisting across forwards is deliberate, as in the vendor. */+ int *shared_topk;+ int shared_topk_rows, shared_topk_width;+ /* The index keys an owner last published, and the layer that owns them.+ *+ * model.py keeps this in one global slot and republishes it only when a layer+ * COMPLETES a compression group (`if self.owns_k and latent is not None`). On a+ * decode step where a ratio-2 layer's group is still filling, that layer therefore+ * scores its queries against whichever cache was published last -- in the released+ * config, layer 20's, whose rows are ratio-1 latents and mean something else.+ *+ * That is the released behaviour and every published number for this model was+ * produced with it, so it is what this engine reproduces by default and what the+ * oracle in tools/dsv41_ref.py encodes. V41_INDEX_OWNER=1 selects the reading the+ * architecture implies instead -- each layer against its own owner's keys -- which+ * is a different model, not a bug fix, and is why it is not the default. */+ const float *published_index_k;+ int published_index_layer;+ uint8_t **ehit; /* experts routed this turn (dashboard HITS) */+ struct Vision *vision; /* the VL tower, NULL on a text-only container */+} Model;++/* ------------------------------------------------------------ rope --------- */++static float rope_correction_dim(float rotations, int dim, float base, int max_seq) {+ return dim * logf(max_seq / (rotations * 2.0f * (float)M_PI)) / (2.0f * logf(base));+}++/* model.py precompute_freqs_cis, YaRN included, materialized as cos/sin pairs. */+static float *rope_table(int dim, int seqlen, int original_seq_len, float base,+ float factor, int beta_fast, int beta_slow) {+ int half = dim / 2;+ float *freqs = xmalloc((size_t)half * sizeof(float), "rope freqs");+ for (int i = 0; i < half; i++)+ freqs[i] = 1.0f / powf(base, (float)(2 * i) / (float)dim);+ if (original_seq_len > 0 && seqlen > original_seq_len) {+ float low = floorf(rope_correction_dim((float)beta_fast, dim, base, original_seq_len));+ float high = ceilf(rope_correction_dim((float)beta_slow, dim, base, original_seq_len));+ if (low < 0) low = 0;+ if (high > dim - 1) high = dim - 1;+ if (low == high) high += 0.001f;+ for (int i = 0; i < half; i++) {+ float ramp = ((float)i - low) / (high - low);+ if (ramp < 0) ramp = 0;+ if (ramp > 1) ramp = 1;+ float smooth = 1.0f - ramp;+ freqs[i] = freqs[i] / factor * (1.0f - smooth) + freqs[i] * smooth;+ }+ }+ float *table = xmalloc((size_t)seqlen * half * 2 * sizeof(float), "rope table");+ for (int pos = 0; pos < seqlen; pos++)+ for (int i = 0; i < half; i++) {+ float angle = (float)pos * freqs[i];+ table[((size_t)pos * half + i) * 2 + 0] = cosf(angle);+ table[((size_t)pos * half + i) * 2 + 1] = sinf(angle);+ }+ free(freqs);+ return table;+}++/* Rotate the trailing `rope_dim` entries of `v` in place, as pairs. `inverse` undoes+ * the rotation, which the output projection needs. */+static void rope_apply(float *v, const float *table, int pos, int rope_dim, int inverse) {+ int half = rope_dim / 2;+ const float *row = table + (size_t)pos * half * 2;+ for (int i = 0; i < half; i++) {+ float cosine = row[i * 2 + 0], sine = row[i * 2 + 1];+ if (inverse) sine = -sine;+ float a = v[2 * i], b = v[2 * i + 1];+ v[2 * i] = a * cosine - b * sine;+ v[2 * i + 1] = a * sine + b * cosine;+ }+}++static void rms_into(float *out, const float *x, const float *weight, int n, float eps) {+ double square = 0.0;+ for (int i = 0; i < n; i++) square += (double)x[i] * x[i];+ float inverse = 1.0f / sqrtf((float)(square / n) + eps);+ for (int i = 0; i < n; i++) out[i] = weight[i] * x[i] * inverse;+}++/* --------------------------------------------------------- expert cache ---- */++static void expert_read(Model *m, int layer, int eid, Slot *s) {+ Cfg *c = &m->c;+ char name[256];+ int64_t packed_gate = (int64_t)c->moe_inter * c->dim / 2;+ int64_t packed_down = (int64_t)c->dim * c->moe_inter / 2;+ int64_t scales_gate = (int64_t)c->moe_inter * (c->dim / 32);+ int64_t scales_down = (int64_t)c->dim * (c->moe_inter / 32);+ double started = now_s();+ struct { const char *suffix; uint8_t *bytes; int64_t size; uint8_t *scale; int64_t scale_size; } part[3] = {+ { "w1", s->w1, packed_gate, s->s1, scales_gate },+ { "w3", s->w3, packed_gate, s->s3, scales_gate },+ { "w2", s->w2, packed_down, s->s2, scales_down },+ };+ for (int i = 0; i < 3; i++) {+ snprintf(name, sizeof(name), "layers.%d.ffn.experts.%d.%s.weight", layer, eid, part[i].suffix);+ st_read_raw_cap(&m->S, name, part[i].bytes, part[i].size, 1);+ snprintf(name, sizeof(name), "layers.%d.ffn.experts.%d.%s.scale", layer, eid, part[i].suffix);+ st_read_raw_cap(&m->S, name, part[i].scale, part[i].scale_size, 1);+ m->expert_bytes += part[i].size + part[i].scale_size;+ }+ s->eid = eid;+ m->t_disk += now_s() - started;+}++/* One byte per expert: routed in this turn or not, for the dashboard's HITS line. */+static void ehit_mark(Model *m, int layer, int eid) {+ Cfg *c = &m->c;+ if (!m->ehit) {+ m->ehit = xmalloc((size_t)c->n_layers * sizeof(uint8_t *), "expert hit map");+ for (int i = 0; i < c->n_layers; i++) {+ m->ehit[i] = xmalloc((size_t)c->n_routed, "expert hit row");+ memset(m->ehit[i], 0, (size_t)c->n_routed);+ }+ }+ if (layer >= 0 && layer < c->n_layers && eid >= 0 && eid < c->n_routed) m->ehit[layer][eid] = 1;+}++static Slot *expert_slot(Model *m, int layer, int eid) {+ ehit_mark(m, layer, eid);+ LCache *cache = &m->cache[layer];+ for (int i = 0; i < cache->n; i++)+ if (cache->slot[i].eid == eid) {+ cache->slot[i].used = ++m->clock;+ m->hits++;+ return &cache->slot[i];+ }+ m->miss++;+ Slot *victim;+ if (cache->n < cache->cap) {+ victim = &cache->slot[cache->n++];+ } else {+ int oldest = 0;+ for (int i = 1; i < cache->n; i++)+ if (cache->slot[i].used < cache->slot[oldest].used) oldest = i;+ victim = &cache->slot[oldest];+ }+ expert_read(m, layer, eid, victim);+ victim->used = ++m->clock;+ return victim;+}++/* ------------------------------------------------------------- loading ----- */++typedef struct {+ WF norm1, norm2, qkv_b, o_b;+ WB qkv_w, o_w, w1, w2;+} VisionBlock;++typedef struct Vision {+ int active;+ WB proj_w; WF proj_b;+ VisionBlock *block;+ WF norm;+ WB align_w1, align_w2;+ WF align_b1, align_b2;+ WF image_start, image_end, image_newline;+} Vision;++static void vision_load(Model *m, Vision *v);+static void vision_forward(Model *m, Vision *v, const float *patches, int n_h, int n_w, float *out);+static int vision_tokens(const Cfg *c, int n_h, int n_w);++static void model_load(Model *m, const char *snap, int ecap, int engram_cache_rows) {+ Cfg *c = &m->c;+ cfg_load(c, snap);+ st_init(&m->S, snap);+ engram_load_sidecar(&m->engram, snap);++ int dim = c->dim, hd = c->head_dim, nh = c->n_heads, hc = c->hc_mult;+ m->L = xmalloc((size_t)c->n_layers * sizeof(Layer), "layers");+ memset(m->L, 0, (size_t)c->n_layers * sizeof(Layer));+ wb_load(&m->S, &m->embed, "embed.weight", c->vocab, dim);+ wb_load(&m->S, &m->head, "head.weight", c->vocab, dim);+ wf_load(&m->S, &m->norm, "norm.weight", dim);++ char name[256];+ #define NAME(fmt, ...) (snprintf(name, sizeof(name), fmt, __VA_ARGS__), name)+ for (int i = 0; i < c->n_layers; i++) {+ Layer *l = &m->L[i];+ l->engram_index = -1;+ w8_load(&m->S, &l->wq_a, NAME("layers.%d.attn.wq_a.weight", i), c->q_lora, dim);+ w8_load(&m->S, &l->wq_b, NAME("layers.%d.attn.wq_b.weight", i), nh * hd, c->q_lora);+ w8_load(&m->S, &l->wkv, NAME("layers.%d.attn.wkv.weight", i), hd, dim);+ w8_load(&m->S, &l->wo_a, NAME("layers.%d.attn.wo_a.weight", i),+ c->o_groups * c->o_lora, nh * hd / c->o_groups);+ w8_load(&m->S, &l->wo_b, NAME("layers.%d.attn.wo_b.weight", i), dim, c->o_groups * c->o_lora);+ wf_load(&m->S, &l->q_norm, NAME("layers.%d.attn.q_norm.weight", i), c->q_lora);+ wf_load(&m->S, &l->kv_norm, NAME("layers.%d.attn.kv_norm.weight", i), hd);+ wf_load(&m->S, &l->attn_sink,NAME("layers.%d.attn.attn_sink", i), nh);+ wf_load(&m->S, &l->attn_norm,NAME("layers.%d.attn_norm.weight", i), dim);+ wf_load(&m->S, &l->ffn_norm, NAME("layers.%d.ffn_norm.weight", i), dim);+ int mix = (2 + hc) * hc;+ wf_load(&m->S, &l->hc_attn_fn, NAME("layers.%d.hc_attn_fn", i), (int64_t)mix * hc * dim);+ wf_load(&m->S, &l->hc_ffn_fn, NAME("layers.%d.hc_ffn_fn", i), (int64_t)mix * hc * dim);+ wf_load(&m->S, &l->hc_attn_base, NAME("layers.%d.hc_attn_base", i), mix);+ wf_load(&m->S, &l->hc_ffn_base, NAME("layers.%d.hc_ffn_base", i), mix);+ wf_load(&m->S, &l->hc_attn_scale,NAME("layers.%d.hc_attn_scale", i), 3);+ wf_load(&m->S, &l->hc_ffn_scale, NAME("layers.%d.hc_ffn_scale", i), 3);+ wb_load(&m->S, &l->gate_w, NAME("layers.%d.ffn.gate.weight", i), c->n_routed, dim);+ wf_load(&m->S, &l->gate_bias, NAME("layers.%d.ffn.gate.bias", i), c->n_routed);+ w8_load(&m->S, &l->sh_w1, NAME("layers.%d.ffn.shared_experts.w1.weight", i), c->moe_inter, dim);+ w8_load(&m->S, &l->sh_w3, NAME("layers.%d.ffn.shared_experts.w3.weight", i), c->moe_inter, dim);+ w8_load(&m->S, &l->sh_w2, NAME("layers.%d.ffn.shared_experts.w2.weight", i), dim, c->moe_inter);++ l->window = xmalloc((size_t)c->window * hd * sizeof(float), "window ring");+ memset(l->window, 0, (size_t)c->window * hd * sizeof(float));+ int ratio = c->compress_ratio[i];+ if (c->kv_source[i]) {+ wb_load(&m->S, &l->comp_wkv, NAME("layers.%d.attn.compressor.wkv.weight", i), hd, dim);+ wf_load(&m->S, &l->comp_norm, NAME("layers.%d.attn.compressor.norm.weight", i), hd);+ if (ratio > 1) {+ wb_load(&m->S, &l->comp_wgate, NAME("layers.%d.attn.compressor.wgate.weight", i), hd, dim);+ l->cstate_kv = xmalloc((size_t)ratio * hd * sizeof(float), "compressor group");+ l->cstate_score = xmalloc((size_t)ratio * hd * sizeof(float), "compressor scores");+ memset(l->cstate_kv, 0, (size_t)ratio * hd * sizeof(float));+ for (int k = 0; k < ratio * hd; k++) l->cstate_score[k] = -INFINITY;+ }+ int slots = c->max_positions / (ratio > 0 ? ratio : 1);+ l->ckv = xmalloc((size_t)slots * hd * sizeof(float), "compressed kv");+ memset(l->ckv, 0, (size_t)slots * hd * sizeof(float));+ l->ikey = xmalloc((size_t)slots * c->index_head_dim * sizeof(float), "index keys");+ memset(l->ikey, 0, (size_t)slots * c->index_head_dim * sizeof(float));+ wb_load(&m->S, &l->idx_wk, NAME("layers.%d.attn.indexer.wk.weight", i),+ c->index_head_dim, hd);+ wf_load(&m->S, &l->idx_knorm, NAME("layers.%d.attn.indexer.k_norm.weight", i),+ c->index_head_dim);+ }+ if (c->index_source[i]) {+ w8_load(&m->S, &l->idx_wq_b, NAME("layers.%d.attn.indexer.wq_b.weight", i),+ c->index_n_heads * c->index_head_dim, c->q_lora);+ wb_load(&m->S, &l->idx_wproj, NAME("layers.%d.attn.indexer.weights_proj.weight", i),+ c->index_n_heads, dim);+ }+ }+ if (m->engram.active) {+ Engram *e = &m->engram;+ for (int t = 0; t < e->n_layers; t++) {+ int layer = e->layer_of[t];+ if (layer < 0 || layer >= c->n_layers) {+ fprintf(stderr, "[engram] table %d names layer %d\n", t, layer); exit(1); }+ m->L[layer].engram_index = t;+ engram_table_open(&e->table[t], &m->S, layer, e->head_dim, engram_cache_rows);+ w8_load(&m->S, &m->L[layer].eng_wkv, NAME("layers.%d.engram.wkv.weight", layer),+ dim * (hc + 1), e->cols * e->head_dim);+ wf_load(&m->S, &m->L[layer].eng_q, NAME("layers.%d.engram.q_weight", layer),+ (int64_t)hc * dim);+ wf_load(&m->S, &m->L[layer].eng_k, NAME("layers.%d.engram.k_weight", layer),+ (int64_t)hc * dim);+ }+ }+ #undef NAME++ /* expert cache: `ecap` slots per layer, each holding one expert's three matrices */+ m->ecap = ecap;+ m->cache = xmalloc((size_t)c->n_layers * sizeof(LCache), "expert caches");+ int64_t packed_gate = (int64_t)c->moe_inter * dim / 2, packed_down = (int64_t)dim * c->moe_inter / 2;+ int64_t scales_gate = (int64_t)c->moe_inter * (dim / 32), scales_down = (int64_t)dim * (c->moe_inter / 32);+ for (int i = 0; i < c->n_layers; i++) {+ LCache *cache = &m->cache[i];+ cache->cap = ecap; cache->n = 0;+ cache->slot = xmalloc((size_t)ecap * sizeof(Slot), "expert slots");+ for (int k = 0; k < ecap; k++) {+ Slot *s = &cache->slot[k];+ s->eid = -1; s->used = 0;+ s->w1 = xmalloc((size_t)packed_gate, "expert w1");+ s->w3 = xmalloc((size_t)packed_gate, "expert w3");+ s->w2 = xmalloc((size_t)packed_down, "expert w2");+ s->s1 = xmalloc((size_t)scales_gate, "expert w1 scale");+ s->s3 = xmalloc((size_t)scales_gate, "expert w3 scale");+ s->s2 = xmalloc((size_t)scales_down, "expert w2 scale");+ }+ }+ if (c->vision_layers > 0) {+ m->vision = xmalloc(sizeof(Vision), "vision tower");+ memset(m->vision, 0, sizeof(Vision));+ vision_load(m, m->vision);+ if (!m->vision->active) { free(m->vision); m->vision = NULL; }+ }+ m->rope_window = rope_table(c->rope_dim, c->max_positions, 0, c->rope_theta,+ c->rope_factor, c->beta_fast, c->beta_slow);+ m->rope_compress = rope_table(c->rope_dim, c->max_positions, c->original_seq_len,+ c->compress_rope_theta, c->rope_factor,+ c->beta_fast, c->beta_slow);+ m->pos = 0;+}++static const float *rope_for(const Model *m, int layer) {+ return m->c.compress_ratio[layer] ? m->rope_compress : m->rope_window;+}++/* ----------------------------------------------------------- attention ----- */++/* model.py get_window_topk_idxs, one batch: which ring slots query `t` may read.+ * Prefill indexes the chunk itself (slot i is position i); decode indexes the ring. */+static void window_idxs(const Cfg *c, int n, int start_pos, int t, int *out, int *count) {+ int win = c->window;+ if (start_pos == 0) {+ int width = n < win ? n : win;+ int first = t - win + 1; if (first < 0) first = 0;+ for (int i = 0; i < width; i++) {+ int idx = first + i;+ out[i] = idx > t ? -1 : idx;+ }+ *count = width;+ } else {+ int oldest = start_pos % win + 1;+ int at = 0;+ for (int i = oldest; i < win; i++) out[at++] = i > start_pos ? -1 : i;+ for (int i = 0; i < oldest; i++) out[at++] = i > start_pos ? -1 : i;+ *count = win;+ }+}++/* kernel.py sparse_attn for one query: `idx` lists the rows of `kv` this query reads,+ * -1 meaning nothing. The sink joins the denominator only, so a query with no readable+ * row comes out zero instead of NaN. */+static void sparse_attend(float *out, const float *q, const float *kv, const int *idx,+ int count, int nh, int hd, float sink_h, float scale) {+ float best = -1e30f;+ float *score = xmalloc((size_t)count * sizeof(float), "attention scores");+ for (int j = 0; j < count; j++) {+ if (idx[j] < 0) { score[j] = -INFINITY; continue; }+ const float *k = kv + (size_t)idx[j] * hd;+ float dot = 0.0f;+ for (int i = 0; i < hd; i++) dot += q[i] * k[i];+ score[j] = dot * scale;+ if (score[j] > best) best = score[j];+ }+ float denom = expf(sink_h - best);+ for (int i = 0; i < hd; i++) out[i] = 0.0f;+ for (int j = 0; j < count; j++) {+ if (!(score[j] > -INFINITY)) continue;+ float weight = expf(score[j] - best);+ denom += weight;+ const float *k = kv + (size_t)idx[j] * hd;+ for (int i = 0; i < hd; i++) out[i] += weight * k[i];+ }+ for (int i = 0; i < hd; i++) out[i] /= denom;+ free(score);+ (void)nh;+}++/* model.py Compressor.forward. Writes the latents this chunk completes into `latent`+ * and returns how many there are (pre-RoPE, as the indexer needs them unrotated). */+static int compressor_run(Model *m, int layer, const float *x, int n, int start_pos, float *latent) {+ Cfg *c = &m->c;+ Layer *l = &m->L[layer];+ int hd = c->head_dim, ratio = c->compress_ratio[layer];+ if (ratio == 1) {+ for (int t = 0; t < n; t++) {+ float kv[512];+ if (hd > (int)(sizeof(kv) / sizeof(kv[0]))) {+ fprintf(stderr, "[compressor] head_dim %d exceeds the scratch\n", hd); exit(1); }+ mvb(kv, &l->comp_wkv, x + (size_t)t * c->dim);+ rms_into(latent + (size_t)t * hd, kv, l->comp_norm.w, hd, c->norm_eps);+ }+ return n;+ }+ float *kv = xmalloc((size_t)n * hd * sizeof(float), "compressor kv");+ float *score = xmalloc((size_t)n * hd * sizeof(float), "compressor scores");+ for (int t = 0; t < n; t++) {+ mvb(kv + (size_t)t * hd, &l->comp_wkv, x + (size_t)t * c->dim);+ mvb(score + (size_t)t * hd, &l->comp_wgate, x + (size_t)t * c->dim);+ }+ int produced = 0;+ if (start_pos == 0) {+ int remainder = n % ratio, cutoff = n - remainder;+ for (int g = 0; g * ratio < cutoff; g++) {+ for (int i = 0; i < hd; i++) {+ float best = -INFINITY;+ for (int k = 0; k < ratio; k++) {+ float value = score[(size_t)(g * ratio + k) * hd + i];+ if (value > best) best = value;+ }+ float total = 0.0f, mixed = 0.0f;+ for (int k = 0; k < ratio; k++) {+ float weight = expf(score[(size_t)(g * ratio + k) * hd + i] - best);+ total += weight;+ mixed += weight * kv[(size_t)(g * ratio + k) * hd + i];+ }+ latent[(size_t)g * hd + i] = mixed / total;+ }+ produced++;+ }+ for (int k = 0; k < remainder; k++) {+ memcpy(l->cstate_kv + (size_t)k * hd, kv + (size_t)(cutoff + k) * hd, (size_t)hd * sizeof(float));+ memcpy(l->cstate_score + (size_t)k * hd, score + (size_t)(cutoff + k) * hd, (size_t)hd * sizeof(float));+ }+ } else {+ int slot = start_pos % ratio;+ memcpy(l->cstate_kv + (size_t)slot * hd, kv, (size_t)hd * sizeof(float));+ memcpy(l->cstate_score + (size_t)slot * hd, score, (size_t)hd * sizeof(float));+ if ((start_pos + 1) % ratio == 0) {+ for (int i = 0; i < hd; i++) {+ float best = -INFINITY;+ for (int k = 0; k < ratio; k++) {+ float value = l->cstate_score[(size_t)k * hd + i];+ if (value > best) best = value;+ }+ float total = 0.0f, mixed = 0.0f;+ for (int k = 0; k < ratio; k++) {+ float weight = expf(l->cstate_score[(size_t)k * hd + i] - best);+ total += weight;+ mixed += weight * l->cstate_kv[(size_t)k * hd + i];+ }+ latent[i] = mixed / total;+ }+ produced = 1;+ }+ }+ if (produced) {+ float *pooled = xmalloc((size_t)produced * hd * sizeof(float), "pooled latents");+ memcpy(pooled, latent, (size_t)produced * hd * sizeof(float));+ for (int g = 0; g < produced; g++)+ rms_into(latent + (size_t)g * hd, pooled + (size_t)g * hd, l->comp_norm.w, hd, c->norm_eps);+ free(pooled);+ }+ free(kv); free(score);+ return produced;+}++/* model.py select_candidate_blocks, one query row. `keep` is `width` bytes. */+static void candidate_blocks(const Cfg *c, const float *score, int width, int lens, uint8_t *keep) {+ int block = c->candidate_block_size;+ int blocks = (width + block - 1) / block;+ float *best = xmalloc((size_t)blocks * sizeof(float), "block scores");+ for (int b = 0; b < blocks; b++) {+ float top = -INFINITY;+ for (int i = b * block; i < (b + 1) * block && i < width; i++)+ if (score[i] > top) top = score[i];+ best[b] = top;+ }+ int last = (lens - 1) / block;+ if (last >= 0 && last < blocks) best[last] = INFINITY; /* the newest block is pinned in */+ int wanted = c->candidate_topk_blocks < blocks ? c->candidate_topk_blocks : blocks;+ memset(keep, 0, (size_t)width);+ for (int pick = 0; pick < wanted; pick++) {+ int chosen = -1;+ for (int b = 0; b < blocks; b++)+ if (best[b] > -INFINITY && (chosen < 0 || best[b] > best[chosen])) chosen = b;+ if (chosen < 0) break;+ for (int i = chosen * block; i < (chosen + 1) * block && i < width; i++) keep[i] = 1;+ best[chosen] = -INFINITY;+ }+ free(best);+}++/* model.py Indexer.forward: score every compressed position this query can reach and+ * keep the best `index_topk`, in position order, shifted by `offset`. */+static void indexer_run(Model *m, int layer, const float *x, const float *qr, int n,+ int start_pos, int offset, int compress_len,+ int *out, int stride, int topk) {+ Cfg *c = &m->c;+ Layer *l = &m->L[layer];+ int owner = c->index_owner[layer];+ int nh = c->index_n_heads, ihd = c->index_head_dim, ratio = c->compress_ratio[layer];+ const float *ikey = m->L[owner].ikey;+ if (!getenv("V41_INDEX_OWNER") && m->published_index_k) ikey = m->published_index_k;+ const float *rope = rope_for(m, layer);+ float *q = xmalloc((size_t)nh * ihd * sizeof(float), "indexer queries");+ float *weights = xmalloc((size_t)nh * sizeof(float), "indexer weights");+ float *score = xmalloc((size_t)compress_len * sizeof(float), "indexer scores");+ float scale = (1.0f / sqrtf((float)ihd)) * (1.0f / sqrtf((float)nh));++ for (int t = 0; t < n; t++) {+ mv8(q, &l->idx_wq_b, qr + (size_t)t * c->q_lora);+ for (int h = 0; h < nh; h++)+ rope_apply(q + (size_t)h * ihd + ihd - c->rope_dim, rope, start_pos + t, c->rope_dim, 0);+ mvb(weights, &l->idx_wproj, x + (size_t)t * c->dim);+ for (int h = 0; h < nh; h++) weights[h] *= scale;+ int lens = start_pos == 0 ? (t + 1) / ratio : (start_pos + n) / ratio;+ for (int j = 0; j < compress_len; j++) {+ if (j >= lens) { score[j] = -INFINITY; continue; }+ float total = 0.0f;+ for (int h = 0; h < nh; h++) {+ const float *qh = q + (size_t)h * ihd;+ const float *k = ikey + (size_t)j * ihd;+ float dot = 0.0f;+ for (int i = 0; i < ihd; i++) dot += qh[i] * k[i];+ if (dot > 0.0f) total += dot * weights[h]; /* relu, then the head weight */+ }+ score[j] = total;+ }+ if (layer == c->candidate_source) {+ if (m->candidate_width != compress_len) {+ free(m->candidates);+ m->candidates = xmalloc((size_t)n * compress_len, "candidate mask");+ m->candidate_width = compress_len;+ }+ candidate_blocks(c, score, compress_len, lens, m->candidates + (size_t)t * compress_len);+ } else if (c->candidate_source >= 0 && c->candidate_source < layer && m->candidates) {+ const uint8_t *keep = m->candidates + (size_t)t * m->candidate_width;+ for (int j = 0; j < compress_len && j < m->candidate_width; j++)+ if (!keep[j]) score[j] = -INFINITY;+ }+ /* top-k, then back into position order: the attention kernel treats every slot+ * independently, but keeping them sorted makes the concatenated index list+ * readable and matches the reference's `.sort()`. */+ int *row = out + (size_t)t * stride; /* the compressed half of this query's list */+ for (int k = 0; k < topk; k++) row[k] = -1;+ int taken = 0;+ for (int k = 0; k < topk; k++) {+ int best = -1;+ for (int j = 0; j < compress_len; j++) {+ if (score[j] == -INFINITY) continue;+ int already = 0;+ for (int u = 0; u < taken; u++) if (row[u] == j) { already = 1; break; }+ if (already) continue;+ if (best < 0 || score[j] > score[best]) best = j;+ }+ if (best < 0) break;+ row[taken++] = best;+ }+ for (int a = 0; a < taken; a++) /* insertion sort: taken <= index_topk */+ for (int b = a + 1; b < taken; b++)+ if (row[b] < row[a]) { int swap = row[a]; row[a] = row[b]; row[b] = swap; }+ int lens_now = start_pos == 0 ? (t + 1) / ratio : (start_pos + n) / ratio;+ for (int k = 0; k < topk; k++)+ row[k] = (k < taken && row[k] < lens_now) ? row[k] + offset : -1;+ }+ free(q); free(weights); free(score);+}++/* model.py Attention.forward. `x` is the normalized block input [n, dim]. */+static void attention_run(Model *m, int layer, const float *x, int n, int start_pos, float *out) {+ Cfg *c = &m->c;+ Layer *l = &m->L[layer];+ int dim = c->dim, hd = c->head_dim, nh = c->n_heads, rd = c->rope_dim;+ int ratio = c->compress_ratio[layer], owner = c->index_owner[layer];+ const float *rope = rope_for(m, layer);+ double started = now_s();++ float *qr = xmalloc((size_t)n * c->q_lora * sizeof(float), "q latent");+ float *q = xmalloc((size_t)n * nh * hd * sizeof(float), "queries");+ float *kv = xmalloc((size_t)n * hd * sizeof(float), "kv");+ float *scratch = xmalloc((size_t)(nh * hd > dim ? nh * hd : dim) * sizeof(float), "scratch");++ for (int t = 0; t < n; t++) {+ mv8(scratch, &l->wq_a, x + (size_t)t * dim);+ rms_into(qr + (size_t)t * c->q_lora, scratch, l->q_norm.w, c->q_lora, c->norm_eps);+ mv8(q + (size_t)t * nh * hd, &l->wq_b, qr + (size_t)t * c->q_lora);+ for (int h = 0; h < nh; h++)+ rope_apply(q + (size_t)t * nh * hd + (size_t)h * hd + hd - rd, rope, start_pos + t, rd, 0);+ mv8(scratch, &l->wkv, x + (size_t)t * dim);+ rms_into(kv + (size_t)t * hd, scratch, l->kv_norm.w, hd, c->norm_eps);+ rope_apply(kv + (size_t)t * hd + hd - rd, rope, start_pos + t, rd, 0);+ }++ /* the window half: prefill reads the chunk, decode reads the ring */+ const float *window_kv;+ int window_rows;+ if (start_pos == 0) {+ int win = c->window;+ if (n <= win) {+ memcpy(l->window, kv, (size_t)n * hd * sizeof(float));+ } else {+ int cut = n % win;+ const float *tail = kv + (size_t)(n - win) * hd;+ memcpy(l->window + (size_t)cut * hd, tail, (size_t)(win - cut) * hd * sizeof(float));+ memcpy(l->window, tail + (size_t)(win - cut) * hd, (size_t)cut * hd * sizeof(float));+ }+ window_kv = kv; window_rows = n;+ } else {+ memcpy(l->window + (size_t)(start_pos % c->window) * hd, kv, (size_t)hd * sizeof(float));+ window_kv = l->window; window_rows = c->window;+ }++ int window_width = start_pos == 0 ? (n < c->window ? n : c->window) : c->window;+ int compress_len = ratio ? (start_pos + n) / ratio : 0;+ int index_topk = 0;+ if (ratio) {+ index_topk = c->index_topk < compress_len ? c->index_topk : compress_len;+ if (index_topk < 0) index_topk = 0;+ }+ int total_idx = window_width + index_topk;+ int *idx = xmalloc((size_t)n * total_idx * sizeof(int), "attention indices");+ for (int t = 0; t < n; t++) {+ int count = 0;+ window_idxs(c, n, start_pos, t, idx + (size_t)t * total_idx, &count);+ for (int k = count; k < window_width; k++) idx[(size_t)t * total_idx + k] = -1;+ }++ float *kv_all = NULL;+ if (ratio) {+ /* the compressor runs before the indexer: the indexer scores the latent before+ * RoPE, and the cache write below rotates it in place */+ float *latent = NULL;+ int produced = 0;+ if (c->kv_source[layer]) {+ latent = xmalloc((size_t)(n / (ratio ? ratio : 1) + 1) * hd * sizeof(float), "latents");+ produced = compressor_run(m, layer, x, n, start_pos, latent);+ if (produced) {+ /* index keys first, from the un-rotated latent */+ for (int g = 0; g < produced; g++) {+ float key[512];+ if (c->index_head_dim > (int)(sizeof(key) / sizeof(key[0]))) {+ fprintf(stderr, "[indexer] index_head_dim too large\n"); exit(1); }+ mvb(key, &l->idx_wk, latent + (size_t)g * hd);+ float *dest = l->ikey + (size_t)(start_pos / ratio + g) * c->index_head_dim;+ rms_into(dest, key, l->idx_knorm.w, c->index_head_dim, c->norm_eps);+ int position = start_pos == 0 ? g * ratio : start_pos + 1 - ratio;+ rope_apply(dest + c->index_head_dim - rd, rope, position, rd, 0);+ }+ /* publish, as model.py does, only when a group completed */+ m->published_index_k = l->ikey;+ m->published_index_layer = layer;+ }+ }+ if (c->index_source[layer]) {+ if (compress_len > 0 && index_topk > 0)+ /* The offset is how many ROWS the window half occupies in kv_all, not+ * how many index columns it takes: during prefill the window half is+ * the whole chunk (n rows) while each query lists at most `window`+ * columns of it. model.py passes kv.size(1) here for the same reason. */+ indexer_run(m, layer, x, qr, n, start_pos, window_rows, compress_len,+ idx + window_width, total_idx, index_topk);+ else+ for (int t = 0; t < n; t++)+ for (int k = window_width; k < total_idx; k++) idx[(size_t)t * total_idx + k] = -1;+ /* publish for the layers between here and the next index source */+ if (m->shared_topk_rows != n || m->shared_topk_width != index_topk) {+ free(m->shared_topk);+ m->shared_topk = xmalloc((size_t)n * (index_topk > 0 ? index_topk : 1) * sizeof(int),+ "published index list");+ m->shared_topk_rows = n; m->shared_topk_width = index_topk;+ }+ for (int t = 0; t < n; t++)+ for (int k = 0; k < index_topk; k++)+ m->shared_topk[(size_t)t * index_topk + k] = idx[(size_t)t * total_idx + window_width + k];+ } else {+ /* Not an index source: reuse what the last one published, exactly as+ * model.py does through shared_attn.topk_idxs. Recomputing here would be+ * wrong as well as wasteful -- these layers have no indexer weights. */+ for (int t = 0; t < n; t++)+ for (int k = 0; k < index_topk; k++) {+ int value = -1;+ if (m->shared_topk && t < m->shared_topk_rows && k < m->shared_topk_width)+ value = m->shared_topk[(size_t)t * m->shared_topk_width + k];+ idx[(size_t)t * total_idx + window_width + k] = value;+ }+ }+ if (produced) {+ for (int g = 0; g < produced; g++) {+ float *dest = l->ckv + (size_t)(start_pos / ratio + g) * hd;+ memcpy(dest, latent + (size_t)g * hd, (size_t)hd * sizeof(float));+ int position = start_pos == 0 ? g * ratio : start_pos + 1 - ratio;+ rope_apply(dest + hd - rd, rope, position, rd, 0);+ }+ }+ free(latent);+ kv_all = xmalloc((size_t)(window_rows + compress_len) * hd * sizeof(float), "kv all");+ memcpy(kv_all, window_kv, (size_t)window_rows * hd * sizeof(float));+ memcpy(kv_all + (size_t)window_rows * hd, m->L[owner].ckv,+ (size_t)compress_len * hd * sizeof(float));+ }++ const float *kv_read = ratio ? kv_all : window_kv;+ float *heads = xmalloc((size_t)nh * hd * sizeof(float), "attention output");+ float attn_scale = 1.0f / sqrtf((float)hd);+ for (int t = 0; t < n; t++) {+ const int *row = idx + (size_t)t * total_idx;+ #pragma omp parallel for schedule(static)+ for (int h = 0; h < nh; h++)+ sparse_attend(heads + (size_t)h * hd, q + (size_t)t * nh * hd + (size_t)h * hd,+ kv_read, row, total_idx, nh, hd, l->attn_sink.w[h], attn_scale);+ for (int h = 0; h < nh; h++)+ rope_apply(heads + (size_t)h * hd + hd - rd, rope, start_pos + t, rd, 1);+ /* wo_a is block diagonal over o_groups: each group projects only its own heads */+ int per_group = nh * hd / c->o_groups;+ float *grouped = xmalloc((size_t)c->o_groups * c->o_lora * sizeof(float), "grouped");+ for (int g = 0; g < c->o_groups; g++) {+ const uint8_t *rows = l->wo_a.q + (size_t)g * c->o_lora * per_group;+ const uint8_t *scales = l->wo_a.s;+ int tiles_i = (per_group + FP8_TILE - 1) / FP8_TILE;+ for (int r = 0; r < c->o_lora; r++) {+ int o = g * c->o_lora + r;+ const uint8_t *w = rows + (size_t)r * per_group;+ const uint8_t *scale_row = scales + (size_t)(o / FP8_TILE) * tiles_i;+ const float *xg = heads + (size_t)g * per_group;+ float sum = 0.0f;+ for (int base = 0; base < per_group; base += FP8_TILE) {+ int width = per_group - base < FP8_TILE ? per_group - base : FP8_TILE;+ float tile = ue8m0(scale_row[base / FP8_TILE]);+ float part = 0.0f;+ for (int i = 0; i < width; i++) part += e4m3_decode(w[base + i]) * xg[base + i];+ sum += part * tile;+ }+ grouped[o] = sum;+ }+ }+ mv8(out + (size_t)t * dim, &l->wo_b, grouped);+ free(grouped);+ }+ m->t_attn += now_s() - started;+ free(heads); free(kv_all); free(idx); free(scratch); free(kv); free(q); free(qr);+}++/* ------------------------------------------------------------------ MoE ---- */++/* One expert's SwiGLU. The clamps are the training kernel's, and they matter: they+ * are what keeps fp4 activations in range. */+static void expert_ffn(Model *m, const uint8_t *w1, const uint8_t *s1,+ const uint8_t *w3, const uint8_t *s3,+ const uint8_t *w2, const uint8_t *s2,+ const float *x, float *out, float weight) {+ Cfg *c = &m->c;+ int inter = c->moe_inter, dim = c->dim;+ float *gate = xmalloc((size_t)inter * sizeof(float), "expert gate");+ float *up = xmalloc((size_t)inter * sizeof(float), "expert up");+ float *mid = xmalloc((size_t)inter * sizeof(float), "expert mid");+ double started = now_s();+ matmul_mxfp4(gate, x, w1, s1, 1, dim, inter);+ matmul_mxfp4(up, x, w3, s3, 1, dim, inter);+ for (int i = 0; i < inter; i++) {+ float g = gate[i], u = up[i];+ if (c->swiglu_limit > 0.0f) {+ if (u > c->swiglu_limit) u = c->swiglu_limit;+ if (u < -c->swiglu_limit) u = -c->swiglu_limit;+ if (g > c->swiglu_limit) g = c->swiglu_limit;+ }+ mid[i] = (g / (1.0f + expf(-g))) * u;+ }+ float *down = xmalloc((size_t)dim * sizeof(float), "expert down");+ matmul_mxfp4(down, mid, w2, s2, 1, inter, dim);+ for (int i = 0; i < dim; i++) out[i] += weight * down[i];+ m->t_expert += now_s() - started;+ free(down); free(mid); free(up); free(gate);+}++/* The shared expert every token pays for; fp8, so it stays resident and never streams. */+static void shared_ffn(Model *m, Layer *l, const float *x, float *out) {+ Cfg *c = &m->c;+ int inter = c->moe_inter, dim = c->dim;+ float *gate = xmalloc((size_t)inter * sizeof(float), "shared gate");+ float *up = xmalloc((size_t)inter * sizeof(float), "shared up");+ mv8(gate, &l->sh_w1, x);+ mv8(up, &l->sh_w3, x);+ for (int i = 0; i < inter; i++) {+ float g = gate[i], u = up[i];+ if (c->swiglu_limit > 0.0f) {+ if (u > c->swiglu_limit) u = c->swiglu_limit;+ if (u < -c->swiglu_limit) u = -c->swiglu_limit;+ if (g > c->swiglu_limit) g = c->swiglu_limit;+ }+ gate[i] = (g / (1.0f + expf(-g))) * u;+ }+ float *down = xmalloc((size_t)dim * sizeof(float), "shared down");+ mv8(down, &l->sh_w2, gate);+ for (int i = 0; i < dim; i++) out[i] += down[i];+ free(down); free(up); free(gate);+}++/* model.py Gate + MoE. The bias steers the choice of experts and nothing else: the+ * weights come from the unbiased scores, which is the whole point of noaux_tc. */+static void moe_run(Model *m, int layer, const float *x, float *out) {+ Cfg *c = &m->c;+ Layer *l = &m->L[layer];+ int E = c->n_routed, topk = c->n_activated;+ float *scores = xmalloc((size_t)E * sizeof(float), "gate scores");+ mvb(scores, &l->gate_w, x);+ for (int e = 0; e < E; e++) {+ float value = scores[e] / c->gate_temp;+ /* sqrtsoftplus: softplus then square root, in fp32 as the vendor does */+ float softplus = value > 20.0f ? value : logf(1.0f + expf(value));+ scores[e] = sqrtf(softplus);+ }+ int chosen[64];+ float weights[64];+ if (topk > (int)(sizeof(chosen) / sizeof(chosen[0]))) {+ fprintf(stderr, "[moe] n_activated %d exceeds the scratch\n", topk); exit(1); }+ for (int k = 0; k < topk; k++) {+ int best = -1;+ for (int e = 0; e < E; e++) {+ int taken = 0;+ for (int u = 0; u < k; u++) if (chosen[u] == e) { taken = 1; break; }+ if (taken) continue;+ if (best < 0 || scores[e] + l->gate_bias.w[e] > scores[best] + l->gate_bias.w[best]) best = e;+ }+ chosen[k] = best;+ weights[k] = scores[best];+ }+ if (c->norm_topk_prob && topk > 1) {+ float total = 0.0f;+ for (int k = 0; k < topk; k++) total += weights[k];+ total += 1e-20f; /* the vendor's constant, not norm_eps */+ for (int k = 0; k < topk; k++) weights[k] /= total;+ }+ for (int k = 0; k < topk; k++) weights[k] *= c->route_scale;+ memset(out, 0, (size_t)c->dim * sizeof(float));+ for (int k = 0; k < topk; k++) {+ Slot *s = expert_slot(m, layer, chosen[k]);+ expert_ffn(m, s->w1, s->s1, s->w3, s->s3, s->w2, s->s2, x, out, weights[k]);+ }+ shared_ffn(m, l, x, out);+ free(scores);+}++/* --------------------------------------------------------------- engram ---- */++/* model.py Engram.forward: look the n-grams up, project them into one key per residual+ * copy plus a shared value, and gate the value in by how well key and stream agree. */+static void engram_run(Model *m, int layer, float *h, int n, int start_pos) {+ Cfg *c = &m->c;+ Engram *e = &m->engram;+ Layer *l = &m->L[layer];+ int table = l->engram_index, hc = c->hc_mult, dim = c->dim;+ double started = now_s();+ float *rows = xmalloc((size_t)e->cols * e->head_dim * sizeof(float), "engram rows");+ float *kv = xmalloc((size_t)dim * (hc + 1) * sizeof(float), "engram kv");+ int64_t ids[V41_MAX_NGRAM * V41_MAX_EHEADS];+ for (int t = 0; t < n; t++) {+ engram_hash(e, table, start_pos + t, ids);+ for (int col = 0; col < e->cols; col++) {+ const float *row = engram_row(&e->table[table], ids[col], e->head_dim);+ memcpy(rows + (size_t)col * e->head_dim, row, (size_t)e->head_dim * sizeof(float));+ }+ mv8(kv, &l->eng_wkv, rows);+ const float *value = kv + (size_t)hc * dim;+ float *stream = h + (size_t)t * hc * dim;+ for (int copy = 0; copy < hc; copy++) {+ const float *key = kv + (size_t)copy * dim;+ const float *qw = l->eng_q.w + (size_t)copy * dim;+ const float *kw = l->eng_k.w + (size_t)copy * dim;+ float *stream_copy = stream + (size_t)copy * dim;+ double stream_square = 0.0, key_square = 0.0;+ double dot = 0.0;+ for (int i = 0; i < dim; i++) {+ stream_square += (double)stream_copy[i] * stream_copy[i];+ key_square += (double)key[i] * key[i];+ dot += (double)stream_copy[i] * qw[i] * kw[i] * key[i];+ }+ float rstd = (1.0f / sqrtf((float)(stream_square / dim) + c->norm_eps)) *+ (1.0f / sqrtf((float)(key_square / dim) + c->norm_eps));+ float scaled = (float)dot * rstd / sqrtf((float)dim);+ /* signed square root before the sigmoid, matching the training kernel */+ float magnitude = fabsf(scaled);+ if (magnitude < 1e-6f) magnitude = 1e-6f;+ float signed_root = sqrtf(magnitude);+ if (scaled < 0.0f) signed_root = -signed_root;+ float gate = coli_hc_sigmoid(signed_root);+ for (int i = 0; i < dim; i++) stream_copy[i] += gate * value[i];+ }+ }+ trace("engram", layer, h + (size_t)(n - 1) * hc * dim, hc * dim);+ free(kv); free(rows);+ m->t_engram += now_s() - started;+}++/* --------------------------------------------------------------- vision ---- */++/* The ViT is small next to the language model (about 600 MB in the released+ * checkpoint, bf16) and every image needs all of it, so it stays resident: there is+ * nothing to stream here. What matters for correctness is that its two conventions+ * differ from the language model's and are easy to get silently wrong:+ *+ * - RoPE is SPLIT-HALF (x[:d/2] against x[d/2:]), not the interleaved pairs the+ * text side uses, and it is 2D: each patch carries its row and column angle.+ * - the aligner's 3x3 block is ordered channel-major, because torch's F.unfold+ * lays a block out as (channel, kh, kw) -- read it row-major and the projection+ * sees a permuted image.+ */+static void vision_load(Model *m, Vision *v) {+ Cfg *c = &m->c;+ if (c->vision_layers < 1) { v->active = 0; return; }+ if (!st_has(&m->S, "vision.patch_embed.proj.weight")) { v->active = 0; return; }+ char name[256];+ #define VNAME(fmt, ...) (snprintf(name, sizeof(name), fmt, __VA_ARGS__), name)+ int vd = c->vision_dim, patch_in = 3 * c->vision_patch * c->vision_patch;+ wb_load(&m->S, &v->proj_w, "vision.patch_embed.proj.weight", vd, patch_in);+ wf_load(&m->S, &v->proj_b, "vision.patch_embed.proj.bias", vd);+ v->block = xmalloc((size_t)c->vision_layers * sizeof(VisionBlock), "vision blocks");+ for (int i = 0; i < c->vision_layers; i++) {+ VisionBlock *b = &v->block[i];+ wf_load(&m->S, &b->norm1, VNAME("vision.blocks.%d.norm1.weight", i), vd);+ wf_load(&m->S, &b->norm2, VNAME("vision.blocks.%d.norm2.weight", i), vd);+ wb_load(&m->S, &b->qkv_w, VNAME("vision.blocks.%d.attn.wqkv.weight", i), 3 * vd, vd);+ wf_load(&m->S, &b->qkv_b, VNAME("vision.blocks.%d.attn.wqkv.bias", i), 3 * vd);+ wb_load(&m->S, &b->o_w, VNAME("vision.blocks.%d.attn.wo.weight", i), vd, vd);+ wf_load(&m->S, &b->o_b, VNAME("vision.blocks.%d.attn.wo.bias", i), vd);+ wb_load(&m->S, &b->w1, VNAME("vision.blocks.%d.mlp.w1.weight", i), 2 * c->vision_inter, vd);+ wb_load(&m->S, &b->w2, VNAME("vision.blocks.%d.mlp.w2.weight", i), vd, c->vision_inter);+ }+ wf_load(&m->S, &v->norm, "vision.norm.weight", vd);+ int ratio = c->vision_ratio;+ wb_load(&m->S, &v->align_w1, "aligner.w1.weight", c->dim, vd * ratio * ratio);+ wf_load(&m->S, &v->align_b1, "aligner.w1.bias", c->dim);+ wb_load(&m->S, &v->align_w2, "aligner.w2.weight", c->dim, c->dim);+ wf_load(&m->S, &v->align_b2, "aligner.w2.bias", c->dim);+ wf_load(&m->S, &v->image_start, "image_start", c->dim);+ wf_load(&m->S, &v->image_end, "image_end", c->dim);+ wf_load(&m->S, &v->image_newline, "image_newline", c->dim);+ #undef VNAME+ v->active = 1;+}++/* How many rows the aligner returns for a grid: the grid is padded up to the ratio. */+static int vision_tokens(const Cfg *c, int n_h, int n_w) {+ int ratio = c->vision_ratio;+ return ((n_h + ratio - 1) / ratio) * ((n_w + ratio - 1) / ratio);+}++/* patches: [n_h * n_w, 3 * patch * patch] row-major. out: [vision_tokens, dim]. */+static void vision_forward(Model *m, Vision *v, const float *patches, int n_h, int n_w, float *out) {+ Cfg *c = &m->c;+ int vd = c->vision_dim, heads = c->vision_heads, hd = vd / heads, half = hd / 2;+ int n = n_h * n_w, patch_in = 3 * c->vision_patch * c->vision_patch;+ float *x = xmalloc((size_t)n * vd * sizeof(float), "vision stream");+ for (int i = 0; i < n; i++) {+ mvb(x + (size_t)i * vd, &v->proj_w, patches + (size_t)i * patch_in);+ for (int j = 0; j < vd; j++) x[(size_t)i * vd + j] += v->proj_b.w[j];+ }+ /* 2D RoPE tables: one angle per (patch, frequency), row and column interleaved+ * exactly as vision.py stacks them */+ float *cosine = xmalloc((size_t)n * half * sizeof(float), "vision cos");+ float *sine = xmalloc((size_t)n * half * sizeof(float), "vision sin");+ for (int p = 0; p < n; p++) {+ int row = p / n_w, col = p % n_w;+ for (int f = 0; f < half; f++) {+ int axis = f < half / 2 ? 0 : 1; /* first half rows, second columns */+ int index = axis ? f - half / 2 : f;+ float inv = 1.0f / powf(c->vision_rope_theta, (float)(2 * index) / (float)half);+ float angle = (axis ? col : row) * inv;+ cosine[(size_t)p * half + f] = cosf(angle);+ sine[(size_t)p * half + f] = sinf(angle);+ }+ }+ float *qkv = xmalloc((size_t)3 * vd * sizeof(float), "vision qkv");+ float *q = xmalloc((size_t)n * vd * sizeof(float), "vision q");+ float *k = xmalloc((size_t)n * vd * sizeof(float), "vision k");+ float *val = xmalloc((size_t)n * vd * sizeof(float), "vision v");+ float *normed = xmalloc((size_t)n * vd * sizeof(float), "vision normed");+ float *attended = xmalloc((size_t)n * vd * sizeof(float), "vision attended");+ float *hidden = xmalloc((size_t)2 * c->vision_inter * sizeof(float), "vision mlp");+ float *scores = xmalloc((size_t)n * sizeof(float), "vision scores");+ for (int layer = 0; layer < c->vision_layers; layer++) {+ VisionBlock *b = &v->block[layer];+ for (int i = 0; i < n; i++)+ rms_into(normed + (size_t)i * vd, x + (size_t)i * vd, b->norm1.w, vd, 1e-6f);+ for (int i = 0; i < n; i++) {+ mvb(qkv, &b->qkv_w, normed + (size_t)i * vd);+ for (int j = 0; j < 3 * vd; j++) qkv[j] += b->qkv_b.w[j];+ for (int h = 0; h < heads; h++) {+ const float *co = cosine + (size_t)i * half, *si = sine + (size_t)i * half;+ for (int part = 0; part < 2; part++) {+ const float *src = qkv + part * vd + (size_t)h * hd;+ float *dst = (part ? k : q) + (size_t)i * vd + (size_t)h * hd;+ for (int f = 0; f < half; f++) {+ float a = src[f], bb = src[f + half];+ dst[f] = a * co[f] - bb * si[f];+ dst[f + half] = bb * co[f] + a * si[f];+ }+ }+ memcpy(val + (size_t)i * vd + (size_t)h * hd, qkv + 2 * vd + (size_t)h * hd,+ (size_t)hd * sizeof(float));+ }+ }+ float scale = 1.0f / sqrtf((float)hd);+ for (int i = 0; i < n; i++)+ for (int h = 0; h < heads; h++) {+ const float *qi = q + (size_t)i * vd + (size_t)h * hd;+ float best = -INFINITY;+ for (int j = 0; j < n; j++) {+ const float *kj = k + (size_t)j * vd + (size_t)h * hd;+ float dot = 0.0f;+ for (int d = 0; d < hd; d++) dot += qi[d] * kj[d];+ scores[j] = dot * scale;+ if (scores[j] > best) best = scores[j];+ }+ float total = 0.0f;+ for (int j = 0; j < n; j++) { scores[j] = expf(scores[j] - best); total += scores[j]; }+ float *dst = attended + (size_t)i * vd + (size_t)h * hd;+ for (int d = 0; d < hd; d++) dst[d] = 0.0f;+ for (int j = 0; j < n; j++) {+ const float *vj = val + (size_t)j * vd + (size_t)h * hd;+ float weight = scores[j] / total;+ for (int d = 0; d < hd; d++) dst[d] += weight * vj[d];+ }+ }+ for (int i = 0; i < n; i++) {+ float projected[4096];+ if (vd > (int)(sizeof(projected) / sizeof(projected[0]))) {+ fprintf(stderr, "[vision] vision_dim %d exceeds the scratch\n", vd); exit(1); }+ mvb(projected, &b->o_w, attended + (size_t)i * vd);+ for (int j = 0; j < vd; j++) x[(size_t)i * vd + j] += projected[j] + b->o_b.w[j];+ }+ for (int i = 0; i < n; i++)+ rms_into(normed + (size_t)i * vd, x + (size_t)i * vd, b->norm2.w, vd, 1e-6f);+ for (int i = 0; i < n; i++) {+ float projected[4096];+ mvb(hidden, &b->w1, normed + (size_t)i * vd);+ for (int j = 0; j < c->vision_inter; j++) {+ float gate = hidden[j], up = hidden[c->vision_inter + j];+ hidden[j] = (gate / (1.0f + expf(-gate))) * up;+ }+ mvb(projected, &b->w2, hidden);+ for (int j = 0; j < vd; j++) x[(size_t)i * vd + j] += projected[j];+ }+ }+ for (int i = 0; i < n; i++)+ rms_into(normed + (size_t)i * vd, x + (size_t)i * vd, v->norm.w, vd, 1e-6f);++ /* aligner: pad the grid, take ratio x ratio blocks channel-major, project */+ int ratio = c->vision_ratio;+ int blocks_h = (n_h + ratio - 1) / ratio, blocks_w = (n_w + ratio - 1) / ratio;+ int block_dim = vd * ratio * ratio;+ float *block = xmalloc((size_t)block_dim * sizeof(float), "aligner block");+ float *projected = xmalloc((size_t)c->dim * sizeof(float), "aligner hidden");+ for (int bh = 0; bh < blocks_h; bh++)+ for (int bw = 0; bw < blocks_w; bw++) {+ for (int ch = 0; ch < vd; ch++)+ for (int kh = 0; kh < ratio; kh++)+ for (int kw = 0; kw < ratio; kw++) {+ int row = bh * ratio + kh, col = bw * ratio + kw;+ float value = 0.0f; /* F.pad fills the ragged edge with zeros */+ if (row < n_h && col < n_w)+ value = normed[(size_t)(row * n_w + col) * vd + ch];+ block[((size_t)ch * ratio + kh) * ratio + kw] = value;+ }+ float *dest = out + (size_t)(bh * blocks_w + bw) * c->dim;+ mvb(projected, &v->align_w1, block);+ for (int j = 0; j < c->dim; j++) {+ float value = projected[j] + v->align_b1.w[j];+ /* exact GELU, matching torch's default (erf, not the tanh approximation) */+ projected[j] = 0.5f * value * (1.0f + erff(value / sqrtf(2.0f)));+ }+ mvb(dest, &v->align_w2, projected);+ for (int j = 0; j < c->dim; j++) dest[j] += v->align_b2.w[j];+ }+ free(projected); free(block); free(scores); free(hidden); free(attended);+ free(normed); free(val); free(k); free(q); free(qkv); free(sine); free(cosine); free(x);+}++/* -------------------------------------------------------------- forward ---- */++/* The mix coefficients a sublayer computes are used by the NEXT one (model.py+ * Block.forward): attention collapses with what the previous block's FFN produced,+ * the FFN with what this attention produced. Keeping `pre` out of coli_hc_pre is+ * exactly why this engine calls coli_hc_split_sinkhorn directly. */+static void hc_mixes(Model *m, const float *hc_fn, const float *scale, const float *base,+ const float *stream, float *pre, float *post, float *comb) {+ Cfg *c = &m->c;+ int hc = c->hc_mult, dim = c->dim, flat = hc * dim, mix = (2 + hc) * hc;+ double square = 0.0;+ for (int i = 0; i < flat; i++) square += (double)stream[i] * stream[i];+ float inverse = 1.0f / sqrtf((float)(square / flat) + c->norm_eps);+ float *mixes = xmalloc((size_t)mix * sizeof(float), "hc mixes");+ #pragma omp parallel for schedule(static)+ for (int row = 0; row < mix; row++) {+ const float *w = hc_fn + (size_t)row * flat;+ float sum = 0.0f;+ for (int i = 0; i < flat; i++) sum += w[i] * stream[i];+ mixes[row] = sum * inverse;+ }+ if (coli_hc_split_sinkhorn(pre, post, comb, mixes, scale, base, hc, c->hc_iters, c->hc_eps) != 0) {+ fprintf(stderr, "[hc] sinkhorn refused its arguments\n"); exit(1); }+ free(mixes);+}++/* Run one chunk: the whole prompt on the first call, one token per call after.+ * Returns the logits of the last position (the caller owns the buffer). */+/* `image_rows` (or NULL) is the aligner's output for a pending image and `image_at`+ * the position where its span starts; the span's embeddings are replaced rather than+ * looked up. `image_mask` marks those positions for the engram. */+static void forward_with_image(Model *m, const int *ids, int n, float *logits,+ const float *image_rows, int image_at, int image_h, int image_w,+ const uint8_t *image_mask);++static void forward(Model *m, const int *ids, int n, float *logits) {+ forward_with_image(m, ids, n, logits, NULL, -1, 0, 0, NULL);+}++static void forward_with_image(Model *m, const int *ids, int n, float *logits,+ const float *image_rows, int image_at, int image_h, int image_w,+ const uint8_t *image_mask) {+ Cfg *c = &m->c;+ int dim = c->dim, hc = c->hc_mult;+ int start_pos = m->pos;+ if (n > 1 && start_pos > 0) {+ fprintf(stderr, "[forward] chunked prefill past position 0 is not supported: the "+ "indexer's reachability mask is per-position only for the first "+ "chunk (model.py Indexer.forward)\n");+ exit(1);+ }+ if (start_pos + n > c->max_positions) {+ fprintf(stderr, "CONTEXT_EXCEEDED %d %d\n", start_pos + n, c->max_positions);+ exit(1);+ }+ if (m->engram.active) engram_push(&m->engram, ids, n, image_mask);++ float *h = xmalloc((size_t)n * hc * dim * sizeof(float), "residual streams");+ float *embedded = xmalloc((size_t)dim * sizeof(float), "embedding row");+ for (int t = 0; t < n; t++) {+ const uint16_t *row = m->embed.w + (size_t)ids[t] * dim;+ for (int i = 0; i < dim; i++) embedded[i] = bf16_to_f32(row[i]);+ /* An image span carries the placeholder id at every position; what each one+ * MEANS follows from the grid, exactly as image_processor.py lays it out:+ * [start] then h rows of (w image tokens + newline) then [end].+ * The delimiters take learned embeddings, the image slots take the aligner's+ * rows in order. Reconstructing it from the grid keeps the wire protocol at+ * one IMAGE frame plus placeholders, with no parallel token-type channel to+ * fall out of step with the ids. */+ if (image_rows && m->vision && t >= image_at) {+ int offset = t - image_at;+ int span = 1 + (image_w + 1) * image_h + 1;+ if (offset < span) {+ const float *source = NULL;+ if (offset == 0) source = m->vision->image_start.w;+ else if (offset == span - 1) source = m->vision->image_end.w;+ else {+ int inner = offset - 1;+ int row_index = inner / (image_w + 1), column = inner % (image_w + 1);+ source = column == image_w ? m->vision->image_newline.w+ : image_rows + (size_t)(row_index * image_w + column) * dim;+ }+ memcpy(embedded, source, (size_t)dim * sizeof(float));+ }+ }+ for (int copy = 0; copy < hc; copy++)+ memcpy(h + ((size_t)t * hc + copy) * dim, embedded, (size_t)dim * sizeof(float));+ }+ free(embedded);+ float *pre_mix = xmalloc((size_t)n * hc * sizeof(float), "pre mix");+ for (int t = 0; t < n; t++)+ for (int copy = 0; copy < hc; copy++) pre_mix[(size_t)t * hc + copy] = copy == 0 ? 1.0f : 0.0f;++ float *branch_in = xmalloc((size_t)n * dim * sizeof(float), "sublayer input");+ float *branch_out = xmalloc((size_t)n * dim * sizeof(float), "sublayer output");+ float *residual = xmalloc((size_t)n * hc * dim * sizeof(float), "residual copy");+ float *pre = xmalloc((size_t)n * hc * sizeof(float), "hc pre");+ float *post = xmalloc((size_t)n * hc * sizeof(float), "hc post");+ float *comb = xmalloc((size_t)n * hc * hc * sizeof(float), "hc comb");+ float *collapsed = xmalloc((size_t)dim * sizeof(float), "collapsed stream");++ for (int layer = 0; layer < c->n_layers; layer++) {+ Layer *l = &m->L[layer];+ if (l->engram_index >= 0) engram_run(m, layer, h, n, start_pos);++ trace("stream", layer, h + (size_t)(n - 1) * hc * dim, hc * dim);+ memcpy(residual, h, (size_t)n * hc * dim * sizeof(float));+ for (int t = 0; t < n; t++) {+ hc_mixes(m, l->hc_attn_fn.w, l->hc_attn_scale.w, l->hc_attn_base.w,+ h + (size_t)t * hc * dim, pre + (size_t)t * hc,+ post + (size_t)t * hc, comb + (size_t)t * hc * hc);+ const float *mix = pre_mix + (size_t)t * hc;+ for (int i = 0; i < dim; i++) {+ float sum = 0.0f;+ for (int copy = 0; copy < hc; copy++)+ sum += mix[copy] * h[((size_t)t * hc + copy) * dim + i];+ collapsed[i] = sum;+ }+ rms_into(branch_in + (size_t)t * dim, collapsed, l->attn_norm.w, dim, c->norm_eps);+ }+ trace("attn_in", layer, branch_in + (size_t)(n - 1) * dim, dim);+ trace("attn_pre", layer, pre + (size_t)(n - 1) * hc, hc);+ trace("attn_post", layer, post + (size_t)(n - 1) * hc, hc);+ trace("attn_comb", layer, comb + (size_t)(n - 1) * hc * hc, hc * hc);+ attention_run(m, layer, branch_in, n, start_pos, branch_out);+ trace("attn_out", layer, branch_out + (size_t)(n - 1) * dim, dim);+ for (int t = 0; t < n; t++)+ coli_hc_post(h + (size_t)t * hc * dim, branch_out + (size_t)t * dim,+ residual + (size_t)t * hc * dim, post + (size_t)t * hc,+ comb + (size_t)t * hc * hc, hc, dim);+ /* the attention's own `pre` collapses the FFN input */+ memcpy(pre_mix, pre, (size_t)n * hc * sizeof(float));++ memcpy(residual, h, (size_t)n * hc * dim * sizeof(float));+ for (int t = 0; t < n; t++) {+ hc_mixes(m, l->hc_ffn_fn.w, l->hc_ffn_scale.w, l->hc_ffn_base.w,+ h + (size_t)t * hc * dim, pre + (size_t)t * hc,+ post + (size_t)t * hc, comb + (size_t)t * hc * hc);+ const float *mix = pre_mix + (size_t)t * hc;+ for (int i = 0; i < dim; i++) {+ float sum = 0.0f;+ for (int copy = 0; copy < hc; copy++)+ sum += mix[copy] * h[((size_t)t * hc + copy) * dim + i];+ collapsed[i] = sum;+ }+ rms_into(branch_in + (size_t)t * dim, collapsed, l->ffn_norm.w, dim, c->norm_eps);+ moe_run(m, layer, branch_in + (size_t)t * dim, branch_out + (size_t)t * dim);+ if (t == n - 1) {+ trace("ffn_in", layer, branch_in + (size_t)t * dim, dim);+ trace("ffn_out", layer, branch_out + (size_t)t * dim, dim);+ }+ }+ for (int t = 0; t < n; t++)+ coli_hc_post(h + (size_t)t * hc * dim, branch_out + (size_t)t * dim,+ residual + (size_t)t * hc * dim, post + (size_t)t * hc,+ comb + (size_t)t * hc * hc, hc, dim);+ memcpy(pre_mix, pre, (size_t)n * hc * sizeof(float)); /* the FFN's, for the next block */+ }++ /* the last block's FFN mix collapses the stream one final time */+ const float *mix = pre_mix + (size_t)(n - 1) * hc;+ for (int i = 0; i < dim; i++) {+ float sum = 0.0f;+ for (int copy = 0; copy < hc; copy++)+ sum += mix[copy] * h[((size_t)(n - 1) * hc + copy) * dim + i];+ collapsed[i] = sum;+ }+ trace("final", -1, collapsed, dim);+ rms_into(branch_in, collapsed, m->norm.w, dim, c->norm_eps);+ mvb(logits, &m->head, branch_in);+ trace("logits", -1, logits, c->vocab);++ m->pos += n;+ m->forwards++;+ free(collapsed); free(comb); free(post); free(pre);+ free(residual); free(branch_out); free(branch_in); free(pre_mix); free(h);+}++static int argmax(const float *values, int n) {+ int best = 0;+ for (int i = 1; i < n; i++) if (values[i] > values[best]) best = i;+ return best;+}++/* ---------------------------------------------------------------- serve ---- */++/* Every turn starts from a clean state: the window rings, the compressed caches, the+ * compressor's partial group and the engram history all describe one sequence. Prefix+ * reuse across turns is a later step (the KV here is four caches and a ring, not one+ * tensor), and getting it wrong would be silent, so it is refused rather than faked. */+static void model_reset(Model *m) {+ Cfg *c = &m->c;+ for (int i = 0; i < c->n_layers; i++) {+ Layer *l = &m->L[i];+ memset(l->window, 0, (size_t)c->window * c->head_dim * sizeof(float));+ int ratio = c->compress_ratio[i];+ if (c->kv_source[i]) {+ int slots = c->max_positions / (ratio > 0 ? ratio : 1);+ memset(l->ckv, 0, (size_t)slots * c->head_dim * sizeof(float));+ memset(l->ikey, 0, (size_t)slots * c->index_head_dim * sizeof(float));+ if (ratio > 1) {+ memset(l->cstate_kv, 0, (size_t)ratio * c->head_dim * sizeof(float));+ for (int k = 0; k < ratio * c->head_dim; k++) l->cstate_score[k] = -INFINITY;+ }+ }+ }+ m->engram.history_len = 0;+ m->published_index_k = NULL;+ m->shared_topk_rows = m->shared_topk_width = 0;+ m->pos = 0;+}++static const ColiServeWireProfile v41_wire = {+ .max_header_bytes = 511,+ .max_payload_bytes = 1u << 24,+ .max_tokens = 1 << 20,+ .require_exact_lf = 1,+ .require_finite_sampling = 1,+};++typedef struct { float p; int id; } SampleProb;+static int sample_desc(const void *a, const void *b) {+ float pa = ((const SampleProb *)a)->p, pb = ((const SampleProb *)b)->p;+ return (pb > pa) - (pa > pb);+}++static int serve_sample(const float *logits, int vocab, float temperature, float top_p) {+ if (temperature <= 0.0f) return argmax(logits, vocab);+ SampleProb *rank = xmalloc((size_t)vocab * sizeof(SampleProb), "sampling");+ float top = logits[0];+ for (int i = 1; i < vocab; i++) if (logits[i] > top) top = logits[i];+ double total = 0.0;+ for (int i = 0; i < vocab; i++) {+ float p = expf((logits[i] - top) / temperature);+ total += p;+ rank[i].p = p; rank[i].id = i;+ }+ qsort(rank, (size_t)vocab, sizeof(SampleProb), sample_desc);+ double cut = (top_p > 0.0f && top_p < 1.0f) ? top_p * total : total, kept = 0.0;+ int n = 0;+ while (n < vocab && kept < cut) kept += rank[n++].p;+ double draw = ((double)rand() / RAND_MAX) * kept, acc = 0.0;+ int pick = rank[0].id;+ for (int i = 0; i < n; i++) { acc += rank[i].p; if (acc >= draw) { pick = rank[i].id; break; } }+ free(rank);+ return pick;+}++static void serve_line(const char *format, ...) {+ va_list args;+ va_start(args, format);+ vfprintf(stdout, format, args);+ va_end(args);+ fflush(stdout);+}++/* --- the dashboard's four lines -------------------------------------------+ * Same bytes colibri.c emits, so the gateway parses this engine like any other:+ * EMAP rows cols hex the grid, after READY and STAT and after every turn+ * HITS rows cols hex the experts a turn routed, after DONE next to PROF+ * PROF ... wall, tokens, disk, wait, matmul, attention, head, forwards+ * Rows are the MoE layers (every layer here), columns the routed experts. */+static void serve_emap(Model *m) {+ Cfg *c = &m->c;+ int rows = c->n_layers, cols = c->n_routed;+ char *hex = xmalloc((size_t)rows * cols * 2 + 1, "emap");+ int w = 0;+ for (int i = 0; i < rows; i++) {+ LCache *cache = &m->cache[i];+ for (int e = 0; e < cols; e++) {+ int resident = 0;+ for (int k = 0; k < cache->n; k++) if (cache->slot[k].eid == e) { resident = 1; break; }+ int byte = resident << 6; /* tier in bits 6-7; no usage counter here, heat 0 */+ hex[w++] = "0123456789abcdef"[byte >> 4];+ hex[w++] = "0123456789abcdef"[byte & 15];+ }+ }+ hex[w] = 0;+ serve_line("EMAP %d %d %s\n", rows, cols, hex);+ free(hex);+}++static void serve_hits(Model *m) {+ Cfg *c = &m->c;+ int rows = c->n_layers, cols = c->n_routed, nb = (rows * cols + 7) / 8;+ uint8_t *bitmap = xmalloc((size_t)nb, "hits bitmap");+ memset(bitmap, 0, (size_t)nb);+ int bit = 0;+ for (int i = 0; i < rows; i++)+ for (int e = 0; e < cols; e++, bit++)+ if (m->ehit && m->ehit[i][e]) { bitmap[bit >> 3] |= (uint8_t)(1 << (bit & 7)); m->ehit[i][e] = 0; }+ char *hex = xmalloc((size_t)nb * 2 + 1, "hits hex");+ int w = 0;+ for (int b = 0; b < nb; b++) {+ hex[w++] = "0123456789abcdef"[bitmap[b] >> 4];+ hex[w++] = "0123456789abcdef"[bitmap[b] & 15];+ }+ hex[w] = 0;+ serve_line("HITS %d %d %s\n", rows, cols, hex);+ free(hex); free(bitmap);+}++static int serve_eos(Model *m, const char *snap, int *ids, int cap) {+ (void)m;+ char path[1024];+ snprintf(path, sizeof(path), "%s/config.json", snap);+ FILE *f = fopen(path, "rb");+ int n = 0;+ if (!f) return 0;+ fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET);+ char *text = xmalloc((size_t)size + 1, "config");+ if (fread(text, 1, (size_t)size, f) == (size_t)size) {+ text[size] = 0;+ char *arena = NULL;+ jval *root = json_parse(text, &arena);+ if (root) {+ jval *eos = json_get(root, "eos_token_id");+ if (eos && eos->t == J_NUM && n < cap) ids[n++] = (int)eos->num;+ else if (eos && eos->t == J_ARR)+ for (int i = 0; i < eos->len && n < cap; i++) ids[n++] = (int)eos->kids[i]->num;+ json_free(root); free(arena);+ }+ }+ fclose(f); free(text);+ return n;+}++static void serve_loop(Model *m, Tok *tokenizer, const char *snap) {+ Cfg *c = &m->c;+ coli_serve_stdio_init();+ int eos_ids[8];+ int n_eos = serve_eos(m, snap, eos_ids, 8);+ coli_serve_write_ready(stdout, rss_gb());+ serve_emap(m);+ float *logits = xmalloc((size_t)c->vocab * sizeof(float), "logits");+ int *ids = xmalloc((size_t)c->max_positions * sizeof(int), "prompt ids");+ float *pending_image = NULL;+ int pending_h = 0, pending_w = 0;++ for (;;) {+ ColiServeCommand command;+ ColiServeReadResult result = coli_serve_read_command(stdin, &v41_wire, &command);+ if (result == COLI_SERVE_READ_EOF || result == COLI_SERVE_READ_BAD_FRAME) break;+ if (result == COLI_SERVE_READ_NOMEM) {+ coli_serve_write_error(stdout, command.id, "out of memory"); break; }+ if (result == COLI_SERVE_READ_BAD_REQUEST) {+ if (command.kind == COLI_SERVE_COMMAND_SUBMIT)+ coli_serve_write_error(stdout, command.id, "bad submit header");+ coli_serve_command_dispose(&command);+ continue;+ }+ if (command.kind == COLI_SERVE_COMMAND_IMAGE) {+ /* One image waits for the SUBMIT that names it. A second one before that+ * SUBMIT replaces the first and says so: answering about the wrong photo+ * is worse than refusing. */+ if (!m->vision) {+ coli_serve_write_error(stdout, command.id, "this container has no vision tower");+ coli_serve_command_dispose(&command);+ continue;+ }+ int patch_in = 3 * c->vision_patch * c->vision_patch;+ uint64_t expected = (uint64_t)command.grid_h * command.grid_w * patch_in * sizeof(float);+ if (command.grid_h < 1 || command.grid_w < 1 || command.payload_bytes != expected) {+ coli_serve_write_error(stdout, command.id, "IMAGE payload does not match its grid");+ coli_serve_command_dispose(&command);+ continue;+ }+ if (pending_image) fprintf(stderr, "[v41] a second IMAGE replaced the first\n");+ free(pending_image);+ pending_image = (float *)coli_serve_command_take_payload(&command);+ pending_h = command.grid_h; pending_w = command.grid_w;+ coli_serve_command_dispose(&command);+ continue;+ }+ if (command.kind != COLI_SERVE_COMMAND_SUBMIT) {+ /* CANCEL and STOP for a turn that is not running: the protocol's NOT_FOUND */+ if (command.kind == COLI_SERVE_COMMAND_CANCEL)+ coli_serve_write_error(stdout, command.id, "NOT_FOUND");+ coli_serve_command_dispose(&command);+ continue;+ }+ double turn_started = now_s();+ double disk0 = m->t_disk, expert0 = m->t_expert, attn0 = m->t_attn, engram0 = m->t_engram;+ uint64_t forwards0 = m->forwards, hits0 = m->hits, miss0 = m->miss;+ model_reset(m);+ int n_prompt = tok_encode(tokenizer, (const char *)command.payload,+ (int)command.payload_bytes, ids, c->max_positions);+ if (n_prompt < 1) {+ coli_serve_write_error(stdout, command.id, "EMPTY_PROMPT");+ coli_serve_command_dispose(&command); continue;+ }+ int budget = command.max_tokens > 0 ? command.max_tokens : 256;+ if (n_prompt + budget > c->max_positions) {+ char message[128];+ snprintf(message, sizeof(message), "CONTEXT_EXCEEDED %d %d",+ n_prompt + budget, c->max_positions);+ coli_serve_write_error(stdout, command.id, message);+ coli_serve_command_dispose(&command); continue;+ }+ coli_serve_write_accept(stdout, command.id, n_prompt);+ float *aligned = NULL;+ uint8_t *image_mask = NULL;+ int image_at = -1, image_h = 0, image_w = 0;+ if (pending_image && m->vision && c->image_token_id >= 0) {+ /* the span is the run of placeholder ids the gateway inserted */+ for (int t = 0; t < n_prompt; t++)+ if (ids[t] == c->image_token_id) { image_at = t; break; }+ int ratio = c->vision_ratio;+ image_h = (pending_h + ratio - 1) / ratio;+ image_w = (pending_w + ratio - 1) / ratio;+ int span = 1 + (image_w + 1) * image_h + 1;+ int run = 0;+ for (int t = image_at; t >= 0 && t < n_prompt && ids[t] == c->image_token_id; t++) run++;+ if (image_at < 0 || run != span) {+ fprintf(stderr, "[v41] image span is %d tokens, the %dx%d grid needs %d: "+ "answering without the image\n", run, image_h, image_w, span);+ image_at = -1;+ } else {+ int rows = vision_tokens(c, pending_h, pending_w);+ aligned = xmalloc((size_t)rows * c->dim * sizeof(float), "image rows");+ double vision_started = now_s();+ vision_forward(m, m->vision, pending_image, pending_h, pending_w, aligned);+ fprintf(stderr, "[v41] image %dx%d patches -> %d rows in %.2fs\n",+ pending_h, pending_w, rows, now_s() - vision_started);+ image_mask = xmalloc((size_t)n_prompt, "image mask");+ memset(image_mask, 0, (size_t)n_prompt);+ for (int t = image_at; t < image_at + span; t++) image_mask[t] = 1;+ }+ }+ free(pending_image); pending_image = NULL;+ forward_with_image(m, ids, n_prompt, logits, aligned, image_at, image_h, image_w, image_mask);+ free(aligned); free(image_mask);++ int emitted = 0, limited = 1, cancelled = 0;+ char piece[512];+ for (int step = 0; step < budget; step++) {+ int token = serve_sample(logits, c->vocab, command.temperature, command.top_p);+ int stop = 0;+ for (int i = 0; i < n_eos; i++) if (token == eos_ids[i]) stop = 1;+ if (stop) { limited = 0; break; }+ int written = tok_decode(tokenizer, &token, 1, piece, (int)sizeof(piece));+ if (written > 0) coli_serve_write_data(stdout, command.id, piece, (size_t)written);+ emitted++;+ /* #1332: look at stdin once per token so a client that walked away stops+ * paying for a turn nobody wants. A CANCEL aborts, a STOP ends it through+ * the normal DONE path -- the two are not the same frame and must not+ * share an outcome. */+ while (coli_serve_stdin_ready()) {+ ColiServeCommand control;+ ColiServeReadResult inner = coli_serve_read_command(stdin, &v41_wire, &control);+ if (inner == COLI_SERVE_READ_EOF) { step = budget; break; }+ if (control.kind == COLI_SERVE_COMMAND_CANCEL &&+ !strcmp(control.id, command.id)) cancelled = 1;+ else if (control.kind == COLI_SERVE_COMMAND_STOP &&+ !strcmp(control.id, command.id)) { limited = 0; step = budget; }+ else if (control.kind == COLI_SERVE_COMMAND_SUBMIT)+ coli_serve_write_error(stdout, control.id, "SLOT_BUSY");+ coli_serve_command_dispose(&control);+ }+ if (cancelled) break;+ if (step + 1 < budget) forward(m, &token, 1, logits);+ }+ if (cancelled) {+ coli_serve_write_error(stdout, command.id, "CANCELLED");+ coli_serve_command_dispose(&command);+ continue;+ }+ double wall = now_s() - turn_started;+ uint64_t turn_hits = m->hits - hits0, turn_miss = m->miss - miss0;+ ColiServeDone done = {+ emitted, wall > 0 ? emitted / wall : 0.0,+ (turn_hits + turn_miss) ? 100.0 * turn_hits / (double)(turn_hits + turn_miss) : 0.0,+ rss_gb(), n_prompt, limited,+ };+ coli_serve_write_done(stdout, command.id, &done);+ serve_line("PROF %.3f %d %d %.3f %.3f %.3f %.3f %.3f %llu\n", wall, n_prompt, emitted,+ m->t_disk - disk0, 0.0, m->t_expert - expert0, m->t_attn - attn0,+ m->t_engram - engram0, (unsigned long long)(m->forwards - forwards0));+ serve_hits(m);+ serve_emap(m);+ coli_serve_command_dispose(&command);+ }+ free(ids); free(logits);+}++/* ----------------------------------------------------------------- main ---- */++static int *load_ids(jval *root, const char *key, int *count) {+ jval *array = json_get(root, key);+ if (!array || array->t != J_ARR) { *count = 0; return NULL; }+ int *out = xmalloc((size_t)array->len * sizeof(int), "reference ids");+ for (int i = 0; i < array->len; i++) out[i] = (int)array->kids[i]->num;+ *count = array->len;+ return out;+}++int main(int argc, char **argv) {+ const char *snap = getenv("SNAP");+ if (!snap) { fprintf(stderr, "SNAP=<container dir> is required\n"); return 2; }+ int cap = argc > 1 ? coli_arg_int(argv[1], "cache/layer") : 8;+ const char *ref_path = argc > 2 ? argv[2] : NULL;+ int engram_rows = getenv("V41_ENGRAM_ROWS") ? atoi(getenv("V41_ENGRAM_ROWS")) : 65536;+ g_trace = getenv("V41_TRACE") && atoi(getenv("V41_TRACE"));++ Model m;+ memset(&m, 0, sizeof(m));+ double started = now_s();+ model_load(&m, snap, cap, engram_rows);+ Cfg *c = &m.c;+ fprintf(stderr, "[v41] %d layers, %d experts/layer (%d routed), dim %d, hc %d, "+ "window %d, engram %s — loaded in %.2fs\n",+ c->n_layers, c->n_routed, c->n_activated, c->dim, c->hc_mult, c->window,+ m.engram.active ? "on" : "off", now_s() - started);++ if (getenv("SERVE") && atoi(getenv("SERVE"))) {+ char path[1024];+ snprintf(path, sizeof(path), "%s/tokenizer.json", snap);+ Tok tokenizer;+ tok_load(&tokenizer, path);+ const char *seed = getenv("SEED");+ srand(seed ? (unsigned)strtoul(seed, NULL, 10) : (unsigned)time(NULL));+ serve_loop(&m, &tokenizer, snap);+ return 0;+ }+ if (!ref_path) {+ fprintf(stderr, "usage: SNAP=<dir> %s <cap> <ref.json> (or SERVE=1 for the "+ "serve protocol)\n", argv[0]);+ return 2;+ }+ FILE *f = fopen(ref_path, "rb");+ if (!f) { fprintf(stderr, "%s: %s\n", ref_path, strerror(errno)); return 1; }+ fseek(f, 0, SEEK_END); long size = ftell(f); fseek(f, 0, SEEK_SET);+ char *text = xmalloc((size_t)size + 1, "reference");+ if (fread(text, 1, (size_t)size, f) != (size_t)size) { fprintf(stderr, "short read\n"); return 1; }+ text[size] = 0; fclose(f);+ char *arena = NULL;+ jval *root = json_parse(text, &arena);+ if (!root) { fprintf(stderr, "%s is not valid JSON\n", ref_path); return 1; }+ int n_prompt = 0, n_expected = 0;+ int *prompt = load_ids(root, "prompt_ids", &n_prompt);+ int *expected = load_ids(root, "output_ids", &n_expected);+ if (!prompt || !expected) { fprintf(stderr, "%s lacks prompt_ids/output_ids\n", ref_path); return 1; }++ /* the vision reference, when the fixture carries one: same patches in, the+ * aligner's rows out, compared as floats rather than as tokens because nothing+ * downstream of it is an argmax. */+ jval *vision_ref = json_get(root, "vision");+ int vision_failed = 0;+ if (vision_ref && vision_ref->t == J_OBJ && m.vision) {+ int n_h = (int)jnum(vision_ref, "grid_h", 0), n_w = (int)jnum(vision_ref, "grid_w", 0);+ jval *patch_values = json_get(vision_ref, "patches");+ jval *expected_values = json_get(vision_ref, "aligned");+ int patch_in = 3 * c->vision_patch * c->vision_patch;+ if (patch_values && expected_values && n_h > 0 && n_w > 0 &&+ patch_values->len == n_h * n_w * patch_in) {+ float *patches = xmalloc((size_t)patch_values->len * sizeof(float), "patches");+ for (int i = 0; i < patch_values->len; i++) patches[i] = (float)patch_values->kids[i]->num;+ int rows = vision_tokens(c, n_h, n_w);+ float *aligned = xmalloc((size_t)rows * c->dim * sizeof(float), "aligned");+ vision_forward(&m, m.vision, patches, n_h, n_w, aligned);+ double worst = 0.0;+ for (int i = 0; i < rows * c->dim && i < expected_values->len; i++) {+ double delta = fabs(aligned[i] - expected_values->kids[i]->num);+ if (delta > worst) worst = delta;+ }+ /* 2e-3: the reference rounds to five decimals in the JSON and both sides+ * accumulate a 32-layer tower in fp32; a real divergence is orders larger. */+ vision_failed = !(rows * c->dim == expected_values->len && worst < 2e-3);+ fprintf(stderr, "[v41] vision: %d x %d patches -> %d rows, max |delta| %.2e%s\n",+ n_h, n_w, rows, worst, vision_failed ? " MISMATCH" : "");+ free(aligned); free(patches);+ }+ }++ float *logits = xmalloc((size_t)c->vocab * sizeof(float), "logits");+ double prefill_started = now_s();+ forward(&m, prompt, n_prompt, logits);+ double prefill = now_s() - prefill_started;++ int matched = 0;+ double decode_started = now_s();+ for (int step = 0; step < n_expected; step++) {+ int token = argmax(logits, c->vocab);+ printf("%s%d", step ? " " : "", token);+ if (token == expected[step]) matched++;+ else fprintf(stderr, "\n[mismatch] step %d: got %d, reference %d\n", step, token, expected[step]);+ forward(&m, &token, 1, logits);+ }+ double decode = now_s() - decode_started;+ printf("\n");+ fprintf(stderr, "Matching tokens: %d/%d\n", matched, n_expected);+ fprintf(stderr, "[v41] prefill %d tokens in %.2fs | decode %d in %.2fs (%.2f tok/s)\n",+ n_prompt, prefill, n_expected, decode, n_expected / (decode > 0 ? decode : 1));+ fprintf(stderr, "[v41] experts: %llu hits, %llu misses, %.1f MB read | disk %.2fs, "+ "expert matmul %.2fs, attention %.2fs, engram %.2fs\n",+ (unsigned long long)m.hits, (unsigned long long)m.miss,+ m.expert_bytes / 1e6, m.t_disk, m.t_expert, m.t_attn, m.t_engram);+ if (m.engram.active)+ for (int t = 0; t < m.engram.n_layers; t++)+ fprintf(stderr, "[v41] engram table %d (layer %d): %lld rows, %llu cache hits, "+ "%llu reads\n", t, m.engram.layer_of[t],+ (long long)m.engram.table[t].rows,+ (unsigned long long)m.engram.table[t].hits,+ (unsigned long long)m.engram.table[t].misses);+ free(logits); free(prompt); free(expected); json_free(root); free(arena); free(text);+ return (matched == n_expected && !vision_failed) ? 0 : 1;+}diff --git a/c/tools/dsv41_image.py b/c/tools/dsv41_image.pynew file mode 100644index 00000000..bc3e2f8f--- /dev/null+++ b/c/tools/dsv41_image.py@@ -0,0 +1,113 @@+#!/usr/bin/env python3+"""Turn an image into DeepSeek-V4.1-Flash ViT patches, gateway side.++The engine reads patches, not pixels: this is the vendor's inference/image_processor.py+(`plan_image_grid` + `load_image`) with its resize rules kept exactly, because the grid+it chooses decides how many tokens the image costs and the engine reconstructs the span+layout from that same grid.++Returns (patches, n_vit_h, n_vit_w, n_llm_h, n_llm_w):+ patches float32 [n_vit_h * n_vit_w, 3 * patch * patch], the ViT's input+ n_vit_* the patch grid+ n_llm_* the token grid after the aligner's downsample, which is what the prompt+ span has to be sized for: 1 + (n_llm_w + 1) * n_llm_h + 1 placeholders+"""+from __future__ import annotations++import io+import json+import math+from pathlib import Path++DEFAULTS = dict(patch_size=14, downsample_ratio=3, max_image_tokens=1024,+ min_pixels=295936, max_wh_ratio=None)+++def load_config(model_dir) -> dict:+ settings = dict(DEFAULTS)+ if model_dir:+ path = Path(model_dir) / "config.json"+ if path.is_file():+ vision = json.loads(path.read_text()).get("vision_config") or {}+ for key in DEFAULTS:+ if key in vision:+ settings[key] = vision[key]+ return settings+++def _llm_grid(height: int, width: int, patch: int, ratio: int):+ return math.ceil((height // patch) / ratio), math.ceil((width // patch) / ratio)+++def _token_count(n_llm_h: int, n_llm_w: int) -> int:+ """image_processor.num_image_tokens: start, a newline per row, end."""+ return 1 + (n_llm_w + 1) * n_llm_h + 1+++def _solve_resize(height, width, patch, ratio, max_tokens):+ """image_processor.solve_resize_ratio: the largest aspect-preserving size that fits."""+ r = height / width+ max_w = math.sqrt((max_tokens - 2) / r + 0.25) - 0.5+ max_h = max_w * r+ cell = patch * ratio+ if max_w < 1.0:+ return (max_tokens - 2) // 2 * cell, cell+ if max_h < 1.0:+ return cell, (max_tokens - 3) * cell+ beta = min(math.floor(max_w) * cell / width, math.floor(max_h) * cell / height)+ return (math.floor(height * beta / patch) * patch,+ math.floor(width * beta / patch) * patch)+++def plan_grid(width: int, height: int, settings: dict, max_tokens=None):+ """image_processor.plan_image_grid + safe_resize."""+ patch = int(settings["patch_size"])+ ratio = int(settings["downsample_ratio"])+ budget = int(max_tokens or settings["max_image_tokens"])+ wh_ratio = settings.get("max_wh_ratio")+ if wh_ratio is not None and width > height * wh_ratio:+ width = int(height * wh_ratio)+ min_pixels = int(settings["min_pixels"])+ if 0 < width * height < min_pixels:+ scale = (min_pixels / (width * height)) ** 0.5+ width, height = int(width * scale), int(height * scale)+ best_w = math.ceil(width / patch) * patch+ best_h = math.ceil(height / patch) * patch+ n_llm_h, n_llm_w = _llm_grid(best_h, best_w, patch, ratio)+ if _token_count(n_llm_h, n_llm_w) > budget:+ best_h, best_w = _solve_resize(height, width, patch, ratio, budget)+ n_llm_h, n_llm_w = _llm_grid(best_h, best_w, patch, ratio)+ return n_llm_h, n_llm_w, best_h, best_w+++def preprocess(source, model_dir=None, max_tokens=None):+ try:+ import numpy+ from PIL import Image, ImageOps+ except ImportError as exc: # pragma: no cover+ raise SystemExit(f"image input needs Pillow and numpy: {exc}")+ settings = load_config(model_dir)+ patch = int(settings["patch_size"])+ data = source if isinstance(source, (bytes, bytearray)) else Path(source).read_bytes()+ with Image.open(io.BytesIO(data)) as opened:+ image = opened.convert("RGB")+ n_llm_h, n_llm_w, best_h, best_w = plan_grid(image.width, image.height, settings, max_tokens)+ wh_ratio = settings.get("max_wh_ratio")+ if wh_ratio is not None and image.width >= wh_ratio * image.height:+ image = image.resize((best_w, best_h))+ else:+ # pad, not crop: what a letterboxed image loses is canvas, not content+ image = ImageOps.pad(image, (best_w, best_h), color=(127, 127, 127))+ pixels = numpy.asarray(image, dtype=numpy.float32) / 255.0+ pixels = (pixels - 0.5) / 0.5 # the vendor's normalization+ n_vit_h, n_vit_w = best_h // patch, best_w // patch+ # [H, W, 3] -> [n_h, n_w, 3, p, p] -> flat rows of 3 * p * p, the order PatchEmbed reads+ grid = pixels.reshape(n_vit_h, patch, n_vit_w, patch, 3).transpose(0, 2, 4, 1, 3)+ patches = numpy.ascontiguousarray(grid.reshape(n_vit_h * n_vit_w, 3 * patch * patch),+ dtype=numpy.float32)+ return patches, n_vit_h, n_vit_w, n_llm_h, n_llm_w+++def span_tokens(n_llm_h: int, n_llm_w: int) -> int:+ """How many placeholder ids the prompt must carry for this image."""+ return _token_count(n_llm_h, n_llm_w)diff --git a/c/tools/dsv41_ref.py b/c/tools/dsv41_ref.pynew file mode 100644index 00000000..4ef3f08d--- /dev/null+++ b/c/tools/dsv41_ref.py@@ -0,0 +1,643 @@+#!/usr/bin/env python3+"""Torch-only reference for DeepSeek-V4.1-Flash, and the quantizers its container uses.++The vendor's `inference/model.py` is the authority on this architecture, but it cannot+be the oracle: its attention, quantization and Sinkhorn all run through tilelang JIT+kernels that need a GPU. This file re-implements the same math in plain torch on the+CPU so `make_dsv41_tiny.py` can emit a token-exact reference the C engine is held to.++Everything here mirrors a named piece of the vendor file; where the two could drift the+vendor's line is quoted. Deviations that are deliberate:++- fp32 everywhere. The vendor keeps activations in bf16 between sublayers; colibri's+ engines carry fp32. On the tiny fixture the two agree token-for-token, and fp32 is+ what the C side has to reproduce, so the oracle is written in it.+- weights are dequantized once, up front, exactly as the engine dequantizes them+ (`fp8_dequant` / `fp4_dequant` below). The oracle therefore validates the engine's+ arithmetic, not its ability to guess a rounding mode.+- no distributed anything: world_size == 1, so the parallel/sharded classes collapse.+"""+from __future__ import annotations++import math++import torch+import torch.nn.functional as F++# ---------------------------------------------------------------- quantization++E4M3_MAX = 448.0+# e2m1: 3 magnitude bits index this table, bit 3 is the sign (quant.h, matmul_mxfp4)+E2M1_LEVELS = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0])+E2M1_MAX = 6.0+++def _pow2(exponent: torch.Tensor) -> torch.Tensor:+ """2**e for an integer tensor, as fp32. torch.ldexp keeps this exact."""+ return torch.ldexp(torch.ones_like(exponent, dtype=torch.float32), exponent)+++def ue8m0_exponent(amax: torch.Tensor, dtype_max: float) -> torch.Tensor:+ """The ue8m0 byte for a block whose largest magnitude is `amax`.++ ue8m0 stores a power of two as a bare exponent byte with bias 127, so the scale can+ only be 2**k: pick the smallest k that brings the block inside the target format's+ range. amax == 0 gives k = 0 rather than -inf, which keeps an all-zero block's byte+ at 127 instead of 0 (0 would decode as a denormal and the SIMD path in quant.h+ flushes it to +0 -- harmless here, but a needless difference between the two paths).+ """+ safe = torch.where(amax > 0, amax, torch.ones_like(amax))+ exponent = torch.ceil(torch.log2(safe / dtype_max))+ exponent = torch.where(amax > 0, exponent, torch.zeros_like(exponent))+ return exponent.to(torch.int32).clamp(-127, 128)+++def fp8_quant_blocked(w: torch.Tensor, block: int = 32):+ """Quantize [O, I] to e4m3 bytes with one ue8m0 scale per `block` x `block` tile.++ Returns (bytes [O, I] uint8-viewed e4m3, scale bytes [O/block, I/block] uint8).+ The released checkpoint stores exactly this: `attn.wkv.weight F8_E4M3 [512, 5120]`+ beside `attn.wkv.scale F8_E8M0 [16, 160]`, i.e. 512/16 == 5120/160 == 32.+ """+ rows, cols = w.shape+ assert rows % block == 0 and cols % block == 0, (rows, cols, block)+ tiles = w.reshape(rows // block, block, cols // block, block).permute(0, 2, 1, 3)+ exponent = ue8m0_exponent(tiles.abs().amax(dim=(-2, -1)), E4M3_MAX)+ scaled = tiles / _pow2(exponent)[..., None, None]+ q = scaled.to(torch.float8_e4m3fn)+ packed = q.permute(0, 2, 1, 3).reshape(rows, cols)+ return packed, (exponent + 127).to(torch.uint8)+++def fp8_dequant_blocked(q: torch.Tensor, scale: torch.Tensor, block: int = 32) -> torch.Tensor:+ """Inverse of fp8_quant_blocked; this is the read path the C engine implements."""+ rows, cols = q.shape+ values = q.to(torch.float32).reshape(rows // block, block, cols // block, block).permute(0, 2, 1, 3)+ exponent = scale.to(torch.int32) - 127+ out = values * _pow2(exponent)[..., None, None]+ return out.permute(0, 2, 1, 3).reshape(rows, cols)+++def fp4_quant_rowgroups(w: torch.Tensor, group: int = 32):+ """Quantize [O, I] to packed e2m1 nibbles with one ue8m0 scale per row group of 32.++ Returns (packed [O, I/2] uint8, scale [O, I/group] uint8). This is the released+ expert layout: `ffn.experts.0.w1.weight I8 [2304, 2560]` for a [2304, 5120] matrix+ beside `w1.scale F8_E8M0 [2304, 160]`, and it is also colibri's existing mxfp4+ layout, so `matmul_mxfp4` in quant.h reads it unchanged.++ LOW nibble = even column, exactly as quant.h documents and as torch's+ float4_e2m1fn_x2 packs.+ """+ rows, cols = w.shape+ assert cols % group == 0 and group % 2 == 0, (cols, group)+ grouped = w.reshape(rows, cols // group, group)+ exponent = ue8m0_exponent(grouped.abs().amax(dim=-1), E2M1_MAX)+ scaled = grouped / _pow2(exponent)[..., None]+ levels = E2M1_LEVELS.to(scaled.dtype)+ # nearest level, ties away from zero -- torch.bucketize on midpoints is exact and+ # avoids depending on any float8/float4 cast rounding mode+ mids = (levels[1:] + levels[:-1]) / 2+ idx = torch.bucketize(scaled.abs().contiguous(), mids.contiguous())+ nibble = idx.to(torch.uint8) | (torch.signbit(scaled).to(torch.uint8) << 3)+ nibble = nibble.reshape(rows, cols)+ packed = nibble[:, 0::2] | (nibble[:, 1::2] << 4)+ return packed.contiguous(), (exponent + 127).to(torch.uint8)+++def fp4_dequant_rowgroups(packed: torch.Tensor, scale: torch.Tensor, cols: int, group: int = 32) -> torch.Tensor:+ rows = packed.shape[0]+ low = packed & 0x0F+ high = (packed >> 4) & 0x0F+ nibble = torch.stack([low, high], dim=-1).reshape(rows, cols).to(torch.int64)+ values = E2M1_LEVELS.to(torch.float32)[nibble & 0x7] * torch.where(+ (nibble & 0x8) != 0, -1.0, 1.0+ )+ exponent = scale.to(torch.int32) - 127+ return (values.reshape(rows, cols // group, group) * _pow2(exponent)[..., None]).reshape(rows, cols)+++def fp8_quant_rowgroups(w: torch.Tensor, group: int = 32):+ """e4m3 values with one ue8m0 scale per row group -- the engram table's layout+ (`embed.weight F8_E4M3 [rows, 256]` beside `embed.scale F8_E8M0 [rows, 8]`)."""+ rows, cols = w.shape+ assert cols % group == 0+ grouped = w.reshape(rows, cols // group, group)+ exponent = ue8m0_exponent(grouped.abs().amax(dim=-1), E4M3_MAX)+ q = (grouped / _pow2(exponent)[..., None]).to(torch.float8_e4m3fn)+ return q.reshape(rows, cols), (exponent + 127).to(torch.uint8)+++def fp8_dequant_rowgroups(q: torch.Tensor, scale: torch.Tensor, group: int = 32) -> torch.Tensor:+ rows, cols = q.shape+ exponent = scale.to(torch.int32) - 127+ values = q.to(torch.float32).reshape(rows, cols // group, group)+ return (values * _pow2(exponent)[..., None]).reshape(rows, cols)+++# ------------------------------------------------------------------- primitives+++def rms_norm(x: torch.Tensor, weight: torch.Tensor, eps: float) -> torch.Tensor:+ """model.py RMSNorm: the mean of squares, in fp32, weight applied after."""+ var = x.float().square().mean(-1, keepdim=True)+ return weight.float() * x.float() * torch.rsqrt(var + eps)+++def precompute_freqs_cis(dim, seqlen, original_seq_len, base, factor, beta_fast, beta_slow):+ """model.py precompute_freqs_cis, YaRN included. Returns [seqlen, dim/2] complex."""++ def find_correction_dim(num_rotations, d, b, max_seq_len):+ return d * math.log(max_seq_len / (num_rotations * 2 * math.pi)) / (2 * math.log(b))++ def find_correction_range(low_rot, high_rot, d, b, max_seq_len):+ low = math.floor(find_correction_dim(low_rot, d, b, max_seq_len))+ high = math.ceil(find_correction_dim(high_rot, d, b, max_seq_len))+ return max(low, 0), min(high, d - 1)++ def linear_ramp_factor(minimum, maximum, d):+ if minimum == maximum:+ maximum += 0.001+ ramp = (torch.arange(d, dtype=torch.float32) - minimum) / (maximum - minimum)+ return torch.clamp(ramp, 0, 1)++ freqs = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))+ if original_seq_len > 0 and seqlen > original_seq_len:+ low, high = find_correction_range(beta_fast, beta_slow, dim, base, original_seq_len)+ smooth = 1 - linear_ramp_factor(low, high, dim // 2)+ freqs = freqs / factor * (1 - smooth) + freqs * smooth+ t = torch.arange(seqlen, dtype=torch.float32)+ return torch.polar(torch.ones(seqlen, dim // 2), torch.outer(t, freqs))+++def apply_rotary(x: torch.Tensor, freqs_cis: torch.Tensor, inverse: bool = False) -> torch.Tensor:+ """model.py apply_rotary_emb. `x` is the RoPE tail only, shaped [..., rope_dim];+ freqs_cis broadcasts over the leading dims. `inverse` rotates the other way, which+ the output projection uses to undo the query rotation."""+ shape = x.shape+ pairs = torch.view_as_complex(x.float().reshape(*shape[:-1], -1, 2))+ while freqs_cis.dim() < pairs.dim():+ freqs_cis = freqs_cis.unsqueeze(-2)+ rotated = pairs * (freqs_cis.conj() if inverse else freqs_cis)+ return torch.view_as_real(rotated).reshape(shape)+++def hc_split_sinkhorn(mixes, hc_scale, hc_base, hc_mult, iters, eps):+ """kernel.py hc_split_sinkhorn, in torch. mixes: [n, (2+hc)*hc]."""+ pre = torch.sigmoid(mixes[..., :hc_mult] * hc_scale[0] + hc_base[:hc_mult]) + eps+ post = 2 * torch.sigmoid(mixes[..., hc_mult : 2 * hc_mult] * hc_scale[1] + hc_base[hc_mult : 2 * hc_mult])+ comb = mixes[..., 2 * hc_mult :] * hc_scale[2] + hc_base[2 * hc_mult :]+ comb = comb.reshape(*comb.shape[:-1], hc_mult, hc_mult)+ comb = comb.softmax(dim=-1) + eps+ comb = comb / (comb.sum(dim=-2, keepdim=True) + eps)+ for _ in range(iters - 1):+ comb = comb / (comb.sum(dim=-1, keepdim=True) + eps)+ comb = comb / (comb.sum(dim=-2, keepdim=True) + eps)+ return pre, post, comb+++def sparse_attn(q, kv, attn_sink, topk_idxs, softmax_scale):+ """kernel.py sparse_attn, in torch.++ q: [s, h, d]; kv: [n, d] (one KV per position -- this model is MQA, num_key_value+ heads == 1); topk_idxs: [s, topk] with -1 for "nothing here". The sink adds+ exp(sink_h - max) to the denominator only, so a row with no valid index comes out+ all zero instead of NaN -- the kernel's -1e30 floor does the same.+ """+ s, h, d = q.shape+ out = torch.zeros_like(q)+ for i in range(s):+ idx = topk_idxs[i]+ valid = idx >= 0+ scores = torch.full((h, idx.numel()), -float("inf"))+ if valid.any():+ keys = kv[idx[valid]] # [k, d]+ scores[:, valid] = (q[i] @ keys.T) * softmax_scale+ row_max = torch.maximum(scores.max(dim=-1).values, torch.full((h,), -1e30))+ weights = torch.exp(scores - row_max[:, None])+ weights = torch.where(torch.isfinite(scores), weights, torch.zeros_like(weights))+ denom = weights.sum(dim=-1) + torch.exp(attn_sink.float() - row_max)+ if valid.any():+ out[i] = (weights[:, valid] @ kv[idx[valid]]) / denom[:, None]+ else:+ out[i] = 0+ return out+++# ------------------------------------------------------------------- n-gram hash+++class NgramHash:+ """engram.py NgramHashState, driven by tables computed once at conversion time.++ The vendor builds the compressed-token map from the tokenizer, the bucket primes with+ sympy and the per-(layer, lookback) multipliers from `np.random.default_rng(10007 *+ layer_id)`. None of that belongs in a C engine at load time, so `prepare_dsv41.py`+ computes it and ships it in the container; this class and the engine both read those+ arrays. The hash itself is the part that must agree byte for byte, so it lives here+ in one place.+ """++ DEAD = -1++ def __init__(self, token_map, primes, offsets, multipliers, pad_id, max_ngram_size, n_heads):+ self.token_map = token_map # [vocab] int64+ self.primes = primes # [n_layers, max_ngram-1, n_heads] int64+ self.offsets = offsets # [n_layers, (max_ngram-1)*n_heads] int64+ self.multipliers = multipliers # [n_layers, max_ngram] int64+ self.pad_id = pad_id+ self.max_ngram_size = max_ngram_size+ self.n_heads = n_heads+ self.history: list[int] = [] # compressed ids, DEAD for image positions++ def reset(self):+ self.history = []++ def push(self, compressed_ids: list[int]) -> torch.Tensor:+ """Extend the history and return the hash ids of the new positions,+ shaped [n_new, n_engram_layers, (max_ngram_size - 1) * n_heads]."""+ start = len(self.history)+ self.history.extend(compressed_ids)+ rows = []+ for pos in range(start, len(self.history)):+ tokens, blocked = [], False+ for shift in range(self.max_ngram_size):+ source = self.history[pos - shift] if pos - shift >= 0 else self.pad_id+ blocked = blocked or pos < shift or source == self.DEAD+ tokens.append(self.pad_id if blocked else source)+ tokens = torch.tensor(tokens, dtype=torch.int64)+ products = tokens[None, :] * self.multipliers # [layers, max_ngram]+ rolling, hashes = products[:, 0], []+ for i in range(1, self.max_ngram_size):+ rolling = torch.bitwise_xor(rolling, products[:, i])+ hashes.append(rolling[:, None] % self.primes[:, i - 1])+ rows.append(torch.cat(hashes, dim=-1) + self.offsets)+ return torch.stack(rows) if rows else torch.zeros(0, self.primes.shape[0], 0, dtype=torch.int64)+++# ------------------------------------------------------------------- the model+++class RefModel:+ """One-batch reference. `w` holds every tensor already dequantized to fp32, keyed by+ the checkpoint's own names, so this class never sees a scale."""++ def __init__(self, cfg: dict, w: dict, ngram: NgramHash | None = None):+ self.c = cfg+ self.w = w+ self.ngram = ngram+ c = cfg+ self.hc = c["hc_mult"]+ self.dim = c["dim"]+ self.rd = c["rope_head_dim"]+ self.nlayers = c["n_layers"]+ self.max_seq = c["max_seq_len"]+ # RoPE tables: a compressing layer rotates at compress_rope_theta with YaRN, a+ # window-only layer at rope_theta with none (model.py Attention.__init__).+ self.freqs_compress = precompute_freqs_cis(+ self.rd, self.max_seq, c["original_seq_len"], c["compress_rope_theta"],+ c["rope_factor"], c["beta_fast"], c["beta_slow"])+ self.freqs_window = precompute_freqs_cis(+ self.rd, self.max_seq, 0, c["rope_theta"], c["rope_factor"], c["beta_fast"], c["beta_slow"])+ self.reset()++ def freqs(self, layer: int) -> torch.Tensor:+ return self.freqs_compress if self.c["compress_ratios"][layer] else self.freqs_window++ def reset(self):+ c, hd = self.c, self.c["head_dim"]+ self.pos = 0+ self.window = [torch.zeros(c["window_size"], hd) for _ in range(self.nlayers)]+ self.compress_kv = {}+ self.index_k = {}+ self.comp_state = {}+ for layer in c["kv_source_layers"]:+ ratio = c["compress_ratios"][layer]+ self.compress_kv[layer] = torch.zeros(self.max_seq // max(ratio, 1), hd)+ self.index_k[layer] = torch.zeros(self.max_seq // max(ratio, 1), c["index_head_dim"])+ self.comp_state[layer] = (torch.zeros(ratio, hd), torch.full((ratio, hd), -float("inf")))+ if self.ngram is not None:+ self.ngram.reset()+ # model.py's `shared_attn` is a module-level object: what a source layer+ # publishes stays published ACROSS forwards, which is what a decode step reads+ # when its own compression group is still filling (latent is None there, and the+ # indexer still needs the key cache the source layer wrote two tokens ago).+ self.shared = {"compress_kv": None, "index_k": None, "topk_idxs": None, "candidates": None}++ # -- attention -----------------------------------------------------------++ def compressor(self, layer: int, x: torch.Tensor, start_pos: int):+ """model.py Compressor.forward. Returns the pre-RoPE latents produced by this+ chunk, or None while a group is still filling."""+ c = self.c+ ratio = c["compress_ratios"][layer]+ p = f"layers.{layer}.attn.compressor."+ kv = x @ self.w[p + "wkv.weight"].T+ if ratio == 1:+ return rms_norm(kv, self.w[p + "norm.weight"], c["norm_eps"])+ score = x @ self.w[p + "wgate.weight"].T+ state_kv, state_score = self.comp_state[layer]+ if start_pos == 0:+ seqlen = x.shape[0]+ remainder = seqlen % ratio+ cutoff = seqlen - remainder+ if remainder:+ state_kv[:remainder] = kv[cutoff:]+ state_score[:remainder] = score[cutoff:]+ kv, score = kv[:cutoff], score[:cutoff]+ if cutoff == 0:+ return None+ kv = kv.reshape(-1, ratio, kv.shape[-1])+ score = score.reshape(-1, ratio, score.shape[-1])+ pooled = (kv * score.softmax(dim=1)).sum(dim=1)+ else:+ slot = start_pos % ratio+ state_kv[slot] = kv[0]+ state_score[slot] = score[0]+ if (start_pos + 1) % ratio != 0:+ return None+ pooled = (state_kv * state_score.softmax(dim=0)).sum(dim=0, keepdim=True)+ return rms_norm(pooled, self.w[p + "norm.weight"], c["norm_eps"])++ def indexer(self, layer: int, x, qr, latent, start_pos, offset, compress_len, shared):+ """model.py Indexer.forward, minus the fp4 activation quantization."""+ c = self.c+ p = f"layers.{layer}.attn.indexer."+ ratio = c["compress_ratios"][layer]+ seqlen = x.shape[0]+ end_pos = start_pos + seqlen+ if layer in c["kv_source_layers"] and latent is not None:+ freqs = (self.freqs(layer)[: seqlen - seqlen % ratio : ratio] if start_pos == 0+ else self.freqs(layer)[start_pos + 1 - ratio].unsqueeze(0))+ k = rms_norm(latent @ self.w[p + "wk.weight"].T, self.w[p + "k_norm.weight"], c["norm_eps"])+ k = torch.cat([k[..., : -self.rd], apply_rotary(k[..., -self.rd :], freqs)], dim=-1)+ base = start_pos // ratio+ self.index_k[layer][base : base + k.shape[0]] = k+ shared["index_k"] = self.index_k[layer]+ nh, hd = c["index_n_heads"], c["index_head_dim"]+ q = (qr @ self.w[p + "wq_b.weight"].T).reshape(seqlen, nh, hd)+ q = torch.cat([q[..., : -self.rd], apply_rotary(q[..., -self.rd :], self.freqs(layer)[start_pos:end_pos])], dim=-1)+ index_k = shared["index_k"][: end_pos // ratio]+ weights = (x @ self.w[p + "weights_proj.weight"].T) * (hd**-0.5 * nh**-0.5)+ score = torch.einsum("shd,td->sht", q, index_k)+ score = (score.relu() * weights[..., None]).sum(dim=1) # [s, t]+ if start_pos == 0:+ lens = (torch.arange(1, seqlen + 1) // ratio).unsqueeze(-1)+ score = score.masked_fill(torch.arange(score.shape[-1]) >= lens, -float("inf"))+ else:+ lens = torch.tensor(end_pos // ratio)+ if layer == c["candidate_source_layer"]:+ shared["candidates"] = select_candidate_blocks(+ score, lens, c["candidate_topk_blocks"], c["candidate_block_size"])+ elif 0 <= c["candidate_source_layer"] < layer:+ score = score.masked_fill(~shared["candidates"], -float("inf"))+ topk = min(c["index_topk"], end_pos // ratio)+ idxs = score.topk(topk, dim=-1, sorted=False).indices.sort(dim=-1).values+ return torch.where(idxs < lens, idxs + offset, torch.tensor(-1)).int()++ def attention(self, layer: int, x: torch.Tensor, start_pos: int, shared: dict) -> torch.Tensor:+ c = self.c+ p = f"layers.{layer}.attn."+ seqlen, hd, rd = x.shape[0], c["head_dim"], self.rd+ nh, win, ratio = c["n_heads"], c["window_size"], c["compress_ratios"][layer]+ freqs_cis = self.freqs(layer)[start_pos : start_pos + seqlen]++ qr = rms_norm(x @ self.w[p + "wq_a.weight"].T, self.w[p + "q_norm.weight"], c["norm_eps"])+ q = (qr @ self.w[p + "wq_b.weight"].T).reshape(seqlen, nh, hd)+ q = torch.cat([q[..., :-rd], apply_rotary(q[..., -rd:], freqs_cis)], dim=-1)++ kv = rms_norm(x @ self.w[p + "wkv.weight"].T, self.w[p + "kv_norm.weight"], c["norm_eps"])+ kv = torch.cat([kv[..., :-rd], apply_rotary(kv[..., -rd:], freqs_cis)], dim=-1)+ ring = self.window[layer]+ if start_pos == 0:+ if seqlen <= win:+ ring[:seqlen] = kv+ else:+ cut = seqlen % win+ ring[cut:win], ring[:cut] = kv[-win:][: win - cut], kv[-win:][win - cut :]+ window_kv, window_idxs = kv, window_topk_idxs(win, seqlen, 0)+ else:+ ring[start_pos % win] = kv[0]+ window_kv, window_idxs = ring, window_topk_idxs(win, seqlen, start_pos)++ kv_all, idxs = window_kv, window_idxs+ if ratio:+ compress_len = (start_pos + seqlen) // ratio+ latent = None+ if layer in c["kv_source_layers"]:+ latent = self.compressor(layer, x, start_pos)+ shared["compress_kv"] = self.compress_kv[layer]+ if layer in c["index_source_layers"]:+ shared["topk_idxs"] = (+ torch.zeros(seqlen, 0, dtype=torch.int32) if compress_len == 0+ else self.indexer(layer, x, qr, latent, start_pos, window_kv.shape[0], compress_len, shared))+ if latent is not None:+ freqs = (self.freqs(layer)[: seqlen - seqlen % ratio : ratio] if start_pos == 0+ else self.freqs(layer)[start_pos + 1 - ratio].unsqueeze(0))+ latent = torch.cat([latent[..., :-rd], apply_rotary(latent[..., -rd:], freqs)], dim=-1)+ base = start_pos // ratio+ self.compress_kv[layer][base : base + latent.shape[0]] = latent+ kv_all = torch.cat([window_kv, shared["compress_kv"][:compress_len]], dim=0)+ idxs = torch.cat([window_idxs, shared["topk_idxs"]], dim=-1)++ o = sparse_attn(q, kv_all, self.w[p + "attn_sink"], idxs, hd**-0.5)+ o = torch.cat([o[..., :-rd], apply_rotary(o[..., -rd:], freqs_cis, inverse=True)], dim=-1)+ groups, olora = c["o_groups"], c["o_lora_rank"]+ o = o.reshape(seqlen, groups, -1)+ wo_a = self.w[p + "wo_a.weight"].reshape(groups, olora, -1)+ o = torch.einsum("sgd,grd->sgr", o, wo_a).reshape(seqlen, groups * olora)+ return o @ self.w[p + "wo_b.weight"].T++ # -- MoE -----------------------------------------------------------------++ def expert(self, prefix: str, x: torch.Tensor) -> torch.Tensor:+ limit = self.c["swiglu_limit"]+ gate = x @ self.w[prefix + "w1.weight"].T+ up = x @ self.w[prefix + "w3.weight"].T+ if limit > 0:+ up = up.clamp(-limit, limit)+ gate = gate.clamp(max=limit)+ return (F.silu(gate) * up) @ self.w[prefix + "w2.weight"].T++ def moe(self, layer: int, x: torch.Tensor) -> torch.Tensor:+ c = self.c+ p = f"layers.{layer}.ffn."+ scores = F.softplus(x @ self.w[p + "gate.weight"].T).sqrt()+ idx = (scores + self.w[p + "gate.bias"]).topk(c["n_activated_experts"], dim=-1).indices+ weights = scores.gather(1, idx)+ if c["norm_topk_prob"] and c["n_activated_experts"] > 1:+ weights = weights / (weights.sum(dim=-1, keepdim=True) + 1e-20)+ weights = weights * c["route_scale"]+ y = torch.zeros_like(x)+ for token in range(x.shape[0]):+ for k in range(idx.shape[1]):+ e = int(idx[token, k])+ y[token] += weights[token, k] * self.expert(p + f"experts.{e}.", x[token : token + 1])[0]+ return y + self.expert(p + "shared_experts.", x)++ # -- block / forward -----------------------------------------------------++ def hc_mixes(self, x, which: str, layer: int):+ c = self.c+ flat = x.reshape(x.shape[0], -1)+ rsqrt = torch.rsqrt(flat.square().mean(-1, keepdim=True) + c["norm_eps"])+ mixes = (flat @ self.w[f"layers.{layer}.hc_{which}_fn"].T) * rsqrt+ return hc_split_sinkhorn(mixes, self.w[f"layers.{layer}.hc_{which}_scale"],+ self.w[f"layers.{layer}.hc_{which}_base"],+ self.hc, c["hc_sinkhorn_iters"], c["hc_eps"])++ def engram(self, layer: int, x: torch.Tensor, hash_ids: torch.Tensor) -> torch.Tensor:+ """model.py Engram.forward. `x` is [s, hc, dim]; hash_ids [s, n_hash_cols]."""+ c = self.c+ p = f"layers.{layer}.engram."+ rows = self.w[p + "embed.weight"][hash_ids.reshape(-1)].reshape(hash_ids.shape[0], -1)+ kv = rows @ self.w[p + "wkv.weight"].T+ key, value = kv.split([self.hc * self.dim, self.dim], dim=-1)+ key = key.reshape(-1, self.hc, self.dim)+ weight = self.w[p + "q_weight"] * self.w[p + "k_weight"]+ eps = c["norm_eps"]+ rstd = torch.rsqrt(x.square().mean(-1) + eps) * torch.rsqrt(key.square().mean(-1) + eps)+ dot = (x * weight * key).sum(-1) * rstd * self.dim**-0.5+ gate = torch.sigmoid(torch.copysign(dot.abs().clamp_min(1e-6).sqrt(), dot))+ return x + gate[..., None] * value[:, None, :]++ def forward(self, ids: list[int], compressed: list[int] | None = None) -> torch.Tensor:+ """Run one chunk (prefill when the model is fresh, one token per call after) and+ return the logits of its last position."""+ c = self.c+ start_pos = self.pos+ hashes = None+ if self.ngram is not None:+ hashes = self.ngram.push(compressed if compressed is not None else ids)+ h = self.w["embed.weight"][torch.tensor(ids)]+ h = h[:, None, :].repeat(1, self.hc, 1)+ pre_mix = torch.zeros(h.shape[0], self.hc)+ pre_mix[:, 0] = 1.0+ shared = self.shared+ for layer in range(self.nlayers):+ if layer in c["engram_layer_ids"]:+ which = c["engram_layer_ids"].index(layer)+ h = self.engram(layer, h, hashes[:, which, :])+ residual = h+ attn_pre, attn_post, attn_comb = self.hc_mixes(h, "attn", layer)+ y = (pre_mix[..., None] * h).sum(dim=1)+ y = rms_norm(y, self.w[f"layers.{layer}.attn_norm.weight"], c["norm_eps"])+ y = self.attention(layer, y, start_pos, shared)+ h = attn_post[..., None] * y[:, None, :] + hc_combine(attn_comb, residual)++ residual = h+ ffn_pre, ffn_post, ffn_comb = self.hc_mixes(h, "ffn", layer)+ y = (attn_pre[..., None] * h).sum(dim=1)+ y = rms_norm(y, self.w[f"layers.{layer}.ffn_norm.weight"], c["norm_eps"])+ y = self.moe(layer, y)+ h = ffn_post[..., None] * y[:, None, :] + hc_combine(ffn_comb, residual)+ pre_mix = ffn_pre+ h = (pre_mix[..., None] * h).sum(dim=1)+ h = rms_norm(h, self.w["norm.weight"], c["norm_eps"])+ self.pos += len(ids)+ return (h[-1:] @ self.w["head.weight"].T)[0]+++def hc_combine(comb: torch.Tensor, residual: torch.Tensor) -> torch.Tensor:+ """out[j] = sum_i comb[i, j] * residual[i], the mix model.py Block.hc_post applies.++ The summed axis is comb's FIRST index. Written out rather than left to broadcasting:+ with the batch axis dropped, `comb[..., None] * residual[:, None]` lines comb's+ SECOND index up with the residual copies and sums the transpose -- which is what+ this reference did until the C engine disagreed with it, and the C engine was right.+ """+ return torch.einsum("nij,nid->njd", comb, residual)+++def window_topk_idxs(window_size: int, seqlen: int, start_pos: int) -> torch.Tensor:+ """model.py get_window_topk_idxs, one batch."""+ if start_pos == 0:+ end = torch.arange(seqlen).unsqueeze(1)+ idxs = (end - window_size + 1).clamp(0) + torch.arange(min(seqlen, window_size))+ return torch.where(idxs > end, torch.tensor(-1), idxs).int()+ oldest = start_pos % window_size + 1+ idxs = torch.cat([torch.arange(oldest, window_size), torch.arange(oldest)])+ return torch.where(idxs > start_pos, torch.tensor(-1), idxs).int().unsqueeze(0)+++def select_candidate_blocks(logits, compress_lens, topk_blocks, block_size):+ """model.py select_candidate_blocks, one batch."""+ width = logits.shape[-1]+ pad = (-width) % block_size+ scores = F.pad(logits, (0, pad), value=-float("inf"))+ scores = scores.reshape(*scores.shape[:-1], -1, block_size).amax(dim=-1)+ num_blocks = scores.shape[-1]+ last = (compress_lens - 1) // block_size+ scores = scores.masked_fill(torch.arange(num_blocks) == last, float("inf"))+ top = scores.topk(min(topk_blocks, num_blocks), dim=-1)+ keep = torch.zeros_like(scores, dtype=torch.bool).scatter_(-1, top.indices, top.values > -float("inf"))+ return keep.repeat_interleave(block_size, dim=-1)[..., :width]+++# -------------------------------------------------------------------- vision+++def vision_cos_sin(n_h: int, n_w: int, dim: int, theta: float):+ """vision.py get_vision_cos_sin: 2D RoPE over the patch grid, one row per patch."""+ inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))+ hpos = torch.arange(n_h).unsqueeze(1).expand(n_h, n_w)+ wpos = torch.arange(n_w).unsqueeze(0).expand(n_h, n_w)+ freqs = torch.stack([hpos, wpos], dim=-1).reshape(-1, 2, 1).float() * inv_freq+ freqs = freqs.flatten(1)+ return freqs.cos(), freqs.sin()+++def vision_rotary(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:+ """vision.py apply_rotary: the SPLIT-HALF convention, not the interleaved pairs the+ language model uses. x is [n, heads, head_dim] and cos/sin are [n, head_dim/2]."""+ x1, x2 = x.float().chunk(2, dim=-1)+ cos = cos.unsqueeze(1)+ sin = sin.unsqueeze(1)+ return torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin], dim=-1)+++class RefVision:+ """vision.py ViT + Aligner: a full-attention tower over one image, then a 3x3+ downsample into the language model's width."""++ def __init__(self, cfg: dict, w: dict):+ self.c = cfg+ self.w = w++ def forward(self, patches: torch.Tensor, n_h: int, n_w: int) -> torch.Tensor:+ c = self.c+ dim, heads = c["vision_dim"], c["vision_n_heads"]+ head_dim = dim // heads+ w = self.w+ x = patches.reshape(patches.shape[0], -1) @ w["vision.patch_embed.proj.weight"].T \+ + w["vision.patch_embed.proj.bias"]+ cos, sin = vision_cos_sin(n_h, n_w, head_dim // 2, c["vision_rope_theta"])+ for layer in range(c["vision_n_layers"]):+ p = f"vision.blocks.{layer}."+ h = rms_norm(x, w[p + "norm1.weight"], 1e-6)+ qkv = h @ w[p + "attn.wqkv.weight"].T + w[p + "attn.wqkv.bias"]+ q, k, v = qkv.chunk(3, dim=-1)+ n = x.shape[0]+ q = vision_rotary(q.reshape(n, heads, head_dim), cos, sin)+ k = vision_rotary(k.reshape(n, heads, head_dim), cos, sin)+ v = v.reshape(n, heads, head_dim).float()+ scores = torch.einsum("qhd,khd->hqk", q, k) / head_dim**0.5+ attended = torch.einsum("hqk,khd->qhd", scores.softmax(dim=-1), v)+ x = x + (attended.reshape(n, dim) @ w[p + "attn.wo.weight"].T + w[p + "attn.wo.bias"])+ h = rms_norm(x, w[p + "norm2.weight"], 1e-6)+ gate, up = (h @ w[p + "mlp.w1.weight"].T).chunk(2, dim=-1)+ x = x + (F.silu(gate) * up) @ w[p + "mlp.w2.weight"].T+ x = rms_norm(x, w["vision.norm.weight"], 1e-6)+ return self.align(x, n_h, n_w)++ def align(self, x: torch.Tensor, n_h: int, n_w: int) -> torch.Tensor:+ """vision.py Aligner.forward: pad the grid to a multiple of the ratio, take+ ratio x ratio blocks, and project. F.unfold orders a block channel-major, which+ is the detail the C side has to get right."""+ c = self.c+ ratio = c["vision_downsample_ratio"]+ grid = x.reshape(n_h, n_w, -1).permute(2, 0, 1)+ grid = F.pad(grid, (0, -n_w % ratio, 0, -n_h % ratio))+ blocks = F.unfold(grid.unsqueeze(0), ratio, stride=ratio).squeeze(0).transpose(0, 1)+ hidden = blocks @ self.w["aligner.w1.weight"].T + self.w["aligner.w1.bias"]+ return F.gelu(hidden) @ self.w["aligner.w2.weight"].T + self.w["aligner.w2.bias"]diff --git a/c/tools/make_dsv41_tiny.py b/c/tools/make_dsv41_tiny.pynew file mode 100644index 00000000..c532be8e--- /dev/null+++ b/c/tools/make_dsv41_tiny.py@@ -0,0 +1,415 @@+#!/usr/bin/env python3+"""Build a tiny DeepSeek-V4.1-Flash-shaped container plus a token-exact reference.++Same layout as the released checkpoint -- the same tensor names, the same dtypes, the+same fp8/fp4 block-scale conventions -- at toy dimensions, so the C engine reads the+real format and every mechanism is exercised:++ hyper-connections (hc_mult copies + Sinkhorn), sliding-window attention with an+ attention sink, compressed KV shared from source layers, the two-level DSA indexer+ with candidate blocks, engram n-gram memory, fp4 routed experts with a shared expert,+ sqrtsoftplus routing with the noaux_tc bias.++The reference (`dsv41_ref.RefModel`) is torch on the CPU: the vendor's own forward pass+goes through tilelang JIT kernels that need a GPU, so it cannot run here and cannot be+the oracle. What this file guarantees is that the C engine reproduces THIS reference+token for token, and that the reference is the vendor's math transcribed with its own+lines quoted where they could drift.++ python3 tools/make_dsv41_tiny.py --out dsv41_tiny --emit-ref dsv41_tiny/ref.json+"""+from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path++import torch+from safetensors.torch import save_file++sys.path.insert(0, str(Path(__file__).resolve().parent))+import dsv41_ref as R # noqa: E402++SEED = 20260910+++def tiny_config() -> dict:+ """Toy shapes, real structure. Every dimension a quantizer touches is a multiple of+ 32 because both block layouts (fp8 32x32, fp4 row groups of 32) require it, exactly+ as the released shapes do."""+ return dict(+ vocab_size=256,+ dim=128,+ moe_inter_dim=64,+ n_layers=6,+ n_heads=4,+ head_dim=64,+ rope_head_dim=16,+ q_lora_rank=64,+ o_lora_rank=32,+ o_groups=2,+ norm_eps=1e-20,+ n_routed_experts=8,+ n_shared_experts=1,+ n_activated_experts=2,+ score_func="sqrtsoftplus",+ gate_temp=1.0,+ norm_topk_prob=True,+ route_scale=1.5,+ swiglu_limit=10.0,+ window_size=8,+ # one entry per layer: 0 = sliding window only, r = KV compressed r-to-1+ compress_ratios=[0, 2, 2, 1, 1, 0],+ kv_source_layers=[1, 3],+ index_source_layers=[1, 3, 4],+ compress_rope_theta=40000.0,+ original_seq_len=32,+ rope_theta=10000.0,+ rope_factor=16.0,+ beta_fast=32,+ beta_slow=1,+ index_n_heads=4,+ index_head_dim=32,+ index_topk=4,+ # The two-level top-k is on. The candidate source must sit in the same+ # compress-ratio group as the layers that filter with its mask, or the mask is+ # the wrong width: the released config has it at layer 20, first of the ratio-1+ # group (20..39), with 24/28/32/36 as its consumers. Here layer 3 owns the+ # ratio-1 group and layer 4 filters with it.+ candidate_source_layer=3,+ candidate_topk_blocks=2,+ candidate_block_size=2,+ hc_mult=4,+ hc_sinkhorn_iters=20,+ hc_eps=1e-6,+ engram_layer_ids=[1, 4],+ engram_max_ngram_size=4,+ engram_n_heads=2,+ engram_head_dim=32,+ engram_vocab_size=97,+ engram_pad_id=2,+ max_seq_len=64,+ # the vision tower, at toy dimensions but with the released structure: a+ # full-attention ViT with 2D RoPE, then a ratio x ratio aligner into `dim`+ vision_n_layers=2,+ vision_dim=64,+ vision_n_heads=2,+ vision_inter_dim=96,+ vision_patch_size=4,+ vision_rope_theta=10000.0,+ vision_downsample_ratio=3,+ vision_max_n_token=64,+ image_token_id=255,+ )+++def engram_layout(cfg: dict) -> dict:+ """engram.py EngramLayout + compute_hash_multipliers, resolved to plain arrays.++ Primes and multipliers are computed once here and shipped in the container: the+ vendor derives them from sympy and numpy's PCG64 at load time, and neither belongs+ in a C engine. `prepare_dsv41.py` writes the same file for the real checkpoint.+ """+ import numpy as np+ from sympy import isprime++ seen: set[int] = set()+ primes, offsets, nrows = [], [], []+ for _ in cfg["engram_layer_ids"]:+ per_layer, flat = [], []+ for _ in range(cfg["engram_max_ngram_size"] - 1):+ row, candidate = [], cfg["engram_vocab_size"] - 1+ for _ in range(cfg["engram_n_heads"]):+ candidate += 1+ while not isprime(candidate) or candidate in seen:+ candidate += 1+ seen.add(candidate)+ row.append(candidate)+ per_layer.append(row)+ flat.extend(row)+ primes.append(per_layer)+ offsets.append(list(np.cumsum([0, *flat[:-1]])))+ nrows.append(int(sum(flat)))+ multipliers = []+ for layer_id in cfg["engram_layer_ids"]:+ rng = np.random.default_rng(10007 * layer_id)+ values = rng.integers(+ low=0,+ high=max(1, (np.iinfo(np.int64).max // cfg["engram_compressed_vocab_size"]) // 2),+ size=(cfg["engram_max_ngram_size"],),+ dtype=np.int64,+ )+ multipliers.append([int(v) * 2 + 1 for v in values])+ return dict(primes=primes, offsets=[[int(o) for o in row] for row in offsets],+ multipliers=multipliers, num_embeddings=nrows)+++def build(out: Path, cfg: dict, ref_path: Path | None, max_new: int, prompt_len: int):+ torch.manual_seed(SEED)+ out.mkdir(parents=True, exist_ok=True)++ # A synthetic "compressed token map": the real one collapses tokens that normalize+ # alike (" The", "the", "THE"), which needs the tokenizer. Here every id maps to+ # itself modulo a smaller vocab, which exercises the same code path in the engine.+ cfg = dict(cfg)+ cfg["engram_compressed_vocab_size"] = 64+ token_map = [i % cfg["engram_compressed_vocab_size"] for i in range(cfg["vocab_size"])]+ layout = engram_layout(cfg)++ tensors: dict[str, torch.Tensor] = {}+ dequant: dict[str, torch.Tensor] = {}++ def bf16(name: str, *shape, scale: float = 0.02):+ t = torch.randn(*shape) * scale+ tensors[name] = t.to(torch.bfloat16)+ dequant[name] = tensors[name].to(torch.float32)++ def f32(name: str, tensor: torch.Tensor):+ tensors[name] = tensor.to(torch.float32)+ dequant[name] = tensors[name].clone()++ def fp8(name: str, rows: int, cols: int, scale: float = 0.02):+ """A dense fp8 weight the way the checkpoint stores it: e4m3 bytes plus one+ ue8m0 exponent per 32x32 tile."""+ w = torch.randn(rows, cols) * scale+ q, s = R.fp8_quant_blocked(w, 32)+ tensors[name] = q+ tensors[name.replace(".weight", ".scale")] = s+ dequant[name] = R.fp8_dequant_blocked(q, s, 32)++ def fp4(name: str, rows: int, cols: int, scale: float = 0.05):+ w = torch.randn(rows, cols) * scale+ packed, s = R.fp4_quant_rowgroups(w, 32)+ tensors[name] = packed.view(torch.int8)+ tensors[name.replace(".weight", ".scale")] = s+ dequant[name] = R.fp4_dequant_rowgroups(packed, s, cols, 32)++ dim, hc = cfg["dim"], cfg["hc_mult"]+ hd, rd, nh = cfg["head_dim"], cfg["rope_head_dim"], cfg["n_heads"]+ bf16("embed.weight", cfg["vocab_size"], dim, scale=0.05)+ bf16("head.weight", cfg["vocab_size"], dim, scale=0.05)+ bf16("norm.weight", dim, scale=0.0)+ dequant["norm.weight"] = dequant["norm.weight"] + 1.0+ tensors["norm.weight"] = dequant["norm.weight"].to(torch.bfloat16)++ for layer in range(cfg["n_layers"]):+ p = f"layers.{layer}."+ for which in ("attn_norm", "ffn_norm"):+ t = torch.ones(dim) + torch.randn(dim) * 0.01+ tensors[p + which + ".weight"] = t.to(torch.bfloat16)+ dequant[p + which + ".weight"] = tensors[p + which + ".weight"].to(torch.float32)+ # hyper-connections: fp32 in the checkpoint, small so Sinkhorn stays well conditioned+ mix_hc = (2 + hc) * hc+ for which in ("attn", "ffn"):+ f32(p + f"hc_{which}_fn", torch.randn(mix_hc, hc * dim) * 0.01)+ f32(p + f"hc_{which}_base", torch.randn(mix_hc) * 0.1)+ f32(p + f"hc_{which}_scale", torch.ones(3) * 0.5)+ # attention+ f32(p + "attn.attn_sink", torch.randn(nh) * 0.1)+ fp8(p + "attn.wq_a.weight", cfg["q_lora_rank"], dim)+ bf16(p + "attn.q_norm.weight", cfg["q_lora_rank"], scale=0.0)+ dequant[p + "attn.q_norm.weight"] += 1.0+ tensors[p + "attn.q_norm.weight"] = dequant[p + "attn.q_norm.weight"].to(torch.bfloat16)+ fp8(p + "attn.wq_b.weight", nh * hd, cfg["q_lora_rank"])+ fp8(p + "attn.wkv.weight", hd, dim)+ bf16(p + "attn.kv_norm.weight", hd, scale=0.0)+ dequant[p + "attn.kv_norm.weight"] += 1.0+ tensors[p + "attn.kv_norm.weight"] = dequant[p + "attn.kv_norm.weight"].to(torch.bfloat16)+ fp8(p + "attn.wo_a.weight", cfg["o_groups"] * cfg["o_lora_rank"], nh * hd // cfg["o_groups"])+ fp8(p + "attn.wo_b.weight", dim, cfg["o_groups"] * cfg["o_lora_rank"])+ if layer in cfg["kv_source_layers"]:+ # the compressor stays bf16/fp32 in the checkpoint: its pooling runs in fp32+ bf16(p + "attn.compressor.wkv.weight", hd, dim)+ bf16(p + "attn.compressor.norm.weight", hd, scale=0.0)+ dequant[p + "attn.compressor.norm.weight"] += 1.0+ tensors[p + "attn.compressor.norm.weight"] = dequant[p + "attn.compressor.norm.weight"].to(torch.bfloat16)+ if cfg["compress_ratios"][layer] > 1:+ bf16(p + "attn.compressor.wgate.weight", hd, dim)+ if layer in cfg["index_source_layers"]:+ fp8(p + "attn.indexer.wq_b.weight", cfg["index_n_heads"] * cfg["index_head_dim"], cfg["q_lora_rank"])+ bf16(p + "attn.indexer.weights_proj.weight", cfg["index_n_heads"], dim)+ if layer in cfg["kv_source_layers"]:+ bf16(p + "attn.indexer.wk.weight", cfg["index_head_dim"], hd)+ bf16(p + "attn.indexer.k_norm.weight", cfg["index_head_dim"], scale=0.0)+ dequant[p + "attn.indexer.k_norm.weight"] += 1.0+ tensors[p + "attn.indexer.k_norm.weight"] = dequant[p + "attn.indexer.k_norm.weight"].to(torch.bfloat16)+ # MoE+ bf16(p + "ffn.gate.weight", cfg["n_routed_experts"], dim, scale=0.05)+ f32(p + "ffn.gate.bias", torch.randn(cfg["n_routed_experts"]) * 0.1)+ for e in range(cfg["n_routed_experts"]):+ q = p + f"ffn.experts.{e}."+ fp4(q + "w1.weight", cfg["moe_inter_dim"], dim)+ fp4(q + "w3.weight", cfg["moe_inter_dim"], dim)+ fp4(q + "w2.weight", dim, cfg["moe_inter_dim"])+ s = p + "ffn.shared_experts."+ fp8(s + "w1.weight", cfg["moe_inter_dim"], dim)+ fp8(s + "w3.weight", cfg["moe_inter_dim"], dim)+ fp8(s + "w2.weight", dim, cfg["moe_inter_dim"])+ # engram+ if layer in cfg["engram_layer_ids"]:+ which = cfg["engram_layer_ids"].index(layer)+ rows = layout["num_embeddings"][which]+ table = torch.randn(rows, cfg["engram_head_dim"]) * 0.05+ q, sc = R.fp8_quant_rowgroups(table, 32)+ tensors[p + "engram.embed.weight"] = q+ tensors[p + "engram.embed.scale"] = sc+ dequant[p + "engram.embed.weight"] = R.fp8_dequant_rowgroups(q, sc, 32)+ n_hash_cols = (cfg["engram_max_ngram_size"] - 1) * cfg["engram_n_heads"]+ fp8(p + "engram.wkv.weight", dim * (hc + 1), n_hash_cols * cfg["engram_head_dim"])+ f32(p + "engram.q_weight", torch.ones(hc, dim) + torch.randn(hc, dim) * 0.05)+ f32(p + "engram.k_weight", torch.ones(hc, dim) + torch.randn(hc, dim) * 0.05)++ # --- vision tower ---------------------------------------------------------+ vdim, vheads, vinter = cfg["vision_dim"], cfg["vision_n_heads"], cfg["vision_inter_dim"]+ patch_in = 3 * cfg["vision_patch_size"] ** 2+ bf16("vision.patch_embed.proj.weight", vdim, patch_in)+ bf16("vision.patch_embed.proj.bias", vdim, scale=0.01)+ for layer in range(cfg["vision_n_layers"]):+ p = f"vision.blocks.{layer}."+ for which in ("norm1", "norm2"):+ t = torch.ones(vdim) + torch.randn(vdim) * 0.01+ tensors[p + which + ".weight"] = t.to(torch.bfloat16)+ dequant[p + which + ".weight"] = tensors[p + which + ".weight"].to(torch.float32)+ bf16(p + "attn.wqkv.weight", 3 * vdim, vdim)+ bf16(p + "attn.wqkv.bias", 3 * vdim, scale=0.01)+ bf16(p + "attn.wo.weight", vdim, vdim)+ bf16(p + "attn.wo.bias", vdim, scale=0.01)+ bf16(p + "mlp.w1.weight", 2 * vinter, vdim)+ bf16(p + "mlp.w2.weight", vdim, vinter)+ t = torch.ones(vdim) + torch.randn(vdim) * 0.01+ tensors["vision.norm.weight"] = t.to(torch.bfloat16)+ dequant["vision.norm.weight"] = tensors["vision.norm.weight"].to(torch.float32)+ ratio = cfg["vision_downsample_ratio"]+ bf16("aligner.w1.weight", dim, vdim * ratio * ratio)+ bf16("aligner.w1.bias", dim, scale=0.01)+ bf16("aligner.w2.weight", dim, dim)+ bf16("aligner.w2.bias", dim, scale=0.01)+ for name in ("image_start", "image_end", "image_newline"):+ bf16(name, dim, scale=0.05)++ save_file(tensors, str(out / "model.safetensors"))++ # config.json in the released shape: everything under text_config, vision absent+ text = {k: v for k, v in cfg.items() if k not in ("max_seq_len",)}+ config = {+ "architectures": ["DeepseekV41ForCausalLM"],+ "model_type": "deepseek_v41",+ "dtype": "bfloat16",+ "quantization_config": {"quant_method": "fp8", "activation_scheme": "dynamic",+ "weight_block_size": [32, 32], "scale_fmt": "ue8m0",+ "expert_dtype": "fp4"},+ "vision_config": {+ "model_type": "deepseek_v41_vision",+ "num_hidden_layers": cfg["vision_n_layers"],+ "hidden_size": cfg["vision_dim"],+ "num_attention_heads": cfg["vision_n_heads"],+ "intermediate_size": cfg["vision_inter_dim"],+ "patch_size": cfg["vision_patch_size"],+ "rope_theta": cfg["vision_rope_theta"],+ "downsample_ratio": cfg["vision_downsample_ratio"],+ "max_image_tokens": cfg["vision_max_n_token"],+ },+ "image_token_id": cfg["image_token_id"],+ "text_config": dict(text, model_type="deepseek_v41_text",+ hidden_size=cfg["dim"],+ num_hidden_layers=cfg["n_layers"],+ num_attention_heads=cfg["n_heads"],+ moe_intermediate_size=cfg["moe_inter_dim"],+ num_experts_per_tok=cfg["n_activated_experts"],+ max_position_embeddings=cfg["max_seq_len"],+ engram_num_embeddings=layout["num_embeddings"],+ engram_compressed_vocab_size=cfg["engram_compressed_vocab_size"],+ # the released config's spellings for the same fields: the+ # engine and the planner read either, and a fixture that+ # only spoke the short names would not exercise the ones a+ # user's checkpoint actually has+ sliding_window=cfg["window_size"],+ kv_source_layer_ids=cfg["kv_source_layers"],+ index_source_layer_ids=cfg["index_source_layers"],+ candidate_source_layer_id=cfg["candidate_source_layer"],+ engram_pad_token_id=cfg["engram_pad_id"]),+ }+ (out / "config.json").write_text(json.dumps(config, indent=2))++ # the engram sidecar: what the engine cannot derive without sympy and a tokenizer+ (out / "dsv41_engram.json").write_text(json.dumps({+ "max_ngram_size": cfg["engram_max_ngram_size"],+ "n_heads": cfg["engram_n_heads"],+ "head_dim": cfg["engram_head_dim"],+ "pad_id": token_map[cfg["engram_pad_id"]],+ "layer_ids": cfg["engram_layer_ids"],+ "num_embeddings": layout["num_embeddings"],+ "primes": layout["primes"],+ "offsets": layout["offsets"],+ # decimal STRINGS, not JSON numbers: a multiplier is bounded only by int64 /+ # compressed_vocab, which for a small vocabulary is past a double's 53-bit+ # mantissa. A JSON reader that stores numbers as doubles would round it, and a+ # rounded multiplier rehashes the whole table into the wrong rows -- silently,+ # because every id it produces is still a valid row.+ "multipliers": [[str(v) for v in row] for row in layout["multipliers"]],+ "token_map": token_map,+ }))++ if ref_path is None:+ return+ ngram = R.NgramHash(+ token_map=torch.tensor(token_map),+ primes=torch.tensor(layout["primes"]),+ offsets=torch.tensor(layout["offsets"]),+ multipliers=torch.tensor(layout["multipliers"]),+ pad_id=token_map[cfg["engram_pad_id"]],+ max_ngram_size=cfg["engram_max_ngram_size"],+ n_heads=cfg["engram_n_heads"],+ )+ model = R.RefModel(cfg, dequant, ngram)+ generator = torch.Generator().manual_seed(SEED + 1)+ prompt = torch.randint(0, cfg["vocab_size"], (prompt_len,), generator=generator).tolist()+ compressed = [token_map[i] for i in prompt]+ logits = model.forward(prompt, compressed)+ ids, out_ids = list(prompt), []+ for _ in range(max_new):+ nxt = int(logits.argmax())+ out_ids.append(nxt)+ ids.append(nxt)+ logits = model.forward([nxt], [token_map[nxt]])+ # the vision tower gets its own reference: a fixed patch grid in, the aligner's+ # rows out. The engine is held to these, so a ViT that drifts fails here rather+ # than as an image that describes itself slightly wrong.+ vision_generator = torch.Generator().manual_seed(SEED + 2)+ n_h, n_w = 4, 5+ patches = torch.randn(n_h * n_w, 3 * cfg["vision_patch_size"] ** 2,+ generator=vision_generator) * 0.5+ aligned = R.RefVision(cfg, dequant).forward(patches, n_h, n_w)+ ref_path.parent.mkdir(parents=True, exist_ok=True)+ ref_path.write_text(json.dumps({+ "model": "dsv41_tiny", "seed": SEED,+ "prompt_ids": prompt, "output_ids": out_ids,+ "full_ids": prompt + out_ids,+ "vision": {+ "grid_h": n_h, "grid_w": n_w,+ "patches": [round(float(v), 6) for v in patches.reshape(-1)],+ "aligned_rows": aligned.shape[0],+ "aligned": [round(float(v), 5) for v in aligned.reshape(-1)],+ },+ }, indent=2))+ print(f"ref -> {ref_path}")+ print(f" prompt {prompt[:8]}... output {out_ids}")+++def main() -> int:+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ ap.add_argument("--out", type=Path, required=True)+ ap.add_argument("--emit-ref", type=Path, default=None)+ ap.add_argument("--max-new", type=int, default=8)+ ap.add_argument("--prompt-len", type=int, default=12)+ args = ap.parse_args()+ cfg = tiny_config()+ build(args.out, cfg, args.emit_ref, args.max_new, args.prompt_len)+ total = sum(p.stat().st_size for p in args.out.iterdir() if p.is_file())+ print(f"container -> {args.out} ({total/1e6:.2f} MB)")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/c/tools/prepare_dsv41.py b/c/tools/prepare_dsv41.pynew file mode 100644index 00000000..ab98d4ee--- /dev/null+++ b/c/tools/prepare_dsv41.py@@ -0,0 +1,152 @@+#!/usr/bin/env python3+"""Write the engram sidecar a DeepSeek-V4.1-Flash container needs, once.++The engine cannot derive these three tables at load time and should not try:++ token_map every token id mapped onto a smaller space where ids that normalize+ alike collapse together, so " The", "the" and "THE" hash the same.+ Needs the checkpoint's own tokenizer and its normalizer chain.+ primes each (n-gram size, head) pair owns a disjoint prime-sized bucket range+ in its layer's table. Needs a primality test.+ multipliers one odd multiplier per (layer, lookback), drawn from numpy's PCG64+ seeded with 10007 * layer_id -- reproducing that generator in C would+ be a liability, and it never changes for a given checkpoint.++All three come straight from the vendor's inference/engram.py; this script is that+code with its results written to disk instead of held in memory.++ python3 tools/prepare_dsv41.py --model ~/Models/DeepSeek-V4.1-Flash++The sidecar lands beside config.json as dsv41_engram.json (about 1 MB for the released+vocabulary) and the container is then complete: nothing else about this model needs+converting, because its dense weights already ship as fp8 and its experts as fp4.+"""+from __future__ import annotations++import argparse+import json+from pathlib import Path+++def build_compressed_token_map(tokenizer):+ """engram.py build_compressed_token_map, unchanged in substance.++ The returned size is not a detail: every hash multiplier is derived from it, so a+ map built with a different normalizer silently rehashes the whole table.+ """+ from tokenizers import Regex, normalizers++ sentinel = "" # a private-use char, so a single-space token survives Strip()+ normalizer = normalizers.Sequence([+ normalizers.NFKC(),+ normalizers.NFD(),+ normalizers.StripAccents(),+ normalizers.Lowercase(),+ normalizers.Replace(Regex(r"[ \t\r\n]+"), " "),+ normalizers.Replace(Regex(r"^ $"), sentinel),+ normalizers.Strip(),+ normalizers.Replace(sentinel, " "),+ ])+ backend = tokenizer.backend_tokenizer if hasattr(tokenizer, "backend_tokenizer") else tokenizer+ size = backend.get_vocab_size(with_added_tokens=True)+ key_to_new: dict[str, int] = {}+ lookup = [0] * size+ for token_id in range(size):+ text = backend.decode([token_id], skip_special_tokens=False)+ if "�" in text:+ key = backend.id_to_token(token_id) # a partial UTF-8 byte token+ else:+ normalized = normalizer.normalize_str(text)+ key = normalized if normalized else text+ new_id = key_to_new.get(key)+ if new_id is None:+ new_id = len(key_to_new)+ key_to_new[key] = new_id+ lookup[token_id] = new_id+ return lookup, len(key_to_new)+++def layout(cfg: dict, compressed_vocab: int) -> dict:+ """engram.py EngramLayout.from_args + compute_hash_multipliers."""+ import numpy as np+ from sympy import isprime++ layer_ids = list(cfg["engram_layer_ids"])+ max_ngram = int(cfg["engram_max_ngram_size"])+ heads = int(cfg["engram_n_heads"])+ seen: set[int] = set()+ primes, offsets, rows = [], [], []+ for _ in layer_ids:+ per_layer, flat = [], []+ for _ in range(max_ngram - 1):+ row, candidate = [], int(cfg["engram_vocab_size"]) - 1+ for _ in range(heads):+ candidate += 1+ while not isprime(candidate) or candidate in seen:+ candidate += 1+ seen.add(candidate)+ row.append(candidate)+ per_layer.append(row)+ flat.extend(row)+ primes.append(per_layer)+ offsets.append([int(v) for v in np.cumsum([0, *flat[:-1]])])+ rows.append(int(sum(flat)))+ bound = max(1, (np.iinfo(np.int64).max // compressed_vocab) // 2)+ multipliers = []+ for layer_id in layer_ids:+ rng = np.random.default_rng(10007 * layer_id)+ values = rng.integers(low=0, high=bound, size=(max_ngram,), dtype=np.int64)+ multipliers.append([str(int(v) * 2 + 1) for v in values])+ return dict(primes=primes, offsets=offsets, multipliers=multipliers, num_embeddings=rows)+++def main() -> int:+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ ap.add_argument("--model", type=Path, required=True, help="the container directory")+ ap.add_argument("--out", type=Path, default=None, help="defaults to <model>/dsv41_engram.json")+ args = ap.parse_args()++ config = json.loads((args.model / "config.json").read_text())+ cfg = config.get("text_config", config)+ if not cfg.get("engram_layer_ids"):+ print("this checkpoint declares no engram layers: nothing to prepare")+ return 0++ from transformers import AutoTokenizer+ tokenizer = AutoTokenizer.from_pretrained(str(args.model), trust_remote_code=True)+ token_map, compressed = build_compressed_token_map(tokenizer)+ declared = int(cfg.get("engram_compressed_vocab_size", compressed))+ if compressed != declared:+ raise SystemExit(+ f"the normalized vocabulary came out at {compressed} ids, the config declares "+ f"{declared}. Every hash multiplier is derived from that number, so the tables "+ f"this would write hash into different rows than the model was trained on. "+ f"Check the tokenizer version rather than overriding this.")++ tables = layout(cfg, compressed)+ for i, rows in enumerate(tables["num_embeddings"]):+ declared_rows = int(cfg["engram_num_embeddings"][i])+ if rows != declared_rows:+ raise SystemExit(f"table {i}: primes sum to {rows} rows, the config declares "+ f"{declared_rows}")+ out = args.out or (args.model / "dsv41_engram.json")+ out.write_text(json.dumps({+ "max_ngram_size": int(cfg["engram_max_ngram_size"]),+ "n_heads": int(cfg["engram_n_heads"]),+ "head_dim": int(cfg["engram_head_dim"]),+ "pad_id": token_map[int(cfg.get("engram_pad_token_id", cfg.get("engram_pad_id", 2)))],+ "layer_ids": list(cfg["engram_layer_ids"]),+ "num_embeddings": tables["num_embeddings"],+ "primes": tables["primes"],+ "offsets": tables["offsets"],+ "multipliers": tables["multipliers"],+ "token_map": token_map,+ }))+ print(f"{out} ({out.stat().st_size/1e6:.2f} MB)")+ print(f" {len(cfg['engram_layer_ids'])} tables, {compressed} compressed ids, "+ f"{tables['num_embeddings']} rows")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())