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

tune: dispatch per architecture, and give every engine a throughput line (#898)

JustVuggbac9bd73079c
diff --git a/c/autotune.py b/c/autotune.py
index b63413e3..a44efc8d 100644
--- a/c/autotune.py
+++ b/c/autotune.py
@@ -22,7 +22,12 @@ from pathlib import Path
SCHEMA_VERSION = 1
PROMPT_RE = re.compile(r"\[PROMPT_TOKENS\]\s+\d+:\s*([0-9 ]+)")
TOKENS_RE = re.compile(r"\[TOKENS\]\s+\d+\s+generated:\s*([0-9 ]+)")
-TIMING_RE = re.compile(r"REPLAY decode:\s+(\d+)\s+tokens in\s+([0-9.]+)s")
+# Two shapes, one meaning. colibri emits the richer REPLAY line from its fixed
+# oracle replay; the sibling engines emit `TUNE decode: N tokens in T.TTTs` at
+# the end of an ordinary greedy run, which is deterministic for a fixed prompt
+# and NGEN and therefore comparable across candidates. Accepting both is what
+# lets `coli tune` work on more than GLM (#898).
+TIMING_RE = re.compile(r"(?:REPLAY|TUNE) decode:\s+(\d+)\s+tokens in\s+([0-9.]+)s")
SPEED_RE = re.compile(r"REPLAY decode:\s+\d+\s+tokens.*?\|\s*([0-9.]+)\s+tok/s")
HIT_RE = re.compile(r"expert hit\s+([0-9.]+)%")
LATENCY_RE = re.compile(r"latency p50\s+([0-9.]+)\s*ms.*?p99\s+([0-9.]+)\s*ms")
@@ -135,8 +140,16 @@ def save_profile(profile: dict, profile_dir: str | None = None) -> Path:
return path
-def candidate_steps(plan: dict, base_env: dict) -> list[tuple[str, dict]]:
- """Return a bounded coordinate-descent sweep for this topology."""
+def candidate_steps(plan: dict, base_env: dict, arch: str = "glm") -> list[tuple[str, dict]]:
+ """Return a bounded coordinate-descent sweep for this topology and engine.
+
+ `arch` gates the knobs that are not universal. OMP_NUM_THREADS and COLI_NUMA
+ are read by every engine (they are OpenMP and NUMA, not engine features), so
+ they are always eligible. PIPE and DIRECT are read by colibri alone --
+ `grep -c 'getenv("PIPE")'` is 3 in colibri.c and 0 in the other four -- so
+ offering them elsewhere would sweep candidates that cannot differ, spend the
+ replay budget proving it, and report a 0% gain as if it were a measurement
+ (#898)."""
steps = []
cores = max(1, int(plan.get("cpu", {}).get("physical_cores", os.cpu_count() or 1)))
current_threads = int(base_env.get("OMP_NUM_THREADS", cores))
@@ -153,7 +166,7 @@ def candidate_steps(plan: dict, base_env: dict) -> list[tuple[str, dict]]:
if value != pipe:
steps.append((f"cuda-pipe-{value}", {"COLI_CUDA_PIPE": str(value)}))
steps.append(("cuda-sync", {"COLI_CUDA_ASYNC": "0"}))
- if plan.get("tiers", {}).get("disk", {}).get("cold_expert_bytes", 0) > 0:
+ if arch == "glm" and plan.get("tiers", {}).get("disk", {}).get("cold_expert_bytes", 0) > 0:
direct = int(base_env.get("DIRECT", "0"))
if direct != 1:
steps.append(("direct-on", {"DIRECT": "1"}))
@@ -164,15 +177,18 @@ def candidate_steps(plan: dict, base_env: dict) -> list[tuple[str, dict]]:
def parse_replay(output: str) -> dict:
- speed = SPEED_RE.search(output)
- if not speed:
- raise ValueError("engine did not emit REPLAY throughput")
- tok_s = float(speed.group(1))
timing = TIMING_RE.search(output)
+ speed = SPEED_RE.search(output)
+ if not timing and not speed:
+ raise ValueError("engine emitted neither a REPLAY nor a TUNE decode line")
+ # Prefer tokens/elapsed: the printed tok/s carries two decimals, which is one
+ # significant digit at 0.04 tok/s and decides the 3% gate on rounding (#852).
if timing and float(timing.group(2)) > 0:
- tokens = int(timing.group(1))
- elapsed_s = float(timing.group(2))
- tok_s = tokens / elapsed_s
+ tok_s = int(timing.group(1)) / float(timing.group(2))
+ elif speed:
+ tok_s = float(speed.group(1))
+ else:
+ raise ValueError("TUNE decode line reported zero elapsed time")
hit = HIT_RE.search(output)
latency = LATENCY_RE.search(output)
return {
@@ -207,7 +223,8 @@ def create_replay(engine: str, cap: int, env: dict, prompt: str, tokens: int,
def run_tune(engine: str, cap: int, base_env: dict, plan: dict, model: str,
- prompt: str, tokens: int = 16, repeats: int = 2, timeout: int = 900,
+ prompt: str, arch: str = "glm",
+ tokens: int = 16, repeats: int = 2, timeout: int = 900,
min_gain: float = 0.03, profile_dir: str | None = None,
progress=None) -> tuple[dict, Path]:
"""Coordinate-descent tuning with a reverse-order confirmation gate."""
@@ -247,7 +264,7 @@ def run_tune(engine: str, cap: int, base_env: dict, plan: dict, model: str,
winner = baseline
accumulated = {}
candidates = [baseline]
- for name, change in candidate_steps(plan, base_env):
+ for name, change in candidate_steps(plan, base_env, arch):
trial_env = dict(accumulated)
trial_env.update(change)
trial = measure(name, trial_env)
diff --git a/c/coli b/c/coli
index 63b724c9..055253d2 100755
--- a/c/coli
+++ b/c/coli
@@ -795,14 +795,29 @@ def cmd_tune(a):
sys.exit(f"{C.yel}cannot create tuning plan:{C.r} {error}")
a.auto_tier=True
a.no_tune_profile=True
- base_env=env_for(a)
- prompt=f"[gMASK]<sop><|user|>{a.prompt}<|assistant|><think></think>"
+ # Dispatch like every other command. cmd_tune used to hardcode GLM: the
+ # banner read config.json and printed "DeepSeek V4 Flash", then calibration
+ # launched the GLM engine, which died on "this engine requires n_group=1"
+ # (#898). Same shape as #879, one command over -- the launcher naming a
+ # family it then mis-dispatched.
+ arch=model_arch(a.model)
+ engine=engine_for(a.model)
+ need_model(a.model,engine)
+ base_env=env_for_engine(a,arch) if arch!="glm" else env_for(a)
+ # The replay prompt has to be the engine's own template: GLM's [gMASK]<sop>
+ # markers are ordinary text to every other tokenizer, so the sweep would have
+ # measured a different workload than the one users run.
+ prompt=({"glm": f"[gMASK]<sop><|user|>{a.prompt}<|assistant|><think></think>",
+ "inkling": f"<|user|>{a.prompt}<|assistant|>",
+ "kimi": f"K3CHAT1\nM user {len(a.prompt)}\n{a.prompt}G 0\n\n",
+ "olmoe": f"<|user|>\n{a.prompt}\n<|assistant|>\n",
+ }.get(arch, a.prompt))
banner("tune · measured execution profile", model=a.model)
print(f" fixed replay: {a.tokens} tokens · {a.repeats} run(s) per candidate")
print(" only quality-preserving scheduling knobs are eligible\n")
try:
profile,path=run_tune(
- GLM,a.cap,base_env,plan,a.model,prompt,tokens=a.tokens,
+ engine,a.cap,base_env,plan,a.model,prompt,arch=arch,tokens=a.tokens,
repeats=a.repeats,timeout=a.timeout,min_gain=a.min_gain,
profile_dir=a.profile_dir,
progress=lambda message: print(f" {C.dim}· {message}{C.r}",flush=True),
diff --git a/c/deepseek_v4.c b/c/deepseek_v4.c
index 9fe5d651..06d5026a 100644
--- a/c/deepseek_v4.c
+++ b/c/deepseek_v4.c
@@ -7118,6 +7118,7 @@ int main(int argc, char **argv) {
text_mode ? generated_count : token_count,
(unsigned long long)stats.misses,
(unsigned long long)stats.bytes_read);
+
if (text_mode) {
size_t text_capacity = (size_t)generated_count * 256 + 1;
char *text = malloc(text_capacity);
@@ -8759,6 +8760,10 @@ int main(int argc, char **argv) {
};
ColiV4SessionGenerateStats gen_stats;
memset(&gen_stats, 0, sizeof(gen_stats));
+ /* clock_gettime inline rather than a helper: the amalgamated build compiles
+ * this file once per COLI_V4_UNIT_*, and hot_now() is static to another one. */
+ struct timespec tune_a, tune_b;
+ clock_gettime(CLOCK_MONOTONIC, &tune_a);
if (coli_v4_session_generate(session, prompt, prompt_length, &gen_opts,
NULL, NULL, &gen_stats, error,
sizeof(error))) {
@@ -8784,6 +8789,18 @@ int main(int argc, char **argv) {
(unsigned long long)stats_end.hits,
(unsigned long long)stats_end.misses, stats_hit_rate(stats_end),
(unsigned long long)stats_end.bytes_read, target_only);
+ /* One line, every engine, one format: `coli tune` sweeps scheduling knobs and
+ * needs tokens-and-elapsed to compare candidates. Before this only colibri
+ * emitted a parseable throughput line (REPLAY decode), so the tuner was
+ * GLM-only and bannered the right model while launching the wrong engine
+ * (#898). stdout, which is what autotune captures -- the v4_* diagnostics
+ * above go to stderr. Tokens and seconds rather than tok/s: the ratio is
+ * derived by the caller at full precision (#852). */
+ clock_gettime(CLOCK_MONOTONIC, &tune_b);
+ printf("TUNE decode: %d tokens in %.3fs\n", gen_stats.generated_tokens,
+ (double)(tune_b.tv_sec - tune_a.tv_sec) +
+ (tune_b.tv_nsec - tune_a.tv_nsec) * 1e-9);
+ fflush(stdout);
fprintf(stderr, "generated_text=");
if (out_len) fwrite(out_text, 1, out_len, stderr);
fprintf(stderr, "\ntiming time_to_first_token=%.3fs after_first=%.3fs\n",
diff --git a/c/inkling.c b/c/inkling.c
index 1ecb4738..3a15b7be 100644
--- a/c/inkling.c
+++ b/c/inkling.c
@@ -1694,6 +1694,15 @@ static void generate_stream(Model *m, Tok *T, const char *prompt, int n_new,
int gen = len - np;
printf("\n[prefill %.1fs | %d tokens in %.1fs = %.2f tok/s | RSS %.1f GB]\n",
t1 - t0, gen, dt, gen > 1 ? (gen-1)/dt : 0.0, rss_gb());
+ /* One line, every engine, one format: `coli tune` sweeps scheduling knobs and
+ * needs tokens-and-elapsed to compare candidates. Before this only colibri
+ * emitted a parseable throughput line (REPLAY decode), so the tuner was
+ * GLM-only and bannered the right model while launching the wrong engine
+ * (#898). Printed to stdout, which is what autotune captures.
+ * Tokens and seconds, not tok/s: the ratio is derived by the caller at full
+ * precision (#852 -- two decimals of tok/s is one significant digit at the
+ * rates this engine runs at). */
+ printf("TUNE decode: %d tokens in %.3fs\n", gen > 1 ? gen - 1 : gen, dt);
double wall = now_s() - t0;
#ifdef COLI_METAL
if (g_metal) {
diff --git a/c/kimi_k3.c b/c/kimi_k3.c
index 5fd33706..153e1a99 100644
--- a/c/kimi_k3.c
+++ b/c/kimi_k3.c
@@ -2131,6 +2131,15 @@ int main(int argc, char **argv){
(unsigned long long)m.hits,(unsigned long long)(m.hits+m.miss),m.ebytes/1e9);
fprintf(stderr,"[K3] time: attn %.1fs moe %.1fs (eload %.1fs) head %.1fs | RSS %.1f GB\n",
m.t_attn,m.t_moe,m.t_eload,m.t_head,rss_gb());
+ /* One line, every engine, one format: `coli tune` sweeps scheduling knobs and
+ * needs tokens-and-elapsed to compare candidates. Before this only colibri
+ * emitted a parseable throughput line (REPLAY decode), so the tuner was
+ * GLM-only and bannered the right model while launching the wrong engine
+ * (#898). Printed to stdout, which is what autotune captures.
+ * Tokens and seconds, not tok/s: the ratio is derived by the caller at full
+ * precision (#852 -- two decimals of tok/s is one significant digit at the
+ * rates this engine runs at). */
+ printf("TUNE decode: %d tokens in %.3fs\n", ntok, dt);
if(m.trace) fclose(m.trace);
{ const char *sv=getenv("USAGE_SAVE");
if(!(sv && atoi(sv)==0) && g_k3_usage[0])
diff --git a/c/olmoe.c b/c/olmoe.c
index 87a52638..150fce0b 100644
--- a/c/olmoe.c
+++ b/c/olmoe.c
@@ -1409,6 +1409,15 @@ int main(int argc, char **argv) {
{ const char *up = getenv("COLI_USAGE");
if (up && *up) rt_save(up, 0); } /* same bytes as every other engine */
printf("Speed: %.2f tok/s (%.1fs for %d tokens)\n", n_new/dt, dt, n_new);
+ /* One line, every engine, one format: `coli tune` sweeps scheduling knobs and
+ * needs tokens-and-elapsed to compare candidates. Before this only colibri
+ * emitted a parseable throughput line (REPLAY decode), so the tuner was
+ * GLM-only and bannered the right model while launching the wrong engine
+ * (#898). Printed to stdout, which is what autotune captures.
+ * Tokens and seconds, not tok/s: the ratio is derived by the caller at full
+ * precision (#852 -- two decimals of tok/s is one significant digit at the
+ * rates this engine runs at). */
+ printf("TUNE decode: %d tokens in %.3fs\n", n_new, dt);
free(buf); free(arena);
return 0;
}
diff --git a/c/tests/test_autotune.py b/c/tests/test_autotune.py
index bd91e676..a2188df4 100644
--- a/c/tests/test_autotune.py
+++ b/c/tests/test_autotune.py
@@ -79,6 +79,38 @@ class AutotuneUnitTest(unittest.TestCase):
)
self.assertEqual(result["tok_s"], 1234.56)
+ def test_accepts_the_common_TUNE_line_from_the_sibling_engines(self):
+ """#898: only colibri emitted a parseable throughput line, so the tuner
+ was GLM-only. The four sibling engines now print `TUNE decode: N tokens
+ in T.TTTs` at the end of an ordinary greedy run."""
+ result = parse_replay("TUNE decode: 16 tokens in 8.000s\n")
+ self.assertAlmostEqual(result["tok_s"], 2.0)
+
+ def test_refuses_output_with_neither_line(self):
+ """An engine that printed nothing parseable used to raise 'did not emit
+ REPLAY throughput'. It must still refuse rather than score it as zero."""
+ with self.assertRaises(ValueError):
+ parse_replay("no decode line here\n")
+
+ def test_glm_only_knobs_are_not_swept_on_other_engines(self):
+ """PIPE and DIRECT are read by colibri alone -- 3 and 1 occurrences in
+ colibri.c, 0 in each of the other four. Sweeping them elsewhere spends
+ the replay budget proving two identical runs are identical, then reports
+ the 0% difference as a measurement."""
+ plan = {"cpu": {"physical_cores": 8, "sockets": 1},
+ "tiers": {"disk": {"cold_expert_bytes": 1 << 30}, "vram": {"devices": []}}}
+ glm = dict(candidate_steps(plan, {}, "glm"))
+ self.assertIn("direct-on", glm)
+ self.assertIn("io-pipe-on", glm)
+ for arch in ("deepseek_v4", "kimi", "inkling", "olmoe"):
+ with self.subTest(arch=arch):
+ steps = dict(candidate_steps(plan, {}, arch))
+ self.assertNotIn("direct-on", steps)
+ self.assertNotIn("io-pipe-on", steps)
+ # OMP and NUMA are engine-agnostic and must survive, or the
+ # sweep has nothing left to measure on those engines.
+ self.assertTrue(any(name.startswith("omp-") for name in steps), steps)
+
def test_profile_round_trip_and_explicit_environment_wins(self):
with tempfile.TemporaryDirectory() as directory:
engine = Path(directory) / "engine"
diff --git a/c/tests/test_deepseek_v4_tiny.py b/c/tests/test_deepseek_v4_tiny.py
index e07de41b..8661226a 100644
--- a/c/tests/test_deepseek_v4_tiny.py
+++ b/c/tests/test_deepseek_v4_tiny.py
@@ -227,6 +227,20 @@ def check_cli_uses_engine_context(binary: Path, model: Path, temporary: Path) ->
],
env=dict(os.environ, CTX="768"),
)
+ # `coli tune` compares candidates from tokens-and-elapsed, and before #898
+ # only the GLM engine emitted a parseable line -- so the tuner ran GLM at
+ # every checkpoint. Assert the line here rather than trusting a one-off
+ # manual check: the first placement of it compiled fine and sat in a branch
+ # text mode never reaches, so it never printed and nothing noticed.
+ tune = re.search(r"TUNE decode: (\d+) tokens in ([0-9.]+)s", result.stdout)
+ if not tune:
+ raise AssertionError(
+ f"target CLI: no TUNE decode line on stdout: {result.stdout!r}"
+ )
+ if int(tune.group(1)) != 1 or not float(tune.group(2)) > 0:
+ raise AssertionError(f"target CLI: implausible TUNE decode line {tune.group(0)!r}")
+ print("PASS target CLI: TUNE decode line is present and parseable")
+
stats = re.search(r"v4_tokens prompt=(\d+) generated=(\d+)", result.stderr)
if not stats or tuple(map(int, stats.groups())) != (prompt_tokens, 1):
raise AssertionError(