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: turn the offload planner on by default (#9779)

Daniel Han60d2a636ba03
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 43463a600f2..c6cba23eebf 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -7425,6 +7425,64 @@ class LlamaCppBackend:
except Exception:
return False
+ @staticmethod
+ def _integrated_cuda_gpu_ids() -> set[int]:
+ """PHYSICAL ids of visible CUDA GPUs whose "VRAM" is shared system RAM.
+
+ Jetson and DGX Spark class parts set cudaDeviceProp::integrated, which torch
+ surfaces as ``is_integrated``; the diffusion memory policy reads the same flag
+ (diffusion_memory.py:292-294). ROCm is excluded because it reuses
+ ``torch.cuda.*`` and ``_rocm_unified_memory_gpu_ids`` already answers for it.
+ Empty off CUDA and on error, so every caller keeps its discrete-GPU default.
+ """
+ try:
+ import torch
+
+ if LlamaCppBackend._torch_is_rocm(torch):
+ return set()
+ if not (hasattr(torch, "cuda") and torch.cuda.is_available()):
+ return set()
+ # Same ordinal -> physical mapping the ROCm twin uses, so a masked host
+ # (CUDA_VISIBLE_DEVICES=2) does not answer for the wrong card.
+ physical_ids = LlamaCppBackend._resolve_visible_physical_ids()
+ integrated: set[int] = set()
+ for ordinal in range(torch.cuda.device_count()):
+ try:
+ props = torch.cuda.get_device_properties(ordinal)
+ except Exception:
+ continue
+ # Both spellings: the attribute was `integrated` before torch renamed
+ # it, and an old wheel exposing neither reads discrete.
+ if not (
+ getattr(props, "is_integrated", False) or getattr(props, "integrated", False)
+ ):
+ continue
+ integrated.add(
+ physical_ids[ordinal]
+ if physical_ids is not None and ordinal < len(physical_ids)
+ else ordinal
+ )
+ return integrated
+ except Exception:
+ return set()
+
+ @staticmethod
+ def _integrated_cuda_unified_memory(gpu_indices = None) -> bool:
+ """True when a credited CUDA device is an integrated (unified-memory) SoC.
+
+ Scoped by gpu_indices (PHYSICAL ids) like its ROCm twin, so a dGPU on a
+ mixed host is not treated as unified; None means every visible GPU. Any
+ integrated device is enough: one shared pool in the credited set is already
+ the double count.
+ """
+ try:
+ integrated = LlamaCppBackend._integrated_cuda_gpu_ids()
+ if gpu_indices is None:
+ return bool(integrated)
+ return any(_i in integrated for _i in gpu_indices)
+ except Exception:
+ return False
+
# "Off" spellings ggml itself ignores (it tests presence); we honour them.
_UNIFIED_MEMORY_OFF = frozenset({"", "0", "false", "no", "off"})
@@ -18959,8 +19017,16 @@ class LlamaCppBackend:
# Raw free_mib is 3.5 GiB per card larger at 0.80 on a
# 24 GiB card, so planning on it under-spills and then pins
# the result with --fit off.
+ #
+ # _pin_fraction, not the bare _vram_frac: when the drafter
+ # engages but its KV cannot be sized, the placement paths
+ # spend _MTP_VRAM_RESERVE_FRAC less of every card and
+ # _mtp_reserve_bytes carries no replacement for the unsized
+ # part, so crediting the full fraction here would hand the
+ # planner 5% of VRAM the fit deliberately kept free. Equal to
+ # _vram_frac on every other load (_flat_mtp_reserve is 0).
"gpu_usable_mib": {
- _idx: max(0.0, _gpu_usable((_idx, _free)))
+ _idx: max(0.0, _gpu_usable((_idx, _free), _pin_fraction))
for _idx, _free in (gpus or ())
},
"gpu_indices": gpu_indices,
@@ -18991,6 +19057,11 @@ class LlamaCppBackend:
# same type (common/speculative.cpp:2257-2261).
# Over-charging only spills more.
"mtp_will_engage": bool(_mtp_will_engage),
+ # A SEPARATE drafter that stays on the GPU: a second model,
+ # whose weights and KV llama.cpp distributes like any other.
+ # None once the drafter is CPU-offloaded (_mtp_draft_for_budget
+ # is nulled there), which is the case that really is off-GPU.
+ "separate_draft_on_gpu": bool(_mtp_will_engage and _mtp_draft_for_budget),
# The planner reads the real tensor table, not a bucket
# total, so it can spill the MINIMUM set of blocks.
"model_path": model_path,
@@ -19158,6 +19229,20 @@ class LlamaCppBackend:
_fit_env_mmproj_bytes,
on_host = _fit_env_mmproj_on_host,
)
+ # The same projector, handed to the spill planner. Its
+ # extra_gpu_bytes carries the RESOLVED one only, so without this
+ # an inherited LLAMA_ARG_MMPROJ is VRAM no term in the plan has
+ # paid for -- and a plan is pinned with --fit off, so llama.cpp's
+ # fitter never gets to absorb it. Weights plus the runtime
+ # allowance, exactly what _fit_model_size and _fit_soft_overhead
+ # just charged, and the same abstain when it cannot be sized.
+ _spill_inputs["env_mmproj_unsized"] = _fit_env_mmproj_unsized
+ _spill_inputs["env_mmproj_bytes"] = (
+ 0
+ if _fit_env_mmproj_on_host
+ else _fit_env_mmproj_bytes
+ + self._inherited_mmproj_soft_overhead(_fit_env_mmproj_bytes, on_host = False)
+ )
_fit_load_mode = self._fit_derived_load_mode(
model_size = _fit_model_size,
mmproj_pinned_bytes = _mmproj_pinned_bytes
@@ -19219,6 +19304,10 @@ class LlamaCppBackend:
_placement_verdict_partial = False
# Same reasoning: an unpriced load keeps llama.cpp's default.
_fit_load_mode = None
+ # 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.
+ _spill_inputs = None
tp_tensor_split = None
effective_ctx = requested_ctx # fall back to original
@@ -23775,6 +23864,18 @@ class LlamaCppBackend:
if is_apple_silicon():
return None
+ # An integrated CUDA SoC (Jetson, DGX Spark) is unified memory too, and
+ # nothing else here sees it: _amd_apu_wants_unified_memory answers only for
+ # ROCm, and shared_gpu_ids is populated only on Vulkan, which reports total
+ # 0 for an iGPU. CUDA states it directly (cudaDeviceProp::integrated, torch's
+ # is_integrated), and Studio's diffusion policy already classifies such a
+ # device as unified memory for exactly this reason -- CPU offload frees
+ # nothing there (diffusion_memory.py:292-294). A spill would count one pool
+ # twice and then pin the result with --fit off.
+ if self._integrated_cuda_unified_memory(inputs.get("gpu_indices")):
+ logger.debug("Tensor spill: declined, an integrated CUDA device is unified memory")
+ return None
+
# Someone else owns the placement -- decline. Each of these re-places the
# model out from under a plan made here: -ot / --cpu-moe (or its env twin)
# already moves tensors, a layer count overrides -ngl -1, a device list
@@ -23826,6 +23927,18 @@ class LlamaCppBackend:
for a in (extra_args or ())
)
or str(source_env.get("LLAMA_ARG_FIT", "")).strip()
+ # --rpc devices are REMOTE and go at the FRONT of the list
+ # (llama.cpp:275), so the free-memory row split hands the first slice
+ # of layers to a card Studio never detected. Every number here comes
+ # from the local `gpus` snapshot, so the plan would credit local VRAM
+ # for layers that went elsewhere and pin it with --fit off.
+ or (_extra_args_device(extra_args, {"--rpc"}) or "").strip()
+ or str(source_env.get("LLAMA_ARG_RPC", "")).strip()
+ # --fit-target is VRAM the user told the fitter it may not spend
+ # (common/fit.cpp:282-288). Emitting --fit off skips
+ # common_params_fit_impl and drops the margin silently, while this
+ # planner spends it. Decline, like any other explicit --fit.
+ or fit_target_margin_in(extra_args, source_env) is not None
):
logger.debug("Tensor spill: declined, pass-through arguments own the placement")
return None
@@ -23941,6 +24054,26 @@ class LlamaCppBackend:
if avail_mib is None:
return None
+ # A separate drafter is a second MODEL, and an UNPINNED one is placed like
+ # any other: common_base_params_to_speculative copies the draft device list
+ # verbatim (common/speculative.cpp:2319-2331), and an empty one drops
+ # llama_prepare_model_devices into its default enumeration of every visible
+ # GPU (llama.cpp:184-276), so the drafter's weights AND its context follow
+ # the free-memory row split onto every card. A PINNED one already declined
+ # above. Its reserve rides in extra_resident_bytes, which
+ # _per_device_shortfall books entirely on device 0, so every other card is
+ # under-booked by its share -- and --fit off means common/fit.cpp never runs
+ # to catch the overflow. Nothing here says how llama.cpp will split a model
+ # this layout knows nothing about, so decline, like the pass-through adapter
+ # below.
+ if inputs.get("separate_draft_on_gpu") and len(vram_per_device) > 1:
+ logger.debug(
+ "Tensor spill: declined, a separate drafter's bytes cannot be placed "
+ "across %d devices",
+ len(vram_per_device),
+ )
+ return None
+
# The trailing nextn/MTP blocks the layout dropped, charged back when a
# draft will engage. Unsloth's budget already assumed they were paid for (an
# embedded head contributes 0 to _mtp_draft_weights because its weights sit
@@ -23955,6 +24088,48 @@ class LlamaCppBackend:
# against the pool and booked onto device 0, where it lives.
extra_gpu_bytes += int(inputs.get("compute_buffer_flat") or 0)
+ # A projector Studio never resolved but the child loads anyway. arg.cpp
+ # applies LLAMA_ARG_MMPROJ before argv (common/arg.cpp:780-802) and a
+ # LLAMA_ARG_MMPROJ_URL download overwrites even the --mmproj this launch
+ # emits (common/arg.cpp:500-503, :632-634), and the projector is GPU
+ # resident unless --no-mmproj-offload says otherwise. extra_gpu_bytes above
+ # carries only the RESOLVED projector, so those bytes sit in no term here
+ # and the plan pins the shortfall with --fit off. The seam hands over the
+ # same numbers the load-mode fit used, including its abstain for a URL or
+ # an unreadable path.
+ if inputs.get("env_mmproj_unsized"):
+ logger.debug("Tensor spill: declined, an inherited projector could not be sized")
+ return None
+ extra_gpu_bytes += int(inputs.get("env_mmproj_bytes") or 0)
+
+ # Pass-through --lora / --lora-scaled / --control-vector weights, GPU
+ # resident and in no other term here. Both land on the base layer's buffer
+ # type (llama-adapter.cpp:335, :67) and neither mmaps: the file is staged
+ # with ggml_backend_tensor_set (:407), so the bytes are resident whatever
+ # --load-mode says, and `model_size` is the base GGUF alone. Same treatment
+ # _fits_without_paging gives them: a term, and an unreadable file abstains.
+ sidecar_bytes = _sidecar_adapter_bytes(extra_args)
+ if sidecar_bytes is None:
+ logger.debug("Tensor spill: declined, a pass-through adapter could not be sized")
+ return None
+ # ...but a flat term is only right on ONE device. extra_resident_bytes is
+ # charged entirely to device 0 (_per_device_shortfall), while a LoRA tensor
+ # is allocated on its BASE tensor's buffer (llama-adapter.cpp:335) and a
+ # control-vector row on model.select_buft(il) (:67) -- so on a layer split
+ # they follow the layers onto every card. Booking them all on the main GPU
+ # under-books the others, and --fit off means common/fit.cpp never runs to
+ # catch the overflow. The layout is built from the base GGUF alone and holds
+ # no adapter tensor table, so the per-device share cannot be derived here.
+ # Decline, like every other placement this planner cannot price.
+ if sidecar_bytes and len(vram_per_device) > 1:
+ logger.debug(
+ "Tensor spill: declined, a pass-through adapter's bytes cannot be placed "
+ "across %d devices",
+ len(vram_per_device),
+ )
+ return None
+ extra_gpu_bytes += sidecar_bytes
+
return plan_placement(
layout,
vram_per_device,
diff --git a/studio/backend/core/inference/offload_planner.py b/studio/backend/core/inference/offload_planner.py
index efd203bf565..de8014414ea 100644
--- a/studio/backend/core/inference/offload_planner.py
+++ b/studio/backend/core/inference/offload_planner.py
@@ -853,13 +853,25 @@ def plan_to_args(plan: Plan) -> list[str]:
return args
+_SMART_OFFLOAD_ON = ("1", "true", "yes", "on", "enabled")
+
+
def smart_offload_enabled(env: Optional[Mapping[str, str]] = None) -> bool:
- """Whether the launch path may emit a spill plan.
+ """Whether the launch path may plan a spill. ON unless explicitly disabled.
+
+ It shipped opt-in "until it has run on more than one machine". It has: 118
+ paired runs across T4, L4, RTX PRO 6000, A100, B200 and a real gfx1151 APU,
+ faster on generation in 111, and 100% KV cache retention in all 83 runs
+ where the layer-count arm would have split the cache to host RAM.
+
+ Default does not mean it places every load: it abstains often, and every
+ abstain still falls through to ``--fit on``.
- Off by default. The planner changes how a model is placed, and the failure
- mode of getting it wrong is a load that OOMs where llama.cpp's own default
- would have paged, so it opts in rather than out until it has run on more
- than one machine.
+ An UNRECOGNISED value disables. The typos are not symmetric for an opt-OUT
+ flag: ``flase`` meaning off must not hand back the thing it was switching
+ off, while fumbling an on-spelling only keeps the old behaviour.
"""
- raw = (os.environ if env is None else env).get("UNSLOTH_SMART_OFFLOAD", "")
- return str(raw).strip().lower() in ("1", "true", "yes", "on", "enabled")
+ raw = (os.environ if env is None else env).get("UNSLOTH_SMART_OFFLOAD")
+ if raw is None:
+ return True
+ return str(raw).strip().lower() in _SMART_OFFLOAD_ON
diff --git a/studio/backend/tests/test_offload_planner_seam.py b/studio/backend/tests/test_offload_planner_seam.py
index e8769082bb1..8a08d278c6e 100644
--- a/studio/backend/tests/test_offload_planner_seam.py
+++ b/studio/backend/tests/test_offload_planner_seam.py
@@ -42,6 +42,24 @@ def _discrete_host(monkeypatch):
monkeypatch.setattr(utils.hardware, "is_apple_silicon", lambda: False)
[email protected](scope = "session")
+def sparse_adapter(tmp_path_factory):
+ """A 3 GiB adapter file that costs neither RAM nor (on ext4/APFS) disk.
+
+ ``_sidecar_adapter_bytes`` reads ``os.stat().st_size`` and nothing else, so
+ the fixture only has to be the right SIZE. Materialising it as real zeros
+ spiked RSS by 3 GiB per test and left up to 9 GiB in the session's tmp dir
+ (pytest keeps every test's directory for the whole run), which the 14 GB
+ runner disk does not have to spare. ``truncate`` sets the length without
+ writing: a hole on ext4/APFS, and on NTFS space that is reserved but never
+ zero-filled. One file for the session, since every caller only stats it.
+ """
+ path = tmp_path_factory.mktemp("adapters") / "adapter.gguf"
+ with open(path, "wb") as handle:
+ handle.truncate(3 * GIB)
+ return path
+
+
class _Stub:
"""Only what the seam touches."""
@@ -53,10 +71,16 @@ class _Stub:
# Bytes of trailing nextn/MTP blocks the layout dropped. 0 = an ordinary
# model, which is every existing case here.
_excluded_bytes = 0
+ # Discrete CUDA by default. An integrated SoC (Jetson, DGX Spark) is the
+ # unified-memory answer on the CUDA side, exercised deliberately below.
+ _integrated_cuda = False
def _amd_apu_wants_unified_memory(self, gpu_indices = None):
return self._unified
+ def _integrated_cuda_unified_memory(self, gpu_indices = None):
+ return self._integrated_cuda
+
def __init__(
self,
avail_mib = 64 * 1024,
@@ -124,6 +148,9 @@ def _inputs(
n_parallel = 1,
compute_flat = 0,
ctx_compute = 0,
+ env_mmproj = 0,
+ env_mmproj_unsized = False,
+ separate_draft = False,
):
return {
"model_size": model_size,
@@ -133,12 +160,15 @@ def _inputs(
"compute_buffer_flat": compute_flat,
"ctx_compute_per_device": ctx_compute,
"extra_gpu_bytes": extra_gpu,
+ "env_mmproj_bytes": env_mmproj,
+ "env_mmproj_unsized": env_mmproj_unsized,
"gpu_indices": indices,
"soft_overhead": 0,
"model_path": "/models/stub.gguf",
"n_ctx": 32768,
"n_parallel": n_parallel,
"shared_gpu_ids": set() if shared is None else set(shared),
+ "separate_draft_on_gpu": separate_draft,
**({} if mtp is None else {"mtp_will_engage": mtp}),
}
@@ -159,10 +189,16 @@ def _plan(
# ------------------------------------------------------------------ the gate
-def test_the_planner_is_off_by_default():
- """No env, no plan. An old install cannot change behaviour by upgrading."""
- assert smart_offload_enabled({}) is False
- assert _Stub()._planned_tensor_spill(_inputs(), env = {}) is None
+def test_the_planner_is_on_by_default():
+ """No env, a plan. The flag is now opt-OUT."""
+ assert smart_offload_enabled({}) is True
+ # A load that fits is still PLANNED, it just spills nothing.
+ roomy = _Stub()._planned_tensor_spill(_inputs(), env = {})
+ assert roomy is not None and not roomy.spills_anything
+
+ # A load that does not fit gets a real plan with no env set at all.
+ tight = _Stub()._planned_tensor_spill(_inputs(free_mib = 14 * 1024), env = {})
+ assert tight is not None and tight.spills_anything
@pytest.mark.parametrize("value", ["1", "on", "true", "yes", "enabled", "ON", " 1 "])
@@ -170,8 +206,18 @@ def test_the_gate_accepts_the_usual_spellings(value):
assert smart_offload_enabled({"UNSLOTH_SMART_OFFLOAD": value}) is True
[email protected]("value", ["0", "off", "", "no", "nope"])
-def test_the_gate_rejects_everything_else(value):
[email protected]("value", ["0", "off", "", "no", "disabled", "false"])
+def test_an_explicit_off_still_disables(value):
+ """The escape hatch has to keep working."""
+ assert smart_offload_enabled({"UNSLOTH_SMART_OFFLOAD": value}) is False
+ assert _Stub()._planned_tensor_spill(_inputs(), env = {"UNSLOTH_SMART_OFFLOAD": value}) is None
+
+
[email protected]("value", ["nope", "flase", "onn", "2"])
+def test_an_unrecognised_value_disables_rather_than_enables(value):
+ """The typos are not symmetric for an opt-OUT flag: `flase` meaning off must
+ not hand back the thing it was switching off, while fumbling an on-spelling
+ only keeps the previous behaviour."""
assert smart_offload_enabled({"UNSLOTH_SMART_OFFLOAD": value}) is False
@@ -912,6 +958,292 @@ def test_a_pass_through_parallel_that_grows_the_cache_declines_the_plan():
assert _plan(stub, n_parallel = 1) is not None
+# --------------------------------------- newly reachable now the gate is default-on
+
+
+ "extra_args,env",
+ [
+ (["--rpc", "10.0.0.2:50052"], None),
+ (["--rpc=10.0.0.2:50052"], None),
+ (None, {"LLAMA_ARG_RPC": "10.0.0.2:50052"}),
+ ],
+)
+def test_an_rpc_device_declines_the_plan(extra_args, env):
+ """--rpc devices are REMOTE and llama.cpp puts them at the FRONT of the device
+ list (llama.cpp:275), so the row split hands the first slice of layers to a
+ card this planner never saw: every number it has comes from Studio's LOCAL
+ gpus snapshot. Crediting local VRAM for layers that went to another host and
+ then pinning it with --fit off has nothing left to catch it."""
+ assert _plan(_Stub(), extra_args = extra_args, env = env) is None
+ assert _plan(_Stub()) is not None, "not vacuous: the same load plans without it"
+
+
+ "extra_args,env",
+ [
+ (["--fit-target", "4096"], None),
+ (["-fitt", "4096"], None),
+ (["--fit-target=4096,4096"], None),
+ (None, {"LLAMA_ARG_FIT_TARGET": "4096"}),
+ ],
+)
+def test_an_explicit_fit_target_declines_the_plan(extra_args, env):
+ """--fit-target is VRAM the user told the fitter it may not spend: it becomes
+ `targets.push_back(dmds_full[id].free - margins[id])` (common/fit.cpp:282-288).
+ This planner credits that same VRAM and emits --fit off, so
+ common_params_fit_impl never runs and the reservation is silently dropped
+ while Studio's own load-mode fit still honours it."""
+ assert _plan(_Stub(), extra_args = extra_args, env = env) is None
+ assert _plan(_Stub()) is not None, "not vacuous"
+
+
+def test_a_pass_through_adapter_is_charged_as_resident_vram(sparse_adapter, monkeypatch):
+ """LoRA and control-vector sidecars are GPU-resident and in NO other term
+ here: they are created on the base layer's buffer type (llama-adapter.cpp:335,
+ :67) and neither mmaps (:407). `model_size` is the base GGUF alone, so an
+ unpriced adapter is a plan claiming a fit that is not there."""
+ adapter = sparse_adapter
+
+ # Sized so the base load fits with room to spare and the adapter is what
+ # tips it over: the term has to be load-bearing, not merely present.
+ stub = _Stub()
+ free = 17 * 1024
+ bare = _plan(stub, free_mib = free)
+ with_lora = _plan(stub, free_mib = free, extra_args = ["--lora", str(adapter)])
+ assert bare is not None and with_lora is not None
+ assert not bare.spills_anything, "the base load fits on its own"
+ assert with_lora.spills_anything, "3 GiB of resident adapter comes out of the same VRAM"
+
+ ctrl = _plan(stub, free_mib = free, extra_args = ["--control-vector", str(adapter)])
+ assert ctrl.spilled_blocks == with_lora.spilled_blocks
+
+ # The colon-scaled form, from a directory the path can be spelled relative to.
+ # An ABSOLUTE path is not usable here: on Windows it carries a drive letter,
+ # and `C:\...\adapter.gguf:0.5` is three parts to string_split, which upstream
+ # rejects outright (`parts.size() != 2` -> throw, common/arg.cpp:2944-2946).
+ # Pricing a token that never starts a child would be the wrong answer, so the
+ # test asks for the reading that exists on every platform.
+ monkeypatch.chdir(adapter.parent)
+ scaled = _plan(stub, free_mib = free, extra_args = ["--lora-scaled", "adapter.gguf:0.5"])
+ assert scaled.spilled_blocks == with_lora.spilled_blocks
+
+
+def test_a_drive_lettered_scaled_adapter_is_skipped_rather_than_priced():
+ """The other half of the same syntax. string_split on ':' gives three parts for
+ `C:\\dir\\adapter.gguf:0.5`, so upstream throws and the child never starts;
+ there is no placement to misprice, and guessing which colon was the separator
+ would price a launch that cannot happen. Skipped, not sized, not abstained.
+
+ No file is created: the drive-lettered form names a path that exists on no
+ runner, and the point is that it is never stat'd."""
+ drive_lettered = "C:\\dir\\adapter.gguf:0.5"
+
+ stub = _Stub()
+ free = 17 * 1024
+ plan = _plan(stub, free_mib = free, extra_args = ["--lora-scaled", drive_lettered])
+ assert plan is not None, "a form the child rejects is not the unsized-abstain case"
+ assert not plan.spills_anything, "nothing priced, so the base load still fits"
+
+
+def test_an_unreadable_adapter_abstains():
+ """Engaged but unsized: os.stat fails, so abstain rather than plan a footprint
+ short by an unknown amount. Same answer _fits_without_paging gives."""
+ assert _plan(_Stub(), extra_args = ["--lora", "/no/such/adapter.gguf"]) is None
+ assert _plan(_Stub()) is not None, "not vacuous"
+
+
+def test_an_inherited_projector_is_charged_rather_than_ignored():
+ """A projector that arrives only through LLAMA_ARG_MMPROJ is still GPU
+ resident: arg.cpp applies the environment before argv (common/arg.cpp:780-802,
+ the handler loop that runs ahead of parse_cli_args), and `extra_gpu_bytes`
+ carries only the projector Studio itself resolved. Unbudgeted bytes here are a
+ plan pinned with --fit off over a footprint that does not fit."""
+ stub = _Stub()
+ free = 17 * 1024
+ bare = _plan(stub, free_mib = free)
+ inherited = _plan(stub, free_mib = free, env_mmproj = 3 * GIB)
+ assert bare is not None and inherited is not None
+ assert not bare.spills_anything, "the base load fits on its own"
+ assert inherited.spills_anything, "3 GiB of inherited projector comes out of the same VRAM"
+
+
+def test_an_unsized_inherited_projector_abstains():
+ """LLAMA_ARG_MMPROJ_URL names a download that has not happened yet (and it
+ outranks even the --mmproj this launch emits: the fetch rewrites
+ params.mmproj.path, common/arg.cpp:500-503, :632-634), and an unreadable path
+ cannot be stat'd. Unknown bytes, so abstain rather than plan short."""
+ assert _plan(_Stub(), free_mib = 14 * 1024, env_mmproj_unsized = True) is None
+ assert _plan(_Stub(), free_mib = 14 * 1024) is not None, "not vacuous"
+
+
+def test_the_seam_hands_the_planner_the_inherited_projector():
+ """The planner can only charge what the launch path snapshots for it, and the
+ load-mode fit already computes exactly these two values."""
+ import inspect
+
+ compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
+ assert '_spill_inputs["env_mmproj_unsized"]=_fit_env_mmproj_unsized' in compact
+ assert '_spill_inputs["env_mmproj_bytes"]=' in compact
+
+
+class _FlatAttentionStub(_Stub):
+ """A layout _per_device_shortfall can actually check: every layer holds a
+ cache, no sliding window, no trailing blocks. The default stub abstains on the
+ per-device test, which hides what a multi-GPU plan does with a flat term."""
+
+ def _tensor_spill_layout(self, model_path):
+ n = 8
+ return ModelLayout(
+ arch = "qwen35",
+ n_layers = n,
+ n_attention_layers = n,
+ blocks = tuple(
+ BlockLayout(index = i, spillable_bytes = 2 * GIB, resident_bytes = GIB // 2)
+ for i in range(n)
+ ),
+ lm_head_bytes = 1 * GIB,
+ token_embd_bytes = 512 * MIB,
+ kv_bytes_per_token_f16 = 16384,
+ n_ctx_train = 262144,
+ complete = True,
+ )
+
+
+def test_a_multi_gpu_adapter_declines_rather_than_booking_it_all_on_device_0(sparse_adapter):
+ """Adapter bytes are not a device-0 lump on a layer split.
+
+ A LoRA tensor is allocated on its BASE tensor's buffer
+ (`ggml_backend_buffer_get_type(model_tensor->buffer)`, llama-adapter.cpp:335)
+ and a control-vector row on `model.select_buft(il)` (:67), so they follow the
+ contiguous layer ranges llama.cpp hands each card. `extra_resident_bytes`, on
+ the other hand, is charged entirely to device 0 by `_per_device_shortfall`, so
+ a tight second card passes the per-device check on bytes it will really be
+ asked to hold -- and the plan then emits --fit off, so common/fit.cpp never
+ runs to catch the overflow. The base GGUF's layout carries no adapter tensor
+ table, so the split cannot be derived; abstain instead.
+ """
+ adapter = sparse_adapter
+
+ stub = _FlatAttentionStub()
+ # 10 + 3 GiB free with a 3 GiB adapter: the deficit needs EVERY block spilled,
+ # which is the only multi-GPU shape that reaches the per-device check at all
+ # (a partial spill already abstains above it). Before this abstain the same
+ # inputs produced a real plan -- all 8 blocks spilled, -ngl -1 --fit off
+ # emitted -- with the whole 3 GiB booked on device 0 and nothing on device 1,
+ # which is where the adapter rows for that card's layers actually go.
+ two_cards = dict(model_size = 21 * GIB, kv = 2 * GIB, gpus = [(0, 10 * 1024), (1, 3 * 1024)])
+ for flag in ("--lora", "--control-vector"):
+ assert _plan(stub, extra_args = [flag, str(adapter)], **two_cards) is None
+
+ # Only the adapter is refused: the same two-card load still reaches the
+ # planner, so the abstain above is not the whole configuration being dropped.
+ assert _plan(stub, **two_cards) is not None
+
+ # Single card is unchanged: there the flat charge IS the right one, and the
+ # adapter is still priced rather than ignored.
+ one_card = _plan(_Stub(), free_mib = 17 * 1024, extra_args = ["--lora", str(adapter)])
+ assert one_card is not None and one_card.spills_anything
+
+
+def test_apple_silicon_declines_the_plan(monkeypatch):
+ """Unified memory: an -ot spill moves bytes inside one pool, so the trade does
+ not exist, and Metal keeps mmap zero copy through buffer_from_host_ptr. The
+ seam reads this from the host, so it is the one fact the autouse fixture pins
+ and the one that has to be asserted with the fixture overridden."""
+ import utils.hardware
+
+ monkeypatch.setattr(utils.hardware, "is_apple_silicon", lambda: True)
+ assert _plan(_Stub(), free_mib = 14 * 1024) is None
+
+ monkeypatch.setattr(utils.hardware, "is_apple_silicon", lambda: False)
+ assert _plan(_Stub(), free_mib = 14 * 1024) is not None, "not vacuous"
+
+
+def test_an_integrated_cuda_device_declines_the_plan():
+ """A CUDA SoC (Jetson, DGX Spark) is unified memory and no other guard sees it.
+
+ `_amd_apu_wants_unified_memory` answers only for ROCm, and `shared_gpu_ids`
+ is filled only on Vulkan (an iGPU reports total VRAM 0), so an integrated
+ CUDA device arrives with its "VRAM" credited AND host RAM credited: one pool
+ counted twice. Spilling out of it frees no device memory, and the plan then
+ pins that with --fit off, which is the load llama.cpp's own fitter used to
+ place. The repository already classifies such a device as unified memory for
+ the diffusion path (diffusion_memory.py:292-294, cudaDeviceProp::integrated
+ via torch's is_integrated).
+ """
+ discrete = _Stub()
+ soc = _Stub()
+ soc._integrated_cuda = True
+
+ # Same numbers either way, so the difference is attributable to the flag.
+ assert _plan(soc, free_mib = 14 * 1024) is None
+ assert _plan(discrete, free_mib = 14 * 1024) is not None, "not vacuous"
+
+
+def test_a_multi_gpu_separate_drafter_declines_rather_than_booking_it_on_device_0():
+ """An unpinned drafter is distributed, not a device-0 lump.
+
+ `common_base_params_to_speculative` copies the draft device list verbatim
+ (common/speculative.cpp:2319-2331) and an EMPTY one drops
+ `llama_prepare_model_devices` into its default enumeration of every visible
+ GPU (llama.cpp:184-276), so the drafter's weights and its context follow the
+ free-memory row split onto every card. `_mtp_reserve_bytes` rides in
+ `extra_resident_bytes`, which `_per_device_shortfall` books entirely on
+ device 0, so a tight second card passes the per-device check on bytes it will
+ really be asked to hold -- and --fit off means common/fit.cpp never runs to
+ catch the overflow. A PINNED drafter already declines on
+ `_extra_args_draft_device_pin`.
+ """
+ stub = _FlatAttentionStub()
+ # The all-blocks-spilled shape, the only multi-GPU one that reaches the
+ # per-device check at all (a partial spill abstains above it). extra_gpu is
+ # the drafter's own reserve, which is how the seam really carries it: the
+ # snapshot folds _mtp_reserve_bytes into extra_gpu_bytes.
+ two_cards = dict(
+ model_size = 21 * GIB,
+ kv = 2 * GIB,
+ extra_gpu = 3 * GIB,
+ gpus = [(0, 10 * 1024), (1, 3 * 1024)],
+ )
+ # Before this abstain the same inputs produced a real plan -- every block
+ # spilled, -ngl -1 --fit off emitted -- with the whole 3 GiB booked on
+ # device 0 and nothing on device 1, which is where the drafter's rows for
+ # that card's layers actually go.
+ assert _plan(stub, separate_draft = True, **two_cards) is None
+
+ # Only the drafter is refused: the same two cards without one still plan, and
+ # really spill, so the abstain is not the whole configuration being dropped.
+ without = _plan(stub, **two_cards)
+ assert without is not None and without.spills_anything
+
+ # Single card is unchanged: there the flat charge IS the right one.
+ one_card = _plan(_Stub(), free_mib = 14 * 1024, separate_draft = True)
+ assert one_card is not None and one_card.spills_anything
+
+
+def test_the_flat_mtp_reserve_reaches_the_spill_budget():
+ """An unsized draft KV is paid for with _MTP_VRAM_RESERVE_FRAC of every card.
+
+ The placement paths spend `_pin_fraction = _vram_frac - _MTP_VRAM_RESERVE_FRAC`
+ when the byte-accurate `mtp_overhead_fn` cannot size the draft KV, and
+ `_mtp_reserve_bytes` carries no replacement for the unsized part (it is 0 when
+ `mtp_overhead_fn is None`). The snapshot has to hand the planner that same
+ reduced budget, or the plan spends 5% of VRAM the fit deliberately kept free
+ and then pins it with --fit off.
+ """
+ import inspect
+
+ compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
+ assert '"gpu_usable_mib":{_idx:max(0.0,_gpu_usable((_idx,_free),_pin_fraction))' in compact
+
+ # And the budget really is what the planner spends: the same load plans a
+ # bigger spill on the smaller budget.
+ stub = _Stub()
+ generous = _plan(stub, free_mib = 24 * 1024, usable_mib = 15 * 1024)
+ reserved = _plan(stub, free_mib = 24 * 1024, usable_mib = 14 * 1024)
+ assert generous is not None and reserved is not None
+ assert len(reserved.spilled_blocks) > len(generous.spilled_blocks)
def test_the_seam_computes_a_per_layer_kv_vector():
"""The data already existed on the backend (_sliding_window_pattern); it just
never crossed into the planner. Only the RATIOS travel: full attention holds