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): read the expert stream from more than one drive
Gawr Gura 07218eb197e5900e
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex c7842eac..114e9a0e 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -629,6 +629,42 @@ jobs:SNAP=dsv41_tiny ./deepseek_v41 "$cap" dsv41_tiny/ref.jsonecho "::endgroup::"done+ - name: "Multi-SSD mirror and O_DIRECT change nothing about the answer"+ run: |+ cd c+ # A replica answers the same bytes: the same container in a second directory+ # must produce the same token stream, on the primary and through the mirror,+ # with the O_DIRECT window and with the buffered path it replaces. Routing an+ # expert to a drive is an I/O decision and must not be visible downstream.+ mkdir -p dsv41_mirror+ cp dsv41_tiny/model.safetensors dsv41_mirror/+ SNAP=dsv41_tiny ./deepseek_v41 8 dsv41_tiny/ref.json > primary.txt 2>/dev/null+ SNAP=dsv41_tiny COLI_MODEL_MIRROR=dsv41_mirror ./deepseek_v41 8 dsv41_tiny/ref.json > mirror.txt 2>/dev/null+ SNAP=dsv41_tiny COLI_MODEL_MIRROR=dsv41_mirror V41_DIRECT=0 ./deepseek_v41 8 dsv41_tiny/ref.json > buffered.txt 2>/dev/null+ cmp primary.txt mirror.txt+ cmp primary.txt buffered.txt+ # COLI_MODEL_DIRS splits the container as DISTINCT shards -- no second copy,+ # which is the only multi-drive layout most people can build out of a 510 GB+ # checkpoint. The shards move; the answer must not.+ mkdir -p dsv41_split_meta dsv41_split_shard+ cp dsv41_tiny/config.json dsv41_tiny/tokenizer.json dsv41_tiny/dsv41_engram.json dsv41_split_meta/+ cp dsv41_tiny/model.safetensors dsv41_split_shard/+ SNAP=dsv41_split_meta COLI_MODEL_DIRS=dsv41_split_shard ./deepseek_v41 8 dsv41_tiny/ref.json > split.txt 2>split.err+ cmp primary.txt split.txt+ grep -q "\[SPLIT\] model across 2 dir(s)" split.err+ # A copy that is not byte-identical is not a replica: it is refused, and the+ # run stays on the primary rather than reading someone else's offsets.+ mkdir -p dsv41_divergent+ python3 - <<'PY'+ import pathlib+ src = pathlib.Path("dsv41_tiny/model.safetensors")+ data = bytearray(src.read_bytes())+ data[8] ^= 0x01 # inside the safetensors header+ pathlib.Path("dsv41_divergent/model.safetensors").write_bytes(bytes(data))+ PY+ SNAP=dsv41_tiny COLI_MODEL_MIRROR=dsv41_divergent ./deepseek_v41 8 dsv41_tiny/ref.json > divergent.txt 2>divergent.err+ cmp primary.txt divergent.txt+ grep -q "header differs from the primary copy" divergent.err- name: "A prompt longer than one block, so the block boundary is crossed"run: |cd cdiff --git a/c/Makefile b/c/Makefileindex 0d490bc1..aa13d5a2 100644--- a/c/Makefile+++ b/c/Makefile@@ -1289,6 +1289,9 @@ tests/test_compat_mem$(EXE): tests/test_compat_mem.c compat.htests/test_st_missing$(EXE): tests/test_st_missing.c st.h json.h compat.h$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)+tests/test_st_range_rep$(EXE): tests/test_st_range_rep.c st.h json.h compat.h+ $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)+tests/test_tier$(EXE): tests/test_tier.c tier.h$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)diff --git a/c/deepseek_v41.c b/c/deepseek_v41.cindex 172ee5bd..888dd4a2 100644--- a/c/deepseek_v41.c+++ b/c/deepseek_v41.c@@ -683,6 +683,11 @@ static void engram_push(Engram *e, const int *ids, int n, const uint8_t *image)/* -------------------------------------------------------------- model ------ */+/* Six tensors make one expert: three packed weight matrices and their three+ * ue8m0 scale sidecars. expert_read_list emits them in this order and Slot+ * stores one window per part, so both sides can agree through slot_part(). */+#define V41_EXPERT_TENSORS 6+/* 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. */@@ -690,9 +695,28 @@ typedef struct {int eid;uint8_t *w1, *w3, *w2; /* packed nibbles */uint8_t *s1, *s3, *s2; /* ue8m0, one byte per 32-column group */+ /* The window each of those six pointers was carved out of. A tensor sits at+ * an arbitrary file offset, and the O_DIRECT path reads from the enclosing+ * block boundary (st_read_range_rep takes the slack behind the destination+ * for exactly this), so the bytes a slot serves begin some way into their+ * window and the six pointers above are republished from these once the read+ * lands. Only the read path needs the windows. */+ uint8_t *base[V41_EXPERT_TENSORS];uint64_t used;} Slot;+/* The six buffers of a slot, in the order expert_read_list emits them. */+static uint8_t **slot_part(Slot *s, int part) {+ switch (part) {+ case 0: return &s->w1;+ case 1: return &s->s1;+ case 2: return &s->w3;+ case 3: return &s->s3;+ case 4: return &s->w2;+ default: return &s->s2;+ }+}+typedef struct { Slot *slot; int n, cap; } LCache;typedef struct {@@ -884,35 +908,258 @@ static void rms_into(float *out, const float *x, const float *weight, int n, flo/* --------------------------------------------------------- expert cache ---- */-/* One tensor still to fetch: which one, and where it lands. An expert is six of- * these -- three weight matrices and their three scale sidecars. */-typedef struct { char name[160]; uint8_t *dest; int64_t size; } ExpertRead;+/* ---- which drive answers for an expert (multi-SSD mirror) ----------------+ * An expert is what this engine streams: 88.5 GB of them for a 26-token turn on+ * the released checkpoint, so where those bytes come from is most of the engine.+ * Two things move them that the sibling engines already have and this one did+ * not:+ *+ * - COLI_MODEL_MIRROR=<dir>[;<dir>...] registers read-only copies of the+ * checkpoint on other drives. st_mirror_add above accepts a copy only when+ * its size and safetensors header are byte-identical to the primary's, so+ * every data offset matches by construction and each expert can be served+ * by any replica. A partial mirror is legal and a shard it does not carry+ * simply stays on the primary.+ * - the split between replicas follows COLI_DISK_WEIGHTS, or is measured at+ * startup with this engine's own access pattern when that is absent.+ *+ * Two independent drives answer in parallel; one drive split two ways answers no+ * faster than itself, which is why the split is a measurement and not an+ * assumption. */+#define V41_MIR_REPS (1 + ST_MAX_MIR)++static int g_mirror = 0; /* 1 = at least one replica accepted */+static int g_mir_nrep = 1; /* replicas incl. the primary */+static int g_mir_cut[V41_MIR_REPS] = {256}; /* cumulative hash cuts of 256 */+static int g_mir_epl = 384; /* experts per layer, for the hash */+static uint64_t g_mir_bytes[V41_MIR_REPS];+static uint64_t g_mir_nread[V41_MIR_REPS];++/* Replica of one expert. Deterministic: the hash depends on nothing but the+ * expert's identity, so the same expert always lands on the same drive and a+ * drive never caches a copy the next read will not ask it for.+ *+ * Over the FLAT index, not the two ids apart: deepseek_v4.c records why. An XOR+ * of layer and eid spread the full 43x256 grid evenly but clustered the twelve+ * or so experts a decode step actually touches onto one replica; multiplying the+ * flat index by the golden-ratio constant and taking bits 16..23 inherits the+ * uniformity of that index, so hot and cold subsets split alike. */+static inline int expert_route(int layer, int eid) {+ if (!g_mirror) return 0;+ uint32_t h = (uint32_t)(layer * g_mir_epl + eid) * 2654435761u;+ int hv = (int)((h >> 16) & 255), r = 0;+ while (hv >= g_mir_cut[r]) r++; /* cut[nrep-1]==256 terminates the scan */+ return r;+}++/* Measure one replica's read bandwidth. Uses the engine's own pattern -- the+ * depth the expert reader uses, and the O_DIRECT twin when there is one -- over+ * `V41_MIR_PROBE_BLOCKS` blocks of V41_MIR_PROBE_BYTES spread across the largest+ * shard the replica carries. The probe exists only to weight a split; reading+ * through the page cache here would weigh the cache instead of the drive, so it+ * says so when it cannot avoid it. */+#define V41_MIR_PROBE_BYTES (19 << 20)+#define V41_MIR_PROBE_BLOCKS 8++static double mirror_probe_bw(shards *S, int rep) {+ int big = -1;+ int64_t bsz = 0;+ for (int i = 0; i < S->nfd; i++) {+ int fd = st_fd_rep(S, S->fds[i], rep);+ if (fd < 0) continue;+ int64_t sz = lseek(fd, 0, SEEK_END);+ if (sz > bsz) { bsz = sz; big = i; }+ }+ const int64_t blk = V41_MIR_PROBE_BYTES;+ if (big < 0 || bsz < blk * (V41_MIR_PROBE_BLOCKS + 1)) return 0;+ int dfd = st_direct_fd_rep(S, S->fds[big], rep);+ int fd = dfd >= 0 ? dfd : st_fd_rep(S, S->fds[big], rep);+ if (fd < 0) return 0;+ double t0 = now_s();+ int64_t total = 0;+#if defined(_OPENMP)+ #pragma omp parallel for schedule(dynamic, 1) reduction(+:total)+#endif+ for (int i = 0; i < V41_MIR_PROBE_BLOCKS; i++) {+ void *buf = NULL;+ if (posix_memalign(&buf, ST_DIRECT_ALIGN, (size_t)blk) != 0) continue;+ int64_t off = (((bsz - blk) / V41_MIR_PROBE_BLOCKS) * i) & ~(int64_t)(4096 - 1);+ ssize_t r = pread(fd, buf, (size_t)blk, off);+ if (r > 0) total += r;+ compat_aligned_free(buf);+ }+ double dt = now_s() - t0;+ return (dt > 0 && total > 0) ? (double)total / 1e9 / dt : 0;+}++/* Register the replicas and derive the split. Runs after the shard index is+ * open and before the first expert read, so nothing is already cached from the+ * primary by the time the split exists. */+static void mirror_setup(shards *S, const char *model_dir, int experts_per_layer) {+ if (experts_per_layer > 0) g_mir_epl = experts_per_layer;+ const char *dirs = getenv("COLI_MODEL_MIRROR");+ if (!dirs || !*dirs) dirs = getenv("SNAP_MIRROR");+ if (!dirs || !*dirs) return;+ st_mirror_reset(S);+ int nrep = 1;+ char buf[4096];+ snprintf(buf, sizeof(buf), "%s", dirs);+ for (char *p = buf; p && *p; ) {+ char *sep = p;+ while (*sep && *sep != ';' && *sep != ',') sep++;+ int last = (*sep == 0);+ *sep = 0;+ while (*p == ' ') p++;+ size_t len = strlen(p);+ while (len > 0 && p[len - 1] == ' ') p[--len] = 0;+ if (*p) {+ if (model_dir && !strcmp(model_dir, p))+ fprintf(stderr, "[MIRROR] %s equals the model dir β ignored\n", p);+ else if (nrep >= V41_MIR_REPS)+ fprintf(stderr, "[MIRROR] %s: too many mirrors (max %d) β ignored\n", p, ST_MAX_MIR);+ else {+ int nf = st_mirror_add(S, p);+ if (nf <= 0)+ fprintf(stderr, "[MIRROR] %s: no usable shard (missing or divergent "+ "copy) β skipped\n", p);+ else {+ fprintf(stderr, "[MIRROR] %s: %d/%d shards (replica %d)\n",+ p, nf, S->nfd, nrep);+ nrep++;+ }+ }+ }+ p = last ? NULL : sep + 1;+ }+ if (nrep < 2) {+ fprintf(stderr, "[MIRROR] no usable mirror β reading the primary drive only\n");+ return;+ }+ g_mirror = 1; g_mir_nrep = nrep;+ double weight[V41_MIR_REPS];+ int have = 0;+ const char *spec = getenv("COLI_DISK_WEIGHTS");+ const char *how = "COLI_DISK_WEIGHTS";+ if (spec && *spec) {+ char wb[256];+ snprintf(wb, sizeof(wb), "%s", spec);+ int n = 0, bad = 0;+ for (char *tok = strtok(wb, ", "); tok; tok = strtok(NULL, ", ")) {+ double v = atof(tok);+ if (v <= 0 || n >= V41_MIR_REPS) { bad = 1; break; }+ weight[n++] = v;+ }+ if (!bad && n == nrep) have = 1;+ else+ fprintf(stderr, "[MIRROR] invalid COLI_DISK_WEIGHTS '%s' (want %d positive "+ "comma-separated weights, e.g. 9,3) β probing instead\n", spec, nrep);+ }+ if (!have) {+ how = "measured";+ have = 1;+ for (int r = 0; r < nrep; r++) {+ weight[r] = mirror_probe_bw(S, r);+ if (weight[r] <= 0) have = 0;+ }+ if (have) {+ fprintf(stderr, "[MIRROR] probe:");+ for (int r = 0; r < nrep; r++)+ fprintf(stderr, "%s %s %.2f GB/s", r ? " |" : "",+ r ? "mirror" : "primary", weight[r]);+ fprintf(stderr, "\n");+ } else {+ for (int r = 0; r < nrep; r++) weight[r] = 1;+ how = "fallback 1:1 (probe failed)";+ }+ }+ double sum = 0;+ for (int r = 0; r < nrep; r++) sum += weight[r];+ int acc = 0;+ double cum = 0;+ for (int r = 0; r < nrep; r++) {+ cum += weight[r];+ int cut = (int)(256.0 * cum / sum + 0.5);+ if (cut <= acc) cut = acc + 1;+ if (cut > 256) cut = 256;+ g_mir_cut[r] = cut;+ acc = cut;+ }+ fprintf(stderr, "[MIRROR] %d replicas, split %s:", nrep, how);+ for (int r = 0; r < nrep; r++) {+ int share = (r ? g_mir_cut[r] : g_mir_cut[0]) - (r ? g_mir_cut[r - 1] : 0);+ fprintf(stderr, " %s %d%%", r ? "mirror" : "primary", (share * 100 + 128) / 256);+ }+ fprintf(stderr, "\n");+}++/* The per-drive line ENVIRONMENT.md documents ("Per-drive byte counts are+ * reported in a MIRROR: stats line"), in the shape colibri.c prints. Counters+ * are cumulative; passing the values from before a turn reports that turn. On+ * stderr, because stdout carries the serve protocol. */+static void mirror_report(const uint64_t *bytes0, const uint64_t *reads0) {+ if (!g_mirror) return;+ double per[V41_MIR_REPS], total = 0;+ for (int r = 0; r < g_mir_nrep; r++) {+ uint64_t bytes = g_mir_bytes[r] - (bytes0 ? bytes0[r] : 0);+ per[r] = (double)bytes / 1e9;+ total += per[r];+ }+ fprintf(stderr, "MIRROR: primary %.2f GB (%llu reads)", per[0],+ (unsigned long long)(g_mir_nread[0] - (reads0 ? reads0[0] : 0)));+ for (int r = 1; r < g_mir_nrep; r++)+ fprintf(stderr, " | mirror%d %.2f GB (%llu reads)", r, per[r],+ (unsigned long long)(g_mir_nread[r] - (reads0 ? reads0[r] : 0)));+ fprintf(stderr, " β %.0f%% of expert bytes from the mirrors\n",+ total > 0 ? 100.0 * (total - per[0]) / total : 0.0);+}++/* One tensor still to fetch: which tensor, which window it lands in, and which+ * replica answers for it. An expert is six of these -- three weight matrices and+ * their three scale sidecars. */+typedef struct {+ const st_tensor *t; /* resolved once, so a read is a pread and not a hash lookup */+ Slot *slot; /* whose window, and which of the six, to republish after */+ int part;+ int rep;+} ExpertRead;-#define V41_EXPERT_TENSORS 6+/* Bytes one part of an expert occupies, from the config rather than the file:+ * this is the capacity the slot's window was sized for, and the reader refuses a+ * tensor that declares more than that (see expert_fetch). */+static int64_t expert_part_bytes(const Cfg *c, int part) {+ switch (part) {+ case 0: case 2: return (int64_t)c->moe_inter * c->dim / 2; /* w1, w3 */+ case 1: case 3: return (int64_t)c->moe_inter * (c->dim / 32); /* their scales */+ case 4: return (int64_t)c->dim * c->moe_inter / 2; /* w2 */+ default: return (int64_t)c->dim * (c->moe_inter / 32); /* its scale */+ }+}/* Fill in the six reads that make up one expert. Naming them into a list instead* of reading them on the spot is the whole point: the list is what lets a layer's- * misses go to the device together rather than one behind another. */+ * misses go to the device together rather than one behind another. Resolution+ * happens here too, once per miss, so the read itself is a pread through the+ * chosen replica's fd rather than a name lookup followed by a primary-drive one. */static int expert_read_list(Model *m, const char *kind, int layer, int eid, Slot *s,- ExpertRead *out) {- Cfg *c = &m->c;- 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);- 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 },+ int rep, ExpertRead *out) {+ static const struct { const char *suffix; int weight_part, scale_part; } part[3] = {+ { "w1", 0, 1 }, { "w3", 2, 3 }, { "w2", 4, 5 },};+ static const char *const leaf[2] = { "weight", "scale" };+ char name[160];int n = 0;for (int i = 0; i < 3; i++) {- snprintf(out[n].name, sizeof(out[n].name), "%s.%d.ffn.experts.%d.%s.weight",- kind, layer, eid, part[i].suffix);- out[n].dest = part[i].bytes; out[n].size = part[i].size; n++;- snprintf(out[n].name, sizeof(out[n].name), "%s.%d.ffn.experts.%d.%s.scale",- kind, layer, eid, part[i].suffix);- out[n].dest = part[i].scale; out[n].size = part[i].scale_size; n++;+ for (int f = 0; f < 2; f++) {+ snprintf(name, sizeof(name), "%s.%d.ffn.experts.%d.%s.%s",+ kind, layer, eid, part[i].suffix, leaf[f]);+ const st_tensor *t = st_find(&m->S, name);+ if (!t) st_die_missing(&m->S, name);+ out[n].t = t;+ out[n].slot = s;+ out[n].part = f ? part[i].scale_part : part[i].weight_part;+ out[n].rep = rep;+ n++;+ }}return n;}@@ -934,6 +1181,19 @@ static int expert_read_depth(void) {return depth;}+/* O_DIRECT for the expert reads. On by default, as in the V4 engine, because of+ * what an expert read is: each is read once and wanted no longer, the engine+ * tells the kernel so afterwards (drop=1 -> POSIX_FADV_DONTNEED), and a buffered+ * read of it therefore pays for the bytes twice -- once into the page cache and+ * once out of it -- to leave the cache exactly as cold as it was. V41_DIRECT=0+ * restores the buffered path, which is the arm of the A/B and the escape hatch+ * on a device where the direct path turns out to be slower. */+static int expert_direct(void) {+ static int on = -1;+ if (on < 0) on = getenv("V41_DIRECT") ? atoi(getenv("V41_DIRECT")) : 1;+ return on != 0;+}+/* Read `n` reserved experts at once. The slot ids are stamped only after every* read has landed, so a slot never advertises an expert it does not yet hold. */static void expert_fetch(Model *m, const char *kind, int layer,@@ -943,7 +1203,20 @@ static void expert_fetch(Model *m, const char *kind, int layer,ExpertRead *list = xmalloc((size_t)n * V41_EXPERT_TENSORS * sizeof(ExpertRead),"expert read list");for (int i = 0; i < n; i++)- total += expert_read_list(m, kind, layer, eid[i], slot[i], list + total);+ total += expert_read_list(m, kind, layer, eid[i], slot[i],+ expert_route(layer, eid[i]), list + total);+ /* The window is sized from the config, so a container whose tensor declares+ * more than that must not be read into it -- same refusal st_read_raw_cap+ * applied when the read went by name. */+ for (int i = 0; i < total; i++) {+ int64_t cap = expert_part_bytes(&m->c, list[i].part);+ if (list[i].t->nbytes < 0 || list[i].t->nbytes > cap) {+ fprintf(stderr, "%s: expert tensor declares %lld bytes, the slot holds %lld β "+ "refusing (untrusted container)\n", list[i].t->name,+ (long long)list[i].t->nbytes, (long long)cap);+ exit(1);+ }+ }double started = now_s();int threads = expert_read_depth();if (threads > total) threads = total;@@ -952,9 +1225,28 @@ static void expert_fetch(Model *m, const char *kind, int layer,#pragma omp parallel for schedule(dynamic, 1) num_threads(threads) reduction(+:bytes)#endiffor (int i = 0; i < total; i++) {- st_read_raw_cap(&m->S, list[i].name, list[i].dest, list[i].size, 1);- bytes += (uint64_t)list[i].size;- }+ const ExpertRead *r = &list[i];+ int64_t pad = r->t->off % ST_DIRECT_ALIGN;+ /* The payload pointer carries the slack st_read_range_rep needs to read+ * from the enclosing block boundary, so an O_DIRECT transfer lands the+ * data exactly where the slot wants it and nothing is copied afterwards. */+ st_read_range_rep(&m->S, r->t->fd, r->rep, r->t->off, r->t->nbytes,+ r->slot->base[r->part] + pad, r->t->nbytes, 1, expert_direct(),+ "pread expert");+ /* Which drive actually answered. A partial mirror leaves shards on the+ * primary, so the replica the route picked is not always the one that read. */+ int rep = r->rep;+ if (st_fd_rep(&m->S, r->t->fd, rep) < 0) rep = 0;+ __atomic_fetch_add(&g_mir_bytes[rep], (uint64_t)r->t->nbytes, __ATOMIC_RELAXED);+ __atomic_fetch_add(&g_mir_nread[rep], 1, __ATOMIC_RELAXED);+ bytes += (uint64_t)r->t->nbytes;+ }+ /* Publish the payload pointers only now. A slot that advertises an expert has+ * to address that expert, and until the read landed the window base was the+ * only pointer that meant anything. */+ for (int i = 0; i < total; i++)+ *slot_part(list[i].slot, list[i].part) =+ list[i].slot->base[list[i].part] + (list[i].t->off % ST_DIRECT_ALIGN);m->expert_bytes += bytes;m->t_disk += now_s() - started;for (int i = 0; i < n; i++) slot[i]->eid = eid[i];@@ -1088,21 +1380,26 @@ static void spec_load(Model *m, int ecap);* but the experts themselves are the same shape, so the slots are too. */static void cache_init(Model *m, LCache *cache, int ecap) {Cfg *c = &m->c;- 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);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");+ /* One window per tensor, page-aligned and with ST_DIRECT_ALIGN of slack+ * past its payload. The slack is not padding for its own sake: it is what+ * lets st_read_range_rep turn an unaligned safetensors range into one+ * aligned O_DIRECT pread, instead of bouncing every expert through a+ * scratch buffer and copying it again (see the expert reader). */+ for (int part = 0; part < V41_EXPERT_TENSORS; part++) {+ size_t bytes = (size_t)expert_part_bytes(c, part) + ST_DIRECT_ALIGN;+ void *window = NULL;+ if (posix_memalign(&window, ST_DIRECT_ALIGN, bytes) != 0) {+ fprintf(stderr, "OOM allocating expert window (%zu bytes)\n", bytes);+ exit(1);+ }+ s->base[part] = window;+ *slot_part(s, part) = window; /* until the first read republishes it */+ }}}@@ -1112,7 +1409,19 @@ static void model_load(Model *m, const char *snap, int ecap, int engram_cache_roCfg *c = &m->c;cfg_load(c, snap);attn_project_check(c);- st_init(&m->S, snap);+ /* COLI_MODEL_DIRS: the container split across drives as DISTINCT shards, so+ * the 510 GB this engine streams can live on two drives of ~256 GB instead+ * of one of 512 -- which is the configuration most people can actually+ * build, and it needs no second copy. The mirror below is the other half of+ * the same idea: that one duplicates the bytes and splits the reads, this+ * one splits the bytes and reads each shard from the one drive holding it.+ * They compose: a mirror dir may copy any subset of the split's shards. */+ const char *extra_dirs = getenv("COLI_MODEL_DIRS");+ st_init_multi(&m->S, snap, (extra_dirs && *extra_dirs) ? extra_dirs : NULL);+ /* DUAL-SSD: register COLI_MODEL_MIRROR copies and settle the read split+ * before the first expert read, so nothing has been pulled from the primary+ * by the time the replicas exist. */+ mirror_setup(&m->S, snap, c->n_routed);engram_load_sidecar(&m->engram, snap);int dim = c->dim, hd = c->head_dim, nh = c->n_heads, hc = c->hc_mult;@@ -3149,6 +3458,11 @@ static void serve_loop(Model *m, Tok *tokenizer, const char *snap) {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;uint64_t ebytes0 = m->expert_bytes;+ uint64_t mir_bytes0[V41_MIR_REPS], mir_reads0[V41_MIR_REPS];+ for (int r = 0; r < V41_MIR_REPS; r++) {+ mir_bytes0[r] = g_mir_bytes[r];+ mir_reads0[r] = g_mir_nread[r];+ }model_reset(m);int n_prompt = tok_encode(tokenizer, (const char *)command.payload,(int)command.payload_bytes, ids, c->max_positions);@@ -3297,6 +3611,11 @@ static void serve_loop(Model *m, Tok *tokenizer, const char *snap) {(unsigned long long)(m->miss - miss0), turn_bytes / 1e6, seconds,seconds > 0 ? turn_bytes / 1e9 / seconds : 0.0,prefill_bytes / 1e6, prefill_disk, prefill_expert, prefill_wall);+ /* Which drive answered, per turn. The split is the whole point of a+ * mirror and the only honest way to check it is to count: a replica+ * that was registered but never read from would look like a win in+ * every number except the one that matters. */+ if (turn_bytes) mirror_report(mir_bytes0, mir_reads0);}if (stats && m->spec.active && m->spec.proposed > proposed0)fprintf(stderr, "[v41] DSpark: %llu of %llu drafts accepted this turn\n",@@ -3517,6 +3836,7 @@ int main(int argc, char **argv) {"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);+ mirror_report(NULL, NULL);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, "diff --git a/c/st.h b/c/st.hindex dd6939bf..9a21ba47 100644--- a/c/st.h+++ b/c/st.h@@ -1100,6 +1100,90 @@ static void st_read_range_raw_cap(shards *S, int fd, int64_t off,if(drop&&nbytes>0)posix_fadvise(fd,off,nbytes,POSIX_FADV_DONTNEED);}+/* ---- replica-aware range read (multi-SSD streaming) ---------------------+ * st_read_range_raw_cap serves the range from the primary copy and leaves the+ * bytes in the page cache on the way through. An engine that streams large+ * expert tensors wants two more things, and the mirror machinery above already+ * knows where to find them:+ *+ * - the range served by replica `rep` (0 = primary, 1..nrep = mirrors), so+ * independent drives can answer together instead of one behind another;+ * - that replica's O_DIRECT twin, because a large transient read that is+ * copied into the page cache and out again pays for the same bytes twice,+ * and an engine that reads them once does not want them cached at all.+ *+ * O_DIRECT constrains buffer address, file offset and length to the logical+ * block size, and a safetensors range starts wherever the writer put it. The+ * obvious fix -- bounce the range through an aligned scratch buffer -- adds one+ * full copy of every expert byte to a workload where the disk is the point, so+ * this instead expects the caller to reserve `off % ST_DIRECT_ALIGN` bytes of+ * scratch BEHIND the destination and hand over the payload pointer. The window+ * starting at the enclosing block boundary is then already aligned: one+ * O_DIRECT pread carries the block-aligned bulk, one short buffered pread+ * carries the sub-block tail, and the payload lands exactly where the caller+ * asked for it with nothing to copy afterwards.+ *+ * ST_DIRECT_ALIGN is the slack a caller must add to each such buffer. The+ * alignment is verified rather than assumed, and a caller that did not reserve+ * the prefix -- or a platform with no O_DIRECT, or a replica without a twin --+ * silently gets the buffered path. `direct` is the caller's own switch: 0 forces+ * that path everywhere, which is what an engine exposes so the choice can be+ * A/B'd on the hardware in front of it rather than argued about. */+#define ST_DIRECT_ALIGN 4096++/* One aligned pread, EINTR retried. Returns 0 only on a full transfer: O_DIRECT+ * wants a block-aligned length, so a short read cannot be finished by simply+ * asking for the rest -- the caller falls back to the buffered path instead. */+static int st_pread_aligned_try(int fd, void *buf, int64_t n, int64_t off) {+ for (;;) {+ ssize_t r = pread(fd, buf, (size_t)n, (off_t)off);+ if (r == n) return 0;+ if (r < 0 && errno == EINTR) continue;+ return -1;+ }+}++static void st_read_range_rep(shards *S, int fd, int rep, int64_t off, int64_t nbytes,+ void *out, int64_t cap, int drop, int direct,+ const char *tag) {+ int fidx = S ? st_fidx(S, fd) : -1;+ if (fidx < 0) { fprintf(stderr, "replica range uses an unindexed shard fd\n"); exit(1); }+ if (off < 0 || nbytes < 0 || cap < 0 || nbytes > cap ||+ off > S->sizes[fidx] || nbytes > S->sizes[fidx] - off ||+ (uint64_t)nbytes > SIZE_MAX) {+ fprintf(stderr, "replica range [%lld,+%lld) exceeds file/destination bounds "+ "(file %lld, cap %lld) β refusing (untrusted container)\n",+ (long long)off, (long long)nbytes, (long long)S->sizes[fidx], (long long)cap);+ exit(1);+ }+ if (nbytes == 0) return;+ if (!out) { fprintf(stderr, "replica range has a NULL destination\n"); exit(1); }+ const char *label = tag && *tag ? tag : "pread replica range";+ /* A partial mirror leaves this shard on the primary; so does a replica index+ * that no longer exists. Either way the read is valid, just not split. */+ int rfd = st_fd_rep(S, fd, rep);+ if (rfd < 0) { rfd = fd; rep = 0; }+ int64_t pad = off % ST_DIRECT_ALIGN;+ uint8_t *window = (uint8_t *)out - pad; /* the caller's reserved scratch */+ int dfd = direct ? st_direct_fd_rep(S, fd, rep) : -1;+ if (dfd >= 0 && ((uintptr_t)window & (uintptr_t)(ST_DIRECT_ALIGN - 1)) == 0 &&+ pad + nbytes <= (int64_t)ST_PREAD_CHUNK) {+ int64_t want = pad + nbytes; /* bytes to fill, window-relative */+ int64_t left = S->sizes[fidx] - (off - pad);+ int64_t bulk = want & ~(int64_t)(ST_DIRECT_ALIGN - 1);+ if (bulk > left) bulk = left & ~(int64_t)(ST_DIRECT_ALIGN - 1);+ /* A device that refuses O_DIRECT costs the call some speed and never its+ * correctness: the buffered path below reads exactly the same bytes. */+ if (bulk > 0 && st_pread_aligned_try(dfd, window, bulk, off - pad) == 0) {+ int64_t tail = want - bulk;+ if (tail > 0) st_pread_full(rfd, window + bulk, tail, off - pad + bulk, label);+ return;+ }+ }+ st_pread_full(rfd, out, nbytes, off, label);+ if (drop) posix_fadvise(rfd, off, nbytes, POSIX_FADV_DONTNEED);+}+/* Read-only view of one tensor's exact stored bytes. Unlike st_read_raw this* performs no allocation or copy; unlike a naked mmap pointer it carries the* aligned OS view/handle required for cleanup. Callers must still validatediff --git a/c/tests/test_st_range_rep.c b/c/tests/test_st_range_rep.cnew file mode 100644index 00000000..9f175bf1--- /dev/null+++ b/c/tests/test_st_range_rep.c@@ -0,0 +1,167 @@+/* Replica-aware range reads (st_read_range_rep): the O_DIRECT window has to+ * return exactly the bytes a plain read would, from any replica, at any file+ * offset, without ever writing past the caller's payload -- and it has to fall+ * back to the buffered path when the caller did not reserve the scratch the+ * aligned window needs.+ *+ * The safety property is the interesting one. The optimized path reads from the+ * block boundary BELOW the payload, so the bytes before `out` are the caller's+ * scratch and the bytes after `out + nbytes` are a wall it must never cross.+ * The guards below are that wall. */+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#include "../st.h"++#ifdef _WIN32+#include <direct.h>+#define MKDIR(p) _mkdir(p)+#define RMDIR(p) _rmdir(p)+#else+#include <sys/stat.h>+#include <unistd.h>+#define MKDIR(p) mkdir(p, 0777)+#define RMDIR(p) rmdir(p)+#endif++#define CHECK(condition) do { \+ if (!(condition)) { \+ fprintf(stderr, "%s:%d: check failed: %s\n", __FILE__, __LINE__, #condition); \+ return 1; \+ } \+} while (0)++#define DIR_A "tmp_range_a" /* primary */+#define DIR_B "tmp_range_b" /* byte-identical copy, a different "drive" */+#define DIR_C "tmp_range_c" /* same size, divergent header: must be refused */+#define DIR_E "tmp_range_e" /* empty: nothing to add */++/* Payload big enough that a read spans several blocks and still ends on a+ * non-block boundary, so the aligned bulk and the buffered tail both happen. */+#define PAYLOAD_FLOATS 16693+#define PAYLOAD_BYTES (PAYLOAD_FLOATS * 4)++static uint8_t *g_truth;++/* One tensor, F32, occupying the whole payload. The header is padded to an+ * 8-byte multiple by the format, which leaves the data at an offset that is+ * 8-aligned but generally NOT block-aligned -- exactly the case the window math+ * exists for, and one the caller cannot choose. */+static int write_model(const char *dir, int corrupt_header) {+ char hdr[160], path[256];+ int hl = snprintf(hdr, sizeof(hdr),+ "{\"t0\":{\"dtype\":\"F32\",\"shape\":[%d],\"data_offsets\":[0,%d]}}",+ PAYLOAD_FLOATS, PAYLOAD_BYTES);+ if (hl < 0 || hl >= (int)sizeof(hdr)) return -1;+ if (corrupt_header) hdr[hl - 2] = ' ';+ snprintf(path, sizeof(path), "%s/model.safetensors", dir);+ FILE *f = fopen(path, "wb");+ if (!f) { perror(path); return -1; }+ uint64_t n = (uint64_t)hl;+ if (fwrite(&n, 8, 1, f) != 1) { fclose(f); return -1; }+ if (fwrite(hdr, 1, (size_t)hl, f) != (size_t)hl) { fclose(f); return -1; }+ if (fwrite(g_truth, 1, PAYLOAD_BYTES, f) != PAYLOAD_BYTES) { fclose(f); return -1; }+ fclose(f);+ return 0;+}++static void cleanup(void) {+ const char *dirs[] = { DIR_A, DIR_B, DIR_C, DIR_E };+ for (int i = 0; i < 4; i++) {+ char path[256];+ snprintf(path, sizeof(path), "%s/model.safetensors", dirs[i]);+ remove(path);+ RMDIR(dirs[i]);+ }+}++/* Read [off, off+n) through `rep` the way an engine does, and hold the result to+ * the truth plus a wall of guard bytes past the payload. */+static int read_and_check(shards *S, const st_tensor *t, int rep, int64_t off, int64_t n,+ int direct, int reserve_scratch) {+ /* `off` is relative to the tensor's payload; the reader works in file+ * offsets, and the format leaves the payload at an 8-aligned-but-not-+ * block-aligned offset after the header. */+ int64_t file_off = t->off + off;+ size_t slack = reserve_scratch ? ST_DIRECT_ALIGN : 0;+ uint8_t *buf = NULL;+ size_t want = (size_t)n + slack + ST_DIRECT_ALIGN; /* extra tail for the guards */+ if (posix_memalign((void **)&buf, ST_DIRECT_ALIGN, want) != 0) return 1;+ memset(buf, 0xA5, want);+ /* reserve_scratch=0 hands over a page-aligned destination, so `out - pad` is+ * not aligned and the buffered path is the only correct one. */+ uint8_t *out = reserve_scratch ? buf + ST_DIRECT_ALIGN + (file_off % ST_DIRECT_ALIGN)+ : buf + ST_DIRECT_ALIGN;+ int64_t before = out - buf;+ st_read_range_rep(S, S->fds[0], rep, file_off, n, out, n, 1, direct, "range test");+ int bad = memcmp(out, g_truth + off, (size_t)n) != 0;+ for (size_t i = (size_t)before + (size_t)n; i < want; i++)+ if (buf[i] != 0xA5) { bad |= 2; break; }+ if (bad)+ fprintf(stderr, "rep=%d off=%lld n=%lld direct=%d reserve=%d -> %s\n",+ rep, (long long)file_off, (long long)n, direct, reserve_scratch,+ (bad & 1) ? "WRONG BYTES" : "WROTE PAST THE PAYLOAD");+ compat_aligned_free(buf);+ return bad;+}++/* Boundary, sub-block, multi-block and non-block-terminated ranges, plus a+ * window that would run past EOF and must be clamped to it. */+static const struct { int64_t off, len; } g_ranges[] = {+ { 0, 1 }, { 0, 4096 }, { 1, 4095 }, { 7, 8189 },+ { 1000, 10000 }, { 4096, 4096 * 3 + 77 }, { 33333, 20000 },+ { PAYLOAD_BYTES - 1000, 1000 }, /* tail: aligned window crosses EOF */+ { PAYLOAD_BYTES - 4096, 4096 },+ { 65536, 1 },+};++int main(void) {+ cleanup();+ CHECK(MKDIR(DIR_A) == 0 && MKDIR(DIR_B) == 0 && MKDIR(DIR_C) == 0 && MKDIR(DIR_E) == 0);+ g_truth = malloc(PAYLOAD_BYTES);+ CHECK(g_truth != NULL);+ srand(20260914);+ for (int i = 0; i < PAYLOAD_BYTES; i++) g_truth[i] = (uint8_t)(rand() & 0xFF);+ CHECK(write_model(DIR_A, 0) == 0);+ CHECK(write_model(DIR_B, 0) == 0);+ CHECK(write_model(DIR_C, 1) == 0);++ shards S;+ st_init(&S, DIR_A);+ CHECK(S.nfd == 1);+ const st_tensor *t = st_find(&S, "t0");+ CHECK(t != NULL && t->nbytes == PAYLOAD_BYTES);++ const int nranges = (int)(sizeof(g_ranges) / sizeof(g_ranges[0]));+ for (int i = 0; i < nranges; i++)+ for (int direct = 0; direct <= 1; direct++) {+ CHECK(read_and_check(&S, t, 0, g_ranges[i].off, g_ranges[i].len, direct, 1) == 0);+ /* No scratch reserved: the same bytes, through the buffered path. */+ CHECK(read_and_check(&S, t, 0, g_ranges[i].off, g_ranges[i].len, direct, 0) == 0);+ }++ /* A replica answers the same bytes, and one that is not byte-identical is+ * never trusted. */+ CHECK(st_mirror_add(&S, DIR_C) == 0);+ CHECK(st_mirror_add(&S, DIR_E) == 0);+ CHECK(st_mirror_add(&S, DIR_B) == 1);+ CHECK(S.nrep == 1);+ for (int i = 0; i < nranges; i++)+ for (int direct = 0; direct <= 1; direct++)+ CHECK(read_and_check(&S, t, 1, g_ranges[i].off, g_ranges[i].len, direct, 1) == 0);++ /* A replica index that has no copy of this shard is not an error: the read+ * stays on the primary and returns the same bytes. */+ st_mirror_reset(&S);+ CHECK(S.nrep == 0);+ CHECK(read_and_check(&S, t, 1, 1000, 10000, 1, 1) == 0);+ CHECK(read_and_check(&S, t, ST_MAX_MIR - 1, 1000, 10000, 1, 1) == 0);++ st_destroy(&S);+ free(g_truth);+ cleanup();+ printf("test_st_range_rep: ok\n");+ return 0;+}diff --git a/docs/deepseek-v41.md b/docs/deepseek-v41.mdindex 8b396705..acaf11ee 100644--- a/docs/deepseek-v41.md+++ b/docs/deepseek-v41.md@@ -184,6 +184,69 @@ Prefill is where most of it goes: 52.3 GB of the 87.4, because each of the 26 prpositions routes independently and a 49-slot cache cannot hold what 26 positions askof one layer.+### Where the bytes come from, and whether they touch the page cache++Two things move expert bytes that the V4 and GLM engines already had and this one did+not, and both are about the same fact: an expert is read once and never wanted again.++**A second drive.** `COLI_MODEL_MIRROR=<dir>[;<dir>...]` registers read-only copies of+the checkpoint on other drives; experts are split across the primary and every replica,+each drive answering for a deterministic subset. A copy is accepted only when its size+and safetensors header are byte-identical to the primary's, so the data offsets match+by construction and any expert can be served by any replica -- and a copy that is+*not* identical is refused rather than trusted, which is the whole reason the check is+a header compare and not a filename. Partial mirrors are legal: a smaller SSD holding+only the routed-expert shards is the case this exists for, and a shard a replica does+not carry simply stays on the primary.++The split follows `COLI_DISK_WEIGHTS`, or is measured at startup with this engine's own+access pattern. Splitting is the point and also the risk: two independent drives+answer in parallel, but one drive serving two copies of itself answers no faster than+one drive, so the split is a measurement rather than an assumption.++The hash is over the flat expert index. `deepseek_v4.c` records why that matters: an+XOR of layer and expert spread the whole 43x256 grid evenly and still clustered the+dozen experts a decode step actually touches onto one replica. Multiplying the flat+index by the golden-ratio constant and taking bits 16..23 inherits the uniformity of+that index, so a hot subset splits like a cold one.++**Not through the page cache.** The reader already tells the kernel each expert is not+wanted again (`POSIX_FADV_DONTNEED` after the read), which is the honest admission that+a buffered read of it pays for the bytes twice -- once into the cache, once out -- in+order to leave the cache as cold as it was. `V41_DIRECT=1`, the default, reads them+with `O_DIRECT` instead.++There is a second, cheaper way to put the container on more than one drive, and for a+510 GB checkpoint it is the one most people can actually build.+`COLI_MODEL_DIRS=<dir>` names directories holding **distinct** shards -- no+duplication, combined capacity, each shard read from the one drive that has it -- so+the same container can live on two 256 GB drives instead of one 512 GB drive. It is+the same split the GLM, V4 and Kimi K3 engines already accept. It composes with the+mirror: a mirror directory may copy any subset of the split's shards.++The two mechanisms answer different questions. `COLI_MODEL_DIRS` asks whether the+bytes can be *stored* across drives; `COLI_MODEL_MIRROR` asks whether they can be+*read* from more than one place at once. On a host whose decode is not bound by the+device -- which is what a many-core CPU makes of this engine -- the second one buys+very little, and the measurement is in+[the experiment record](experiments/dsv41-expert-io-2026-09-14.md).++That needs the destination and the file offset to be block-aligned, and a safetensors+range starts wherever the writer put it. The obvious fix is to bounce each transfer+through an aligned scratch buffer, and it is the wrong one here: an extra copy of every+expert byte, over a turn that moves 88.5 GB, is most of what the change was for. Each+slot instead keeps its six buffers in page-aligned windows with `ST_DIRECT_ALIGN` of+scratch in front, and `st.h`'s `st_read_range_rep` starts the read at the enclosing+block boundary, carries the block-aligned bulk with one `O_DIRECT` pread and the+sub-block tail with one short buffered pread, and lands the payload exactly where the+slot wants it. Nothing is copied afterwards.++The alignment is verified, not assumed. A destination that was not set up that way --+or a platform without `O_DIRECT`, or a replica whose twin failed to open -- takes the+buffered path, which reads exactly the same bytes. `V41_DIRECT=0` forces it, both as+the other arm of the A/B and as the escape hatch on a device where direct I/O turns+out to be slower.+## Blocks of positions, not one position at a timeEverything above the experts used to run one position at a time, which meant a block@@ -242,6 +305,10 @@ and costs the contention. Anything that tries again has to start from that.|---|---|---|| `V41_STATS` | off | per-turn accounting on stderr: the n-gram cache, the expert bytes and their rate, and how many drafts were accepted. Off by default because `coli chat` shows the engine's stderr next to the answer. || `V41_READ_DEPTH` | 8 | expert tensors read at once when a step misses the cache (see above). `1` restores the serial read the engine used to do, for an A/B. |+| `COLI_MODEL_MIRROR` | unset | `;`/`,`-separated read-only copies of the checkpoint on other drives; expert reads split across the primary and every replica (see above). `SNAP_MIRROR` is the legacy alias. |+| `COLI_MODEL_DIRS` | unset | `;`/`,`-separated directories holding **distinct** shards of the same container, so it can be split across drives with no second copy (see above). |+| `COLI_DISK_WEIGHTS` | unset (startup probe) | the split ratio, one positive weight per drive (`1,1` for an even pair). Unset measures each drive with the engine's own access pattern. |+| `V41_DIRECT` | 1 | read experts with `O_DIRECT` instead of through the page cache. `0` is the buffered arm and the escape hatch; the two paths return identical bytes. || `V41_ENGRAM_ROWS` | 65536 | rows of engram cache per table. The traffic is Zipfian: common 2-grams repeat constantly, so a small cache absorbs most of it. 65536 rows is 64 MB per table on the released head_dim. || `V41_INDEX_OWNER` | unset | each layer scores against its own owner's index keys (see above). Changes the model's behaviour. || `V41_MAX_IMAGE_TOKENS` | the checkpoint's `max_image_tokens` | a ceiling on what one image costs in prompt tokens. |