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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: read lookup tables lazily when needed to enable the MoE cache (#16444)
oobaboogadf9610444312
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex eb6884310db..cb74f8b53aa 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -24186,6 +24186,8 @@ class LlamaCppBackend:self._moe_spill_batch_restore: Optional[tuple[Optional[int], Optional[int]]] = None_moe_cache_candidate = False_moe_cache_ram_ok = False+ _moe_table_bytes = 0+ _moe_cache_lazy_table = False_shared_gpus = frozenset()_integrated_gpus = frozenset()# The discrete-first tier; accounting keeps _integrated_gpus.@@ -27957,6 +27959,8 @@ class LlamaCppBackend:binary = binary,)if _managed_lazy_flags and _fit_lazy_bytes:+ # Kept resident by --lazy-mode off; the MoE cache below may want it lazy.+ _moe_table_bytes = _fit_lazy_bytesif _fit_load_mode_kwargs["model_size"]:_fit_load_mode_kwargs["model_size"] = max(1, _fit_load_mode_kwargs["model_size"] - _fit_lazy_bytes@@ -28020,6 +28024,31 @@ class LlamaCppBackend:)== self._FIT_LOAD_MODE)+ if not _moe_cache_ram_ok and _moe_table_bytes > 0 and _moe_expert_bytes > 0:+ # Reading the resident table lazily frees the RAM to pin the experts; the cache beats the --fit split.+ _moe_cache_ram_ok = bool(+ _moe_prompt_cache_bytes is not None+ and self._fit_derived_load_mode(+ **{+ **_fit_load_mode_kwargs,+ "model_size": max(+ 1,+ _fit_load_mode_kwargs["model_size"] - _moe_expert_bytes,+ ),+ "host_only_bytes": max(+ 0,+ _fit_load_mode_kwargs["host_only_bytes"]+ - _moe_table_bytes,+ )+ + _moe_expert_bytes+ + _moe_prompt_cache_bytes,+ "announce": False,+ }+ )+ == self._FIT_LOAD_MODE+ )+ # --lazy-mode off goes only where the cache is really added below.+ _moe_cache_lazy_table = _moe_cache_ram_okif not _moe_cache_ram_ok:logger.info("MoE cache: system RAM cannot hold the %.1f GB of routed "@@ -28035,7 +28064,7 @@ class LlamaCppBackend:# Same reasoning: an unpriced load keeps llama.cpp's default._fit_load_mode = None_managed_lazy_flags = None- _moe_cache_candidate = _moe_cache_ram_ok = False+ _moe_cache_candidate = _moe_cache_ram_ok = _moe_cache_lazy_table = False# And a half-built snapshot is not a price either: the throw can# land after the dict exists but before the later terms are added# to it, which would plan against a footprint missing them.@@ -29554,6 +29583,16 @@ class LlamaCppBackend:and _placed_by_fitterand _argv_loads_pinned(cmd, _fit_load_mode_env_view)):+ if _moe_cache_lazy_table and self._lazy_mode_flags:+ # These flags sit after the spec block, so removing them leaves _spec_start valid.+ cmd = _without_subsequence(cmd, self._lazy_mode_flags)+ self._lazy_mode_flags = []+ logger.info(+ "MoE cache: reading the %.1f GB lookup table lazily so system "+ "RAM can pin the %.1f GB of routed experts.",+ _moe_table_bytes / (1024**3),+ _moe_expert_bytes / (1024**3),+ )self._moe_cache_flags = list(_MOE_CACHE_AUTO_TOKENS)cmd.extend(self._moe_cache_flags)logger.info(diff --git a/studio/backend/tests/test_llama_cpp_placement.py b/studio/backend/tests/test_llama_cpp_placement.pyindex 22bb84fb9a1..9700da85412 100644--- a/studio/backend/tests/test_llama_cpp_placement.py+++ b/studio/backend/tests/test_llama_cpp_placement.py@@ -5274,6 +5274,66 @@ def test_the_header_scan_sums_shards(tmp_path):assert LlamaCppBackend()._gguf_tensor_scan(str(tmp_path / "m-00001-of-00002.gguf")) is None+def test_a_resident_table_that_crowds_out_the_pinned_experts_is_read_lazily_for_the_cache(+ tmp_path, _moe_cache_host+):+ """Qwen3.8-Flash-Next on a 94 GB host: RAM holds the lookup table resident or the+ experts pinned, not both. The cache beats the --fit split by far, so the table is+ read lazily (no --lazy-mode off) and the experts stay pinned for the cache."""+ lazy = {"per_layer_token_embd.weight": 8 * _GIB}+ # 32 GiB with 20 GiB of experts on the 20,000 MiB card: pinning the experts needs+ # 20 + 8 (prompt cache) beside the 8 GiB table, more than 34 GiB of RAM.+ shape = dict(lazy = lazy, arch = "qwen4exp", size_gib = 32, expert_gib = 20)+ backend, cmd = _cache_launch(tmp_path, ram_gib = 34, **shape)++ assert _has_moe_cache(cmd), cmd+ assert cmd.count("--moe-cache-mib") == 1+ assert _load_mode(cmd) == "none", cmd+ assert "--lazy-mode" not in cmd and backend._lazy_mode_flags == [], cmd+ assert backend._moe_cache_flags == _MOE_CACHE++ # With the RAM for both, the table stays resident beside the pinned cache.+ backend, cmd = _cache_launch(tmp_path, ram_gib = 256, **shape)+ assert _has_moe_cache(cmd) and _load_mode(cmd) == "none", cmd+ assert cmd[cmd.index("--lazy-mode") + 1] == "off", cmd+ assert backend._lazy_mode_flags == ["--lazy-mode", "off"]++ # Too little RAM even with the table lazy: no cache, and the table decision is the+ # one a build without the cache makes (here the table already streams).+ no_cache = dict(_CACHE_CAPS_ON, supports_moe_cache = False, supports_moe_cache_auto = False)+ reference, reference_cmd = _cache_launch(tmp_path, ram_gib = 26, caps = no_cache, **shape)+ backend, cmd = _cache_launch(tmp_path, ram_gib = 26, **shape)+ assert not _has_moe_cache(cmd), cmd+ assert backend._lazy_mode_flags == reference._lazy_mode_flags, (cmd, reference_cmd)+ assert ("--lazy-mode" in cmd) == ("--lazy-mode" in reference_cmd), (cmd, reference_cmd)+++ "cell, kwargs, env",+ [+ ("setting", dict(load_mode = "mmap"), {}),+ ("extra_args", dict(extra_args = ["--load-mode", "mmap"]), {}),+ ("env", {}, {"LLAMA_ARG_LOAD_MODE": "mmap"}),+ ],+ ids = lambda v: v if isinstance(v, str) else "",+)+def test_a_user_mmap_keeps_the_resident_table_when_the_cache_stays_off(+ tmp_path, _moe_cache_host, monkeypatch, cell, kwargs, env+):+ """The lazy table is only worth it for the cache: a user's mmap keeps the cache off+ (it needs a pinned load), so --lazy-mode off and the resident table must stay."""+ for name, value in env.items():+ monkeypatch.setenv(name, value)+ lazy = {"per_layer_token_embd.weight": 8 * _GIB}+ shape = dict(lazy = lazy, arch = "qwen4exp", size_gib = 32, expert_gib = 20)+ backend, cmd = _cache_launch(tmp_path, ram_gib = 34, **shape, **kwargs)++ assert not _has_moe_cache(cmd), (cell, cmd)+ assert backend._moe_cache_flags == []+ assert cmd[cmd.index("--lazy-mode") + 1] == "off", (cell, cmd)+ assert backend._lazy_mode_flags == ["--lazy-mode", "off"]++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 tableis lazy fits 8 GiB of VRAM plus 12 GiB of RAM only without the table."""