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: emit --moe-cache-mib auto only where the cache measured faster, price the spill micro-batch (#13600)

Daniel Han133a8076d10a
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index adbc553523f..83e91d43f72 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -4633,7 +4633,8 @@ _CPU_MOE_COUNT_FLAGS = frozenset({"-ncmoe", "--n-cpu-moe"})
_CPU_FFN_COUNT_FLAGS = frozenset({"-ncffn", "--n-cpu-ffn"})
# User controls over llama.cpp's own fitter. Studio emits neither on Metal, so a launch carrying
# one is placed by a fitter the Metal memory probe did not run.
-_FIT_CONTROL_FLAGS = frozenset({"-fitt", "--fit-target", "-fitc", "--fit-ctx"})
+_FIT_CTX_FLAGS = frozenset({"-fitc", "--fit-ctx"})
+_FIT_CONTROL_FLAGS = frozenset({"-fitt", "--fit-target"}) | _FIT_CTX_FLAGS
_FIT_CONTROL_ENV_VARS = ("LLAMA_ARG_FIT_TARGET", "LLAMA_ARG_FIT_CTX")
_CPU_PLACEMENT_PRESENCE_FLAGS = (_MOE_OFFLOAD_FLAGS - _CPU_MOE_COUNT_FLAGS) | frozenset(
{"-ot", "--override-tensor"}
@@ -7281,6 +7282,79 @@ def _expert_spill_places_tensors_on_cpu(
# GPU cache of host-resident experts (ggml-org/llama.cpp#29887); "auto" is sized by the
# fork's fitter (unslothai/llama.cpp#251). One run, so a retry can strip it.
_MOE_CACHE_AUTO_TOKENS = ("--moe-cache-mib", "auto")
+# --moe-cache-mib auto only beats the --fit split at a middling resident expert share r
+# (unknown r keeps the split). Cache vs split decode / prompt t/s, L4 gemma-4-26B-A4B:
+# r 0.23 23.5/384 vs 24.5/448, r 0.53 44.9/556 vs 31.2/593, r 0.82 48.5/592 vs 42.0/897.
+# RTX PRO 6000 Qwen3.8-Flash-Next: r <= 0.745 decode +24-42%, r 0.846 prompt -6-40%.
+_MOE_CACHE_MIN_RESIDENT_SHARE = 0.35
+_MOE_CACHE_MAX_RESIDENT_SHARE = 0.75
+# Drafted launches may get the cache. L4 gemma-4 decode cache/split at r 0.53/0.82/0.23:
+# MTP 1.76x/1.25x/0.96x, ngram-mod 1.19x/0.87x/1.11x (the band covers the losses).
+_MOE_CACHE_WITH_DRAFTER = True
+# Skip the spill micro-batch raise if it pushes more than this share of resident experts
+# off the GPU. L4 gemma-4: r 0.23 lost 14% (decode -3%), r 0.53/0.82 lost 4-6%.
+_MOE_SPILL_UB_MAX_RESIDENT_LOSS = 0.10
+# "on" = ungated v0.1.906, "off" = v0.1.905 (no cache / no raise), else auto.
+_MOE_CACHE_ENV = "UNSLOTH_MOE_CACHE"
+_MOE_SPILL_UBATCH_ENV = "UNSLOTH_MOE_SPILL_UBATCH"
+_MOE_SWITCH_ON = frozenset({"1", "on", "true", "yes", "force"})
+_MOE_SWITCH_OFF = frozenset({"0", "off", "false", "no", "never"})
+
+
+def _moe_switch(name: str, env: Optional[Mapping[str, str]] = None) -> str:
+ """``"on"``, ``"off"`` or ``"auto"`` for one of the MoE override env vars."""
+ raw = str((os.environ if env is None else env).get(name) or "").strip().lower()
+ if raw in _MOE_SWITCH_ON:
+ return "on"
+ if raw in _MOE_SWITCH_OFF:
+ return "off"
+ return "auto"
+
+
+def _moe_resident_expert_share(
+ shortfall_bytes: Optional[float], expert_bytes: Optional[int]
+) -> Optional[float]:
+ """1 - shortfall / expert bytes (the fitter offloads experts first); None if unknown."""
+ if shortfall_bytes is None or not expert_bytes or expert_bytes <= 0:
+ return None
+ return min(1.0, max(0.0, 1.0 - float(shortfall_bytes) / float(expert_bytes)))
+
+
+def _moe_cache_share_admits(
+ resident_share: Optional[float],
+ *,
+ drafter: bool,
+ switch: str = "auto",
+) -> bool:
+ """Whether ``--moe-cache-mib auto`` beats the --fit split at this resident share."""
+ if switch != "auto":
+ return switch == "on"
+ if drafter and not _MOE_CACHE_WITH_DRAFTER:
+ return False
+ return (
+ resident_share is not None
+ and _MOE_CACHE_MIN_RESIDENT_SHARE <= resident_share <= _MOE_CACHE_MAX_RESIDENT_SHARE
+ )
+
+
+def _moe_spill_raise_keeps_experts(
+ share_before: Optional[float],
+ share_after: Optional[float],
+ *,
+ switch: str = "auto",
+) -> bool:
+ """Keep the spill micro-batch raise? Nothing spilling = no; unpriceable = yes."""
+ if switch != "auto":
+ return switch == "on"
+ if share_before is None:
+ return True
+ if share_before >= 1.0:
+ return False
+ if share_after is None:
+ return True
+ return share_before - share_after <= _MOE_SPILL_UB_MAX_RESIDENT_LOSS * share_before
+
+
# User placement: the fitter aborts on most of it, and the cache refuses >1 device (--rpc adds one).
_MOE_CACHE_USER_OWNED_FLAGS = (
frozenset({"--moe-cache-mib", "-ot", "--override-tensor", "--rpc"})
@@ -28581,6 +28655,171 @@ class LlamaCppBackend:
max_available_ctx = _ceiling[0]
_vram_fit_ctx = _ceiling[0]
+ # Single-GPU VRAM shortfall vs free less --fit-target (None = unpriceable).
+ _model_size_fit_cb = _compute_buffer_pipeline
+
+ def _fit_ctx_overridden(
+ child_extras: Optional[Iterable[str]], child_env: Mapping[str, str]
+ ) -> bool:
+ """A --fit-ctx / -fitc (argv, else LLAMA_ARG_FIT_CTX) the child
+ runs with that is not the value _ctx_integrity_flags emits."""
+ _studio_fitc: Optional[int] = None
+ if (
+ use_fit
+ and not (gpu_memory_mode == "manual" and gpu_layers >= 0)
+ and server_caps.get("supports_fit_ctx")
+ ):
+ if requested_ctx > 0 and effective_ctx > 0:
+ _studio_fitc = int(effective_ctx)
+ elif gpu_memory_mode == "manual" and gpu_layers < 0:
+ _studio_fitc = 8192
+ try:
+ _raw = _last_flag_value(child_extras, _FIT_CTX_FLAGS)
+ except ValueError:
+ return True
+ # The emitted flag beats the env; argv after it beats both.
+ if _raw is None and _studio_fitc is None:
+ _raw = child_env.get("LLAMA_ARG_FIT_CTX")
+ if _raw is None or not str(_raw).strip():
+ return False
+ try:
+ return int(str(_raw).strip()) != _studio_fitc
+ except ValueError:
+ return True
+
+ def _fitter_vram_shortfall() -> Optional[float]:
+ if not (gpus and effective_ctx > 0 and self._can_estimate_kv()):
+ return None
+ # Smart offload may still pin experts to CPU against Unsloth's budget.
+ from core.inference.offload_planner import smart_offload_enabled
+
+ if smart_offload_enabled(os.environ):
+ return None
+ # A drafter priced with a flat cushion has no draft-KV term here.
+ if _flat_mtp_engages:
+ return None
+ _on = [g for g in gpus if gpu_indices is None or g[0] in gpu_indices]
+ # Per-device placement (common/fit.cpp) can spill despite a pooled fit.
+ if len(_on) != 1:
+ return None
+ _child_extras = (
+ self._strip_device_extra_args(extra_args)
+ if _gpu_ids_own_device_flags
+ else extra_args
+ )
+ _child_env = dict(os.environ)
+ if _gpu_ids_own_device_flags:
+ self._clear_device_placement_env(_child_env)
+ if _pass_through_overrides_placement(
+ _child_extras,
+ _child_env,
+ len(_on),
+ is_vulkan_backend = is_vulkan_backend,
+ gpu_indices = gpu_indices,
+ ):
+ return None
+ # Priced at Unsloth's --parallel; any other pass-through one wins.
+ _np_override = _extra_args_n_parallel(_child_extras, {})
+ if _np_override is not None and _np_override != n_parallel:
+ return None
+ # A later pass-through -c 0 lets llama.cpp pick the context.
+ if parse_ctx_override(_child_extras) == 0:
+ return None
+ # A --fit-ctx Studio did not emit moves llama.cpp's fit.
+ if _fit_ctx_overridden(_child_extras, _child_env):
+ return None
+ # A GPU projector Studio never sized; Vision off keeps only audio-only.
+ _env_mmproj = _child_env.get("LLAMA_ARG_MMPROJ")
+ # The emitted --mmproj replaces an inherited path (argv after env).
+ if effective_is_vision:
+ _env_mmproj = None
+ # --mmproj-device / MTMD_BACKEND_DEVICE re-enable the GPU projector.
+ _mmproj_dev = _extra_args_device(
+ _child_extras, {"--mmproj-device", "-mmdev"}
+ )
+ if _mmproj_dev is None:
+ _mmproj_dev = _child_env.get("MTMD_BACKEND_DEVICE")
+ _mmproj_dev_gpu = bool(
+ _mmproj_dev is not None and str(_mmproj_dev).strip().lower() != "none"
+ )
+ if _resolved_mmproj_offload(_child_extras, _child_env) is False:
+ if _mmproj_dev_gpu:
+ return None
+ elif disable_vision:
+ if _mmproj_env_is_audio_only(_env_mmproj):
+ return None
+ elif (
+ _env_mmproj
+ or _child_env.get("LLAMA_ARG_MMPROJ_URL")
+ or (
+ not launch_mmproj_path
+ and extra_args_mmproj_auto(_child_extras, _child_env)
+ )
+ ):
+ return None
+ # --fit-target precedence: argv, Studio's emitted value, env, default.
+ _supports_fit_target = bool(server_caps.get("supports_fit_target"))
+ _auto_fit = gpu_memory_mode == "manual" and gpu_layers < 0
+ _managed_mib = self._fit_target_margin_mib(
+ auto_fit = _auto_fit,
+ fit_target_delta_mib = _fit_target_delta_mib,
+ supports_fit_target = _supports_fit_target,
+ )
+ # A per-device list reads as its largest entry (the larger shortfall).
+ _margin_mib = fit_target_margin_in(_child_extras or (), None)
+ if _margin_mib is None:
+ _emits = _supports_fit_target and (
+ _auto_fit or _managed_mib != _LLAMA_FIT_TARGET_DEFAULT_MIB
+ )
+ _env_mib = None if _emits else fit_target_margin_in((), _child_env)
+ # An inherited 0 is a valid margin, not "unset".
+ _margin_mib = _managed_mib if _env_mib is None else _env_mib
+ # A lazily read table stays mmap'd on the host, never on the GPU.
+ _lazy_host = self._lazy_read_host_bytes(
+ model_path,
+ caps = server_caps,
+ extra_args = _child_extras,
+ env = _child_env,
+ auto_resolves_off = self._lazy_auto_resolves_off(
+ gpu_indices = gpu_indices,
+ detected_gpus = _detected_gpus,
+ shared_gpu_ids = _shared_gpu_ids,
+ is_vulkan_backend = is_vulkan_backend,
+ ),
+ )
+ _need = (
+ model_size_fit
+ - _lazy_host
+ - _model_size_fit_cb
+ + _compute_buffer_pipeline
+ + (
+ _kv_bytes(effective_ctx)
+ if _kv_offload_from_args(_child_extras, _child_env)
+ else 0
+ )
+ + (
+ _mtp_bytes(effective_ctx, n_parallel, _effective_ubatch)
+ if _mtp_will_engage
+ else 0
+ )
+ + _cc_bytes(effective_ctx, len(_on))
+ )
+ _free = sum(max(0.0, free - _margin_mib) for _idx, free in _on)
+ return _need - _free * 1024 * 1024
+
+ def _moe_resident_share_now() -> Optional[float]:
+ if self.n_moe_layers <= 0:
+ return None
+ try:
+ _short = _fitter_vram_shortfall()
+ if _short is None:
+ return None
+ _scan = self._gguf_tensor_scan(model_path) or (None, {}, 0)
+ return _moe_resident_expert_share(_short, _scan[2])
+ except Exception as e:
+ logger.debug(f"MoE resident share unpriceable ({e})")
+ return None
+
# 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
@@ -28612,14 +28851,18 @@ class LlamaCppBackend:
discrete_gpu = _moe_spill_discrete_gpu,
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,
+ _moe_ub_switch = _moe_switch(_MOE_SPILL_UBATCH_ENV)
+ if _spill_n_ubatch != n_ubatch and _moe_ub_switch != "off":
+ _share_before = (
+ _moe_resident_share_now() if _moe_ub_switch == "auto" else None
+ )
+ _pre_raise = (
+ n_batch,
+ n_ubatch,
+ _effective_ubatch,
+ _compute_buffer_pipeline,
+ _compute_buffer_tensor,
)
- 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.
@@ -28633,6 +28876,41 @@ class LlamaCppBackend:
n_parallel = n_parallel,
per_device_tensor = True,
) or (self._TENSOR_PARALLEL_BUFFER_RESERVE_MIB * 1024 * 1024)
+ _share_after = (
+ _moe_resident_share_now()
+ if _moe_ub_switch == "auto" and _share_before is not None
+ else None
+ )
+ if _moe_spill_raise_keeps_experts(
+ _share_before, _share_after, switch = _moe_ub_switch
+ ):
+ logger.info(
+ "MoE experts are offloaded to system RAM; raising "
+ "--ubatch-size %s -> %s for faster prompt processing.",
+ (
+ _pre_raise[1]
+ if _pre_raise[1] is not None
+ else _DEFAULT_LLAMA_N_UBATCH
+ ),
+ _spill_n_ubatch,
+ )
+ self._moe_spill_batch_restore = (_pre_raise[0], _pre_raise[1])
+ else:
+ (
+ n_batch,
+ n_ubatch,
+ _effective_ubatch,
+ _compute_buffer_pipeline,
+ _compute_buffer_tensor,
+ ) = _pre_raise
+ logger.info(
+ "MoE experts: keeping the default --ubatch-size; %s would "
+ "move the GPU's resident share of the routed experts "
+ "%.0f%% -> %.0f%%.",
+ _spill_n_ubatch,
+ 100 * (_share_before or 0.0),
+ 100 * (_share_after or 0.0),
+ )
_moe_cache_candidate = self._moe_cache_auto_eligible(
caps = server_caps,
@@ -29026,6 +29304,31 @@ class LlamaCppBackend:
lazy_read_bytes = _fit_lazy_bytes,
)
_fit_load_mode = self._fit_derived_load_mode(**_fit_load_mode_kwargs)
+ if _moe_cache_candidate:
+ _moe_cache_switch = _moe_switch(_MOE_CACHE_ENV)
+ _moe_share = (
+ _moe_resident_share_now() if _moe_cache_switch == "auto" else None
+ )
+ if not _moe_cache_share_admits(
+ _moe_share, drafter = _mtp_will_engage, switch = _moe_cache_switch
+ ):
+ _moe_cache_candidate = False
+ if _moe_cache_switch == "off":
+ _why = f"{_MOE_CACHE_ENV} is off"
+ elif _moe_share is None:
+ _why = "the share of routed experts left on the GPU is unknown"
+ elif _mtp_will_engage and not _MOE_CACHE_WITH_DRAFTER:
+ _why = "a drafter is engaged"
+ else:
+ _why = (
+ f"an estimated {100 * _moe_share:.0f}% of the routed "
+ "experts stay on the GPU"
+ )
+ logger.info(
+ "MoE cache: %s; keeping the --fit split without "
+ "--moe-cache-mib.",
+ _why,
+ )
if _moe_cache_candidate:
# The cache frees no host RAM: every routed expert plus the prompt
# cache must fit pinned (moved out of model_size, not counted twice).
diff --git a/studio/backend/tests/test_llama_cpp_placement.py b/studio/backend/tests/test_llama_cpp_placement.py
index e6b1a29cf16..9d91a24262f 100644
--- a/studio/backend/tests/test_llama_cpp_placement.py
+++ b/studio/backend/tests/test_llama_cpp_placement.py
@@ -4339,11 +4339,21 @@ def _batch_values(cmd):
@pytest.fixture
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"):
+ for name in (
+ "LLAMA_ARG_BATCH",
+ "LLAMA_ARG_UBATCH",
+ "LLAMA_ARG_N_CPU_MOE",
+ "LLAMA_ARG_CPU_MOE",
+ "UNSLOTH_MOE_CACHE",
+ "UNSLOTH_MOE_SPILL_UBATCH",
+ ):
monkeypatch.delenv(name, raising = False)
_SPILLED = dict(size_gib = 20, memory = [(0, 8_000, 16_000)])
+_EIGHT_GIB_CARD = [(0, 8_000, 16_000)]
+# 20 GiB with 15 GiB of experts keeps ~53% of the experts resident here: inside the band.
+_IN_BAND_CARD = [(0, 20_000, 32_000)]
_RESIDENT = dict(size_gib = 1, memory = [(0, 40_000, 48_000)])
@@ -4780,11 +4790,13 @@ def _cache_launch(
**load_kwargs,
):
"""One launch of an MoE (or dense) model, priced so the fit can answer
- "none". 20 GiB on an 8 GiB card spills; 1 GiB on a 40 GiB card does not.
+ "none". 20 GiB with 15 GiB of experts on a card with 20,000 MiB free spills and
+ keeps ~53% of the experts resident (inside the cache band); 1 GiB on a 40 GiB card
+ does not spill.
``host_guard`` puts the real host-RAM preflight back."""
if memory is None:
memory = (
- [(i, 8_000, 16_000) for i in range(gpus)]
+ [(i, _IN_BAND_CARD[0][1], _IN_BAND_CARD[0][2]) for i in range(gpus)]
if spilled
else [(i, 40_000, 48_000) for i in range(gpus)]
)
@@ -4922,6 +4934,346 @@ def test_an_inherited_placement_keeps_the_moe_cache_off(
assert not _has_moe_cache(cmd), cmd
+def test_the_resident_expert_share():
+ share = llama_cpp_module._moe_resident_expert_share
+
+ assert share(None, 15 * _GIB) is None
+ assert share(3 * _GIB, 0) is None
+ assert share(3 * _GIB, None) is None
+ assert share(3 * _GIB, 15 * _GIB) == pytest.approx(0.8)
+ assert share(-_GIB, 15 * _GIB) == 1.0
+ assert share(30 * _GIB, 15 * _GIB) == 0.0
+
+
+ "resident_share, admitted",
+ [
+ # L4, gemma-4-26B-A4B UD-Q4_K_XL under the --fit split at 8 / 12 / 16 GB.
+ (0.197, False),
+ (0.23, False),
+ (0.35, True),
+ (0.494, True),
+ (0.527, True),
+ (0.745, True),
+ (0.75, True),
+ (0.791, False),
+ (0.824, False),
+ (1.0, False),
+ (None, False),
+ ],
+)
+def test_the_cache_band(resident_share, admitted):
+ admits = llama_cpp_module._moe_cache_share_admits
+
+ assert admits(resident_share, drafter = False) is admitted
+ assert admits(resident_share, drafter = True) is admitted
+ # The switch overrides the band both ways, unknown share included.
+ assert admits(resident_share, drafter = False, switch = "on") is True
+ assert admits(resident_share, drafter = True, switch = "off") is False
+
+
+def test_the_drafter_gate_is_one_constant(monkeypatch):
+ admits = llama_cpp_module._moe_cache_share_admits
+ monkeypatch.setattr(llama_cpp_module, "_MOE_CACHE_WITH_DRAFTER", False)
+
+ assert admits(0.5, drafter = False) is True
+ assert admits(0.5, drafter = True) is False
+ assert admits(0.5, drafter = True, switch = "on") is True
+
+
+ "before, after, kept",
+ [
+ # L4 gemma-4: the 2048 compute buffer cost 14% of the resident experts at 8 GB,
+ # 6% at 12 GB and 4% at 16 GB.
+ (0.23, 0.197, False),
+ (0.527, 0.494, True),
+ (0.824, 0.791, True),
+ # Nothing spills at the default micro-batch: the raise would only push experts off.
+ (1.0, 0.95, False),
+ (1.0, 1.0, False),
+ # Unpriceable keeps today's raise.
+ (None, None, True),
+ (0.5, None, True),
+ (0.0, 0.0, True),
+ ],
+)
+def test_the_spill_raise_keeps_the_resident_experts(before, after, kept):
+ keeps = llama_cpp_module._moe_spill_raise_keeps_experts
+
+ assert keeps(before, after) is kept
+ assert keeps(before, after, switch = "on") is True
+ assert keeps(before, after, switch = "off") is False
+
+
+ "raw, switch",
+ [
+ (None, "auto"),
+ ("", "auto"),
+ ("auto", "auto"),
+ ("bogus", "auto"),
+ ("1", "on"),
+ (" ON ", "on"),
+ ("force", "on"),
+ ("0", "off"),
+ ("Off", "off"),
+ ("never", "off"),
+ ],
+)
+def test_the_moe_switches(raw, switch):
+ env = {} if raw is None else {"UNSLOTH_MOE_CACHE": raw}
+
+ assert llama_cpp_module._moe_switch("UNSLOTH_MOE_CACHE", env) == switch
+
+
+ "free_mib, cached",
+ # 20 GiB model, 15 GiB of experts, 32 GiB card: the share of experts the --fit split
+ # would keep resident is ~14% / ~53% / ~79%.
+ [(14_000, False), (20_000, True), (24_000, False)],
+ ids = ["below_band_split", "in_band_cache", "above_band_split"],
+)
+def test_the_resident_share_picks_cache_or_split(tmp_path, _moe_cache_host, free_mib, cached):
+ backend, cmd = _cache_launch(tmp_path, memory = [(0, free_mib, 32_000)])
+
+ assert cmd[cmd.index("--fit") + 1] == "on", cmd
+ assert _load_mode(cmd) == "none", cmd
+ assert _has_moe_cache(cmd) is cached, cmd
+ assert backend._moe_cache_flags == (_MOE_CACHE if cached else [])
+ # The flat compute-buffer estimate here costs the raise nothing, so it stays.
+ assert _ubatch_values(cmd) == ["2048"], cmd
+
+
+def test_an_unpriceable_share_keeps_the_split(tmp_path, _moe_cache_host):
+ # A larger pass-through --parallel was never priced, so the share is unknown.
+ backend, cmd = _cache_launch(tmp_path, extra_args = ["--parallel", "4"])
+
+ assert not _has_moe_cache(cmd), cmd
+ assert backend._moe_cache_flags == []
+
+
+def test_a_smaller_pass_through_parallel_keeps_the_split(tmp_path, _moe_cache_host):
+ # Priced at 4 slots, launched with 1: the share would be understated, so it is unknown.
+ caps = dict(_CACHE_CAPS_ON, supports_kv_unified = True)
+ backend, cmd = _cache_launch(tmp_path, caps = caps, n_parallel = 4)
+ assert cmd[cmd.index("--parallel") + 1] == "4", cmd
+ assert _has_moe_cache(cmd), cmd
+
+ backend, cmd = _cache_launch(tmp_path, caps = caps, n_parallel = 4, extra_args = ["--parallel", "1"])
+ assert not _has_moe_cache(cmd), cmd
+ assert backend._moe_cache_flags == []
+ # The same value as Studio's is still priced.
+ backend, cmd = _cache_launch(tmp_path, caps = caps, n_parallel = 4, extra_args = ["-np", "4"])
+ assert _has_moe_cache(cmd), cmd
+
+
+ "extra_args, env",
+ [
+ (["--fit-ctx", "4096"], {}),
+ (["-fitc=65536"], {}),
+ ([], {"LLAMA_ARG_FIT_CTX": "4096"}),
+ ],
+ ids = ["argv", "short_equals", "env"],
+)
+def test_a_pass_through_fit_ctx_keeps_the_split(
+ tmp_path, _moe_cache_host, monkeypatch, extra_args, env
+):
+ for name, value in env.items():
+ monkeypatch.setenv(name, value)
+ backend, cmd = _cache_launch(tmp_path, extra_args = extra_args)
+
+ assert not _has_moe_cache(cmd), cmd
+ assert backend._moe_cache_flags == []
+
+
+def test_a_fit_ctx_equal_to_studios_still_prices_the_share(tmp_path, _moe_cache_host, monkeypatch):
+ caps = dict(_CACHE_CAPS_ON, supports_fit_ctx = True)
+ _backend, cmd = _cache_launch(tmp_path, caps = caps, n_ctx = 8192)
+ assert cmd[cmd.index("--fit-ctx") + 1] == "8192", cmd
+ assert _has_moe_cache(cmd), cmd
+
+ _backend, cmd = _cache_launch(tmp_path, caps = caps, n_ctx = 8192, extra_args = ["--fit-ctx", "8192"])
+ assert _has_moe_cache(cmd), cmd
+ # Studio's emitted --fit-ctx beats an inherited one.
+ monkeypatch.setenv("LLAMA_ARG_FIT_CTX", "4096")
+ _backend, cmd = _cache_launch(tmp_path, caps = caps, n_ctx = 8192)
+ assert _has_moe_cache(cmd), cmd
+ _backend, cmd = _cache_launch(tmp_path, caps = caps, n_ctx = 8192, extra_args = ["--fit-ctx", "4096"])
+ assert not _has_moe_cache(cmd), cmd
+
+
+ "switch, free_mib, cached",
+ [
+ ("on", 24_000, True),
+ ("on", 14_000, True),
+ ("off", 20_000, False),
+ ("auto", 20_000, True),
+ ("bogus", 24_000, False),
+ ],
+)
+def test_the_cache_switch_overrides_the_band(
+ tmp_path, _moe_cache_host, monkeypatch, switch, free_mib, cached
+):
+ monkeypatch.setenv("UNSLOTH_MOE_CACHE", switch)
+ backend, cmd = _cache_launch(tmp_path, memory = [(0, free_mib, 32_000)])
+
+ assert _has_moe_cache(cmd) is cached, cmd
+ assert backend._moe_cache_flags == (_MOE_CACHE if cached else [])
+
+
+def test_the_cache_switch_on_still_needs_an_eligible_launch(tmp_path, _moe_cache_host, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_MOE_CACHE", "on")
+
+ _backend, cmd = _cache_launch(tmp_path, gpus = 2)
+ assert not _has_moe_cache(cmd), cmd
+ _backend, cmd = _cache_launch(tmp_path, ram_gib = 24)
+ assert not _has_moe_cache(cmd), cmd
+ _backend, cmd = _cache_launch(tmp_path, extra_args = ["--moe-cache-mib", "0"])
+ assert cmd.count("--moe-cache-mib") == 1 and cmd[cmd.index("--moe-cache-mib") + 1] == "0"
+
+
+def _ubatch_sized_compute_buffer(monkeypatch, raise_cost_gib):
+ """A compute buffer that grows by ``raise_cost_gib`` from the default micro-batch
+ to the expert-spill one, like gemma-4's 364 -> 616 MiB (plus host share)."""
+
+ def estimate(
+ self,
+ *,
+ n_ubatch = None,
+ n_parallel = 1,
+ per_device_tensor = False,
+ **_kw,
+ ):
+ base = _GIB // 2
+ if n_ubatch is not None and int(n_ubatch) >= 2048:
+ return base + int(raise_cost_gib * _GIB)
+ return base
+
+ monkeypatch.setattr(LlamaCppBackend, "_estimate_compute_buffer_bytes", estimate)
+
+
+ "free_mib, raised, cached",
+ [
+ # ~25% resident, raise costs ~27%: default micro-batch, split.
+ (11_000, False, False),
+ # ~44% resident, the raise would cost ~15%: the cache at the default micro-batch.
+ (14_000, False, True),
+ # ~70% resident, the raise costs ~10% or less: raised, and 63% is in the band.
+ (18_000, True, True),
+ # ~83% resident, the raise costs ~8%: raised, 77% is above the band, so split.
+ (20_000, True, False),
+ ],
+ ids = ["tight_split", "tight_cache", "roomy_cache", "roomy_split"],
+)
+def test_the_spill_raise_is_priced_against_the_resident_experts(
+ tmp_path, _moe_cache_host, monkeypatch, free_mib, raised, cached
+):
+ _ubatch_sized_compute_buffer(monkeypatch, 1.0)
+ backend, cmd = _cache_launch(tmp_path, memory = [(0, free_mib, 32_000)])
+
+ assert _ubatch_values(cmd) == (["2048"] if raised else []), cmd
+ assert (backend._moe_spill_batch_restore is not None) is raised
+ assert _has_moe_cache(cmd) is cached, cmd
+
+
+ "cache_switch, cached",
+ # ~51% resident, and the raise costs ~5% of those experts (under the 10% rule): the
+ # raise stays whether or not the cache follows it.
+ [("auto", True), ("off", False)],
+ ids = ["cache_takes_the_raise", "split_takes_the_raise"],
+)
+def test_a_cache_launch_keeps_a_raise_the_resident_rule_allows(
+ tmp_path, _moe_cache_host, monkeypatch, cache_switch, cached
+):
+ _ubatch_sized_compute_buffer(monkeypatch, 0.4)
+ monkeypatch.setenv("UNSLOTH_MOE_CACHE", cache_switch)
+ backend, cmd = _cache_launch(tmp_path, memory = [(0, 15_000, 32_000)])
+
+ assert _ubatch_values(cmd) == ["2048"], cmd
+ assert backend._moe_spill_batch_restore is not None
+ assert _has_moe_cache(cmd) is cached, cmd
+
+
+ "free_mib, ubatch",
+ [(11_000, ["1120"]), (14_000, ["1120"]), (18_000, ["2048"])],
+ ids = ["tight_split", "tight_cache", "roomy"],
+)
+def test_a_skipped_raise_keeps_the_projector_micro_batch(
+ tmp_path, _moe_cache_host, monkeypatch, free_mib, ubatch
+):
+ """gemma-4's vision projector needs -ub 1120; a skipped 2048 raise must hand it back."""
+ monkeypatch.setattr(llama_cpp_module, "_launch_required_ubatch", lambda *a, **k: 1120)
+ _ubatch_sized_compute_buffer(monkeypatch, 1.0)
+ _backend, cmd = _cache_launch(tmp_path, memory = [(0, free_mib, 32_000)])
+
+ assert _ubatch_values(cmd) == ubatch, cmd
+
+
+def test_the_v0_1_905_workaround_args_are_honoured(tmp_path, _moe_cache_host):
+ """``--moe-cache-mib 0 -ub 512``, the workaround users ran on v0.1.906."""
+ backend, cmd = _cache_launch(tmp_path, extra_args = ["--moe-cache-mib", "0", "-ub", "512"])
+
+ assert backend._moe_cache_flags == []
+ assert cmd.count("--moe-cache-mib") == 1 and cmd[cmd.index("--moe-cache-mib") + 1] == "0"
+ assert _ubatch_values(cmd) == ["512"], cmd
+
+
+def test_the_spill_ubatch_switch(tmp_path, _moe_cache_host, monkeypatch):
+ _ubatch_sized_compute_buffer(monkeypatch, 1.0)
+
+ # Auto skips the raise at 11,000 MiB free and keeps it at 18,000 (see above).
+ monkeypatch.setenv("UNSLOTH_MOE_SPILL_UBATCH", "on")
+ _backend, cmd = _cache_launch(tmp_path, memory = [(0, 11_000, 32_000)])
+ assert _ubatch_values(cmd) == ["2048"], cmd
+
+ monkeypatch.setenv("UNSLOTH_MOE_SPILL_UBATCH", "off")
+ _backend, cmd = _cache_launch(tmp_path, memory = [(0, 18_000, 32_000)])
+ assert _ubatch_values(cmd) == [], cmd
+
+
+def test_both_switches_on_restore_the_ungated_launch(tmp_path, _moe_cache_host, monkeypatch):
+ """v0.1.906: the cache and the 2048 micro-batch on any eligible spill."""
+ _ubatch_sized_compute_buffer(monkeypatch, 1.0)
+ monkeypatch.setenv("UNSLOTH_MOE_CACHE", "on")
+ monkeypatch.setenv("UNSLOTH_MOE_SPILL_UBATCH", "on")
+ # Auto launches neither here (25% resident, a costly raise).
+ _backend, cmd = _cache_launch(tmp_path, memory = [(0, 11_000, 32_000)])
+
+ assert _has_moe_cache(cmd) and _ubatch_values(cmd) == ["2048"], cmd
+
+
+def test_both_switches_off_restore_the_v0_1_905_launch(tmp_path, _moe_cache_host, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_MOE_CACHE", "off")
+ monkeypatch.setenv("UNSLOTH_MOE_SPILL_UBATCH", "off")
+ _backend, cmd = _cache_launch(tmp_path)
+
+ assert not _has_moe_cache(cmd) and _ubatch_values(cmd) == [], cmd
+ assert _batch_values(cmd) in ([], ["2048"]), cmd
+
+
+ "extra_args, ubatch",
+ [(["-ub", "1024"], ["1024"]), (["-b", "4096"], [])],
+ ids = ["user_ubatch", "user_batch"],
+)
+def test_a_user_batch_pair_wins_and_the_band_still_decides(
+ tmp_path, _moe_cache_host, extra_args, ubatch
+):
+ backend, cmd = _cache_launch(tmp_path, extra_args = extra_args)
+
+ assert _ubatch_values(cmd) == ubatch, cmd
+ assert backend._moe_spill_batch_restore is None
+ assert _has_moe_cache(cmd), cmd
+ _backend, cmd = _cache_launch(tmp_path, extra_args = extra_args, memory = [(0, 24_000, 32_000)])
+ assert not _has_moe_cache(cmd), cmd
+
+
def test_an_unsized_inherited_projector_skips_the_cache_not_the_placement(
tmp_path, _moe_cache_host, monkeypatch
):
@@ -5036,7 +5388,7 @@ def test_a_cache_crash_retries_once_without_the_cache(
},
)()
- backend, gguf = _moe_backend(tmp_path, **_SPILLED)
+ backend, gguf = _moe_backend(tmp_path, size_gib = 20, memory = _IN_BAND_CARD)
backend._can_estimate_kv = lambda: True
backend._estimate_kv_cache_bytes = lambda *a, **k: _GIB // 4
backend._available_system_memory_mib = lambda: 256 * 1024
@@ -5225,30 +5577,44 @@ def test_the_launch_discounts_the_lazy_table(tmp_path, _moe_cache_host):
"""The same predicate through the launch: a 20 GiB MoE whose 12 GiB n-gram table
is lazy fits 8 GiB of VRAM plus 12 GiB of RAM only without the table."""
plain = _cache_launch(
- tmp_path, ram_gib = 12, caps = dict(_CACHE_CAPS_ON, supports_moe_cache_auto = False)
+ tmp_path,
+ ram_gib = 12,
+ caps = dict(_CACHE_CAPS_ON, supports_moe_cache_auto = False),
+ memory = _EIGHT_GIB_CARD,
)[1]
assert _load_mode(plain) is None, plain
lazy = {"per_layer_token_embd.weight": 12 * _GIB}
no_auto = dict(_CACHE_CAPS_ON, supports_moe_cache_auto = False)
- _b, cmd = _cache_launch(tmp_path, ram_gib = 12, lazy = lazy, caps = no_auto)
+ card = dict(memory = _EIGHT_GIB_CARD)
+ _b, cmd = _cache_launch(tmp_path, ram_gib = 12, lazy = lazy, caps = no_auto, **card)
assert _load_mode(cmd) is None, "qwen3moe does not mark the table lazy"
- _b, cmd = _cache_launch(tmp_path, ram_gib = 12, lazy = lazy, arch = "qwen4exp", caps = no_auto)
+ _b, cmd = _cache_launch(tmp_path, ram_gib = 12, lazy = lazy, arch = "qwen4exp", caps = no_auto, **card)
assert _load_mode(cmd) == "none", cmd
# And "-lzm off" makes it an ordinary tensor again.
_b, cmd = _cache_launch(
- tmp_path, ram_gib = 12, lazy = lazy, arch = "qwen4exp", caps = no_auto, extra_args = ["-lzm", "off"]
+ tmp_path,
+ ram_gib = 12,
+ lazy = lazy,
+ arch = "qwen4exp",
+ caps = no_auto,
+ extra_args = ["-lzm", "off"],
+ **card,
)
assert _load_mode(cmd) is None, cmd
@pytest.mark.parametrize("ram_gib, cached", [(60, True), (40, False)])
-def test_the_cache_admission_counts_the_experts_once(tmp_path, _moe_cache_host, ram_gib, cached):
+def test_the_cache_admission_counts_the_experts_once(
+ tmp_path, _moe_cache_host, monkeypatch, ram_gib, cached
+):
"""Qwen3.8-Flash-Next IQ1_S on one 24 GiB card. With the lazy table on disk the
load is ~41 GiB; the cache needs the 37.11 GiB of experts plus the 8 GiB prompt
cache pinned in RAM, which 60 GiB holds and 40 GiB does not. Charging the experts
- to RAM on top of model_size, as well as in it, refused the 60 GiB host."""
+ to RAM on top of model_size, as well as in it, refused the 60 GiB host. Forced on,
+ so the RAM admission is what decides, not the resident-share band."""
+ monkeypatch.setenv("UNSLOTH_MOE_CACHE", "on")
backend, cmd = _cache_launch(
tmp_path,
size_gib = _QWEN38_TOTAL / _GIB,
@@ -5267,12 +5633,14 @@ def test_the_cache_admission_counts_the_experts_once(tmp_path, _moe_cache_host,
@pytest.mark.parametrize("ram_gib, cached", [(45, False), (60, True)])
def test_qwen38_on_a_16gib_card_launches_pinned_past_the_host_guard(
- tmp_path, _moe_cache_host, ram_gib, cached
+ tmp_path, _moe_cache_host, monkeypatch, ram_gib, cached
):
"""Qwen3.8-Flash-Next IQ1_S on one 16 GiB card, end to end with the real host-RAM
preflight. The fit leaves the 26.82 GiB lazy table out and picks "none"; the
preflight charged the whole 67.55 GiB file, read a shortfall, and the pageable
- rewrite took the pinned mode (and with it the cache) back out."""
+ rewrite took the pinned mode (and with it the cache) back out. Forced on: ~13% of
+ the experts stay resident, below the band, so auto keeps the split here."""
+ monkeypatch.setenv("UNSLOTH_MOE_CACHE", "on")
backend, cmd = _cache_launch(
tmp_path,
size_gib = _QWEN38_TOTAL / _GIB,
@@ -5313,11 +5681,18 @@ def test_an_igpu_only_child_gets_no_auto_lazy_discount(tmp_path, _moe_cache_host
lazy = {"per_layer_token_embd.weight": 12 * _GIB}
no_auto = dict(_CACHE_CAPS_ON, supports_moe_cache_auto = False)
- _b, cmd = _cache_launch(tmp_path, ram_gib = 12, lazy = lazy, arch = "qwen4exp", caps = no_auto)
+ card = dict(memory = _EIGHT_GIB_CARD)
+ _b, cmd = _cache_launch(tmp_path, ram_gib = 12, lazy = lazy, arch = "qwen4exp", caps = no_auto, **card)
assert _load_mode(cmd) is None, cmd
# An explicit "on" is read lazily on any device.
_b, cmd = _cache_launch(
- tmp_path, ram_gib = 12, lazy = lazy, arch = "qwen4exp", caps = no_auto, extra_args = ["-lzm", "on"]
+ tmp_path,
+ ram_gib = 12,
+ lazy = lazy,
+ arch = "qwen4exp",
+ caps = no_auto,
+ extra_args = ["-lzm", "on"],
+ **card,
)
assert _load_mode(cmd) == "none", cmd