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

feat(tune): measure every engine, not just GLM, via the serve protocol

JustVuggdf5f8f688bdc
diff --git a/c/autotune.py b/c/autotune.py
index f001c4f3..3c5f267a 100644
--- a/c/autotune.py
+++ b/c/autotune.py
@@ -199,6 +199,14 @@ def parse_replay(output: str) -> dict:
}
+class OutputDrift(RuntimeError):
+ """A run produced different tokens than the session's first run.
+
+ The sweep only offers quality-preserving scheduling knobs, so any output
+ change disqualifies that candidate outright (or, on the baseline itself,
+ proves the engine is not deterministic and cannot be tuned this way)."""
+
+
def _run(command: list[str], env: dict, timeout: int) -> subprocess.CompletedProcess:
if Path(command[0]).suffix.lower() == ".py":
command = [sys.executable, *command]
@@ -226,7 +234,7 @@ def run_tune(engine: str, cap: int, base_env: dict, plan: dict, model: str,
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]:
+ progress=None, family=None, engine_cls=None) -> tuple[dict, Path]:
"""Coordinate-descent tuning with a reverse-order confirmation gate."""
progress = progress or (lambda _message: None)
if cap is None:
@@ -241,15 +249,29 @@ def run_tune(engine: str, cap: int, base_env: dict, plan: dict, model: str,
raise ValueError(
"--cap not given and the resource plan carries no resolved "
"cache_slots_per_layer")
- replay, _ = create_replay(engine, cap, base_env, prompt, tokens, timeout)
- with tempfile.TemporaryDirectory(prefix="coli-tune-") as directory:
- ref = Path(directory) / "replay.json"
- ref.write_text(json.dumps(replay), encoding="utf-8")
+ import contextlib
+ # GLM measures through its native replay protocol (REF/REF_FORCE/REPLAY,
+ # the strongest fixed-workload guarantee). The sibling engines implement
+ # none of it (#1191) but ALL of them speak the serve protocol -- it is how
+ # the gateway and tools/datapoint.py drive every engine in production --
+ # so their measurement runs go through openai_server.Engine instead: one
+ # greedy request per run (COLI_TEMP=0, a deterministic fixed workload) with
+ # the DONE frame supplying decode tok/s and cache hit%. Quality is not
+ # assumed but enforced: the first run's bytes are the contract, and any
+ # run that emits different bytes raises OutputDrift -- a drifting
+ # candidate is disqualified, a drifting baseline aborts the tune.
+ if arch == "glm":
+ replay, _ = create_replay(engine, cap, base_env, prompt, tokens, timeout)
+ context = tempfile.TemporaryDirectory(prefix="coli-tune-")
+ else:
+ replay = None
+ context = contextlib.nullcontext()
+ with context as directory:
+ if arch == "glm":
+ ref = Path(directory) / "replay.json"
+ ref.write_text(json.dumps(replay), encoding="utf-8")
- def measure(name, overlay):
- samples = []
- for repeat in range(repeats):
- progress(f"{name} ({repeat + 1}/{repeats})")
+ def run_once(name, overlay):
env = dict(base_env)
env.update(overlay)
env.update({"REF": str(ref), "REF_FORCE": "1", "REPLAY": "1", "PROF": "1"})
@@ -258,7 +280,43 @@ def run_tune(engine: str, cap: int, base_env: dict, plan: dict, model: str,
output = proc.stdout + "\n" + proc.stderr
if proc.returncode:
raise RuntimeError(f"{name} failed ({proc.returncode})\n{output[-2000:]}")
- samples.append(parse_replay(output))
+ return parse_replay(output)
+ else:
+ if engine_cls is None:
+ from openai_server import Engine as engine_cls
+ expected = [] # bytes of the session's first run: the contract
+
+ def run_once(name, overlay):
+ env = dict(base_env)
+ env.update(overlay)
+ env["COLI_TEMP"] = "0"
+ served = engine_cls(engine, model, cap, tokens, env, 1, family)
+ pieces = []
+ try:
+ result = served.generate(prompt, tokens, 0.0, 1.0,
+ pieces.append)
+ finally:
+ served.close()
+ text = "".join(pieces)
+ if not expected:
+ expected.append(text)
+ elif text != expected[0]:
+ raise OutputDrift(
+ f"{name} changed the generated tokens; a scheduling "
+ f"knob must never do that")
+ tok_s = float(result.get("tokens_per_second") or 0.0)
+ if tok_s <= 0:
+ raise RuntimeError(
+ f"{name}: engine reported no decode speed")
+ return {"tok_s": tok_s,
+ "hit_pct": result.get("cache_hit_percent"),
+ "p50_ms": None, "p99_ms": None}
+
+ def measure(name, overlay):
+ samples = []
+ for repeat in range(repeats):
+ progress(f"{name} ({repeat + 1}/{repeats})")
+ samples.append(run_once(name, overlay))
return {
"name": name,
"env": dict(overlay),
@@ -279,7 +337,11 @@ def run_tune(engine: str, cap: int, base_env: dict, plan: dict, model: str,
for name, change in candidate_steps(plan, base_env, arch):
trial_env = dict(accumulated)
trial_env.update(change)
- trial = measure(name, trial_env)
+ try:
+ trial = measure(name, trial_env)
+ except OutputDrift as drift:
+ progress(f"{name}: {drift} -- disqualified")
+ continue
candidates.append(trial)
hit_ok = (baseline["hit_pct"] is None or trial["hit_pct"] is None
or trial["hit_pct"] >= baseline["hit_pct"] - 0.5)
@@ -298,25 +360,36 @@ def run_tune(engine: str, cap: int, base_env: dict, plan: dict, model: str,
# order: winner first, baseline last. This is deliberately
# conservative — a later baseline gets any remaining warm-cache
# advantage. A profile is accepted only if it still wins.
- confirmed_winner = measure("confirm-winner", winner["env"])
- confirmed_winner["name"] = winner["name"]
- confirmed_baseline = measure("confirm-baseline", {})
- hit_ok = (confirmed_baseline["hit_pct"] is None
- or confirmed_winner["hit_pct"] is None
- or confirmed_winner["hit_pct"] >= confirmed_baseline["hit_pct"] - 0.5)
- tail_ok = (confirmed_baseline["p99_ms"] is None
- or confirmed_winner["p99_ms"] is None
- or confirmed_winner["p99_ms"] <= confirmed_baseline["p99_ms"] * 1.20)
- gain = confirmed_winner["tok_s"] / confirmed_baseline["tok_s"] - 1.0
- accepted = hit_ok and tail_ok and gain >= min_gain
- validation = {
- "winner": confirmed_winner,
- "baseline": confirmed_baseline,
- "hit_gate": hit_ok,
- "tail_gate": tail_ok,
- }
- if accepted:
- winner = confirmed_winner
+ try:
+ confirmed_winner = measure("confirm-winner", winner["env"])
+ except OutputDrift as drift:
+ progress(f"confirm-winner: {drift} -- profile rejected")
+ confirmed_winner = None
+ if confirmed_winner is None:
+ winner = baseline
+ validation = {"winner": None, "baseline": None,
+ "hit_gate": False, "tail_gate": False}
+ accepted = False
+ gain = 0.0
+ else:
+ confirmed_winner["name"] = winner["name"]
+ confirmed_baseline = measure("confirm-baseline", {})
+ hit_ok = (confirmed_baseline["hit_pct"] is None
+ or confirmed_winner["hit_pct"] is None
+ or confirmed_winner["hit_pct"] >= confirmed_baseline["hit_pct"] - 0.5)
+ tail_ok = (confirmed_baseline["p99_ms"] is None
+ or confirmed_winner["p99_ms"] is None
+ or confirmed_winner["p99_ms"] <= confirmed_baseline["p99_ms"] * 1.20)
+ gain = confirmed_winner["tok_s"] / confirmed_baseline["tok_s"] - 1.0
+ accepted = hit_ok and tail_ok and gain >= min_gain
+ validation = {
+ "winner": confirmed_winner,
+ "baseline": confirmed_baseline,
+ "hit_gate": hit_ok,
+ "tail_gate": tail_ok,
+ }
+ if accepted:
+ winner = confirmed_winner
fingerprint = machine_fingerprint(plan, model, engine)
profile = {
"schema_version": SCHEMA_VERSION,
diff --git a/c/coli b/c/coli
index b04c9cae..26d286e3 100755
--- a/c/coli
+++ b/c/coli
@@ -1025,7 +1025,8 @@ def cmd_tune(a):
print(" only quality-preserving scheduling knobs are eligible\n")
try:
profile,path=run_tune(
- engine,a.cap,base_env,plan,a.model,prompt,arch=arch,tokens=a.tokens,
+ engine,a.cap,base_env,plan,a.model,prompt,arch=arch,family=family,
+ 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/family_registry.py b/c/family_registry.py
index f46082b4..ca9d3a1f 100644
--- a/c/family_registry.py
+++ b/c/family_registry.py
@@ -483,7 +483,11 @@ FAMILIES = (
),
FamilyDescriptor(
id="kimi",
- model_types=("kimi_k3",),
+ # "kimi_linear" is Moonshot's model_type for the text model itself
+ # (the real checkpoint's text_config carries it; the root "kimi_k3"
+ # belongs to the vision wrapper). A text-only export -- the tiny
+ # fixture included -- is therefore kimi_linear at top level.
+ model_types=("kimi_k3", "kimi_linear"),
display_name="Kimi K3",
display_scale="2.8T",
engine_artifact="kimi_k3",
diff --git a/c/tests/test_autotune.py b/c/tests/test_autotune.py
index defca522..3b4a1065 100644
--- a/c/tests/test_autotune.py
+++ b/c/tests/test_autotune.py
@@ -147,6 +147,91 @@ class AutotuneUnitTest(unittest.TestCase):
self.assertIsNone(load_profile(p, directory, str(engine), directory))
+class FakeServeEngine:
+ """Serve-protocol stand-in for the sibling engines: deterministic greedy
+ text, speed keyed off the universal knobs the sweep offers."""
+
+ launches = []
+ drift_on = None # knob name that changes the OUTPUT (illegal)
+ drift_baseline = False # second run of ANY env differs (nondeterminism)
+ calls = 0
+
+ def __init__(self, executable, model, cap, max_tokens, env, kv_slots,
+ family):
+ FakeServeEngine.launches.append(
+ {"cap": cap, "env": dict(env), "family": family})
+ self.env = env
+
+ def generate(self, prompt, max_tokens, temperature, top_p, on_text,
+ cache_slot=0):
+ FakeServeEngine.calls += 1
+ text = "hello world"
+ if FakeServeEngine.drift_on and \
+ self.env.get(FakeServeEngine.drift_on) is not None:
+ text = "HELLO DRIFT"
+ if FakeServeEngine.drift_baseline and FakeServeEngine.calls > 1:
+ text = f"drift {FakeServeEngine.calls}"
+ on_text(text)
+ threads = self.env.get("OMP_NUM_THREADS")
+ speed = {None: 10.0, "8": 13.0, "4": 11.0}.get(threads, 10.0)
+ return {"completion_tokens": max_tokens, "tokens_per_second": speed,
+ "cache_hit_percent": 95.0, "prompt_tokens": 3}
+
+ def close(self):
+ pass
+
+ @classmethod
+ def reset(cls, drift_on=None, drift_baseline=False):
+ cls.launches, cls.calls = [], 0
+ cls.drift_on, cls.drift_baseline = drift_on, drift_baseline
+
+
+class ServeTuneTest(unittest.TestCase):
+ """The sibling engines have no replay protocol (#1191): their measurement
+ runs go through the serve protocol every engine already speaks."""
+
+ def run_serve_tune(self, **overrides):
+ with tempfile.TemporaryDirectory() as directory:
+ p = plan(cores=8, gpu=False)
+ p["tiers"]["ram"] = {"cache_slots_per_layer": 16}
+ arguments = dict(
+ engine="/unused-binary", cap=None, base_env={}, plan=p,
+ model=directory, prompt="prompt", arch="deepseek_v4",
+ tokens=4, repeats=2, timeout=5, min_gain=0.03,
+ profile_dir=directory, family="fake-family",
+ engine_cls=FakeServeEngine)
+ arguments.update(overrides)
+ return run_tune(**arguments)
+
+ def test_sibling_arch_tunes_through_the_serve_protocol(self):
+ FakeServeEngine.reset()
+ profile, _ = self.run_serve_tune()
+ self.assertTrue(profile["accepted"])
+ # cores=8 with OMP unset means only omp-4 is offered (8 is already
+ # the implicit default), so the sweep's one candidate must win
+ self.assertEqual(profile["winner"]["env"], {"OMP_NUM_THREADS": "4"})
+ self.assertAlmostEqual(profile["gain"], 0.10)
+ # the resolved plan cap and the family reach every engine launch
+ for launch in FakeServeEngine.launches:
+ self.assertEqual(launch["cap"], 16)
+ self.assertEqual(launch["family"], "fake-family")
+ self.assertEqual(launch["env"].get("COLI_TEMP"), "0")
+
+ def test_candidate_that_changes_output_is_disqualified(self):
+ FakeServeEngine.reset(drift_on="OMP_NUM_THREADS")
+ profile, _ = self.run_serve_tune()
+ # every OMP candidate drifts, so nothing may beat the baseline
+ self.assertFalse(profile["accepted"])
+ self.assertEqual(profile["winner"]["env"], {})
+ names = [candidate["name"] for candidate in profile["candidates"]]
+ self.assertNotIn("omp-4", names)
+
+ def test_nondeterministic_baseline_aborts_the_tune(self):
+ FakeServeEngine.reset(drift_baseline=True)
+ with self.assertRaises(RuntimeError):
+ self.run_serve_tune()
+
+
class AutotuneIntegrationTest(unittest.TestCase):
def test_unset_cap_resolves_from_the_plan_not_str_none(self):
# --cap has default=None; str(None) used to reach every engine as