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

perf(tune): measure safe RAM and cache caps

JustVugga55336e805e4
diff --git a/c/autotune.py b/c/autotune.py
index 0fb2514e..74499441 100644
--- a/c/autotune.py
+++ b/c/autotune.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import hashlib
import json
+import math
import os
import platform
import re
@@ -38,8 +39,12 @@ LATENCY_RE = re.compile(r"latency p50\s+([0-9.]+)\s*ms.*?p99\s+([0-9.]+)\s*ms")
TUNABLE_KEYS = frozenset({
"OMP_NUM_THREADS", "COLI_NUMA", "PIPE", "DIRECT",
"COLI_CUDA_PIPE", "COLI_CUDA_ASYNC", "V4_LOADER_LANES",
+ "RAM_GB", "K3_EXPERT_GB",
})
+GIB = 1024 ** 3
+CAP_ARCHES = frozenset({"glm", "inkling", "olmoe", "qwen36"})
+
def _config_path(profile_dir: str | None, fingerprint: str) -> Path:
if profile_dir:
@@ -106,9 +111,37 @@ def load_profile(plan: dict, model: str, engine: str, profile_dir: str | None =
or profile.get("fingerprint") != fingerprint
or not profile.get("accepted")):
return None
- env = profile.get("winner", {}).get("env", {})
+ winner = profile.get("winner", {})
+ env = winner.get("env", {}) if isinstance(winner, dict) else None
if not isinstance(env, dict) or any(key not in TUNABLE_KEYS for key in env):
return None
+ # Available RAM is deliberately absent from the machine fingerprint: it is
+ # volatile, so including it would create a new profile whenever another
+ # application opened. Resource winners therefore need a second admission
+ # gate at load time. A profile measured yesterday may be reused today only
+ # when its cap/budget still fits the freshly-built safe plan.
+ ram = plan.get("tiers", {}).get("ram", {})
+ cap = winner.get("cap")
+ if cap is not None:
+ safe_cap = ram.get("cache_slots_per_layer")
+ if (isinstance(cap, bool) or not isinstance(cap, int) or cap < 1
+ or not isinstance(safe_cap, int) or cap > safe_cap):
+ return None
+ for key, divisor, plan_key in (
+ ("RAM_GB", GIB, "budget_bytes"),
+ ("K3_EXPERT_GB", 1_000_000_000, "expert_cache_bytes")):
+ if key not in env:
+ continue
+ try:
+ requested = float(env[key])
+ safe = float(ram[plan_key]) / divisor
+ except (KeyError, TypeError, ValueError, OverflowError):
+ return None
+ # Values are persisted to three decimals, hence the one-MiB-ish
+ # rounding allowance. NaN/inf and zero are never useful budgets.
+ if (not math.isfinite(requested) or requested <= 0
+ or requested > safe + 0.001):
+ return None
return profile
@@ -191,6 +224,93 @@ def candidate_steps(plan: dict, base_env: dict, arch: str = "glm") -> list[tuple
return steps
+def _scaled_ram_budget(plan: dict, fraction: float) -> float | None:
+ """Scale only the expert-cache portion, never dense/runtime reservations."""
+ ram = plan.get("tiers", {}).get("ram", {})
+ try:
+ budget = int(ram["budget_bytes"])
+ cache = max(0, int(ram["expert_cache_bytes"]))
+ except (KeyError, TypeError, ValueError, OverflowError):
+ return None
+ fixed = max(0, budget - cache)
+ return (fixed + int(cache * fraction)) / GIB
+
+
+def resource_candidate_steps(plan: dict, base_env: dict, arch: str, cap: int,
+ explicit_resources=()) -> list[tuple[str, dict, int]]:
+ """Return bounded, never-larger RAM/cache candidates for disk-backed MoE.
+
+ The planner's current result is the upper bound. We only remove 25% or
+ 50% of the expert-cache portion, leaving dense weights, KV, workspaces and
+ OS reserve untouched. This can recover page-cache/I/O throughput on a
+ memory-pressured host, but the ordinary hit/TTFT/tail gates decide whether
+ that trade is actually worthwhile on this model and workload.
+ """
+ if plan.get("tiers", {}).get("disk", {}).get("cold_expert_bytes", 0) <= 0:
+ return []
+ explicit = set(explicit_resources)
+ fractions = (0.75, 0.50)
+ steps = []
+
+ if arch in CAP_ARCHES:
+ if ("cap" in explicit or cap <= 1
+ or (arch == "glm" and "RAM_GB" in explicit)):
+ return []
+ seen = set()
+ for fraction in fractions:
+ candidate_cap = max(1, int(cap * fraction))
+ if candidate_cap == cap or candidate_cap in seen:
+ continue
+ seen.add(candidate_cap)
+ overlay = {}
+ if arch == "glm" and "RAM_GB" not in explicit:
+ budget = _scaled_ram_budget(plan, fraction)
+ if budget is not None:
+ overlay["RAM_GB"] = f"{budget:.3f}"
+ steps.append((f"cache-{int(fraction * 100)}", overlay, candidate_cap))
+ return steps
+
+ if arch == "deepseek_v4":
+ if "RAM_GB" in explicit:
+ return []
+ seen = set()
+ for fraction in fractions:
+ budget = _scaled_ram_budget(plan, fraction)
+ if budget is None:
+ continue
+ value = f"{budget:.3f}"
+ if value == base_env.get("RAM_GB") or value in seen:
+ continue
+ seen.add(value)
+ steps.append((f"ram-cache-{int(fraction * 100)}",
+ {"RAM_GB": value}, cap))
+ return steps
+
+ if arch == "kimi":
+ if "K3_EXPERT_GB" in explicit:
+ return []
+ try:
+ requested = float(base_env.get("K3_EXPERT_GB", "8"))
+ planned = (float(plan["tiers"]["ram"]["expert_cache_bytes"])
+ / 1_000_000_000)
+ except (KeyError, TypeError, ValueError, OverflowError):
+ return []
+ baseline = min(requested, planned)
+ if not math.isfinite(baseline) or baseline <= 0:
+ return []
+ seen = set()
+ for fraction in fractions:
+ value = f"{baseline * fraction:.3f}"
+ if value in seen:
+ continue
+ seen.add(value)
+ steps.append((f"k3-cache-{int(fraction * 100)}",
+ {"K3_EXPERT_GB": value}, cap))
+ return steps
+
+ return []
+
+
def parse_replay(output: str) -> dict:
timing = TIMING_RE.search(output)
speed = SPEED_RE.search(output)
@@ -214,9 +334,10 @@ def parse_replay(output: str) -> dict:
}
-def _summarize_measurement(name: str, overlay: dict, samples: list[dict]) -> dict:
+def _summarize_measurement(name: str, overlay: dict, samples: list[dict],
+ cap: int | None = None) -> dict:
"""Reduce one candidate's fixed request budget to comparable medians."""
- return {
+ summary = {
"name": name,
"env": dict(overlay),
"tok_s": statistics.median(sample["tok_s"] for sample in samples),
@@ -228,8 +349,26 @@ def _summarize_measurement(name: str, overlay: dict, samples: list[dict]) -> dic
sample["p99_ms"] for sample in samples
if sample["p99_ms"] is not None
) if any(sample["p99_ms"] is not None for sample in samples) else None,
+ "ttft_s": statistics.median(
+ sample["ttft_s"] for sample in samples
+ if sample.get("ttft_s") is not None
+ ) if any(sample.get("ttft_s") is not None for sample in samples) else None,
"samples": samples,
}
+ if cap is not None:
+ summary["cap"] = cap
+ return summary
+
+
+def _safety_gates(baseline: dict, trial: dict) -> dict:
+ return {
+ "hit_gate": (baseline["hit_pct"] is None or trial["hit_pct"] is None
+ or trial["hit_pct"] >= baseline["hit_pct"] - 0.5),
+ "tail_gate": (baseline["p99_ms"] is None or trial["p99_ms"] is None
+ or trial["p99_ms"] <= baseline["p99_ms"] * 1.20),
+ "ttft_gate": (baseline.get("ttft_s") is None or trial.get("ttft_s") is None
+ or trial["ttft_s"] <= baseline["ttft_s"] * 1.20),
+ }
class OutputDrift(RuntimeError):
@@ -268,7 +407,7 @@ def run_tune(engine: str, cap: int, base_env: dict, plan: dict, model: str,
tokens: int = 16, repeats: int = 2, timeout: int = 900,
min_gain: float = 0.03, profile_dir: str | None = None,
progress=None, family=None, engine_cls=None,
- prompts=None) -> tuple[dict, Path]:
+ prompts=None, explicit_resources=()) -> tuple[dict, Path]:
"""Coordinate-descent tuning with a reverse-order confirmation gate."""
progress = progress or (lambda _message: None)
if cap is None:
@@ -309,12 +448,12 @@ def run_tune(engine: str, cap: int, base_env: dict, plan: dict, model: str,
ref = Path(directory) / "replay.json"
ref.write_text(json.dumps(replay), encoding="utf-8")
- def run_once(name, overlay):
+ def run_once(name, overlay, launch_cap):
env = dict(base_env)
env.update(overlay)
env.update({"REF": str(ref), "REF_FORCE": "1", "REPLAY": "1", "PROF": "1"})
env.pop("PROMPT", None); env.pop("TOKENS", None)
- proc = _run([engine, str(cap)], env, timeout)
+ proc = _run([engine, str(launch_cap)], env, timeout)
output = proc.stdout + "\n" + proc.stderr
if proc.returncode:
raise RuntimeError(f"{name} failed ({proc.returncode})\n{output[-2000:]}")
@@ -327,11 +466,11 @@ def run_tune(engine: str, cap: int, base_env: dict, plan: dict, model: str,
# candidates is the quality violation.
expected = {}
- def measure(name, overlay):
+ def measure(name, overlay, launch_cap):
env = dict(base_env)
env.update(overlay)
env["COLI_TEMP"] = "0"
- served = engine_cls(engine, model, cap, tokens, env, 1, family)
+ served = engine_cls(engine, model, launch_cap, tokens, env, 1, family)
samples = []
try:
# Keep this engine alive for the whole candidate. `repeats`
@@ -343,8 +482,17 @@ def run_tune(engine: str, cap: int, base_env: dict, plan: dict, model: str,
f"{repeat % len(serving_prompts) + 1}/"
f"{len(serving_prompts)})")
pieces = []
+ started = time.perf_counter()
+ first_text_at = [None]
+
+ def collect(piece):
+ if piece and first_text_at[0] is None:
+ first_text_at[0] = time.perf_counter()
+ pieces.append(piece)
+
result = served.generate(active_prompt, tokens, 0.0, 1.0,
- pieces.append)
+ collect)
+ finished = time.perf_counter()
text = "".join(pieces)
contract = expected.get(active_prompt)
if contract is None:
@@ -358,44 +506,64 @@ def run_tune(engine: str, cap: int, base_env: dict, plan: dict, model: str,
if tok_s <= 0:
raise RuntimeError(
f"{name}: engine reported no decode speed")
+ reported_ttft = result.get("time_to_first_token")
+ if reported_ttft is None:
+ ttft = ((first_text_at[0] or finished) - started)
+ else:
+ ttft = float(reported_ttft)
+ if not math.isfinite(ttft) or ttft < 0:
+ raise RuntimeError(f"{name}: engine reported invalid TTFT")
samples.append({
"tok_s": tok_s,
"hit_pct": result.get("cache_hit_percent"),
"p50_ms": None,
"p99_ms": None,
+ "ttft_s": ttft,
})
finally:
served.close()
- return _summarize_measurement(name, overlay, samples)
+ recorded_cap = launch_cap if arch in CAP_ARCHES else None
+ return _summarize_measurement(name, overlay, samples, recorded_cap)
if arch == "glm":
- def measure(name, overlay):
+ def measure(name, overlay, launch_cap):
samples = []
for repeat in range(repeats):
progress(f"{name} ({repeat + 1}/{repeats})")
- samples.append(run_once(name, overlay))
- return _summarize_measurement(name, overlay, samples)
+ sample = run_once(name, overlay, launch_cap)
+ sample["ttft_s"] = None
+ samples.append(sample)
+ recorded_cap = launch_cap if arch in CAP_ARCHES else None
+ return _summarize_measurement(name, overlay, samples, recorded_cap)
- baseline = measure("baseline", {})
+ baseline = measure("baseline", {}, cap)
winner = baseline
accumulated = {}
+ winner_cap = cap
candidates = [baseline]
- for name, change in candidate_steps(plan, base_env, arch):
+
+ def consider(name, change, trial_cap):
+ nonlocal winner, accumulated, winner_cap
trial_env = dict(accumulated)
trial_env.update(change)
try:
- trial = measure(name, trial_env)
+ trial = measure(name, trial_env, trial_cap)
except OutputDrift as drift:
progress(f"{name}: {drift} -- disqualified")
- continue
+ return
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)
- tail_ok = (baseline["p99_ms"] is None or trial["p99_ms"] is None
- or trial["p99_ms"] <= baseline["p99_ms"] * 1.20)
- if hit_ok and tail_ok and trial["tok_s"] > winner["tok_s"] * (1.0 + min_gain):
+ gates = _safety_gates(baseline, trial)
+ if (all(gates.values())
+ and trial["tok_s"] > winner["tok_s"] * (1.0 + min_gain)):
winner = trial
accumulated = trial_env
+ winner_cap = trial_cap
+
+ for name, change in candidate_steps(plan, base_env, arch):
+ consider(name, change, winner_cap)
+ for name, change, trial_cap in resource_candidate_steps(
+ plan, base_env, arch, cap, explicit_resources):
+ consider(name, change, trial_cap)
validation = None
accepted = False
@@ -407,32 +575,27 @@ def run_tune(engine: str, cap: int, base_env: dict, plan: dict, model: str,
# conservative — a later baseline gets any remaining warm-cache
# advantage. A profile is accepted only if it still wins.
try:
- confirmed_winner = measure("confirm-winner", winner["env"])
+ confirmed_winner = measure("confirm-winner", winner["env"], winner_cap)
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}
+ "hit_gate": False, "tail_gate": False,
+ "ttft_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)
+ confirmed_baseline = measure("confirm-baseline", {}, cap)
+ gates = _safety_gates(confirmed_baseline, confirmed_winner)
gain = confirmed_winner["tok_s"] / confirmed_baseline["tok_s"] - 1.0
- accepted = hit_ok and tail_ok and gain >= min_gain
+ accepted = all(gates.values()) and gain >= min_gain
validation = {
"winner": confirmed_winner,
"baseline": confirmed_baseline,
- "hit_gate": hit_ok,
- "tail_gate": tail_ok,
+ **gates,
}
if accepted:
winner = confirmed_winner
diff --git a/c/coli b/c/coli
index c87aca20..53d597ea 100755
--- a/c/coli
+++ b/c/coli
@@ -368,11 +368,49 @@ def ngen_for(a, interactive=False, family=None):
return limits.interactive_max_output if interactive else limits.default_max_output
return 16384 if interactive else 1024
+_PROFILE_CAP_ENV = "COLI_PROFILE_CAP"
+
+def apply_measured_profile(env, profile, explicit_env, explicit_cap):
+ """Apply scheduling/resource results while preserving CLI precedence."""
+ from autotune import apply_profile
+ result=apply_profile(env,profile,explicit_env)
+ # This is a launcher-private bridge for engines whose cache capacity is an
+ # argv value rather than an environment variable. It must never leak from a
+ # parent shell or override an explicit --cap.
+ result.pop(_PROFILE_CAP_ENV,None)
+ measured=profile.get("winner",{}).get("cap")
+ if explicit_cap is None and isinstance(measured,int) and not isinstance(measured,bool):
+ result[_PROFILE_CAP_ENV]=str(measured)
+ return result
+
+def cap_for_launch(explicit_cap, env, fallback):
+ """Resolve a measured cap for direct-engine launchers; --cap always wins."""
+ if explicit_cap is not None:
+ return explicit_cap
+ try:
+ measured=int(env.pop(_PROFILE_CAP_ENV,""))
+ except (TypeError,ValueError):
+ measured=0
+ return measured if measured>=1 else fallback
+
+def operator_cap(a, arch):
+ """Return a real operator cap, including GLM's documented CAP channel."""
+ cap=getattr(a,"cap",None)
+ if cap is not None or arch!="glm":
+ return cap
+ try:
+ cap=int(os.environ.get("CAP","0"))
+ except (TypeError,ValueError):
+ cap=0
+ return cap if cap else None
+
def env_for_engine(a, arch, plan=None):
if arch == "glm":
return env_for(a)
explicit_env = set(os.environ)
env = os.environ.copy()
+ env.pop(_PROFILE_CAP_ENV,None)
+ if getattr(a,"ram",0): explicit_env.add("RAM_GB")
# OMP_NUM_THREADS for the sister engines that do not size their own team.
#
# #805 set this from physical cores "on every platform" -- but only inside
@@ -494,10 +532,11 @@ def env_for_engine(a, arch, plan=None):
# a team.
env.pop("OMP_NUM_THREADS",None)
if not getattr(a, "no_tune_profile", False):
- from autotune import apply_profile, load_profile
+ from autotune import load_profile
profile=load_profile(plan,a.model,engine_for(a.model))
if profile:
- env=apply_profile(env,profile,explicit_env)
+ env=apply_measured_profile(env,profile,explicit_env,
+ getattr(a,"cap",None))
gain=100.0*profile["gain"]
print(f" {C.dim}[TUNE] applied measured profile · +{gain:.1f}% "
f"calibration throughput{C.r}",file=sys.stderr)
@@ -569,6 +608,13 @@ def requested_kv_slots(a, env):
def env_for(a):
explicit_env = set(os.environ)
e = dict(os.environ, SNAP=a.model)
+ e.pop(_PROFILE_CAP_ENV,None)
+ if getattr(a,"ram",0): explicit_env.add("RAM_GB")
+ # A GLM resource winner is a measured pair (RAM ceiling + argv cap). An
+ # explicit cap asks the engine to size against the current RAM plan, not a
+ # smaller ceiling remembered from that old pair.
+ requested_cap=operator_cap(a,"glm")
+ if requested_cap is not None: explicit_env.add("RAM_GB")
# OMP_NUM_THREADS on EVERY platform, not only Windows.
#
# glm.c's self-exec tuning (colibri.c, the COLI_OMP_TUNED block) sets
@@ -651,10 +697,10 @@ def env_for(a):
has_cuda=cuda_binary()
e=environment_for_plan(plan,e,has_cuda)
if not getattr(a, "no_tune_profile", False):
- from autotune import apply_profile, load_profile
+ from autotune import load_profile
profile=load_profile(plan,a.model,GLM)
if profile:
- e=apply_profile(e,profile,explicit_env)
+ e=apply_measured_profile(e,profile,explicit_env,requested_cap)
gain=100.0*profile["gain"]
print(f" {C.dim}[TUNE] applied measured profile · +{gain:.1f}% calibration throughput{C.r}",
file=sys.stderr)
@@ -1075,12 +1121,18 @@ def cmd_tune(a):
f"per candidate · {active} distinct prompt(s)")
print(" only quality-preserving scheduling knobs are eligible\n")
try:
+ explicit_resources={key for key in ("RAM_GB","K3_EXPERT_GB")
+ if key in os.environ}
+ if a.ram: explicit_resources.add("RAM_GB")
+ tuning_cap=operator_cap(a,arch)
+ if tuning_cap is not None: explicit_resources.add("cap")
profile,path=run_tune(
- engine,a.cap,base_env,plan,a.model,prompt,arch=arch,family=family,
+ engine,tuning_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,
prompts=prompts,
+ explicit_resources=explicit_resources,
progress=lambda message: print(f" {C.dim}· {message}{C.r}",flush=True),
)
except (OSError,ValueError,RuntimeError,subprocess.SubprocessError) as error:
@@ -1091,7 +1143,10 @@ def cmd_tune(a):
print(f"\n {C.grn}✓ accepted{C.r} {winner['name']}: "
f"{baseline:.2f} → {winner['tok_s']:.2f} tok/s "
f"(+{100*profile['gain']:.1f}%)")
- print(f" env: {' '.join(f'{key}={value}' for key,value in winner['env'].items())}")
+ if winner["env"]:
+ print(f" env: {' '.join(f'{key}={value}' for key,value in winner['env'].items())}")
+ if "cap" in winner:
+ print(f" cache cap: {winner['cap']} slots/layer")
else:
print(f"\n {C.grn}✓ baseline retained{C.r}: no candidate cleared the "
f"{100*a.min_gain:.1f}% gain and safety gates")
@@ -1111,6 +1166,7 @@ def cmd_run(a):
if arch=="deepseek_v4":
prompt_path=None
try:
+ e=env_for_engine(a,arch)
cmd=[engine,os.path.abspath(a.model)]
if sys.platform in ("win32", "msys", "cygwin"):
with tempfile.NamedTemporaryFile(
@@ -1122,9 +1178,11 @@ def cmd_run(a):
else:
cmd.append(prompt)
cmd += ["--max-tokens",str(ngen_for(a,interactive=True,family=family))]
- if a.ram: cmd += ["--memory-gb",str(a.ram)]
+ try: memory_gb=float(e.get("RAM_GB","0"))
+ except (TypeError,ValueError): memory_gb=0.0
+ if memory_gb>0: cmd += ["--memory-gb",str(e["RAM_GB"])]
if os.environ.get("COLI_THINK","0")=="1": cmd.append("--thinking")
- result=subprocess.call(cmd,env=env_for_engine(a,arch))
+ result=subprocess.call(cmd,env=e)
finally:
if prompt_path:
try: os.unlink(prompt_path)
@@ -1137,16 +1195,17 @@ def cmd_run(a):
# over the engine's plain stdin chat loop and close stdin, the engine
# emits the answer and exits cleanly. No reason to spin up the gateway
# for a single non-interactive prompt.
+ e=env_for_engine(a,arch)
result=subprocess.run(
- [engine, str(a.cap if a.cap is not None else 16), "8"],
- input=prompt+"\n", text=True, env=env_for_engine(a,arch), check=False)
+ [engine, str(cap_for_launch(a.cap,e,16)), "8"],
+ input=prompt+"\n", text=True, env=e, check=False)
sys.exit(result.returncode)
# template ufficiale GLM-5.2: niente \n dopo i ruoli; <think></think> = risposta diretta (nothink).
# THINK=1 lascia <think> aperto, stessa convenzione del serve mode (glm.c). EN: THINK=1 leaves
# <think> open so the engine emits its reasoning block; the default stays nothink.
tk="<think>" if os.environ.get("THINK","0")=="1" else "<think></think>"
e=env_for(a); e["PROMPT"]=f"[gMASK]<sop><|user|>{prompt}<|assistant|>{tk}"
- sys.exit(subprocess.call([GLM, str(a.cap if a.cap is not None else 0)], env=e))
+ sys.exit(subprocess.call([GLM, str(cap_for_launch(a.cap,e,0))], env=e))
def server_probe(base, api_key=None, timeout=1.5):
"""Is a coli serve alive at `base`? Returns its model_id, or None.
@@ -1365,7 +1424,7 @@ def cmd_chat(a):
# once the READY sentinel arrives, so the status-line display below works
# exactly as before. (Do NOT add a concurrent stderr drain thread: on
# Windows, reading two child pipes simultaneously deadlocks CPython's IO.)
- p=subprocess.Popen([GLM,str(a.cap if a.cap is not None else 0)], env=e, stdin=subprocess.PIPE,
+ p=subprocess.Popen([GLM,str(cap_for_launch(a.cap,e,0))], env=e, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0)
sp=Spinner("waking the giant (744B)…"); sp.start()
# Keep the pre-READY stdout preamble instead of discarding it: the engine's
diff --git a/c/openai_server.py b/c/openai_server.py
index 619011b9..588b0d79 100644
--- a/c/openai_server.py
+++ b/c/openai_server.py
@@ -1905,7 +1905,7 @@ def model_arch(model):
return resolve_model(model).descriptor.id
-def cap_for_arch(arch, cap):
+def cap_for_arch(arch, cap, env=None):
"""Cap-sentinel shim (#379): CURRENT-STATE CALIBRATION, not durable core.
An absent cap (None) means different things across today's engines --
@@ -1927,6 +1927,17 @@ def cap_for_arch(arch, cap):
-> this shim must be removed and re-derived."""
if cap is not None:
return cap
+ # A measured profile records the exact argv cap used during calibration.
+ # The launcher passes it privately through the server process because cap
+ # is not an engine environment knob. It remains below an explicit --cap
+ # in the precedence chain and is removed before the engine starts.
+ if env is not None:
+ try:
+ measured = int(env.get("COLI_PROFILE_CAP", ""))
+ except (TypeError, ValueError):
+ measured = 0
+ if measured >= 1:
+ return measured
return family_by_id(arch).limits.implicit_cap
@@ -2065,8 +2076,10 @@ class Engine:
child_env = dict(env or os.environ, SNAP=str(model), SERVE="1", SERVE_BATCH="1",
NGEN=str(max_tokens), KV_SLOTS=str(kv_slots))
tune_child_env(child_env, arch)
+ resolved_cap = cap_for_arch(arch, cap, child_env)
+ child_env.pop("COLI_PROFILE_CAP", None)
self.process = subprocess.Popen(
- [str(executable), str(cap_for_arch(arch, cap))], env=child_env,
+ [str(executable), str(resolved_cap)], env=child_env,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=0,
)
# Keep the job handle on the instance: KILL_ON_JOB_CLOSE fires when the
diff --git a/c/tests/test_autotune.py b/c/tests/test_autotune.py
index d5452447..a7fdc420 100644
--- a/c/tests/test_autotune.py
+++ b/c/tests/test_autotune.py
@@ -14,6 +14,7 @@ from autotune import (
load_profile,
machine_fingerprint,
parse_replay,
+ resource_candidate_steps,
run_tune,
save_profile,
)
@@ -128,6 +129,56 @@ class AutotuneUnitTest(unittest.TestCase):
{"COLI_NO_OMP_TUNE": "1"}, "kimi")
self.assertFalse(any(name.startswith("omp-") for name, _ in steps))
+ def test_resource_candidates_only_shrink_the_safe_expert_cache(self):
+ p = plan(cores=16, gpu=False, cold=40 * (1024 ** 3))
+ p["tiers"]["ram"] = {
+ "budget_bytes": 60 * (1024 ** 3),
+ "expert_cache_bytes": 40 * (1024 ** 3),
+ "cache_slots_per_layer": 100,
+ }
+ glm = resource_candidate_steps(p, {"RAM_GB": "60.000"}, "glm", 100)
+ self.assertEqual(glm, [
+ ("cache-75", {"RAM_GB": "50.000"}, 75),
+ ("cache-50", {"RAM_GB": "40.000"}, 50),
+ ])
+ v4 = resource_candidate_steps(
+ p, {"RAM_GB": "60.000"}, "deepseek_v4", 100)
+ self.assertEqual(v4, [
+ ("ram-cache-75", {"RAM_GB": "50.000"}, 100),
+ ("ram-cache-50", {"RAM_GB": "40.000"}, 100),
+ ])
+ for arch in ("inkling", "olmoe", "qwen36"):
+ with self.subTest(arch=arch):
+ self.assertEqual(
+ resource_candidate_steps(p, {}, arch, 100),
+ [("cache-75", {}, 75), ("cache-50", {}, 50)],
+ )
+ # K3's current default is 8 decimal GB; candidates cannot silently
+ # grow it merely because the planner has room for more.
+ self.assertEqual(
+ resource_candidate_steps(p, {}, "kimi", 100),
+ [("k3-cache-75", {"K3_EXPERT_GB": "6.000"}, 100),
+ ("k3-cache-50", {"K3_EXPERT_GB": "4.000"}, 100)],
+ )
+
+ def test_resource_sweep_skips_resident_models_and_explicit_choices(self):
+ p = plan(cores=8, gpu=False, cold=0)
+ p["tiers"]["ram"] = {
+ "budget_bytes": 60 * (1024 ** 3),
+ "expert_cache_bytes": 40 * (1024 ** 3),
+ "cache_slots_per_layer": 100,
+ }
+ self.assertEqual(resource_candidate_steps(p, {}, "glm", 100), [])
+ p["tiers"]["disk"]["cold_expert_bytes"] = 1
+ self.assertEqual(
+ resource_candidate_steps(p, {}, "glm", 100, {"cap"}), [])
+ self.assertEqual(
+ resource_candidate_steps(p, {}, "glm", 100, {"RAM_GB"}), [])
+ self.assertEqual(
+ resource_candidate_steps(p, {}, "deepseek_v4", 100, {"RAM_GB"}), [])
+ self.assertEqual(
+ resource_candidate_steps(p, {}, "kimi", 100, {"K3_EXPERT_GB"}), [])
+
def test_profile_round_trip_and_explicit_environment_wins(self):
with tempfile.TemporaryDirectory() as directory:
engine = Path(directory) / "engine"
@@ -163,6 +214,29 @@ class AutotuneUnitTest(unittest.TestCase):
}, directory)
self.assertIsNone(load_profile(p, directory, str(engine), directory))
+ def test_profile_resource_winner_is_rechecked_against_current_ram(self):
+ with tempfile.TemporaryDirectory() as directory:
+ engine = Path(directory) / "engine"
+ engine.write_bytes(b"engine")
+ p = plan(gpu=False)
+ p["tiers"]["ram"] = {
+ "budget_bytes": 64 * (1024 ** 3),
+ "expert_cache_bytes": 40_000_000_000,
+ "cache_slots_per_layer": 64,
+ }
+ fingerprint = machine_fingerprint(p, directory, str(engine))
+ save_profile({
+ "schema_version": 1, "fingerprint": fingerprint,
+ "accepted": True, "gain": 0.10,
+ "winner": {"env": {"RAM_GB": "48.000"}, "cap": 48},
+ }, directory)
+ self.assertIsNotNone(load_profile(p, directory, str(engine), directory))
+ # Available memory is not fingerprinted, so this is the admission
+ # gate that prevents yesterday's 48-slot winner on today's 32-slot plan.
+ p["tiers"]["ram"]["budget_bytes"] = 32 * (1024 ** 3)
+ p["tiers"]["ram"]["cache_slots_per_layer"] = 32
+ self.assertIsNone(load_profile(p, directory, str(engine), directory))
+
class FakeServeEngine:
"""Serve-protocol stand-in for the sibling engines: deterministic greedy
@@ -173,12 +247,16 @@ class FakeServeEngine:
drift_baseline = False # second run of ANY env differs (nondeterminism)
calls = 0
sessions = []
+ cap_speeds = {}
+ cap_hits = {}
+ cap_ttft = {}
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
+ self.cap = cap
self.prompts = []
FakeServeEngine.sessions.append(self.prompts)
@@ -198,16 +276,23 @@ class FakeServeEngine:
speed *= {None: 1.0, "3": 1.30, "6": 1.10,
"9": 1.0, "12": 0.90}.get(
self.env.get("V4_LOADER_LANES"), 1.0)
+ speed *= FakeServeEngine.cap_speeds.get(self.cap, 1.0)
return {"completion_tokens": max_tokens, "tokens_per_second": speed,
- "cache_hit_percent": 95.0, "prompt_tokens": 3}
+ "cache_hit_percent": FakeServeEngine.cap_hits.get(self.cap, 95.0),
+ "time_to_first_token": FakeServeEngine.cap_ttft.get(self.cap, 1.0),
+ "prompt_tokens": 3}
def close(self):
pass
@classmethod
- def reset(cls, drift_on=None, drift_baseline=False):
+ def reset(cls, drift_on=None, drift_baseline=False, cap_speeds=None,
+ cap_hits=None, cap_ttft=None):
cls.launches, cls.sessions, cls.calls = [], [], 0
cls.drift_on, cls.drift_baseline = drift_on, drift_baseline
+ cls.cap_speeds = dict(cap_speeds or {})
+ cls.cap_hits = dict(cap_hits or {})
+ cls.cap_ttft = dict(cap_ttft or {})
class ServeTuneTest(unittest.TestCase):
@@ -273,6 +358,45 @@ class ServeTuneTest(unittest.TestCase):
with self.assertRaises(RuntimeError):
self.run_serve_tune()
+ def test_faster_smaller_cache_is_measured_confirmed_and_persisted(self):
+ FakeServeEngine.reset(cap_speeds={16: 1.0, 12: 1.30, 8: 1.10})
+ p = plan(cores=8, gpu=False, cold=1 << 30)
+ p["tiers"]["ram"] = {
+ "budget_bytes": 24 * (1024 ** 3),
+ "expert_cache_bytes": 16 * (1024 ** 3),
+ "cache_slots_per_layer": 16,
+ }
+ profile, _ = self.run_serve_tune(
+ arch="inkling", plan=p,
+ base_env={"COLI_NO_OMP_TUNE": "1"},
+ repeats=2, prompts=("prompt-a", "prompt-b"),
+ )
+ self.assertTrue(profile["accepted"])
+ self.assertEqual(profile["winner"]["cap"], 12)
+ self.assertEqual(profile["winner"]["name"], "cache-75")
+ self.assertTrue(profile["validation"]["ttft_gate"])
+ self.assertEqual([launch["cap"] for launch in FakeServeEngine.launches],
+ [16, 12, 8, 12, 16])
+
+ def test_smaller_cache_cannot_trade_away_hit_rate_or_ttft(self):
+ p = plan(cores=8, gpu=False, cold=1 << 30)
+ p["tiers"]["ram"] = {
+ "budget_bytes": 24 * (1024 ** 3),
+ "expert_cache_bytes": 16 * (1024 ** 3),
+ "cache_slots_per_layer": 16,
+ }
+ for hits, ttft in (({12: 94.0}, {}), ({}, {12: 1.30})):
+ with self.subTest(hits=hits, ttft=ttft):
+ FakeServeEngine.reset(
+ cap_speeds={16: 1.0, 12: 1.30, 8: 1.0},
+ cap_hits=hits, cap_ttft=ttft)
+ profile, _ = self.run_serve_tune(
+ arch="inkling", plan=p,
+ base_env={"COLI_NO_OMP_TUNE": "1"},
+ )
+ self.assertFalse(profile["accepted"])
+ self.assertEqual(profile["winner"]["cap"], 16)
+
class AutotuneIntegrationTest(unittest.TestCase):
def test_unset_cap_resolves_from_the_plan_not_str_none(self):
diff --git a/c/tests/test_openai_server.py b/c/tests/test_openai_server.py
index 5c764498..9cd23d59 100644
--- a/c/tests/test_openai_server.py
+++ b/c/tests/test_openai_server.py
@@ -1019,6 +1019,26 @@ class CapSentinelShimTest(unittest.TestCase):
self.assertEqual(cap_for_arch("inkling", 0), 0) # explicit 0 is explicit
self.assertEqual(cap_for_arch("glm", 0), 0)
+ def test_profile_cap_is_below_explicit_cap_and_above_implicit_default(self):
+ profiled = {"COLI_PROFILE_CAP": "24"}
+ self.assertEqual(cap_for_arch("inkling", None, profiled), 24)
+ self.assertEqual(cap_for_arch("inkling", 7, profiled), 7)
+ self.assertEqual(cap_for_arch("inkling", None,
+ {"COLI_PROFILE_CAP": "invalid"}), 8)
+
+ def test_engine_consumes_profile_cap_without_leaking_private_env(self):
+ process = FakeProcess(lambda _process, _frame: None)
+ model = self._model("inkling")
+ with patch("openai_server.subprocess.Popen", return_value=process) as popen:
+ engine = Engine("custom-engine", model,
+ env={"COLI_PROFILE_CAP": "24", "KEEP": "yes"})
+ engine.close()
+ command = popen.call_args[0][0]
+ child_env = popen.call_args[1]["env"]
+ self.assertEqual(command, ["custom-engine", "24"])
+ self.assertNotIn("COLI_PROFILE_CAP", child_env)
+ self.assertEqual(child_env["KEEP"], "yes")
+
def test_model_arch_reads_model_type(self):
self.assertEqual(model_arch(self._model("glm_moe_dsa")), "glm")
self.assertEqual(model_arch(self._model("inkling")), "inkling")
diff --git a/c/tests/test_v4_cli.py b/c/tests/test_v4_cli.py
index 6fc67324..e7e7df61 100644
--- a/c/tests/test_v4_cli.py
+++ b/c/tests/test_v4_cli.py
@@ -145,7 +145,7 @@ class V4CliTest(unittest.TestCase):
)
measured = {
"gain": 0.20,
- "winner": {"env": {"V4_LOADER_LANES": "3"}},
+ "winner": {"env": {"V4_LOADER_LANES": "3", "RAM_GB": "32.000"}},
}
planned = {"sentinel": "same plan used by tune and launch"}
def passthrough(_plan, env, cuda_enabled):
@@ -161,6 +161,7 @@ class V4CliTest(unittest.TestCase):
return_value="/engines/deepseek_v4"):
env = self.cli.env_for_engine(args, "deepseek_v4", plan=planned)
self.assertEqual(env["V4_LOADER_LANES"], "3")
+ self.assertEqual(env["RAM_GB"], "32.000")
self.assertNotIn("OMP_NUM_THREADS", env)
with mock.patch.dict(os.environ, {"V4_LOADER_LANES": "12"}, clear=True), \
@@ -171,9 +172,35 @@ class V4CliTest(unittest.TestCase):
return_value="/engines/deepseek_v4"):
env = self.cli.env_for_engine(args, "deepseek_v4", plan=planned)
self.assertEqual(env["V4_LOADER_LANES"], "12")
+
+ args.ram = 64
+ with mock.patch.dict(os.environ, {}, clear=True), \
+ mock.patch("resource_plan.environment_for_plan",
+ side_effect=passthrough), \
+ mock.patch("autotune.load_profile", return_value=measured), \
+ mock.patch.object(self.cli, "engine_for",
+ return_value="/engines/deepseek_v4"):
+ env = self.cli.env_for_engine(args, "deepseek_v4", plan=planned)
+ self.assertEqual(env["RAM_GB"], "64")
finally:
directory.cleanup()
+ def test_measured_cap_is_private_and_never_overrides_cli_cap(self):
+ measured = {"winner": {"env": {"OMP_NUM_THREADS": "4"}, "cap": 12}}
+ env = self.cli.apply_measured_profile({}, measured, set(), None)
+ self.assertEqual(env["COLI_PROFILE_CAP"], "12")
+ self.assertEqual(env["OMP_NUM_THREADS"], "4")
+ explicit = self.cli.apply_measured_profile({}, measured, set(), 7)
+ self.assertNotIn("COLI_PROFILE_CAP", explicit)
+ self.assertEqual(self.cli.cap_for_launch(None, env, 8), 12)
+ self.assertEqual(self.cli.cap_for_launch(7, env, 8), 7)
+ with mock.patch.dict(os.environ, {"CAP": "9"}, clear=True):
+ args = argparse.Namespace(cap=None)
+ self.assertEqual(self.cli.operator_cap(args, "glm"), 9)
+ explicit_env = self.cli.apply_measured_profile(
+ {}, measured, set(), self.cli.operator_cap(args, "glm"))
+ self.assertNotIn("COLI_PROFILE_CAP", explicit_env)
+
def test_ngen_default_differs_for_interactive_commands(self):
"""#889: `coli web` passed --max-tokens 1024, and openai_server clamps a
request to that ceiling (#260), so the browser's own "max output tokens"
@@ -236,6 +263,37 @@ class V4CliTest(unittest.TestCase):
finally:
directory.cleanup()
+ def test_v4_one_shot_translates_profiled_ram_to_cli_memory_limit(self):
+ directory, root = self.make_model()
+ args = argparse.Namespace(
+ model=str(root), prompt=["hello"], ngen=4, ram=0,
+ temp=None, ctx=0,
+ )
+ captured = {}
+
+ def fake_call(command, env):
+ captured["command"] = command
+ captured["env"] = env
+ return 0
+
+ try:
+ with mock.patch.object(self.cli.sys, "platform", "linux"), \
+ mock.patch.object(self.cli, "engine_for",
+ return_value="/engines/deepseek_v4"), \
+ mock.patch.object(self.cli, "need_model"), \
+ mock.patch.object(self.cli, "banner"), \
+ mock.patch.object(self.cli, "env_for_engine",
+ return_value={"RAM_GB": "32.000"}), \
+ mock.patch.object(self.cli.subprocess, "call",
+ side_effect=fake_call):
+ with self.assertRaises(SystemExit) as stopped:
+ self.cli.cmd_run(args)
+ self.assertEqual(stopped.exception.code, 0)
+ at = captured["command"].index("--memory-gb")
+ self.assertEqual(captured["command"][at + 1], "32.000")
+ finally:
+ directory.cleanup()
+
def test_openai_renderer_uses_native_v4_multiturn_template(self):
import openai_server
diff --git a/docs/SETTINGS.md b/docs/SETTINGS.md
index 7159ac8b..9a9aae49 100644
--- a/docs/SETTINGS.md
+++ b/docs/SETTINGS.md
@@ -79,7 +79,9 @@ Flags may also be given **after** the subcommand. Most flags map onto an engine
**`tune`**: `--prompt <text>`, `--tokens 16`, `--repeats 2`,
`--timeout 900`, `--min-gain 0.03`. The command uses fixed-token replay and
-only tests quality-preserving execution scheduling.
+only tests quality-preserving execution scheduling. For disk-backed MoE it also
+tests smaller, planner-bounded RAM/cache allocations; output, hit rate, TTFT,
+and tail-latency gates prevent a decode-only win from degrading real chat.
**`doctor`**: `--deep` strictly checks every safetensors header and tensor
layout, filename-declared shard completeness, required core tensors, an
diff --git a/docs/tuning.md b/docs/tuning.md
index 149bd931..919ae4d3 100644
--- a/docs/tuning.md
+++ b/docs/tuning.md
@@ -79,19 +79,27 @@ mixed chat instead of repeatedly loading one process or teaching the cache one
exact prompt. Greedy output is compared per prompt across every candidate; any
byte drift disqualifies the scheduling change.
-The bounded sweep only includes execution knobs such as OpenMP thread count,
-NUMA placement, I/O overlap, direct I/O, CUDA pipelining, and DeepSeek V4 expert
-loader lanes when cold experts remain on disk. It never changes weights,
+The bounded sweep includes execution knobs such as OpenMP thread count, NUMA
+placement, I/O overlap, direct I/O, CUDA pipelining, and DeepSeek V4 expert
+loader lanes. When cold experts remain on disk it also tests 75% and 50% of
+the planner's expert-cache allowance. Dense weights, KV/workspace reservations,
+and the OS reserve are never reduced, and no candidate may exceed the planner's
+safe baseline. GLM/Inkling/OLMoE/Qwen receive the measured slots-per-layer cap;
+V4 receives a whole-process `RAM_GB` ceiling; Kimi receives `K3_EXPERT_GB` under
+its unchanged whole-process ceiling. The sweep never changes weights,
quantization, router decisions, `TOPK`, `TOPP`, or sampling. Add repeatable
`--rotate-prompt` options to replace the secondary built-in workload prompt.
A candidate is saved only when median throughput improves by at least 3% while
-expert hit rate remains within 0.5 percentage points and p99 latency stays
-within 20% of the baseline. The winner is then rerun before a final baseline;
-this reverse-order gate gives the baseline any remaining warm-cache advantage
-and rejects startup drift. Otherwise the baseline is recorded and no override
-is applied. Saved profiles are loaded by `--auto-tier`; explicit environment
-variables always win. Use `--no-tune-profile` to bypass a saved profile.
+expert hit rate remains within 0.5 percentage points and reported TTFT/p99
+latency stay within 20% of the baseline. The winner is then rerun before a final
+baseline; this reverse-order gate gives the baseline any remaining warm-cache
+advantage and rejects startup drift. Otherwise the baseline is recorded and no
+override is applied. Saved profiles are loaded by `--auto-tier`; `--ram`,
+`--cap`, `RAM_GB`, `K3_EXPERT_GB`, and other explicit settings always win. A
+resource winner is rechecked against the current plan at every launch, so a
+profile measured with more free RAM is ignored rather than overcommitted later.
+Use `--no-tune-profile` to bypass a saved profile.
Profiles live under `$XDG_CONFIG_HOME/colibri/tuning` (normally
`~/.config/colibri/tuning`) or `%LOCALAPPDATA%\colibri\tuning` on Windows. A