Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: raise the llama-server micro-batch to 2048 when MoE experts spill to RAM (#12950)

Daniel Han3ac616dd70d1
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index ab8b3c2e658..cdcc0958c77 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -6930,6 +6930,83 @@ def _embedding_batch_ubatch(
return (n_batch if batch_named else n_ctx), (n_ubatch if ubatch_named else n_ctx)
+# Micro-batch when MoE experts sit in host RAM. Prompt processing copies each
+# layer's routed experts over PCIe once per micro-batch (ggml op offload), so 4x
+# larger means 4x fewer copies. Measured on T4 / L4 / A100 with Qwen3.6-35B-A3B,
+# gemma-4-26B-A4B, Qwen3.8-Flash-Next and GLM-5.3-Flash: prompt +60% to +260%,
+# decode unchanged. 4096 was slower overall: its bigger compute buffer pushed
+# expert layers off the GPU and cost decode. llama.cpp's default batch (2048)
+# already covers it.
+_MOE_SPILL_N_UBATCH = 2048
+
+
+def _moe_spill_batch_ubatch(
+ n_batch: Optional[int],
+ n_ubatch: Optional[int],
+ *,
+ n_moe_layers: int,
+ experts_on_host: bool,
+ discrete_gpu: bool,
+ user_named_batch: bool,
+) -> tuple[Optional[int], Optional[int]]:
+ """Raise an unset micro-batch to ``_MOE_SPILL_N_UBATCH`` when experts spill.
+
+ Only for an MoE whose experts are (or may be) in host RAM next to a discrete GPU,
+ the transfer-bound prompt path. A batch or micro-batch the user set (first-class
+ field, pass-through flag or LLAMA_ARG_BATCH / LLAMA_ARG_UBATCH) always wins, and
+ a larger projector value already in ``n_ubatch`` is kept, so this only raises.
+ Read ``user_named_batch`` BEFORE the projector and embedding raises set ``n_ubatch``.
+ """
+ if user_named_batch or not experts_on_host or not discrete_gpu or n_moe_layers <= 0:
+ return n_batch, n_ubatch
+ current = _DEFAULT_LLAMA_N_UBATCH if n_ubatch is None else int(n_ubatch)
+ if current >= _MOE_SPILL_N_UBATCH:
+ return n_batch, n_ubatch
+ # llama.cpp caps the micro-batch at the batch, so keep batch >= micro-batch.
+ batch = _DEFAULT_LLAMA_N_BATCH if n_batch is None else int(n_batch)
+ if batch < _MOE_SPILL_N_UBATCH:
+ n_batch = _MOE_SPILL_N_UBATCH
+ return n_batch, _MOE_SPILL_N_UBATCH
+
+
+def _override_targets_host(value: str) -> bool:
+ """Whether an ``--override-tensor`` value sends any tensor to host memory
+ (``CPU``, ``CPU_REPACK``, ``CUDA_Host``, ...), not only to GPUs."""
+ targets = [
+ part.rsplit("=", 1)[-1].strip().lower() for part in str(value).split(",") if "=" in part
+ ]
+ return any(t.startswith("cpu") or t.endswith("_host") for t in targets)
+
+
+def _expert_spill_places_tensors_on_cpu(
+ extra_args: Optional[Iterable[str]] = None, env: Optional[Mapping[str, str]] = None
+) -> bool:
+ """Host placement from extras or env, for the expert-spill micro-batch raise.
+
+ ``_args_place_tensors_on_cpu`` / ``_env_places_tensors_on_cpu`` count any ``-ot``,
+ which suits their residency gates. Here an override counts only when it targets
+ host memory: ``-ot exps=CUDA0`` keeps the weights on a GPU, so there is no copy to
+ amortise, and on ``--fit off`` the larger compute buffer would go unpriced.
+ """
+ args = [str(a) for a in extra_args or ()]
+ kept: list[str] = []
+ i = 0
+ while i < len(args):
+ if _flag_name(args[i]) in {"-ot", "--override-tensor"}:
+ _, eq, inline = args[i].partition("=")
+ step = 1 if eq else 2
+ if _override_targets_host(inline if eq else (args[i + 1] if i + 1 < len(args) else "")):
+ kept.extend(args[i : i + step])
+ i += step
+ continue
+ kept.append(args[i])
+ i += 1
+ source_env = dict(os.environ if env is None else env)
+ if not _override_targets_host(source_env.get("LLAMA_ARG_OVERRIDE_TENSOR") or ""):
+ source_env.pop("LLAMA_ARG_OVERRIDE_TENSOR", None)
+ return _args_place_tensors_on_cpu(kept) or _env_places_tensors_on_cpu(source_env)
+
+
def _build_ngram_mod_flags(
caps: Optional[dict],
n_match: int = 24,
@@ -7783,6 +7860,9 @@ class LlamaCppBackend:
# --batch-size / --ubatch-size the last load asked for; none = defaults or extras / env
self._requested_n_batch: Optional[int] = None
self._requested_n_ubatch: Optional[int] = None
+ # The expert-spill micro-batch raise: the pair before it, and the argv tokens.
+ self._moe_spill_batch_restore: Optional[tuple[Optional[int], Optional[int]]] = None
+ self._moe_spill_batch_tokens: Optional[tuple[list[str], list[str]]] = None
# The tuning group the last load asked for; none = defaults, or left to
# extras / env. What was REQUESTED, not what ran: Model Memory can replace
# the load mode, and Windows full-offload tuning owns the two cache knobs.
@@ -23180,6 +23260,48 @@ class LlamaCppBackend:
env.pop(name, None)
return replay
+ def _undo_moe_spill_batch(self, argv: "list[str]") -> "list[str]":
+ """``argv`` with the expert-spill batch pair restored.
+
+ Replaces only Unsloth's own contiguous tokens; a launch that did not raise
+ them comes back unchanged."""
+ tokens = getattr(self, "_moe_spill_batch_tokens", None)
+ if not tokens:
+ return list(argv)
+ raised, before = tokens
+ argv = list(argv)
+ for i in range(len(argv) - len(raised) + 1):
+ if argv[i : i + len(raised)] == raised:
+ return [*argv[:i], *before, *argv[i + len(raised) :]]
+ return argv
+
+ def _discrete_gpu_for_expert_spill(
+ self,
+ gpu_indices: Optional[Iterable[int]],
+ detected_gpus: Optional[Iterable[tuple[int, int]]],
+ shared_gpu_ids: Optional[Iterable[int]] = None,
+ ) -> bool:
+ """Whether host-resident experts would stream to a discrete GPU.
+
+ The raise only pays off over a PCIe copy. Unified memory (Apple Silicon, an
+ AMD APU, an integrated CUDA SoC, a Vulkan iGPU) has nothing to stream, and no
+ GPU means a CPU launch."""
+ detected = list(detected_gpus or ())
+ if not detected or _metal_capable_host():
+ return False
+ on = set(gpu_indices) if gpu_indices else {idx for idx, _free in detected}
+ if on and on <= set(shared_gpu_ids or ()):
+ return False
+ try:
+ if self._amd_apu_wants_unified_memory(
+ gpu_indices
+ ) or self._integrated_cuda_unified_memory(gpu_indices):
+ return False
+ except Exception as e:
+ logger.debug(f"unified-memory probe failed ({e}); not raising the micro-batch")
+ return False
+ return True
+
def _prepare_cpu_fallback_launch(
self,
binary: Optional[str],
@@ -23223,6 +23345,8 @@ class LlamaCppBackend:
replay = self._drop_managed_dio(
replay, "the CPU fallback runs entirely from host RAM", clear_record = False
)
+ # Nothing to stream without a GPU: put back the pre-raise batch pair.
+ replay = self._undo_moe_spill_batch(replay)
# A user's own "--load-mode none" / "--no-mmap" survives that strip, by design,
# and on this rung it is no longer the mode they were priced for: the replay
# appends "--gpu-layers 0 --fit off --device none", so nothing credits VRAM and
@@ -24337,6 +24461,10 @@ class LlamaCppBackend:
logger.info("Load cancelled after download phase")
return False
+ # Whether the user set the batch pair, read before the embedding and projector
+ # raises below overwrite n_batch / n_ubatch. Gates the expert-spill raise.
+ _user_named_batch = any(_named_batch_sizes(extra_args, None, n_batch, n_ubatch)[2:])
+
# MEAN/CLS inputs must fit one micro-batch (LAST splits). Before the projector raise,
# which would otherwise read as a user-set micro-batch.
if self._pooling_type in (1, 2):
@@ -24832,6 +24960,8 @@ class LlamaCppBackend:
_ctx_capped_for_vram = False
# A path that never prices the launch must not commit the previous one's plan.
self._pending_plan_mib = {}
+ # Set by the expert-spill raise after the fit.
+ self._moe_spill_batch_restore: Optional[tuple[Optional[int], Optional[int]]] = None
_shared_gpus = frozenset()
# Sized inputs for the tensor-spill planner, None when the fit never
# priced them. Bound before the try like _placement_verdict_partial:
@@ -25429,6 +25559,8 @@ class LlamaCppBackend:
if mtp_overhead_fn is None:
return 0
if slots is None:
+ if ubatch:
+ return mtp_overhead_fn(ctx, _n_ubatch = ubatch)
return mtp_overhead_fn(ctx)
return mtp_overhead_fn(
ctx, _np = slots, _n_ubatch = ubatch if ubatch else _effective_ubatch
@@ -27098,6 +27230,58 @@ class LlamaCppBackend:
# selection inversion #9492 removed, pointing the other way.
max_available_ctx = _ceiling[0]
+ # MoE experts in host RAM: a larger micro-batch amortises the expert
+ # copies of prompt processing (see _MOE_SPILL_N_UBATCH). The placement
+ # verdict above was priced at the default micro-batch, so a model that
+ # fits keeps today's launch. This runs before every term that reads the
+ # micro-batch (MTP reserve, KV, compute buffer, spill planner, load mode),
+ # so the larger buffer is priced: the spill planner keeps fewer experts on
+ # the GPU, and llama.cpp's fitter measures a --fit on launch at the emitted
+ # value. Manual pinned layers (--fit off) are the user's placement, where an
+ # unpriced larger buffer could OOM, so they are left alone. A GPU-only -ot
+ # does not count for the same reason. A user --device none / cpu runs on
+ # the CPU with nothing to stream, like the CPU fallback.
+ _moe_experts_on_host = bool(
+ not (gpu_memory_mode == "manual" and gpu_layers >= 0)
+ and not intent.cpu_fallback
+ and not _device_selection_is_cpu(extra_args, os.environ)
+ and (use_fit or _expert_spill_places_tensors_on_cpu(extra_args, os.environ))
+ )
+ _spill_n_batch, _spill_n_ubatch = _moe_spill_batch_ubatch(
+ n_batch,
+ n_ubatch,
+ n_moe_layers = self.n_moe_layers,
+ experts_on_host = _moe_experts_on_host,
+ discrete_gpu = (
+ _moe_experts_on_host
+ and self._discrete_gpu_for_expert_spill(
+ gpu_indices, _detected_gpus, _shared_gpu_ids
+ )
+ ),
+ user_named_batch = _user_named_batch,
+ )
+ if _spill_n_ubatch != n_ubatch:
+ logger.info(
+ "MoE experts are offloaded to system RAM; raising --ubatch-size "
+ "%s -> %s for faster prompt processing.",
+ n_ubatch if n_ubatch is not None else _DEFAULT_LLAMA_N_UBATCH,
+ _spill_n_ubatch,
+ )
+ self._moe_spill_batch_restore = (n_batch, n_ubatch)
+ n_batch, n_ubatch = _spill_n_batch, _spill_n_ubatch
+ _effective_ubatch = _ubatch_for_slots(n_parallel)
+ # Same calls and fallbacks as above, at the new micro-batch.
+ _compute_buffer_pipeline = self._estimate_compute_buffer_bytes(
+ n_ubatch = _effective_ubatch,
+ n_parallel = n_parallel,
+ per_device_tensor = False,
+ ) or (self._TENSOR_PARALLEL_BUFFER_RESERVE_MIB * 1024 * 1024)
+ _compute_buffer_tensor = self._estimate_compute_buffer_bytes(
+ n_ubatch = _effective_ubatch,
+ n_parallel = n_parallel,
+ per_device_tensor = True,
+ ) or (self._TENSOR_PARALLEL_BUFFER_RESERVE_MIB * 1024 * 1024)
+
# Pass the final slot and micro-batch values instead of the defaults
# captured before slot reduction.
_mtp_reserve_bytes = (
@@ -27409,7 +27593,15 @@ class LlamaCppBackend:
# Checkpoints are split into host_only_bytes below.
kv_cache_bytes = _kv_bytes(effective_ctx, 0),
kv_sized = self._can_estimate_kv(),
- mtp_bytes = _mtp_bytes(effective_ctx),
+ # mtp_overhead_fn bound the pre-raise micro-batch; charge the raised one.
+ mtp_bytes = _mtp_bytes(
+ effective_ctx,
+ ubatch = (
+ _effective_ubatch
+ if self._moe_spill_batch_restore is not None
+ else None
+ ),
+ ),
# _flat_mtp_engages whole: its other arm, _mtp_kv_unsized,
# prices weights but NO draft KV, and the placement covers that
# gap with a flat cushion this footprint has no term for --
@@ -27818,6 +28010,27 @@ class LlamaCppBackend:
cmd.extend(["--batch-size", str(_emit_batch)])
if n_ubatch is not None:
cmd.extend(["--ubatch-size", str(n_ubatch)])
+ # The expert-spill raise, as emitted and as it was before, so a CPU
+ # replay (no GPU, nothing to stream) can hand back today's pair.
+ self._moe_spill_batch_tokens = None
+ if self._moe_spill_batch_restore is not None:
+ _orig_batch, _orig_ubatch = self._moe_spill_batch_restore
+ _raised = ["--ubatch-size", str(n_ubatch)]
+ _before = [] if _orig_ubatch is None else ["--ubatch-size", str(_orig_ubatch)]
+ if n_batch is not None and n_batch != _orig_batch:
+ _raised = ["--batch-size", str(_emit_batch), *_raised]
+ _before = [
+ *(
+ []
+ if _orig_batch is None
+ else [
+ "--batch-size",
+ str(_emitted_n_batch(_orig_batch, n_parallel)),
+ ]
+ ),
+ *_before,
+ ]
+ self._moe_spill_batch_tokens = (_raised, _before)
server_caps = _launch_caps(binary)
diff --git a/studio/backend/tests/test_batch_sizes_per_load.py b/studio/backend/tests/test_batch_sizes_per_load.py
index d6a7c83fb78..4d61418378d 100644
--- a/studio/backend/tests/test_batch_sizes_per_load.py
+++ b/studio/backend/tests/test_batch_sizes_per_load.py
@@ -654,9 +654,9 @@ def test_the_recorded_micro_batch_is_derived_from_the_slots_that_launched():
and isinstance(node.func, ast.Name)
and node.func.id == "_ubatch_for_slots"
]
- # sizing pass, embedding slot clamp, candidate split pricing, fit-time reduction, then
- # the post-launch record
- assert len(calls) == 5, f"expected five re-derivations, found {len(calls)}"
+ # sizing pass, embedding slot clamp, candidate split pricing, fit-time reduction, the
+ # MoE expert-spill raise, then the post-launch record
+ assert len(calls) == 6, f"expected six re-derivations, found {len(calls)}"
# the record must not reuse the sizing pass's value
compact = "".join(src.split())
assert "self._n_ubatch=max(0,int(self._DEFAULT_N_UBATCHif_launched_ubatchisNone" in compact
diff --git a/studio/backend/tests/test_llama_cpp_placement.py b/studio/backend/tests/test_llama_cpp_placement.py
index 266d02ccf51..b6e7a7fc18b 100644
--- a/studio/backend/tests/test_llama_cpp_placement.py
+++ b/studio/backend/tests/test_llama_cpp_placement.py
@@ -3941,3 +3941,343 @@ def test_the_loader_prices_the_output_rows_of_its_build(tmp_path, monkeypatch, b
assert calls["flat"], "the fit never priced the flat compute buffer"
assert set(calls["flat"]) == {expected}
+
+
+# MoE experts in host RAM: the larger prompt micro-batch.
+
+_GIB = 1024**3
+
+
+def _moe_backend(
+ tmp_path,
+ *,
+ size_gib,
+ memory,
+ moe = True,
+):
+ """A placement fixture whose GGUF reads as MoE (or dense) at ``size_gib``."""
+ backend, gguf = _backend(tmp_path, vulkan = False, memory = memory)
+ backend._get_gguf_size_bytes = lambda _path: int(size_gib * _GIB)
+ backend._n_layers = 40
+ backend._n_experts = 256 if moe else None
+ backend._leading_dense_block_count = 0
+ return backend, gguf
+
+
+def _ubatch_values(cmd):
+ return [cmd[i + 1] for i, tok in enumerate(cmd) if tok in ("--ubatch-size", "-ub")]
+
+
+def _batch_values(cmd):
+ return [cmd[i + 1] for i, tok in enumerate(cmd) if tok in ("--batch-size", "-b")]
+
+
+def _discrete_linux_host(monkeypatch):
+ monkeypatch.setattr(llama_cpp_module, "_metal_capable_host", lambda: False)
+ for name in ("LLAMA_ARG_BATCH", "LLAMA_ARG_UBATCH", "LLAMA_ARG_N_CPU_MOE", "LLAMA_ARG_CPU_MOE"):
+ monkeypatch.delenv(name, raising = False)
+
+
+_SPILLED = dict(size_gib = 20, memory = [(0, 8_000, 16_000)])
+_RESIDENT = dict(size_gib = 1, memory = [(0, 40_000, 48_000)])
+
+
+def test_spilled_moe_experts_raise_the_micro_batch(tmp_path, _discrete_linux_host):
+ backend, gguf = _moe_backend(tmp_path, **_SPILLED)
+ cmd = _launch(backend, gguf)["cmd"]
+
+ assert "--fit" in cmd and cmd[cmd.index("--fit") + 1] == "on", cmd
+ assert _ubatch_values(cmd) == ["2048"], cmd
+ # No -b: llama.cpp's default batch (2048) already holds the micro-batch.
+ assert all(int(b) >= 2048 for b in _batch_values(cmd)), cmd
+ assert backend._n_ubatch == 2048
+ # The dedupe still compares against what the user asked for: nothing.
+ assert backend.requested_n_ubatch is None
+
+
+def test_a_fully_resident_moe_keeps_the_default_micro_batch(tmp_path, _discrete_linux_host):
+ backend, gguf = _moe_backend(tmp_path, **_RESIDENT)
+ cmd = _launch(backend, gguf)["cmd"]
+
+ assert cmd[cmd.index("--fit") + 1] == "off", cmd
+ assert _ubatch_values(cmd) == [] and _batch_values(cmd) == [], cmd
+ assert backend._n_ubatch == backend._DEFAULT_N_UBATCH
+
+
+def test_a_spilled_dense_model_keeps_the_default_micro_batch(tmp_path, _discrete_linux_host):
+ backend, gguf = _moe_backend(tmp_path, moe = False, **_SPILLED)
+ cmd = _launch(backend, gguf)["cmd"]
+
+ assert cmd[cmd.index("--fit") + 1] == "on", cmd
+ assert _ubatch_values(cmd) == [] and _batch_values(cmd) == [], cmd
+
+
+ "extra_args",
+ [
+ ["--cpu-moe"],
+ ["-ncmoe", "12"],
+ ["-ot", r"blk\.\d+\.ffn_.*_exps\.=CPU"],
+ ],
+ ids = ["cmoe", "ncmoe", "ot_exps"],
+)
+def test_pass_through_expert_offload_raises_the_micro_batch(
+ tmp_path, _discrete_linux_host, extra_args
+):
+ # Fits on the card, so only the pass-through puts experts in host RAM.
+ backend, gguf = _moe_backend(tmp_path, **_RESIDENT)
+ cmd = _launch(backend, gguf, extra_args = extra_args)["cmd"]
+
+ assert _ubatch_values(cmd) == ["2048"], cmd
+
+
+def test_an_inherited_expert_offload_raises_the_micro_batch(
+ tmp_path, _discrete_linux_host, monkeypatch
+):
+ monkeypatch.setenv("LLAMA_ARG_N_CPU_MOE", "20")
+ backend, gguf = _moe_backend(tmp_path, **_RESIDENT)
+ cmd = _launch(backend, gguf)["cmd"]
+
+ assert _ubatch_values(cmd) == ["2048"], cmd
+
+
+ "extra_args, env, expect_ub",
+ [
+ (["-ot", r"blk\.\d+\.ffn_.*_exps\.=CUDA0"], {}, []),
+ ([r"--override-tensor=token_embd\.weight=CUDA0"], {}, []),
+ ([], {"LLAMA_ARG_OVERRIDE_TENSOR": r"blk\.\d+\.ffn_.*_exps\.=CUDA0"}, []),
+ (["-ot", r"blk\.1\.ffn_.*_exps\.=CUDA0,blk\.2\.ffn_.*_exps\.=CPU"], {}, ["2048"]),
+ ([], {"LLAMA_ARG_OVERRIDE_TENSOR": r"blk\.\d+\.ffn_.*_exps\.=CPU"}, ["2048"]),
+ ],
+ ids = ["ot_gpu", "ot_gpu_inline", "env_ot_gpu", "ot_mixed", "env_ot_cpu"],
+)
+def test_an_override_raises_the_micro_batch_only_when_it_targets_the_host(
+ tmp_path, _discrete_linux_host, monkeypatch, extra_args, env, expect_ub
+):
+ # A resident model, so --fit stays off and only the override can move experts.
+ for name, value in env.items():
+ monkeypatch.setenv(name, value)
+ backend, gguf = _moe_backend(tmp_path, **_RESIDENT)
+ cmd = _launch(backend, gguf, extra_args = extra_args)["cmd"]
+
+ assert cmd[cmd.index("--fit") + 1] == "off", cmd
+ assert _ubatch_values(cmd) == expect_ub, cmd
+
+
+ "extra_args, env, expect_ub",
+ [
+ (["--device", "none"], {}, []),
+ (["-dev", "none"], {}, []),
+ (["--device", "cpu"], {}, []),
+ (["--device=none"], {}, []),
+ ([], {"LLAMA_ARG_DEVICE": "none"}, []),
+ ([], {"LLAMA_ARG_DEVICE": "cpu"}, []),
+ # argv beats the env twin, so this one still runs on the GPU.
+ (["--device", "CUDA0"], {"LLAMA_ARG_DEVICE": "none"}, ["2048"]),
+ ],
+ ids = ["dev_none", "dev_short", "dev_cpu", "dev_inline", "env_none", "env_cpu", "argv_wins"],
+)
+def test_a_user_cpu_device_keeps_the_default_micro_batch(
+ tmp_path, _discrete_linux_host, monkeypatch, extra_args, env, expect_ub
+):
+ # Spilled, so the raise would otherwise fire: on the CPU there is nothing to stream.
+ monkeypatch.delenv("LLAMA_ARG_DEVICE", raising = False)
+ for name, value in env.items():
+ monkeypatch.setenv(name, value)
+ backend, gguf = _moe_backend(tmp_path, **_SPILLED)
+ cmd = _launch(backend, gguf, extra_args = extra_args)["cmd"]
+
+ assert _ubatch_values(cmd) == expect_ub, cmd
+
+
+ "load_kwargs, env, expect_ub, expect_b",
+ [
+ (dict(extra_args = ["-ub", "1024"]), {}, ["1024"], []),
+ (dict(extra_args = ["--ubatch-size=256"]), {}, ["--ubatch-size=256"], []),
+ (dict(extra_args = ["-b", "1024"]), {}, [], ["1024"]),
+ (dict(n_ubatch = 1024), {}, ["1024"], []),
+ (dict(n_batch = 4096), {}, [], ["4096"]),
+ ({}, {"LLAMA_ARG_UBATCH": "256"}, [], []),
+ ({}, {"LLAMA_ARG_BATCH": "1024"}, [], []),
+ ],
+ ids = ["argv_ub", "argv_ub_inline", "argv_b", "field_ub", "field_b", "env_ub", "env_b"],
+)
+def test_a_user_batch_pair_wins_over_the_expert_spill_raise(
+ tmp_path, _discrete_linux_host, monkeypatch, load_kwargs, env, expect_ub, expect_b
+):
+ for name, value in env.items():
+ monkeypatch.setenv(name, value)
+ backend, gguf = _moe_backend(tmp_path, **_SPILLED)
+ cmd = _launch(backend, gguf, **load_kwargs)["cmd"]
+
+ if expect_ub == ["--ubatch-size=256"]:
+ assert "--ubatch-size=256" in cmd and _ubatch_values(cmd) == [], cmd
+ else:
+ assert _ubatch_values(cmd) == expect_ub, cmd
+ assert _batch_values(cmd) == expect_b, cmd
+ assert "2048" not in _ubatch_values(cmd)
+
+
+ "required, n_batch, expect_ub, expect_b",
+ [
+ # A small projector floor: the spill raise is the larger, so it wins.
+ (1024, None, ["2048"], []),
+ # A floor at the default batch: one flag, no duplicate.
+ (4096, None, ["2048"], []),
+ # The user's batch lets the projector floor exceed 2048: it is kept, not lowered.
+ (4096, 8192, ["4096"], ["8192"]),
+ ],
+ ids = ["spill_beats_small_floor", "floor_capped_at_batch", "floor_above_2048_kept"],
+)
+def test_a_projector_micro_batch_floor_is_respected(
+ tmp_path, _discrete_linux_host, monkeypatch, required, n_batch, expect_ub, expect_b
+):
+ monkeypatch.setattr(llama_cpp_module, "_launch_required_ubatch", lambda *a, **k: required)
+ backend, gguf = _moe_backend(tmp_path, **_SPILLED)
+ cmd = _launch(backend, gguf, n_batch = n_batch)["cmd"]
+
+ assert _ubatch_values(cmd) == expect_ub, cmd
+ assert _batch_values(cmd) == expect_b, cmd
+
+
+def test_a_cpu_only_host_keeps_the_default_micro_batch(tmp_path, _discrete_linux_host):
+ backend, gguf = _moe_backend(tmp_path, size_gib = 20, memory = [])
+ cmd = _launch(backend, gguf)["cmd"]
+
+ assert _ubatch_values(cmd) == [] and _batch_values(cmd) == [], cmd
+
+
+def test_unified_memory_keeps_the_default_micro_batch(tmp_path, _discrete_linux_host):
+ backend, gguf = _moe_backend(tmp_path, **_SPILLED)
+ backend._amd_apu_wants_unified_memory = lambda *args, **kwargs: True
+ cmd = _launch(backend, gguf)["cmd"]
+
+ assert _ubatch_values(cmd) == [], cmd
+
+
+def test_apple_silicon_keeps_the_default_micro_batch(tmp_path, _discrete_linux_host, monkeypatch):
+ monkeypatch.setattr(llama_cpp_module, "_metal_capable_host", lambda: True)
+ backend, gguf = _moe_backend(tmp_path, **_SPILLED)
+ assert backend._discrete_gpu_for_expert_spill(None, [(0, 8_000)], set()) is False
+
+
+def test_manual_pinned_layers_keep_the_default_micro_batch(tmp_path, _discrete_linux_host):
+ backend, gguf = _moe_backend(tmp_path, **_SPILLED)
+ cmd = _launch(backend, gguf, gpu_memory_mode = "manual", gpu_layers = 40, n_cpu_moe = 20)["cmd"]
+
+ assert "--n-cpu-moe" in cmd, cmd
+ assert _ubatch_values(cmd) == [], cmd
+
+
+def test_the_spill_planner_is_priced_at_the_raised_micro_batch(
+ tmp_path, _discrete_linux_host, monkeypatch
+):
+ """The compute buffer the plan reserves grows with the micro-batch, so the
+ planner keeps fewer experts on the GPU instead of the launch OOMing."""
+ seen = {}
+
+ def capture(self, inputs, **_kwargs):
+ seen["inputs"] = dict(inputs or {})
+ return None
+
+ monkeypatch.setattr(LlamaCppBackend, "_planned_tensor_spill", capture)
+
+ def run(**load_kwargs):
+ backend, gguf = _moe_backend(tmp_path, **_SPILLED)
+ backend._can_estimate_kv = lambda: True
+ backend._estimate_kv_cache_bytes = lambda *a, **k: _GIB
+ backend._estimate_compute_buffer_bytes = (
+ lambda *, n_ubatch = None, **_k: (n_ubatch or 512) * 400 * 1024
+ )
+ backend._compute_buffer_ctx_bytes = lambda *a, **k: 0
+ cmd = _launch(backend, gguf, **load_kwargs)["cmd"]
+ return cmd, seen.pop("inputs")
+
+ cmd, raised = run()
+ assert _ubatch_values(cmd) == ["2048"], cmd
+ assert raised["compute_buffer_flat"] == 2048 * 400 * 1024
+
+ cmd, pinned = run(n_ubatch = 512)
+ assert _ubatch_values(cmd) == ["512"], cmd
+ assert pinned["compute_buffer_flat"] == 512 * 400 * 1024
+
+
+def test_the_load_mode_fit_prices_the_drafter_at_the_raised_micro_batch(
+ tmp_path, _discrete_linux_host
+):
+ """The drafter reserve grows with the micro-batch, so the load-mode RAM fit
+ charges it at the raised value, as the placement does."""
+ backend, gguf = _moe_backend(tmp_path, **_SPILLED)
+ backend.probe_server_capabilities = lambda _binary = None: {
+ "mtp_token": "draft-mtp",
+ "spec_draft_n_max_flag": "--spec-draft-n-max",
+ }
+ backend._resolve_launch_mtp_path = lambda **_k: "/fake/mtp.gguf"
+ priced = []
+ estimate = LlamaCppBackend._estimate_mtp_overhead_bytes
+
+ def price(self, ctx, **kwargs):
+ value = estimate(self, ctx, **kwargs)
+ priced.append((kwargs.get("n_ubatch"), value))
+ return value
+
+ charged = []
+ fit = LlamaCppBackend._fit_derived_load_mode
+
+ def load_mode(self, **kwargs):
+ charged.append((kwargs.get("mtp_bytes"), priced[-1]))
+ return fit(self, **kwargs)
+
+ backend._estimate_mtp_overhead_bytes = price.__get__(backend)
+ backend._fit_derived_load_mode = load_mode.__get__(backend)
+ cmd = _launch(
+ backend, gguf, mtp_draft_path = "/fake/mtp.gguf", speculative_type = "mtp", n_ctx = 131072
+ )["cmd"]
+
+ assert _ubatch_values(cmd) == ["2048"], cmd
+ mtp_bytes, (n_ubatch, value) = charged[-1]
+ assert mtp_bytes > 0 and mtp_bytes == value
+ assert n_ubatch == 2048
+
+
+def test_the_cpu_replay_hands_back_the_default_micro_batch():
+ backend = LlamaCppBackend()
+ argv = ["llama-server", "-m", "x.gguf", "--ubatch-size", "2048", "--jinja"]
+ assert backend._undo_moe_spill_batch(argv) == argv
+
+ backend._moe_spill_batch_tokens = (["--ubatch-size", "2048"], [])
+ assert backend._undo_moe_spill_batch(argv) == ["llama-server", "-m", "x.gguf", "--jinja"]
+
+ # A projector floor that was raised further goes back to the floor, not to nothing.
+ backend._moe_spill_batch_tokens = (["--ubatch-size", "2048"], ["--ubatch-size", "1024"])
+ assert _ubatch_values(backend._undo_moe_spill_batch(argv)) == ["1024"]
+
+
+def test_the_fit_on_retry_keeps_one_micro_batch_flag():
+ backend = LlamaCppBackend()
+ backend._spill_plan_flags = ["-ngl", "-1", "--fit", "off", "-ot", "exps=CPU"]
+ argv = ["llama-server", "--ubatch-size", "2048", *backend._spill_plan_flags]
+ retry = backend._drop_tensor_spill(argv, "test")
+
+ assert retry[-2:] == ["--fit", "on"]
+ assert _ubatch_values(retry) == ["2048"]
+
+
+def test_the_spill_raise_helper_only_raises():
+ from core.inference.llama_cpp import _moe_spill_batch_ubatch
+
+ on = dict(n_moe_layers = 40, experts_on_host = True, discrete_gpu = True, user_named_batch = False)
+ assert _moe_spill_batch_ubatch(None, None, **on) == (None, 2048)
+ assert _moe_spill_batch_ubatch(None, 1024, **on) == (None, 2048)
+ assert _moe_spill_batch_ubatch(None, 4096, **on) == (None, 4096)
+ # An unnamed batch below the target grows with it (llama.cpp caps ubatch at batch).
+ assert _moe_spill_batch_ubatch(1024, None, **on) == (2048, 2048)
+ for off in ("experts_on_host", "discrete_gpu"):
+ assert _moe_spill_batch_ubatch(None, None, **{**on, off: False}) == (None, None)
+ assert _moe_spill_batch_ubatch(None, None, **{**on, "user_named_batch": True}) == (None, None)
+ assert _moe_spill_batch_ubatch(None, None, **{**on, "n_moe_layers": 0}) == (None, None)
diff --git a/studio/backend/tests/test_offload_planner_seam.py b/studio/backend/tests/test_offload_planner_seam.py
index 012de7b3dcf..779dad0c4bd 100644
--- a/studio/backend/tests/test_offload_planner_seam.py
+++ b/studio/backend/tests/test_offload_planner_seam.py
@@ -2171,3 +2171,20 @@ def test_invalid_linux_topology_falls_back_to_psutil(monkeypatch):
)
monkeypatch.setitem(sys.modules, "psutil", _PhysicalHost)
assert llama_mod._spilled_decode_threads() == 12
+
+
+def test_a_larger_micro_batch_compute_buffer_spills_more_experts():
+ """The expert-spill raise (ubatch 512 -> 2048) adds ~0.5-0.9 GiB of compute
+ buffer. Priced into compute_buffer_flat, it comes out of the experts kept on the
+ GPU instead of becoming a graph_reserve OOM."""
+ stub = _Stub(moe = 40)
+ at_512 = _plan(
+ stub, model_size = 30 * GIB, kv = 2 * GIB, free_mib = 12 * 1024, compute_flat = 300 * MIB
+ )
+ at_2048 = _plan(
+ stub, model_size = 30 * GIB, kv = 2 * GIB, free_mib = 12 * 1024, compute_flat = 1100 * MIB
+ )
+
+ assert at_512.spills_anything and at_2048.spills_anything
+ assert len(at_2048.spilled_blocks) > len(at_512.spilled_blocks)
+ assert at_2048.vram_bytes < at_512.vram_bytes