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

inkling, olmoe: HITS after every turn, so the Brain tab lights up

JustVugg6f33f188b19d
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 91a1e7b9..57c438fd 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -446,6 +446,39 @@ jobs:
echo "FAIL: refused, but not for the reason under test"; cat bad.log; exit 1; }
echo "refused as expected:"; grep '^\[cfg\]' bad.log
+ olmoe-tiny-check:
+ name: OLMoE tiny oracle (token-exact + dashboard HITS)
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.12'
+ cache: pip
+ cache-dependency-path: c/tools/oracle-requirements.txt
+ - name: Install torch (CPU) + transformers
+ run: pip install -r c/tools/oracle-requirements.txt
+ - name: Tiny OLMoE checkpoint, converted
+ run: |
+ cd c
+ # 4 layers x 8 experts at toy dimensions, greedy reference from the
+ # HF model in ref_olmoe.json. The converter is the real one.
+ python3 tools/make_olmoe_tiny.py --output olmoe_tiny
+ python3 tools/convert_olmoe_merged.py --model olmoe_tiny --out olmoe_tiny_c
+ # weights only: serve mode needs a tokenizer to encode the prompt
+ python3 tools/make_edge_tiny_tokenizer.py --vocab-size 128 olmoe_tiny_c
+ - name: Token-exact against the reference
+ run: |
+ cd c
+ make olmoe
+ SNAP=olmoe_tiny_c ./olmoe 8 8 olmoe_tiny/ref_olmoe.json | tee oracle.log
+ # the engine prints the score and exits 0 either way: the gate is here
+ grep -qE 'Matching tokens: ([0-9]+)/\1$' oracle.log
+ - name: Brain tab: HITS after every turn, on the grid EMAP declared
+ run: |
+ cd c
+ OLMOE_TINY=olmoe_tiny_c python3 -m unittest -v tests.test_olmoe_dashboard_hits
+
qwen38-tiny-check:
name: Qwen3.8 tiny oracle (GDN + QSA + PLE + MoE)
runs-on: ubuntu-latest
@@ -527,6 +560,10 @@ jobs:
# the only gate that would catch it. Needs the fixture above, which is
# why it runs here and not in `make check`.
INKLING_TINY=tiny_inkling python3 -m unittest -v tests.test_inkling_prefix_serve
+ - name: Brain tab: HITS after every turn, on the grid EMAP declared
+ run: |
+ cd c
+ INKLING_TINY=tiny_inkling python3 -m unittest -v tests.test_inkling_dashboard_hits
# The efficiency suite against the tiny GLM oracle. These 8 tests existed but
# had never run anywhere: they looked for c/glm.exe, a name that stopped
diff --git a/c/inkling.c b/c/inkling.c
index ccc8dc07..1496c362 100644
--- a/c/inkling.c
+++ b/c/inkling.c
@@ -158,6 +158,7 @@ typedef struct {
LCache *cache;
int64_t rb13, rb2; /* container row-bytes (0 = not container) */
uint32_t **eusage; /* per-layer expert selection counts */
+ uint8_t **ehit; /* experts routed this turn, for HITS (dashboard Brain) */
int npin; /* pinned experts per sparse layer */
uint64_t clock, hits, miss;
uint64_t ereq, euse; /* routed richiesti (topk) vs usati dopo TOPP */
@@ -1158,6 +1159,19 @@ static Slot *slot_indexed(Model *m, int layer, int eid) {
if (i < 0 || i >= lc->n || lc->slots[i].eid != eid) return NULL;
return &lc->slots[i];
}
+/* One byte per expert: routed in this turn or not. The dashboard's Brain tab
+ * reads it as the HITS bitmap after every turn (serve_hits), and it is cleared
+ * there. Lives outside INKLING_NO_MAIN because the routing site that marks it
+ * is compiled into the segment adapter object too. */
+static void ehit_mark(Model *m, int layer, int eid) {
+ Cfg *c = &m->c;
+ if (!m->ehit) {
+ m->ehit = calloc((size_t)c->n_layers, sizeof(uint8_t *));
+ for (int i = 0; i < c->n_layers; i++) m->ehit[i] = calloc((size_t)c->n_experts, 1);
+ }
+ if (layer >= 0 && layer < c->n_layers && eid >= 0 && eid < c->n_experts) m->ehit[layer][eid] = 1;
+}
+
static Slot *slot_find(Model *m, int layer, int eid) {
Slot *s = slot_indexed(m, layer, eid);
if (s) s->used = ++m->clock;
@@ -1628,6 +1642,7 @@ static void moe(Model *m, Layer *l, int layer, float *x, int S, float *out) {
if (kk >= keff[s]) { use[t - base] = NULL; continue; } /* scartato da TOPP */
int eid = idx[(int64_t)s*K + kk];
if (m->eusage && m->eusage[layer]) m->eusage[layer][eid]++;
+ ehit_mark(m, layer, eid);
Slot *e = slot_find(m, layer, eid);
if (e) m->hits++;
else {
@@ -2174,6 +2189,29 @@ static int serve_read_cmd(FILE *input, FILE *output, const char *cur_id) {
return 0;
}
+/* HITS rows cols hex: which experts this turn routed, one bit each over the
+ * sparse layers (same rows and columns as EMAP), packed 8 per hex pair. Same
+ * line colibri.c emits; the Brain tab lights up from it. A turn that routed
+ * nothing still reports a bitmap, all zero, so the tab shows THIS turn. */
+static void serve_hits(Model *m) {
+ Cfg *c = &m->c; int E = c->n_experts;
+ if (!m->ehit) ehit_mark(m, -1, -1);
+ int nsp = 0;
+ for (int i = 0; i < c->n_layers; i++) if (c->sparse[i]) nsp++;
+ int nb = (nsp * E + 7) / 8;
+ uint8_t *bm = calloc((size_t)nb, 1); int bit = 0;
+ for (int i = 0; i < c->n_layers; i++) {
+ if (!c->sparse[i]) continue;
+ for (int e = 0; e < E; e++, bit++)
+ if (m->ehit[i][e]) { bm[bit >> 3] |= (uint8_t)(1 << (bit & 7)); m->ehit[i][e] = 0; }
+ }
+ char *hex = malloc((size_t)nb * 2 + 1); int w = 0;
+ for (int b = 0; b < nb; b++) { hex[w++] = "0123456789abcdef"[bm[b] >> 4]; hex[w++] = "0123456789abcdef"[bm[b] & 15]; }
+ hex[w] = 0;
+ printf("HITS %d %d %s\n", nsp, E, hex);
+ fflush(stdout); free(hex); free(bm);
+}
+
static int serve_one(Model *m, Tok *T, SReq *q) {
Cfg *c = &m->c;
int cap = q->plen + 16;
@@ -2235,6 +2273,7 @@ static int serve_one(Model *m, Tok *T, SReq *q) {
/* `reuse` is the ABSOLUTE position of the first fresh token: attention and
* the KV slots are position-indexed, so this has to be the real offset. */
float *logit = step_mm(m, ids + reuse, np - reuse, reuse, NULL, q->audio, naud);
+ int forwards = 1; /* il prefill e' il primo forward */
int len = np, gen = 0, limited = 1, cancelled = 0;
char buf[512];
/* repetition-penalty history: prompt tail + emitted tokens, ring of 128 */
@@ -2257,7 +2296,7 @@ static int serve_one(Model *m, Tok *T, SReq *q) {
if (r > 0) { cancelled = 1; limited = 0; }
}
if (cancelled || s == q->max_tok - 1) break;
- logit = step(m, &tk, 1, len - 1, NULL);
+ logit = step(m, &tk, 1, len - 1, NULL); forwards++;
}
free(logit);
double dt = now_s() - t0;
@@ -2270,8 +2309,9 @@ static int serve_one(Model *m, Tok *T, SReq *q) {
/* PROF: per-turn phase timings for the dashboard (gateway schema — we map
* expert_wait -> shared-expert compute, lm_head folded into 0). */
printf("PROF %.3f %d %d %.3f %.3f %.3f %.3f %.3f %d\n", dt, np, gen,
- m->t_fill - f0, m->t_shared - s0, m->t_expert - e0, m->t_attn - a0, 0.0, gen + 1);
+ m->t_fill - f0, m->t_shared - s0, m->t_expert - e0, m->t_attn - a0, 0.0, forwards);
fflush(stdout);
+ serve_hits(m);
free(ids);
return 0;
}
diff --git a/c/olmoe.c b/c/olmoe.c
index f12ce01f..c0140c80 100644
--- a/c/olmoe.c
+++ b/c/olmoe.c
@@ -101,6 +101,7 @@ typedef struct {
double dense_load_s;
/* IMPROVEMENT 2: expert frequency heatmap */
uint32_t **freq; /* per-layer expert counts, owned by route_trace.h */
+ uint8_t **ehit; /* experts routed this turn, for HITS (dashboard Brain) */
int freq_token_count, hot_pinned, hot_n, warmup_tokens;
int token_count;
/* PREDICTION IMPROVEMENT A: per-layer EMA of gate logits across tokens.
@@ -568,9 +569,22 @@ static void load_expert_merged(Model *m, int layer, int eid, Slot *s) {
}
/* ---------- cache expert: ritorna i pesi quantizzati (q+scale) da cache o disco ---------- */
+/* One byte per expert: routed in this turn or not. The dashboard's Brain tab
+ * reads it as the HITS bitmap after every turn (serve_hits), and it is cleared
+ * there. Outside OLMOE_NO_MAIN: expert_get is in the segment adapter object. */
+static void ehit_mark(Model *m, int layer, int eid) {
+ Cfg *c = &m->c;
+ if (!m->ehit) {
+ m->ehit = calloc((size_t)c->n_layers, sizeof(uint8_t *));
+ for (int i = 0; i < c->n_layers; i++) m->ehit[i] = calloc((size_t)c->n_experts, 1);
+ }
+ if (layer >= 0 && layer < c->n_layers && eid >= 0 && eid < c->n_experts) m->ehit[layer][eid] = 1;
+}
+
static void expert_get(Model *m, int layer, int eid, Slot **out) {
LCache *lc = &m->cache[layer];
pthread_mutex_lock(&g_pilot_mx);
+ ehit_mark(m, layer, eid); /* under the lock: the routing loop is parallel */
Slot *hit = slot_indexed(m, layer, eid);
if (hit) {
m->hits++; hit->used = ++m->clock; *out = hit;
@@ -1326,6 +1340,24 @@ static int serve_read_cmd(FILE *in, FILE *out, const char *cur_id) {
return 0;
}
+/* HITS rows cols hex: which experts this turn routed, one bit each, every
+ * layer (all are MoE here, same rows and columns as EMAP), packed 8 per hex
+ * pair. Same line colibri.c emits; the Brain tab lights up from it. */
+static void serve_hits(Model *m) {
+ Cfg *c = &m->c; int E = c->n_experts, rows = c->n_layers;
+ if (!m->ehit) ehit_mark(m, -1, -1);
+ int nb = (rows * E + 7) / 8;
+ uint8_t *bm = calloc((size_t)nb, 1); int bit = 0;
+ for (int i = 0; i < rows; i++)
+ for (int e = 0; e < E; e++, bit++)
+ if (m->ehit[i][e]) { bm[bit >> 3] |= (uint8_t)(1 << (bit & 7)); m->ehit[i][e] = 0; }
+ char *hex = malloc((size_t)nb * 2 + 1); int w = 0;
+ for (int b = 0; b < nb; b++) { hex[w++] = "0123456789abcdef"[bm[b] >> 4]; hex[w++] = "0123456789abcdef"[bm[b] & 15]; }
+ hex[w] = 0;
+ printf("HITS %d %d %s\n", rows, E, hex);
+ fflush(stdout); free(hex); free(bm);
+}
+
static int serve_one(Model *m, Tok *T, SReq *q, int ctx_cap) {
Cfg *c = &m->c;
int cap = q->plen + 16;
@@ -1380,6 +1412,7 @@ static int serve_one(Model *m, Tok *T, SReq *q, int ctx_cap) {
* is future work, not a protocol requirement. */
printf("PROF %.3f %d %d 0.0 0.0 0.0 0.0 0.0 %d\n", dt, np, gen, gen + 1);
fflush(stdout);
+ serve_hits(m);
free(ids);
return 0;
}
diff --git a/c/tests/test_inkling_dashboard_hits.py b/c/tests/test_inkling_dashboard_hits.py
new file mode 100644
index 00000000..77f0730b
--- /dev/null
+++ b/c/tests/test_inkling_dashboard_hits.py
@@ -0,0 +1,72 @@
+"""The dashboard's Brain tab lights up from a HITS line the engine prints
+after every turn: which experts the turn routed, one bit each, packed 8 per
+hex pair, over the same rows and columns as EMAP. inkling.c printed EMAP
+(the grid, refreshed every turn) but never HITS, so on Inkling the grid
+stayed dark. Same harness as the prefix-reuse test, one turn, read to the
+last line of the turn.
+"""
+import unittest
+
+from tests.test_inkling_prefix_serve import ENGINE, FIXTURE, MAXTOK, Engine, ensure_tokenizer
+
+
+def read_until(engine, kind, limit=200):
+ """Lines after the previous read, up to and including the first `kind`."""
+ lines = []
+ for _ in range(limit):
+ line = engine.p.stdout.readline()
+ if not line:
+ raise RuntimeError("engine closed: " + "".join(engine._err)[-2000:])
+ text = line.decode("latin-1").rstrip("\n")
+ if text.split(" ", 1)[0] == "DATA":
+ engine.p.stdout.read(int(text.split()[2]))
+ engine.p.stdout.readline()
+ continue
+ lines.append(text)
+ if text.startswith(kind + " "):
+ return lines
+ raise RuntimeError(f"no {kind} within {limit} lines:\n" + "\n".join(lines[-10:]))
+
+
[email protected](ENGINE.exists(), "inkling is not built")
[email protected]((FIXTURE / "config.json").exists(),
+ "tiny inkling fixture is absent (tools/make_tiny_inkling.py)")
+class InklingDashboardHitsTest(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ ensure_tokenizer(FIXTURE)
+ engine = Engine(log_prefix=False)
+ try:
+ cls.boot = read_until(engine, "EMAP") # the grid, printed once after READY
+ engine.ask(1, b"abcabcabc") # returns at DONE
+ cls.turn = read_until(engine, "HITS") # PROF, then HITS, then the refreshed grid
+ finally:
+ engine.close()
+
+ @staticmethod
+ def only(lines, kind):
+ found = [l.split() for l in lines if l.startswith(kind + " ")]
+ assert len(found) == 1, f"expected exactly one {kind}: {found}"
+ return found[0]
+
+ def test_hits_matches_the_grid(self):
+ """Rows and columns are EMAP's (the sparse layers), or the Brain tab
+ paints the bits on the wrong cells."""
+ _, rows, cols, hexs = self.only(self.turn, "HITS")
+ _, erows, ecols, emap = self.only(self.boot, "EMAP")
+ self.assertEqual((rows, cols), (erows, ecols))
+ self.assertEqual(len(hexs), ((int(rows) * int(cols) + 7) // 8) * 2)
+ self.assertNotEqual(int(hexs, 16), 0,
+ "a 9-token prompt through the sparse layers routed no expert at all")
+
+ def test_prof_counts_forwards_not_tokens(self):
+ """A turn stopped by max_tokens does not run a forward for the token it
+ never samples: prefill plus one per token after the first."""
+ prof = self.only(self.turn, "PROF")
+ self.assertEqual(len(prof), 10)
+ self.assertEqual(int(prof[3]), MAXTOK, "completion tokens")
+ self.assertEqual(int(prof[9]), MAXTOK)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/c/tests/test_olmoe_dashboard_hits.py b/c/tests/test_olmoe_dashboard_hits.py
new file mode 100644
index 00000000..c38712a8
--- /dev/null
+++ b/c/tests/test_olmoe_dashboard_hits.py
@@ -0,0 +1,107 @@
+"""The dashboard's Brain tab lights up from a HITS line the engine prints
+after every turn: which experts the turn routed, one bit each, packed 8 per
+hex pair, over the same rows and columns as EMAP. olmoe.c printed EMAP (the
+grid) but never HITS, so on OLMoE the grid stayed dark. This test drives the
+engine over stdio the way the gateway does and reads the turn to its last
+line.
+
+It needs a converted OLMoE container with a tokenizer.json and a built
+`olmoe`. Set OLMOE_TINY to the container; without it the test is skipped
+with the reason on the record. CI builds the tiny checkpoint from
+tools/make_olmoe_tiny.py, converts it, and adds the byte tokenizer.
+"""
+import json
+import os
+import subprocess
+import sys
+import unittest
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent.parent
+ENGINE = HERE / ("olmoe.exe" if sys.platform == "win32" else "olmoe")
+FIXTURE = Path(os.environ.get("OLMOE_TINY", ""))
+MAXTOK = 3
+
+
+def one_turn(prompt=b"abcabcabc"):
+ """Run the engine in serve mode, submit one prompt, return the protocol
+ lines of the turn (DATA payloads consumed) up to and including HITS.
+ stdin stays open for the whole turn: the engine polls it per token and an
+ EOF there is a cancel, which is what a `printf | ./olmoe` pipe gets."""
+ env = dict(os.environ, SNAP=str(FIXTURE), SERVE="1")
+ p = subprocess.Popen([str(ENGINE), "4", "8"], env=env, stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0)
+ try:
+ while True:
+ line = p.stdout.readline()
+ if not line:
+ raise RuntimeError("engine exited before READY: "
+ + p.stderr.read().decode(errors="replace")[-2000:])
+ if b"READY" in line:
+ break
+ p.stdin.write(f"SUBMIT 7 0 {len(prompt)} {MAXTOK} 0 1\n".encode() + prompt + b"\n")
+ p.stdin.flush()
+ lines = []
+ for _ in range(200):
+ line = p.stdout.readline()
+ if not line:
+ raise RuntimeError("engine closed mid-turn: "
+ + p.stderr.read().decode(errors="replace")[-2000:])
+ text = line.decode("latin-1").rstrip("\n")
+ kind = text.split(" ", 1)[0]
+ if kind == "DATA":
+ p.stdout.read(int(text.split()[2]))
+ p.stdout.readline()
+ continue
+ lines.append(text)
+ if kind == "HITS":
+ return lines
+ raise RuntimeError("no HITS within 200 lines after SUBMIT:\n" + "\n".join(lines[-10:]))
+ finally:
+ p.stdin.close()
+ try:
+ p.wait(30)
+ except subprocess.TimeoutExpired:
+ p.kill()
+
+
[email protected](ENGINE.exists(), "olmoe is not built")
[email protected]((FIXTURE / "config.json").is_file() and (FIXTURE / "tokenizer.json").is_file(),
+ "OLMOE_TINY not set to a converted OLMoE container with a tokenizer")
+class OlmoeDashboardHitsTest(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.lines = one_turn()
+ cls.config = json.loads((FIXTURE / "config.json").read_text())
+
+ def line(self, kind):
+ found = [l for l in self.lines if l.startswith(kind + " ")]
+ self.assertEqual(len(found), 1, f"expected exactly one {kind} line, got {found}")
+ return found[0].split()
+
+ def test_hits_closes_the_turn_after_done(self):
+ kinds = [l.split(" ", 1)[0] for l in self.lines]
+ self.assertIn("DONE", kinds)
+ self.assertLess(kinds.index("DONE"), kinds.index("HITS"),
+ "HITS belongs to the turn it describes: after DONE, with PROF")
+
+ def test_hits_has_the_grid_shape(self):
+ """Rows and columns must be EMAP's, or the Brain tab paints the bits on
+ the wrong cells: every layer here is a MoE layer."""
+ _, rows, cols, hexs = self.line("HITS")
+ self.assertEqual(int(rows), self.config["num_hidden_layers"])
+ self.assertEqual(int(cols), self.config["num_experts"])
+ self.assertEqual(len(hexs), ((int(rows) * int(cols) + 7) // 8) * 2)
+ self.assertNotEqual(int(hexs, 16), 0,
+ "a 9-token prompt through MoE layers routed no expert at all")
+
+ def test_prof_still_has_its_ten_fields(self):
+ prof = self.line("PROF")
+ self.assertEqual(len(prof), 10)
+ self.assertEqual(int(prof[3]), MAXTOK, "completion tokens")
+ self.assertEqual(int(prof[9]), MAXTOK + 1,
+ "prefill plus one forward per token: this engine steps the last one too")
+
+
+if __name__ == "__main__":
+ unittest.main()