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: lend the KV's room to the expert cache until the context uses it

Marcello Costagliolab9180a4bdc2c
diff --git a/c/olmoe.c b/c/olmoe.c
index ebd5a6f8..2ea70274 100644
--- a/c/olmoe.c
+++ b/c/olmoe.c
@@ -36,6 +36,9 @@
#include <sys/resource.h>
#include <unistd.h>
#endif
+#if defined(__GLIBC__)
+#include <malloc.h> /* malloc_trim: kv_room_fit gives the slots it frees back to the system */
+#endif
#include "cli_args.h"
#include "st.h"
#ifdef _OPENMP
@@ -132,6 +135,10 @@ typedef struct {
* plain double: a per-turn delta of it is what the PROF line reports. */
uint64_t disk_ns;
float **K, **V; int kv_len, max_t;
+ /* The bytes the expert cache and the KV share when the cache was sized from
+ * the automatic budget (0: an explicit cap, nothing shared), and the
+ * positions the KV's pages already reach (see kv_room_fit). */
+ int64_t room_bytes; int kv_room_t;
/* What the cached keys and values were built from, so a serve turn that
* resends the transcript prefills only the new tail. Recorded where the
* tokens are fed (see kv_prefix.h), never derived from a counter. */
@@ -543,6 +550,13 @@ static float *load_t(Model *m, const char *name) {
return p;
}
+/* One slot holds one expert: three int8 matrices plus their row scales, the
+ * same arithmetic the Segment adapter uses to turn a memory limit into a cap. */
+static int64_t slot_bytes(const Cfg *c) {
+ return (int64_t)c->hidden * c->inter * 3 +
+ (int64_t)(c->inter * 2 + c->hidden) * (int64_t)sizeof(float);
+}
+
static void model_init_range(Model *m, const char *snap, int cap, int bits,
int layer_begin, int layer_end,
int load_boundaries, int init_telemetry) {
@@ -598,21 +612,17 @@ static void model_init_range(Model *m, const char *snap, int cap, int bits,
* same fraction and the same reason as the sibling engines: overshoot
* means an OOM kill mid-generation, which is worse than a small cache. */
double budget = ram_arg > 0.0 ? ram_arg : resident + avail * 0.88;
- /* The KV cache is allocated later, at the first request, so project it:
- * two tensors per layer of n_heads * max_t * head_dim floats. CTX caps
- * at 4096 because attention()'s score buffer does. */
- int max_t = getenv("CTX") ? atoi(getenv("CTX")) : 4096;
- if (max_t < 1 || max_t > 4096) max_t = 4096;
- double kv_gb = 2.0 * (double)c->n_layers * c->n_heads * max_t *
- c->head_dim * sizeof(float) / 1e9;
- /* One slot holds one expert: three int8 matrices plus their row scales,
- * the same arithmetic the Segment adapter uses to turn a memory limit
- * into a cap. */
- double slot_gb = ((double)c->hidden * c->inter * 3.0 +
- (double)(c->inter * 2 + c->hidden) * sizeof(float)) / 1e9;
+ /* The KV is not set aside here. Its pages are faulted in as positions
+ * are written, so the cache and the KV share this room: kv_room_fit()
+ * takes a layer's slots back as the KV reaches their bytes. Setting
+ * aside the KV of the whole context (CTX, 1.07 GB at 4096 positions on
+ * OLMoE-1B-7B) cost the cache that much even for a request that writes
+ * a few hundred positions. */
+ double slot_gb = (double)slot_bytes(c) / 1e9;
int layers = layer_end - layer_begin;
if (layers < 1) layers = 1;
- double room = budget - resident - kv_gb - 0.5; /* 0.5 GB: activations */
+ double room = budget - resident - 0.5; /* 0.5 GB: activations */
+ m->room_bytes = room > 0.0 ? (int64_t)(room * 1e9) : 0;
int derived = room > 0.0 && slot_gb > 0.0
? (int)(room / slot_gb / (double)layers) : 0;
if (derived < 1) {
@@ -625,11 +635,11 @@ static void model_init_range(Model *m, const char *snap, int cap, int bits,
}
if (derived > c->n_experts) derived = c->n_experts;
fprintf(stderr, "[cache] %d slots/layer of %d experts: %.1f GB budget "
- "(%s), %.1f GB dense resident, %.1f GB projected KV, "
- "%.0f MB per expert\n",
+ "(%s), %.1f GB dense resident, %.0f MB per expert; "
+ "the KV takes slots back as the context grows\n",
derived, c->n_experts, budget,
ram_arg > 0.0 ? "RAM_GB" : "88% of what the OS still offers",
- resident, kv_gb, slot_gb * 1000.0);
+ resident, slot_gb * 1000.0);
cap = derived;
}
m->cache = calloc(c->n_layers, sizeof(LCache));
@@ -950,6 +960,72 @@ static void expert_put(Slot *s) {
pthread_mutex_unlock(&g_pilot_mx);
}
+/* The bytes the KV's pages reach once `positions` are written: K and V of
+ * every layer hold n_heads rows of max_t * head_dim floats, each written from
+ * its start, and a row's first B bytes touch at most B / 4096 + 2 pages. */
+static int64_t kv_room_bytes(const Model *m, int positions) {
+ const Cfg *c = &m->c;
+ int64_t rows = 2 * (int64_t)c->n_layers * c->n_heads;
+ return rows * ((int64_t)positions * c->head_dim * (int64_t)sizeof(float) + 2 * 4096);
+}
+
+/* The expert cache and the KV share one room (room_bytes, set by the automatic
+ * budget in model_init_range). Before a forward writes positions the KV has
+ * not reached yet, every layer's cap comes down to what the room still holds,
+ * never below one slot, and each layer frees its least recently used slots
+ * down to it (a pinned one only when nothing else is left). Which experts sit
+ * in RAM changes, the logits do not. Called from step(), between forwards: no
+ * slot is busy, and a PILOT read in flight is waited for as in expert_get. */
+static void kv_room_fit(Model *m, int positions) {
+ if (m->room_bytes <= 0 || positions <= m->kv_room_t) return;
+ m->kv_room_t = positions;
+ Cfg *c = &m->c;
+ int64_t left = m->room_bytes - kv_room_bytes(m, positions);
+ int64_t fit = left > 0 ? left / slot_bytes(c) / c->n_layers : 0;
+ int cap = fit < 1 ? 1 : fit > c->n_experts ? c->n_experts : (int)fit;
+ int shrunk = 0;
+ pthread_mutex_lock(&g_pilot_mx);
+ for (int l = 0; l < c->n_layers; l++) {
+ LCache *lc = &m->cache[l];
+ if (!lc->slots || cap >= lc->cap) continue;
+ lc->cap = cap; shrunk = 1;
+ while (lc->n > cap) {
+ int v = -1;
+ for (int i = 0; i < lc->n; i++) {
+ Slot *s = &lc->slots[i];
+ if (s->eid < 0 || s->busy) continue;
+ if (v < 0 || s->pinned < lc->slots[v].pinned ||
+ (s->pinned == lc->slots[v].pinned && s->used < lc->slots[v].used)) v = i;
+ }
+ Slot *last = &lc->slots[lc->n - 1];
+ if (v < 0 || (v != lc->n - 1 && (last->eid < 0 || last->busy))) {
+ /* the slot to free or the one to move into its place is being
+ * read into: wait for that read to publish */
+ pthread_mutex_unlock(&g_pilot_mx);
+ sleep_ms(1);
+ pthread_mutex_lock(&g_pilot_mx);
+ continue;
+ }
+ Slot *s = &lc->slots[v];
+ cache_unindex(m, l, s);
+ free(s->g); free(s->gs); /* the two blocks slot_ensure_allocated made */
+ if (s != last) {
+ *s = *last;
+ if (lc->slot_by_expert && s->eid >= 0 && s->eid < c->n_experts)
+ lc->slot_by_expert[s->eid] = v;
+ }
+ memset(last, 0, sizeof *last);
+ lc->n--;
+ }
+ }
+ pthread_mutex_unlock(&g_pilot_mx);
+ if (!shrunk) return;
+#if defined(__GLIBC__)
+ malloc_trim(0); /* glibc keeps freed blocks in its heap unless asked */
+#endif
+ fprintf(stderr, "[cache] the KV reaches %d positions: %d slots/layer\n", positions, cap);
+}
+
/* ---------- IMPROVEMENT 2: pin top-N hot experts per layer ---------- */
static void pin_hot_experts(Model *m) {
Cfg *c = &m->c;
@@ -1343,6 +1419,7 @@ static void olmoe_echo(const char *id, int pos, int token, const float *lo, int
static float *step(Model *m, const int *ids, int S, int pos_base) {
Cfg *c = &m->c; int D = c->hidden;
+ kv_room_fit(m, pos_base + S); /* before the positions' pages are written */
if (g_pilot && m->token_count > 0) {
/* Flush stale prefetch requests: clear is_queued so pilot_realload
* will skip any entries still sitting in pilot_q for the previous
diff --git a/c/tests/test_olmoe_cache_index.c b/c/tests/test_olmoe_cache_index.c
index 31067499..559ac428 100644
--- a/c/tests/test_olmoe_cache_index.c
+++ b/c/tests/test_olmoe_cache_index.c
@@ -209,6 +209,55 @@ static void check_prefetch_spares_busy(void) {
free_loader(&m);
}
+/* kv_room_fit: the cache gives the KV its slots back. Eight resident experts,
+ * expert e last used at clock 10 + e, expert 0 pinned; a room that holds the
+ * KV of 300 positions plus three and a half slots. The cap must come down to
+ * three, the coldest unpinned experts must go (1..5), the survivors (0, 6, 7)
+ * must stay reachable through the index wherever the compaction moved them,
+ * and a room below one slot must still leave one: the pinned expert. */
+static void check_kv_room_gives_back_slots(void) {
+ Model m; init_cache(&m, 8, 8); LCache *lc = &m.cache[0];
+ m.c.hidden = 64; m.c.inter = 32; m.c.n_heads = 4; m.c.head_dim = 16;
+ for (int e = 0; e < 8; e++) {
+ Slot *s = &lc->slots[lc->n++];
+ slot_ensure_allocated(&m, s);
+ cache_publish(&m, 0, s, e);
+ s->used = 10 + (uint64_t)e;
+ }
+ lc->slots[0].pinned = 1;
+ int64_t slot = slot_bytes(&m.c);
+ m.room_bytes = kv_room_bytes(&m, 300) + 3 * slot + slot / 2;
+ kv_room_fit(&m, 300);
+ CHECK(lc->cap == 3 && lc->n == 3, "cap %d n %d after the KV took its room, expected 3 3",
+ lc->cap, lc->n);
+ CHECK(m.kv_room_t == 300, "the KV's reach was not recorded (%d)", m.kv_room_t);
+ for (int e = 0; e < 8; e++) {
+ int kept = e == 0 || e >= 6;
+ Slot *s = slot_indexed(&m, 0, e);
+ CHECK(kept ? s != NULL && s->eid == e && s->g != NULL : s == NULL,
+ "expert %d %s after the shrink", e, kept ? "is unreachable" : "survived");
+ }
+ for (int i = lc->n; i < 8; i++)
+ CHECK(lc->slots[i].g == NULL, "slot %d past the cap still holds weights", i);
+
+ kv_room_fit(&m, 300); /* the KV reaches nothing new: nothing moves */
+ kv_room_fit(&m, 200);
+ CHECK(lc->cap == 3 && lc->n == 3, "a position already reached moved the cap to %d", lc->cap);
+
+ m.room_bytes = 1; /* below one slot: the floor */
+ kv_room_fit(&m, 301);
+ CHECK(lc->cap == 1 && lc->n == 1 && slot_indexed(&m, 0, 0) == &lc->slots[0],
+ "cap %d n %d: the floor is one slot, the pinned expert's", lc->cap, lc->n);
+
+ m.room_bytes = 0; /* an explicit cap shares nothing */
+ lc->cap = 8;
+ kv_room_fit(&m, 4000);
+ CHECK(lc->cap == 8 && lc->n == 1, "an explicit cap was changed to %d", lc->cap);
+
+ for (int i = 0; i < lc->n; i++) { free(lc->slots[i].g); free(lc->slots[i].gs); }
+ free_cache(&m);
+}
+
int main(void) {
Model m; init_cache(&m, 6, 2); LCache *lc = &m.cache[0]; lc->n = 2;
cache_publish(&m, 0, &lc->slots[0], 1);
@@ -235,6 +284,7 @@ int main(void) {
check_prefetch_skips_demand();
check_demand_joins_demand();
check_prefetch_spares_busy();
+ check_kv_room_gives_back_slots();
if (failures) { fprintf(stderr,"olmoe cache index: %d failure(s)\n", failures); return 1; }
puts("olmoe cache index: ok");
return 0;
diff --git a/c/tests/test_olmoe_cap_budget.py b/c/tests/test_olmoe_cap_budget.py
index c0d6a567..d7ab27ee 100644
--- a/c/tests/test_olmoe_cap_budget.py
+++ b/c/tests/test_olmoe_cap_budget.py
@@ -14,9 +14,11 @@ read the line it prints rather than guessing at behaviour.
Needs a converted tiny OLMoE container and a built engine; both are what the
OLMoE tiny oracle job already builds.
"""
+import json
import os
import re
import subprocess
+import tempfile
import unittest
from pathlib import Path
@@ -24,15 +26,20 @@ HERE = Path(__file__).resolve().parent.parent
ENGINE = HERE / ("olmoe.exe" if os.name == "nt" else "olmoe")
FIXTURE = Path(os.environ.get("COLI_OLMOE_FIXTURE", ""))
CACHE_LINE = re.compile(r"^\[cache\] (\d+) slots/layer of (\d+) experts", re.M)
+SHRINK_LINE = re.compile(r"^\[cache\] the KV reaches (\d+) positions: (\d+) slots/layer", re.M)
-def derived_cap(ram_gb=None, cap="0"):
+def derived_cap(ram_gb=None, cap="0", context=None):
"""Run the engine far enough to print its cache line, then stop it."""
environment = {**os.environ, "SNAP": str(FIXTURE), "SERVE": "1"}
if ram_gb is not None:
environment["RAM_GB"] = str(ram_gb)
else:
environment.pop("RAM_GB", None)
+ if context is not None:
+ environment["CTX"] = str(context)
+ else:
+ environment.pop("CTX", None)
finished = subprocess.run([str(ENGINE), cap, "8"], input=b"",
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
env=environment, timeout=120)
@@ -40,6 +47,48 @@ def derived_cap(ram_gb=None, cap="0"):
return (int(match.group(1)), int(match.group(2))) if match else (None, None)
+def smallest_budget_for_every_expert():
+ """The RAM_GB, to 10 kB, below which the cache stops holding every expert.
+
+ The tiny model's whole expert set is ~213 kB and its KV at the default
+ 4096 positions 8.4 MB, so a budget a few hundred kB above this one is the
+ regime where setting the KV aside would decide the cache."""
+ low, high = 0.4, 0.6
+ _, experts = derived_cap(ram_gb=high, context=1)
+ assert derived_cap(ram_gb=high, context=1)[0] == experts
+ assert derived_cap(ram_gb=low, context=1)[0] < experts
+ while high - low > 1e-5:
+ middle = (low + high) / 2
+ if derived_cap(ram_gb=middle, context=1)[0] == experts:
+ high = middle
+ else:
+ low = middle
+ return high, experts
+
+
+def generate(folder, tokens, ram_gb=None, cap="0"):
+ """Greedy generation of `tokens` positions; returns every forward's logits
+ (DUMP) and the engine's stderr."""
+ reference = folder / "ref.json"
+ prompt = [1, 2, 3]
+ reference.write_text(json.dumps({"prompt_ids": prompt,
+ "full_ids": prompt + [0] * (tokens - len(prompt))}))
+ dump = folder / ("logits_%s_%s.bin" % (cap, ram_gb))
+ environment = {**os.environ, "SNAP": str(FIXTURE), "DUMP": str(dump)}
+ environment.pop("SERVE", None)
+ environment.pop("CTX", None)
+ if ram_gb is not None:
+ environment["RAM_GB"] = str(ram_gb)
+ else:
+ environment.pop("RAM_GB", None)
+ finished = subprocess.run([str(ENGINE), cap, "8", str(reference)],
+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
+ env=environment, timeout=120)
+ if finished.returncode != 0:
+ raise AssertionError(finished.stderr.decode("utf-8", "replace"))
+ return dump.read_bytes(), finished.stderr.decode("utf-8", "replace")
+
+
@unittest.skipUnless(ENGINE.exists(), "olmoe engine is not built")
@unittest.skipUnless(FIXTURE.name and (FIXTURE / "config.json").is_file(),
"COLI_OLMOE_FIXTURE not set to a converted OLMoE container")
@@ -66,6 +115,33 @@ class OlmoeCapBudgetTest(unittest.TestCase):
self.assertLess(small, large,
"the derived cap ignored the budget it was given")
+ def test_the_kv_is_not_set_aside_before_it_is_written(self):
+ """The cache used to subtract the KV of the whole context (CTX) at load,
+ before a single position was written; it now shares that room with the
+ KV as the context grows."""
+ budget, experts = smallest_budget_for_every_expert()
+ budget += 0.002 # 2 MB: above the run-to-run noise, under the 8.4 MB KV
+ self.assertEqual(derived_cap(ram_gb=budget, context=1)[0], experts)
+ self.assertEqual(derived_cap(ram_gb=budget, context=4096)[0], experts,
+ "the cache set aside the KV of a context nothing has written")
+
+ def test_the_kv_takes_its_slots_back_and_the_logits_do_not_move(self):
+ """400 positions reach ~1 MB of KV pages, more than the 0.5 MB of room
+ left over every expert: the cap must come down as the context grows,
+ to the one-slot floor, with the logits of a run that held every expert
+ all along."""
+ budget, experts = smallest_budget_for_every_expert()
+ with tempfile.TemporaryDirectory() as folder:
+ shared, log = generate(Path(folder), 400, ram_gb=budget + 0.0005)
+ alone, alone_log = generate(Path(folder), 400, cap=str(experts))
+ caps = [int(found.group(2)) for found in SHRINK_LINE.finditer(log)]
+ self.assertTrue(caps, "the KV never took a slot back:\n" + log)
+ self.assertEqual(caps, sorted(caps, reverse=True), "the cap went back up")
+ self.assertEqual(caps[-1], 1, "400 positions should leave the floor: " + str(caps))
+ self.assertIsNone(SHRINK_LINE.search(alone_log), "an explicit cap was shrunk")
+ self.assertGreater(len(alone), 0)
+ self.assertEqual(shared, alone, "the logits moved with the cache's size")
+
def test_without_a_budget_it_still_decides(self):
cap, experts = derived_cap(ram_gb=None)
self.assertIsNotNone(cap, "no RAM_GB must mean 'measure', not 'give up'")