Skip to content

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

C

olmoe: take a prompt's MoE expert by expert, the same bits

Marcello Costagliola794d0c096ec2
diff --git a/c/Makefile b/c/Makefile
index d1ac0f7f..9cd39b67 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -1915,6 +1915,9 @@ tests/test_k3_chat_tools$(EXE): tests/test_k3_chat_tools.c kimi_k3.c $(VK_OBJ)
tests/test_olmoe_matmul_q$(EXE): tests/test_olmoe_matmul_q.c olmoe.c $(VK_OBJ)
$(CC) $(NOCUDA_CFLAGS) $< $(VK_OBJ) -o $@ $(NOCUDA_LDFLAGS)
+tests/test_olmoe_moe_by_expert$(EXE): tests/test_olmoe_moe_by_expert.c olmoe.c $(VK_OBJ)
+ $(CC) $(NOCUDA_CFLAGS) $< $(VK_OBJ) -o $@ $(NOCUDA_LDFLAGS)
+
tests/test_olmoe_serve_framing$(EXE): tests/test_olmoe_serve_framing.c olmoe.c $(VK_OBJ)
$(CC) $(NOCUDA_CFLAGS) $< $(VK_OBJ) -o $@ $(NOCUDA_LDFLAGS)
diff --git a/c/olmoe.c b/c/olmoe.c
index ebd5a6f8..98c5395a 100644
--- a/c/olmoe.c
+++ b/c/olmoe.c
@@ -435,6 +435,18 @@ static inline void matmul_q_reset_for_test(void) { matmul_q_idot_force = -1; }
#include "fused_simd.h" /* FUSED3=1: quant_x_q8_avx2 + matmul_q_idot{,_pair}_v3 (bit-exact) */
#endif
+#if defined(HAVE_FAST_DOT_I8)
+/* IDOT, read once (see matmul_q below for why it is opt-in) */
+static int matmul_q_idot(void) {
+ static int idot = -1;
+ if (idot < 0) { const char *e = getenv("IDOT"); idot = (e && *e == '1'); }
+#ifdef OLMOE_TESTING
+ if (matmul_q_idot_force >= 0) idot = matmul_q_idot_force;
+#endif
+ return idot;
+}
+#endif
+
static void matmul_q(float *y, const float *x, const int8_t *q, const float *scale, int I, int O) {
#if defined(HAVE_FAST_DOT_I8)
/* IDOT is OPT-IN. It quantizes the ACTIVATIONS to Q8_0 per 16-block (below),
@@ -450,12 +462,7 @@ static void matmul_q(float *y, const float *x, const int8_t *q, const float *sca
* nats/token on GLM, which is why GLM keeps q/k/v off IDOT). On AVX2-only
* hardware it is also not faster: 11.01 vs 10.67 tok/s measured on an
* i5-9600K, n=4 interleaved. Set IDOT=1 to opt in knowingly. */
- static int idot = -1;
- if (idot < 0) { const char *e = getenv("IDOT"); idot = (e && *e == '1'); }
-#ifdef OLMOE_TESTING
- if (matmul_q_idot_force >= 0) idot = matmul_q_idot_force;
-#endif
- if (idot && I % 16 == 0 && I <= 4096) {
+ if (matmul_q_idot() && I % 16 == 0 && I <= 4096) {
int nb = I / 16; int8_t xi[4096]; float xs[256];
for (int b = 0; b < nb; b++) {
const float *xb = x + b*16;
@@ -484,6 +491,32 @@ static void matmul_q(float *y, const float *x, const int8_t *q, const float *sca
}
}
+/* matmul_q on n rows against one matrix: y[t] = matmul_q(x[t]) for t < n, the
+ * same bits (each element is the loop above, unchanged), but every weight row is
+ * read once for all n rows and the rows share one parallel region. A prompt's
+ * MoE (moe_by_expert) hands it all the rows routed to one expert. The IDOT branch
+ * quantizes each row on its own, so it keeps the one-row call. */
+static void matmul_q_rows(float *const *y, const float *const *x, int n,
+ const int8_t *q, const float *scale, int I, int O) {
+#if defined(HAVE_FAST_DOT_I8)
+ if (matmul_q_idot() && I % 16 == 0 && I <= 4096) {
+ for (int t = 0; t < n; t++) matmul_q(y[t], x[t], q, scale, I, O);
+ return;
+ }
+#endif
+ #pragma omp parallel for schedule(static)
+ for (int o = 0; o < O; o++) {
+ const int8_t *w = q + (int64_t)o * I;
+ for (int t = 0; t < n; t++) {
+ const float *xt = x[t];
+ float acc = 0.f;
+ #pragma omp simd reduction(+:acc)
+ for (int i = 0; i < I; i++) acc += xt[i] * (float)w[i];
+ y[t][o] = acc * scale[o];
+ }
+ }
+}
+
/* rmsnorm su una riga di lunghezza D, in-place su out (out puo' essere == x) */
static void rmsnorm_row(float *out, const float *x, const float *w, int D, float eps) {
@@ -1140,18 +1173,23 @@ static void moe_route_row(Model *m, int layer, int s, float *pr, int *idx, float
if (!m->hot_pinned) rt_route(layer, s, idx, val, K);
}
+#if defined(__AVX2__)
+/* FUSED3: same contract as matmul_q's IDOT fast branch (IDOT env,
+ * dims %16==0, <=4096) — outside it the stock calls run unchanged.
+ * Exact integer arithmetic only: bit-identical output (verified by memcmp
+ * in tests/bench_fused3.c). OFF by default. */
+static int moe_fused3(int D, int I) {
+ static int idot_moe = -1;
+ if (idot_moe < 0) { const char *ie = getenv("IDOT"); idot_moe = !(ie && *ie == '0'); }
+ return g_fused3 && idot_moe && D % 16 == 0 && D <= 4096 && I % 16 == 0 && I <= 4096;
+}
+#endif
/* One routed expert on one row: hh[D] = down(silu(gate(xs)) * up(xs)); g, u are
* scratch of I floats. */
static void moe_expert_row(const Model *m, const Slot *e, const float *xs, float *g, float *u, float *hh) {
const Cfg *c = &m->c; int D = c->hidden, I = c->inter;
#if defined(__AVX2__)
- /* FUSED3: same contract as matmul_q's IDOT fast branch (IDOT env,
- * dims %16==0, <=4096) — outside it the stock calls below run
- * unchanged. Exact integer arithmetic only: bit-identical output
- * (verified by memcmp in tests/bench_fused3.c). OFF by default. */
- static int idot_moe = -1;
- if (idot_moe < 0) { const char *ie = getenv("IDOT"); idot_moe = !(ie && *ie == '0'); }
- if (g_fused3 && idot_moe && D % 16 == 0 && D <= 4096 && I % 16 == 0 && I <= 4096) {
+ if (moe_fused3(D, I)) {
matmul_q_idot_pair_v3(g, u, xs, e->g, e->gs, e->u, e->us, D, I); /* gate+up share one quant of xs */
for (int i = 0; i < I; i++) { float gv = g[i]; g[i] = (gv / (1.f + expf(-gv))) * u[i]; }
matmul_q_idot_v3(hh, g, e->d, e->ds, I, D); /* down_proj [D,I] */
@@ -1164,6 +1202,80 @@ static void moe_expert_row(const Model *m, const Slot *e, const float *xs, float
matmul_q(hh, g, e->d, e->ds, I, D); /* down_proj [D,I] */
}
}
+/* moe_expert_row on n rows of one expert: hh[t] = expert(xs[t]), the same bits;
+ * g[t], u[t] are scratch of I floats each. */
+static void moe_expert_rows(const Model *m, const Slot *e, const float *const *xs, int n,
+ float *const *g, float *const *u, float *const *hh) {
+ const Cfg *c = &m->c; int D = c->hidden, I = c->inter;
+#if defined(__AVX2__)
+ if (moe_fused3(D, I)) {
+ for (int t = 0; t < n; t++) moe_expert_row(m, e, xs[t], g[t], u[t], hh[t]);
+ return;
+ }
+#endif
+ matmul_q_rows(g, xs, n, e->g, e->gs, D, I); /* gate_proj [I,D] */
+ matmul_q_rows(u, xs, n, e->u, e->us, D, I); /* up_proj [I,D] */
+ for (int t = 0; t < n; t++) {
+ float *gt = g[t]; const float *ut = u[t];
+ for (int i = 0; i < I; i++) { float gv = gt[i]; gt[i] = (gv / (1.f + expf(-gv))) * ut[i]; }
+ }
+ matmul_q_rows(hh, (const float *const *)g, n, e->d, e->ds, I, D); /* down_proj [D,I] */
+}
+
+/* A prompt's MoE, expert by expert (S > 1). Per block of OLMOE_PREFILL_ROWS rows:
+ * the rows are routed in order, as the one-row loop routes them; their (row, rank)
+ * pairs are grouped by expert with a counting sort; each expert is fetched once
+ * and multiplies all of its rows (moe_expert_rows) into a row of its own per pair;
+ * then every rank joins its row in rank order, as the one-row loop adds them. So
+ * each expert's weights are read once a block instead of once a row, and the sum's
+ * order, hence the bits, are the one-row loop's. The block's other pairs on an
+ * expert count as hits: they are served by the slot the fetch returned. */
+#define OLMOE_PREFILL_ROWS 128
+static void moe_by_expert(Model *m, int layer, const float *x, int S, float *logits, float *out) {
+ Cfg *c = &m->c; int D = c->hidden, E = c->n_experts, K = c->topk, I = c->inter;
+ int B = S < OLMOE_PREFILL_ROWS ? S : OLMOE_PREFILL_ROWS, P = B * K;
+ int *idx = malloc((size_t)P * sizeof(int)), *pair = malloc((size_t)P * sizeof(int));
+ int *at = malloc(((size_t)E + 1) * sizeof(int));
+ float *val = malloc((size_t)P * sizeof(float));
+ const float **xs = malloc((size_t)B * sizeof(*xs));
+ float **gp = malloc((size_t)B * sizeof(*gp)), **up = malloc((size_t)B * sizeof(*up));
+ float **hp = malloc((size_t)B * sizeof(*hp));
+ float *g = falloc((int64_t)B * I), *u = falloc((int64_t)B * I), *ctb = falloc((int64_t)P * D);
+ if (!idx || !pair || !at || !val || !xs || !gp || !up || !hp) { fprintf(stderr, "OOM moe_by_expert\n"); exit(1); }
+ for (int t = 0; t < B; t++) { gp[t] = g + (int64_t)t * I; up[t] = u + (int64_t)t * I; }
+ for (int s0 = 0; s0 < S; s0 += B) {
+ int rows = S - s0 < B ? S - s0 : B, n = rows * K;
+ for (int s = 0; s < rows; s++)
+ moe_route_row(m, layer, s0 + s, logits + (int64_t)(s0 + s) * E, idx + (int64_t)s * K, val + (int64_t)s * K);
+ memset(at, 0, ((size_t)E + 1) * sizeof(int));
+ for (int i = 0; i < n; i++) at[idx[i] + 1]++;
+ for (int e = 0; e < E; e++) at[e + 1] += at[e];
+ for (int i = 0; i < n; i++) pair[at[idx[i]]++] = i; /* at[e] ends at expert e's end */
+ for (int e = 0, a = 0; e < E; a = at[e++]) {
+ int cnt = at[e] - a; /* a row routes an expert once: cnt <= rows */
+ if (!cnt) continue;
+ for (int t = 0; t < cnt; t++) {
+ int i = pair[a + t];
+ xs[t] = x + (int64_t)(s0 + i / K) * D;
+ hp[t] = ctb + (int64_t)i * D;
+ }
+ Slot *sl; expert_get(m, layer, e, &sl);
+ moe_expert_rows(m, sl, xs, cnt, gp, up, hp);
+ expert_put(sl);
+ if (cnt > 1) { pthread_mutex_lock(&g_pilot_mx); m->hits += cnt - 1; pthread_mutex_unlock(&g_pilot_mx); }
+ }
+ for (int s = 0; s < rows; s++) {
+ float *os = out + (int64_t)(s0 + s) * D;
+ for (int kk = 0; kk < K; kk++) {
+ const float *hh = ctb + ((int64_t)s * K + kk) * D;
+ float w = val[s * K + kk];
+ for (int d = 0; d < D; d++) os[d] += w * hh[d];
+ }
+ }
+ }
+ free(idx); free(pair); free(at); free(val); free(xs); free(gp); free(up); free(hp);
+ free(g); free(u); free(ctb);
+}
#ifdef COLI_VULKAN
/* ---- the Vulkan routed-expert tier (vk_tier.c) ---------------------------------
@@ -1242,6 +1354,11 @@ static void moe_routed(Model *m, int layer, float *x, int S, float *logits, floa
return;
}
#endif
+ if (S > 1) { /* a prompt: expert by expert, the same bits as the loop below */
+ moe_by_expert(m, layer, x, S, logits, out);
+ rt_trace_end();
+ return;
+ }
float *g = falloc(I), *u = falloc(I), *hh = falloc(D);
for (int s = 0; s < S; s++) {
int idx[64]; float val[64];
diff --git a/c/tests/test_olmoe_moe_by_expert.c b/c/tests/test_olmoe_moe_by_expert.c
new file mode 100644
index 00000000..3c898e1b
--- /dev/null
+++ b/c/tests/test_olmoe_moe_by_expert.c
@@ -0,0 +1,143 @@
+/* olmoe: a prompt's MoE expert by expert (moe_by_expert) must give the bits of
+ * the one-row loop.
+ *
+ * moe_routed() takes a prompt (S > 1) through moe_by_expert(), which groups the
+ * block's (row, rank) pairs by expert and multiplies each expert against all of
+ * its rows at once (matmul_q_rows). A decode step (S == 1) keeps the one-row
+ * loop. Both must agree to the byte, or a prompt and the same tokens fed one at
+ * a time would build different KV caches.
+ *
+ * What this file asserts, on a one-layer model held in memory (every expert
+ * resident, so expert_get never reads a file):
+ * 1. matmul_q_rows equals matmul_q row by row, memcmp, for n = 1..9 rows;
+ * 2. moe_routed on S rows equals S calls of moe_routed on one row, memcmp,
+ * for S below, at and past OLMOE_PREFILL_ROWS (one, two and three blocks),
+ * with norm_topk off and on;
+ * 3. the same with IDOT and FUSED3 forced on, where the build has them;
+ * 4. hits + misses still count one request per (row, rank) pair.
+ *
+ * Build: make -C c tests/test_olmoe_moe_by_expert
+ */
+#define OLMOE_TESTING 1
+#define main coli_olmoe_main_unused
+#include "../olmoe.c"
+#undef main
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+enum { D = 128, I = 64, E = 8, K = 3 }; /* % 16 == 0: the IDOT and FUSED3 gates */
+
+static uint32_t rng_state = 0x2545f491u;
+static uint32_t xr32(void) {
+ rng_state ^= rng_state << 13;
+ rng_state ^= rng_state >> 17;
+ rng_state ^= rng_state << 5;
+ return rng_state;
+}
+static float frand(void) { return (float)((double)(xr32() % 20001) / 10000.0 - 1.0); }
+static void fill_q(int8_t *q, int64_t n) { for (int64_t i = 0; i < n; i++) q[i] = (int8_t)((int)(xr32() % 256) - 128); }
+static void fill_s(float *s, int n) { for (int i = 0; i < n; i++) s[i] = 0.001f + (float)(xr32() % 1000) * 1e-5f; }
+
+static int failures;
+static void check(int ok, const char *what) {
+ printf("%s %s\n", ok ? "PASS" : "FAIL", what);
+ if (!ok) failures++;
+}
+
+/* one layer, E experts all resident in slot e, indexed */
+static void model_init_mem(Model *m) {
+ memset(m, 0, sizeof *m);
+ m->c.hidden = D; m->c.inter = I; m->c.n_experts = E; m->c.topk = K; m->c.n_layers = 1;
+ m->hot_pinned = 1; /* no route counters: route_trace.h is not set up here */
+ m->cache = calloc(1, sizeof(LCache));
+ LCache *lc = &m->cache[0];
+ lc->slots = calloc(E, sizeof(Slot));
+ lc->slot_by_expert = malloc(E * sizeof(int));
+ lc->n = lc->cap = E;
+ for (int e = 0; e < E; e++) {
+ Slot *s = &lc->slots[e];
+ s->g = malloc((size_t)I * D); s->u = malloc((size_t)I * D); s->d = malloc((size_t)D * I);
+ s->gs = malloc(I * sizeof(float)); s->us = malloc(I * sizeof(float)); s->ds = malloc(D * sizeof(float));
+ fill_q(s->g, (int64_t)I * D); fill_q(s->u, (int64_t)I * D); fill_q(s->d, (int64_t)D * I);
+ fill_s(s->gs, I); fill_s(s->us, I); fill_s(s->ds, D);
+ s->eid = e; lc->slot_by_expert[e] = e;
+ }
+}
+
+static void rows_vs_one(const char *mode) {
+ const int O = 96, II = 160; /* O past one thread's share; II % 16 == 0 */
+ int8_t *q = malloc((size_t)O * II); float *sc = malloc(O * sizeof(float));
+ float *x = malloc((size_t)9 * II * sizeof(float));
+ float *ya = malloc((size_t)9 * O * sizeof(float)), *yb = malloc((size_t)9 * O * sizeof(float));
+ fill_q(q, (int64_t)O * II); fill_s(sc, O);
+ for (int i = 0; i < 9 * II; i++) x[i] = frand();
+ int same = 1;
+ for (int n = 1; n <= 9; n++) {
+ const float *xs[9]; float *ys[9];
+ for (int t = 0; t < n; t++) { xs[t] = x + (int64_t)t * II; ys[t] = ya + (int64_t)t * O; }
+ matmul_q_rows(ys, xs, n, q, sc, II, O);
+ for (int t = 0; t < n; t++) matmul_q(yb + (int64_t)t * O, xs[t], q, sc, II, O);
+ if (memcmp(ya, yb, (size_t)n * O * sizeof(float))) same = 0;
+ }
+ char what[128]; snprintf(what, sizeof what, "%s: matmul_q_rows == matmul_q per row, n = 1..9", mode);
+ check(same, what);
+ free(q); free(sc); free(x); free(ya); free(yb);
+}
+
+static void prompt_vs_rows(Model *m, const char *mode) {
+ const int sizes[] = { 2, 5, OLMOE_PREFILL_ROWS, OLMOE_PREFILL_ROWS + 1, 2 * OLMOE_PREFILL_ROWS + 37 };
+ for (int norm = 0; norm <= 1; norm++) {
+ m->c.norm_topk = norm;
+ for (size_t z = 0; z < sizeof sizes / sizeof *sizes; z++) {
+ int S = sizes[z];
+ float *x = malloc((size_t)S * D * sizeof(float));
+ float *la = malloc((size_t)S * E * sizeof(float)), *lb = malloc((size_t)S * E * sizeof(float));
+ float *oa = malloc((size_t)S * D * sizeof(float)), *ob = malloc((size_t)S * D * sizeof(float));
+ for (int i = 0; i < S * D; i++) x[i] = frand();
+ for (int i = 0; i < S * E; i++) la[i] = lb[i] = 4.f * frand();
+ uint64_t req0 = m->hits + m->miss;
+ moe_routed(m, 0, x, S, la, oa); /* the prompt: expert by expert */
+ uint64_t req = m->hits + m->miss - req0;
+ for (int s = 0; s < S; s++) /* the same rows, one at a time */
+ moe_routed(m, 0, x + (int64_t)s * D, 1, lb + (int64_t)s * E, ob + (int64_t)s * D);
+ char what[160];
+ snprintf(what, sizeof what, "%s: prompt of %d rows (norm_topk %d) == %d one-row steps, memcmp",
+ mode, S, norm, S);
+ check(!memcmp(oa, ob, (size_t)S * D * sizeof(float)), what);
+ snprintf(what, sizeof what, "%s: prompt of %d rows counts %d requests (%llu)",
+ mode, S, S * K, (unsigned long long)req);
+ check(req == (uint64_t)S * K, what);
+ free(x); free(la); free(lb); free(oa); free(ob);
+ }
+ }
+}
+
+int main(void) {
+ static Model m;
+ model_init_mem(&m);
+ unsetenv("IDOT");
+
+ rows_vs_one("default");
+ prompt_vs_rows(&m, "default");
+
+#if defined(HAVE_FAST_DOT_I8)
+ matmul_q_idot_force = 1;
+ rows_vs_one("IDOT=1");
+ prompt_vs_rows(&m, "IDOT=1");
+ matmul_q_idot_force = 0;
+#else
+ printf("SKIP IDOT: no fast int8 dot in this build\n");
+#endif
+#if defined(__AVX2__)
+ g_fused3 = 1;
+ prompt_vs_rows(&m, "FUSED3=1");
+ g_fused3 = 0;
+#else
+ printf("SKIP FUSED3: no AVX2 in this build\n");
+#endif
+
+ printf("\n%s\n", failures ? "FAILED" : "ALL PASS");
+ return failures ? 1 : 0;
+}