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

fix(v41): size gateway expert cache from the RAM budget

ZacharyZcR6c78834631e3
diff --git a/c/coli b/c/coli
index 59aa7967..2501d5dd 100755
--- a/c/coli
+++ b/c/coli
@@ -492,7 +492,7 @@ def env_for_engine(a, arch, plan=None):
# #855; before that `grep -c RAM_GB c/kimi_k3.c` returned 0, so `coli chat
# --ram 242` on Kimi K3 set an environment variable nobody looked at and the
# user's session ran itself out of memory with the flag apparently set.
- if arch in ("deepseek_v4", "kimi", "glm53", "olmoe"):
+ if arch in ("deepseek_v4", "deepseek_v41", "kimi", "glm53", "olmoe"):
if a.ram: env["RAM_GB"] = str(a.ram)
if arch == "glm53":
# I densi vanno a int4 di default: sono 9,7 B parametri su 321, e in
diff --git a/c/openai_server.py b/c/openai_server.py
index d3de8dea..2275bf1e 100644
--- a/c/openai_server.py
+++ b/c/openai_server.py
@@ -2892,7 +2892,7 @@ def model_arch(model):
return resolve_model(model).descriptor.id
-def cap_for_arch(arch, cap, env=None):
+def cap_for_arch(arch, cap, env=None, model=None):
"""Cap-sentinel shim (#379): CURRENT-STATE CALIBRATION, not durable core.
An absent cap (None) means different things across today's engines --
@@ -2931,6 +2931,22 @@ def cap_for_arch(arch, cap, env=None):
planned = 0
if planned >= 1:
return planned
+ if arch == "deepseek_v41" and model is not None:
+ # V4.1 only reads its argv cap, not RAM_GB. Without --auto-tier the
+ # legacy eight slots silently discarded both --ram and RAM_GB (#1666).
+ from resource_plan import build_plan
+ settings = env if env is not None else os.environ
+ ram = settings.get("RAM_GB", "0")
+ limits = family_by_id(arch).limits
+ plan = build_plan(model, ram_gb=0 if ram == "auto" else float(ram),
+ context=int(settings.get(limits.context_env, limits.default_context)),
+ gpu_indices=[])
+ slots = plan["tiers"]["ram"]["cache_slots_per_layer"]
+ if slots < 1:
+ raise ValueError("DeepSeek V4.1 RAM budget cannot hold one expert slot per layer")
+ print(f"[v41] RAM plan: {slots} expert cache slots/layer; --cap overrides",
+ file=sys.stderr)
+ return slots
return family_by_id(arch).limits.implicit_cap
@@ -3071,7 +3087,7 @@ 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)
+ resolved_cap = cap_for_arch(arch, cap, child_env, model=model)
child_env.pop("COLI_PROFILE_CAP", None)
child_env.pop("COLI_PLAN_CAP", None)
self.process = subprocess.Popen(
diff --git a/c/tests/test_openai_server.py b/c/tests/test_openai_server.py
index 75e691e7..04cb93a6 100644
--- a/c/tests/test_openai_server.py
+++ b/c/tests/test_openai_server.py
@@ -1275,6 +1275,40 @@ class CapSentinelShimTest(unittest.TestCase):
self.assertNotIn("COLI_PLAN_CAP", child_env)
self.assertEqual(child_env["KEEP"], "yes")
+ def test_v41_ram_plan_reaches_engine_argv(self):
+ model = self._model("deepseek_v41")
+ for settings, expected_ram in (({"RAM_GB": "120", "CTX": "8192"}, 120),
+ ({"CTX": "8192"}, 0),
+ ({"RAM_GB": "auto", "CTX": "8192"}, 0)):
+ with self.subTest(settings=settings):
+ process = FakeProcess(lambda _process, _frame: None)
+ with patch("resource_plan.build_plan", return_value={
+ "tiers": {"ram": {"cache_slots_per_layer": 96}}}) as planner, \
+ patch("openai_server.subprocess.Popen", return_value=process) as popen:
+ engine = Engine("deepseek_v41", model, env=settings)
+ engine.close()
+ planner.assert_called_once_with(model, ram_gb=expected_ram,
+ context=8192, gpu_indices=[])
+ self.assertEqual(popen.call_args[0][0], ["deepseek_v41", "96"])
+
+ def test_v41_explicit_and_calibrated_caps_bypass_planning(self):
+ for cap, env, expected in ((7, {}, 7), (0, {}, 0),
+ (None, {"COLI_PROFILE_CAP": "12"}, 12),
+ (None, {"COLI_PLAN_CAP": "24"}, 24)):
+ with self.subTest(cap=cap, env=env), patch("resource_plan.build_plan") as planner:
+ self.assertEqual(cap_for_arch("deepseek_v41", cap, env, model="model"),
+ expected)
+ planner.assert_not_called()
+
+ def test_v41_insufficient_ram_refuses_before_spawning(self):
+ model = self._model("deepseek_v41")
+ with patch("resource_plan.build_plan", return_value={
+ "tiers": {"ram": {"cache_slots_per_layer": 0}}}), \
+ patch("openai_server.subprocess.Popen") as popen:
+ with self.assertRaisesRegex(ValueError, "one expert slot"):
+ Engine("deepseek_v41", model, env={"RAM_GB": "8"})
+ popen.assert_not_called()
+
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_resource_plan.py b/c/tests/test_resource_plan.py
index 232b028c..d149cf77 100644
--- a/c/tests/test_resource_plan.py
+++ b/c/tests/test_resource_plan.py
@@ -146,6 +146,30 @@ class ResourcePlanTest(unittest.TestCase):
with self.subTest(engine_group=group, case=case[:2]):
self.assertEqual(_auto_tune(*case, False, engine_group=group), {})
+ def test_v41_gateway_sizes_cap_from_ram_without_auto_tier(self):
+ from openai_server import cap_for_arch
+
+ (self.model / "config.json").write_text(json.dumps({
+ "model_type": "deepseek_v41", "num_hidden_layers": 2,
+ "n_routed_experts": 128, "hidden_size": 128, "head_dim": 64,
+ "window_size": 8, "index_head_dim": 32, "hc_mult": 4,
+ "compress_ratios": [0, 2], "kv_source_layers": [1],
+ }))
+ write_shard(self.model / "model.safetensors", [
+ ("embed.weight", GB),
+ *[(f"layers.{layer}.ffn.experts.{expert}.w1.weight", 16 * 1024**2)
+ for layer in range(2) for expert in range(128)],
+ ])
+ with mock.patch("resource_plan.memory_available", return_value=16 * GB):
+ small = cap_for_arch("deepseek_v41", None, {"RAM_GB": "8"}, self.model)
+ large = cap_for_arch("deepseek_v41", None, {"RAM_GB": "12"}, self.model)
+ automatic = cap_for_arch("deepseek_v41", None, {}, self.model)
+ self.assertGreater(small, 8)
+ self.assertGreater(large, small)
+ self.assertEqual(large, 128)
+ self.assertEqual(automatic, 128)
+ self.assertEqual(cap_for_arch("deepseek_v41", 4, {"RAM_GB": "12"}, self.model), 4)
+
def test_sibling_plan_advises_no_colibri_knob(self):
other = tempfile.TemporaryDirectory()
self.addCleanup(other.cleanup)
diff --git a/c/tests/test_v4_cli.py b/c/tests/test_v4_cli.py
index 46896681..2d80b155 100644
--- a/c/tests/test_v4_cli.py
+++ b/c/tests/test_v4_cli.py
@@ -135,6 +135,13 @@ class V4CliTest(unittest.TestCase):
os.path.abspath(args.model),
)
+ def test_v41_ram_flag_overrides_inherited_budget(self):
+ args = argparse.Namespace(ngen=8, temp=None, ram=96, ctx=4096)
+ with mock.patch.dict(os.environ, {"RAM_GB": "32"}):
+ env = self.cli.env_for_engine(args, "deepseek_v41")
+ self.assertEqual(env["RAM_GB"], "96")
+ self.assertEqual(env["CTX"], "4096")
+
def test_kimi_engine_environment_forwards_ram(self):
"""#855: `--ram` reached the environment for deepseek_v4 only, so on Kimi
K3 it was set and never read -- the flag a user reaches for to bound
diff --git a/docs/deepseek-v41.md b/docs/deepseek-v41.md
index a4cee5b3..b81d8d94 100644
--- a/docs/deepseek-v41.md
+++ b/docs/deepseek-v41.md
@@ -41,6 +41,18 @@ decimal **strings**: they run past a double's 53-bit mantissa, and a rounded
multiplier would silently hash every n-gram into a different -- and perfectly
valid-looking -- row.
+When `--cap` is omitted, `coli chat`, `coli serve`, and `coli web` size the expert
+cache from the resource plan. `--ram 120` (or `RAM_GB=120`) supplies its RAM budget;
+without either, the planner uses available memory. Dense weights, context state,
+and runtime reserves are subtracted before choosing slots per layer. `--cap N`
+still selects an explicit slot count, and an existing `--auto-tier` plan or measured
+profile retains precedence over this fallback. The startup line reports the chosen
+cap. The budget is a ceiling, not a promise to fill RSS: cache slots fill on demand
+and engram tables continue streaming from disk.
+
+The standalone `deepseek_v41` binary still takes its cap as its first argument;
+`RAM_GB` planning happens in the Python gateway.
+
## What the engine implements
Each mechanism mirrors a named piece of the vendor's `inference/model.py`: