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: place the vision projector on the CPU only when it does not fit in VRAM (#9063)

Daniel Han338c36dfa412
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index d63d75e85e5..e710ca87cd7 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -2554,8 +2554,13 @@ def zero_vram_chat_load(
return False
# Any speculative mode may launch a GPU drafter and only the request's own knobs are known here, so treat every selection as GPU-bearing except
# "off". Canonicalize first: the UI sends the literal "off", which a bare truthiness test read as "speculation requested".
- spec_mode = _canonicalize_spec_mode(speculative_type)
- if needs_mmproj or spec_mode not in (None, "off"):
+ # ...and an ABSENT mode is not a quiet "off": every consumer resolves None to
+ # "auto", where a sidecar can still be discovered and GPU-offloaded. Grouping None
+ # with "off" let a defaulted load skip acquire_for(CHAT) while the launch-time mask
+ # -- reading the FINISHED argv, drafter included -- kept the GPUs visible: no
+ # arbiter, real VRAM, free to OOM a resident image pipeline.
+ spec_mode = _canonicalize_spec_mode(speculative_type) or "auto"
+ if needs_mmproj or spec_mode != "off":
return False
if LlamaCppBackend._is_vulkan_backend():
return False
@@ -2587,6 +2592,14 @@ def _with_gguf_load_marker(load: Callable):
if hf_repo and _hub_download_blocks_gguf_load(
hf_repo,
intent.hf_variant,
+ # Mirrors the download gate below EXACTLY, which is the whole point:
+ # this load fetches the projector whenever the repo ships one and the
+ # extras have not opted out, switch or no switch, because only the
+ # file's metadata says whether it is an image tower or an audio
+ # encoder. So the switch must not relax the interlock here. It did
+ # briefly, and the two together let a vision-off load skip the 409 and
+ # then write into the shared Hub cache next to a running download job,
+ # which is the race this check exists to stop.
require_mmproj = bool(
intent.is_vision and not extra_args_disable_mmproj(intent.extra_args)
),
@@ -3501,6 +3514,99 @@ def _paravirtual_mmproj_pinnable(server_caps: Mapping[str, object]) -> bool:
)
+# Both spellings of the projector-placement boolean. llama.cpp pairs them as one
+# option and takes the last occurrence, so naming either one in the pass-through
+# extras is the user taking ownership of the placement.
+_MMPROJ_OFFLOAD_FLAGS: frozenset = frozenset({"--mmproj-offload", "--no-mmproj-offload"})
+
+
+def _extra_args_set_mmproj_offload(extra_args: Optional[Sequence[str]]) -> bool:
+ """True when the pass-through extras name either projector-placement spelling.
+
+ Matched through _flag_name rather than by string equality: arg.cpp folds
+ underscores to dashes before matching, so --mmproj_offload is the same flag.
+ """
+ return _extra_args_set_any_flag(extra_args, _MMPROJ_OFFLOAD_FLAGS)
+
+
+def _extra_args_mmproj_offload_value(extra_args: Optional[Sequence[str]]) -> Optional[bool]:
+ """The offload the extras actually resolve to, or None when they name neither.
+
+ Detecting ownership is not enough to budget for: --no-mmproj-offload means the
+ child keeps the projector in host RAM, so charging its bytes against VRAM
+ shrinks the context for memory nothing on the GPU takes. Last occurrence wins,
+ as llama.cpp pairs the two spellings into one option.
+ """
+ if not extra_args:
+ return None
+ value: Optional[bool] = None
+ for raw in extra_args:
+ flag = _flag_name(str(raw))
+ if flag == "--mmproj-offload":
+ value = True
+ elif flag == "--no-mmproj-offload":
+ value = False
+ return value
+
+
+# arg.cpp applies set_env options BEFORE argv, so an inherited placement is a choice
+# Studio can reverse with nothing but a llama.cpp warning to show for it, and the child
+# inherits this process's environment. Both spellings: get_value_from_env checks the
+# LLAMA_ARG_NO_ form first and forces falsey on PRESENCE, empty value included.
+_MMPROJ_OFFLOAD_ENV_VAR = "LLAMA_ARG_MMPROJ_OFFLOAD"
+_MMPROJ_OFFLOAD_NEG_ENV_VAR = "LLAMA_ARG_NO_MMPROJ_OFFLOAD"
+
+
+def _env_sets_mmproj_offload(env: Optional[Mapping[str, str]] = None) -> bool:
+ """True when the child's environment names the projector placement at all.
+
+ Ownership, not value: a value arg.cpp parses as neither truthy nor falsey throws
+ out of common_params_parse, and a caller whose load is about to fail on their own
+ variable is still the one who set it. Presence is the test for the same reason
+ llama.cpp uses getenv, so ``LLAMA_ARG_NO_MMPROJ_OFFLOAD=`` counts.
+ """
+ source = os.environ if env is None else env
+ return any(
+ source.get(name) is not None
+ for name in (_MMPROJ_OFFLOAD_ENV_VAR, _MMPROJ_OFFLOAD_NEG_ENV_VAR)
+ )
+
+
+def _env_mmproj_offload_value(env: Optional[Mapping[str, str]] = None) -> Optional[bool]:
+ """The offload the child's environment resolves to, or None for silence.
+
+ get_value_from_env's own order: the negative spelling short-circuits to falsey on
+ presence, then the positive one goes through is_truthy / is_falsey. Anything else
+ is left as None, since arg.cpp raises rather than picking a side and there is no
+ placement to budget for.
+ """
+ source = os.environ if env is None else env
+ if source.get(_MMPROJ_OFFLOAD_NEG_ENV_VAR) is not None:
+ return False
+ raw = source.get(_MMPROJ_OFFLOAD_ENV_VAR)
+ if raw is None:
+ return None
+ value = str(raw).strip().lower()
+ if value in _LLAMA_ARG_TRUE_VALUES:
+ return True
+ if value in _LLAMA_ARG_FALSE_VALUES:
+ return False
+ return None
+
+
+def _resolved_mmproj_offload(
+ extra_args: Optional[Sequence[str]], env: Optional[Mapping[str, str]] = None
+) -> Optional[bool]:
+ """Where the projector actually ends up, over extras and environment together.
+
+ Same precedence the child applies: environment first, then argv on top, so a
+ pass-through flag wins over an inherited variable and only silence in both falls
+ through to None.
+ """
+ from_args = _extra_args_mmproj_offload_value(extra_args)
+ return from_args if from_args is not None else _env_mmproj_offload_value(env)
+
+
_OVERRIDE_TENSOR_FLAGS: frozenset = frozenset(
{
"-ot",
@@ -4476,6 +4582,7 @@ class LlamaCppBackend:
self._pending_cpu_fallback_cleanups: list = []
self._hf_variant: Optional[str] = None
self._is_vision: bool = False
+ # Vision deliberately left unloaded by the caller. Tracked so a reload that
# Block-diffusion model (e.g. DiffusionGemma): served by the diffusion
# runner, not llama-server. Set from the GGUF architecture at load.
self._architecture: Optional[str] = None
@@ -5296,6 +5403,8 @@ class LlamaCppBackend:
if _norm(self._cache_type_kv) != _norm(intent.cache_type_kv):
return False
+ # Toggling vision changes which files the child opens, so it cannot be
+ # satisfied by a live server that was launched the other way. Not on the
extra_args = list(effective_extra_args) if effective_extra_args is not None else None
# A request omitting the extras field inherits the LAUNCHED list; anything else is
# the caller's own. A launch-time rewrite (drafter drop, MTP crash replay) makes
@@ -9310,6 +9419,10 @@ class LlamaCppBackend:
# Soft VRAM the modeled terms omit; charged to the fit budget on tight tiers (#6682).
_CUDA_CONTEXT_RESERVE_BYTES = 320 * 1024 * 1024 # CUDA ctx + cuBLAS workspace (~330 MiB)
_MMPROJ_VRAM_SAFETY = 1.4 # mmproj worst-case buffer vs file size (runtime ~1.3x)
+ # Context the projector's residency is priced at. The placement loop shrinks the
+ # context to this floor long before it would spill a layer, so this is the length
+ # at which "does it fit" means "does every layer stay on the GPU".
+ _MMPROJ_FIT_FLOOR_CTX = 4096
_MTP_DRAFT_COMPUTE_BYTES = 224 * 1024 * 1024 # MTP draft decode graph beyond its KV
# Draft depth to budget when the extras own the spec block and the probe cannot
# read the build's own default off its --help. Shipped values are 3
@@ -13383,13 +13496,27 @@ class LlamaCppBackend:
if not any(_flag(arg) in ("--mmproj", "-mm") for arg in args):
return None
+ # Argv and environment at arg.cpp's own precedence. Two placements the
+ # spelling list below cannot see: LLAMA_ARG_NO_MMPROJ_OFFLOAD (falsey on
+ # presence alone) and the `disabled` token. Either already has the projector in
+ # host RAM, so respawning cannot clear the allocation failure and costs the
+ # caller the real error, which only surfaces when this returns None.
+ #
+ # Only a resolved False means "already on CPU". An explicit --mmproj-offload is
+ # overridden deliberately: this is crash recovery, and the alternative is
+ # losing vision altogether.
+ if _resolved_mmproj_offload(args, env or {}) is False:
+ return None
placements = [
_flag(arg) for arg in args if _flag(arg) in ("--mmproj-offload", "--no-mmproj-offload")
]
- if placements and placements[-1] == "--no-mmproj-offload":
- return None
if not placements:
- env_value = str((env or {}).get("LLAMA_ARG_MMPROJ_OFFLOAD") or "").strip().lower()
+ # Colloquial spellings arg.cpp itself rejects: `no` parses as neither truthy
+ # nor falsey, so common_params_parse throws and the child never starts, which
+ # no retry can fix. Kept as a deliberate superset of the resolution above
+ # rather than tightened, so a value that used to skip the futile retry still
+ # does.
+ env_value = str((env or {}).get(_MMPROJ_OFFLOAD_ENV_VAR) or "").strip().lower()
if env_value in ("0", "false", "off", "no"):
return None
return args + ["--no-mmproj-offload"]
@@ -14941,7 +15068,13 @@ class LlamaCppBackend:
hf_variant = hf_variant,
hf_token = hf_token,
)
- # Auto-download mmproj for vision models unless opted out.
+ # Auto-download mmproj for vision models unless opted out. Vision
+ # switched off does NOT opt out: remote discovery calls any mmproj
+ # filename vision, and only the file's metadata separates an image
+ # tower from an audio encoder (ultravox, Voxtral, Qwen3-ASR).
+ # Skipping the fetch would take audio away from an audio-only model
+ # to save one small companion file. Suppression happens at the
+ # resolve, where the metadata is readable.
if is_vision and not mmproj_path and not extra_args_disable_mmproj(extra_args):
mmproj_path = self._download_mmproj(
hf_repo = hf_repo,
@@ -15428,6 +15561,20 @@ class LlamaCppBackend:
# Auto dropped the drafter because only the target fit. Bound before the
# try: the launch below reads it either way.
_spec_dropped_no_vram = False
+ # The projector runs on the CPU and so allocates no VRAM:
+ # --no-mmproj-offload clears mmproj_use_gpu and clip.cpp gates its whole
+ # GPU backend on that, leaving no partial offload. Only the paravirtual
+ # reason is known this early; the fit below may add the automatic one.
+ # Bound before the try, like _spec_dropped_no_vram.
+ _mmproj_cpu_pinned = bool(
+ launch_mmproj_path
+ and _paravirtual_cpu_forced
+ and _paravirtual_mmproj_pinnable(server_caps)
+ )
+ # What the pin took out of model_size, for the one consumer that must
+ # have it back: _apu_ram_shortfall_message prices SYSTEM RAM, and a
+ # CPU-pinned projector is still in system RAM.
+ _mmproj_pinned_bytes = 0
# Metal unified-memory refusal for a hand-set context, raised AFTER this
# block: the `except Exception` below would swallow the raise into the
# placement fallback and restore the original request, which is the very
@@ -15438,10 +15585,22 @@ class LlamaCppBackend:
_metal_ctx_refusal: Optional[str] = None
try:
gguf_size = self._get_gguf_size_bytes(model_path)
- # Include GPU-loaded mmproj in the fit budget (#5825).
+ # Include GPU-loaded mmproj in the fit budget (#5825). GPU-loaded is
+ # the operative word: --no-mmproj-offload already put the projector in
+ # host RAM, so its bytes are not on the card. Charging them anyway
+ # shrinks the context (measured 9984 -> 4096) or spills layers to make
+ # room for VRAM nothing occupies. The RESOLVED value decides, not just
+ # ownership: arg.cpp reads the env before argv, so the environment
+ # places the projector just as surely as the flag.
+ _user_mmproj_offload = _resolved_mmproj_offload(extra_args)
mmproj_size = (
- self._mmproj_vram_bytes(launch_mmproj_path) if effective_is_vision else 0
+ self._mmproj_vram_bytes(launch_mmproj_path)
+ if (effective_is_vision and _user_mmproj_offload is not False)
+ else 0
)
+ if _user_mmproj_offload is False and launch_mmproj_path:
+ # Still in system RAM, which the APU shortfall guard prices.
+ _mmproj_pinned_bytes = self._mmproj_vram_bytes(launch_mmproj_path)
model_size = gguf_size + mmproj_size
# 2-tuple gpus for existing logic + a total map for the absolute
# per-GPU headroom (correct when the GPU is already partly used).
@@ -16081,6 +16240,209 @@ class LlamaCppBackend:
# --split-mode) so the layer launch re-emits them.
_restore_after_tensor_downgrade()
+ # Normalize the speculative reserve BEFORE anything prices it.
+ # _mtp_bytes reads mtp_overhead_fn at call time, so leaving this
+ # until after the probes below charged the projector probe the full
+ # GPU-drafter footprint for a drafter pinned to the CPU (-ngld 0),
+ # which allocates none of it: the probe then answers "does not fit",
+ # pins the projector, and costs ~8.8x on every image encode for
+ # memory nothing was holding. _draft_cpu_no_embedded is settled well
+ # above, and every input this needs with it, so there is nothing to
+ # wait for.
+ if _draft_cpu_no_embedded and mtp_overhead_fn is not None:
+ # Nothing speculative is GPU-resident: the drafter that launches
+ # is the separate CPU-offloaded one, and any embedded head it
+ # displaced does not run. The flat fraction below is gated on
+ # this; the byte-accurate callback was not, so the fit went on
+ # charging VRAM no drafter allocates.
+ # One term survives: a Hybrid Mamba target's recurrent rollback
+ # snapshots sit in the TARGET context, so pinning the drafter to
+ # CPU does not move them. Charge those alone. Flat in ctx (the
+ # state is per-slot), hence the same _np/_n_ubatch keywords the
+ # replaced callback takes, so _mtp_bytes can still re-price slots.
+ def _cpu_draft_target_state(
+ _ctx: int,
+ _np: int = n_parallel,
+ _n_ubatch: Optional[int] = _effective_ubatch,
+ _n: int = _mtp_eff_n_max,
+ _rollback: bool = _target_rollback,
+ ) -> int:
+ if not _rollback or _n <= 0:
+ return 0
+ return self._mamba_recurrent_state_bytes(_np) * _n
+
+ mtp_overhead_fn = (
+ _cpu_draft_target_state
+ if _cpu_draft_target_state(effective_ctx) > 0
+ else None
+ )
+ _mtp_kv_unsized = False
+
+ # Projector placement, the FIRST thing given up when the load does
+ # not fit: the encoder runs once per image, layers once per token,
+ # so host RAM is its better home when it is what costs residency.
+ # Ahead of the drafter (a bounded per-image cost is cheaper to give
+ # up than a per-token speedup); never a reason to drop vision, which
+ # would answer a pasted screenshot text-only with no signal.
+ #
+ # Does the pin free anything? Only on a device with a budget of its
+ # own. Apple unified memory and AMD APUs / iGPUs report free SYSTEM
+ # RAM as free "VRAM", so the encoder just moves inside one pool.
+ # Their marker is a total of 0, which also covers a total the probe
+ # could not read (MIG/vGPU) -- same answer either way.
+ #
+ # Asked of the budgeted devices, not all of them: a laptop pairing a
+ # discrete card with an APU enumerates both, and demanding every one
+ # be discrete refused the pin there, keeping a projector the discrete
+ # card could have been rid of.
+ _mm_budgeted_gpus = [
+ (_idx, _free) for _idx, _free in gpus if total_by_idx.get(_idx, 0) > 0
+ ]
+ _discrete_vram = bool(_mm_budgeted_gpus)
+ if (
+ effective_is_vision
+ and mmproj_size > 0
+ and _discrete_vram
+ and not _mmproj_cpu_pinned
+ and gpu_memory_mode != "manual"
+ # TP replicates a per-device buffer whose geometry the numbers
+ # below do not model. Same exclusion and same escape as the
+ # MTP-drop probe: the TP downgrades are hoisted above this gate,
+ # but the pooled weight-budget check further down is not, and it
+ # prices weights + projector, so it can downgrade a load this
+ # probe would have rescued. Re-asking after that downgrade is the
+ # non-circular fix and needs this whole probe as a second
+ # application point, so the corner keeps main's behaviour: the
+ # layer-split fit still has --fit on and pays in spilled layers.
+ and not tensor_parallel
+ and _paravirtual_mmproj_pinnable(server_caps)
+ # Last-wins on the placement pair, so whoever named either
+ # spelling owns it. The environment counts: arg.cpp applies
+ # set_env before argv, so --no-mmproj-offload here would
+ # OVERWRITE LLAMA_ARG_MMPROJ_OFFLOAD=1, not lose to it.
+ and not _extra_args_set_mmproj_offload(extra_args)
+ and not _env_sets_mmproj_offload()
+ ):
+ # One question, asked once: at the context this load will
+ # actually run at, with speculative decoding STILL LIVE, does
+ # model + drafter + projector stay resident in VRAM? Which
+ # context that is, is the whole question.
+ #
+ # AUTO gets the FLOOR, which makes this a residency question and
+ # not a context one. Auto shrinks the CONTEXT before it spills
+ # layers, reaching `--fit on` only once even 4096 will not place.
+ # Pricing at the native length would answer "does not fit" for a
+ # load merely heading for a smaller context and pin a projector
+ # that was resident all along -- 8.8x on image encode for nothing.
+ #
+ # An EXPLICIT context gets its requested length, because there
+ # the reasoning points the other way: the loop honors a pinned
+ # context verbatim, so the only give left is `--fit on`, which
+ # spills MODEL LAYERS and collapses decode ~3x. Asking at 4096
+ # would answer "fits", keep the projector, and pay in offloaded
+ # weights -- this probe's trade at its worst rate.
+ #
+ # The drafter IS charged: this runs before the drop probe, so
+ # speculative decoding is still in the footprint. Priced exactly
+ # where the fit prices it below, term for term.
+ _mm_mtp_on_gpu = _mtp_will_engage and not _draft_cpu_no_embedded
+ _mm_frac = _vram_frac - (
+ _MTP_VRAM_RESERVE_FRAC
+ if (_mm_mtp_on_gpu and (mtp_overhead_fn is None or _mtp_kv_unsized))
+ else 0.0
+ )
+ _mm_floor_ctx = (
+ effective_ctx
+ if explicit_ctx
+ else min(self._MMPROJ_FIT_FLOOR_CTX, effective_ctx)
+ )
+ _mm_need = (
+ gguf_size
+ + mmproj_size
+ + _compute_buffer_pipeline
+ + self._CUDA_CONTEXT_RESERVE_BYTES
+ + int(mmproj_size * (self._MMPROJ_VRAM_SAFETY - 1.0))
+ + (self._MTP_DRAFT_COMPUTE_BYTES if _mm_mtp_on_gpu else 0)
+ )
+ if _mm_floor_ctx > 0 and self._can_estimate_kv():
+ _mm_need += (
+ _kv_bytes(_mm_floor_ctx)
+ + _cc_bytes(_mm_floor_ctx)
+ + _mtp_bytes(_mm_floor_ctx)
+ )
+ else:
+ # No KV estimate: the fit builds one flat footprint against
+ # _mtp_bytes at the native length and no context it hands
+ # out lowers it, so charging the reserve at a floor the fit
+ # never applies would promise room the fit never sees.
+ # Rebound rather than used inline so the log below names the
+ # length this actually priced against.
+ _mm_floor_ctx = self._context_length or effective_ctx or 4096
+ _mm_need += _mtp_bytes(_mm_floor_ctx)
+ # Run through whichever selector the branch below will use, at
+ # the same fraction and per-device overhead, so "does not fit"
+ # here is a placement that branch could not have chosen either.
+ # A probe more optimistic than the placement it gates is the
+ # failure mode that matters: projector kept, layers spilled.
+ #
+ # Split-aware, because a layer split replicates a BIGGER
+ # context-compute buffer per device (_CTX_COMPUTE_SPLIT_MULT):
+ # at 65536 on two cards, 96 MiB charged against 768 MiB spent, a
+ # gap wider than the projector surcharge being decided. Mirrored
+ # term for term, including the single-to-split step.
+ #
+ # Plain only where the placement itself is plain: with no KV
+ # estimate it falls to the file-size-only path, which is
+ # _select_gpus at the flat overhead. Same condition that decided
+ # whether _mm_need carries a context-compute term, so the two
+ # cannot drift apart.
+ _mm_split_aware = self._can_estimate_kv()
+ _, _mm_needs_fit = (
+ self._select_gpus_split_aware(
+ _mm_need,
+ _mm_budgeted_gpus,
+ usable_fraction = _mm_frac,
+ total_by_idx = total_by_idx,
+ per_device_overhead_bytes = _pipeline_overhead_bytes
+ + _cc_bytes(_mm_floor_ctx),
+ min_gpus = _layer_min_gpus,
+ split_extra_bytes = _cc_split_extra(_mm_floor_ctx),
+ )
+ if _mm_split_aware
+ else self._select_gpus(
+ _mm_need,
+ _mm_budgeted_gpus,
+ usable_fraction = _mm_frac,
+ total_by_idx = total_by_idx,
+ per_device_overhead_bytes = _pipeline_overhead_bytes,
+ min_gpus = _layer_min_gpus,
+ )
+ )
+ if _mm_needs_fit:
+ _mmproj_cpu_pinned = True
+ _mmproj_pinned_bytes = mmproj_size
+ # Everything downstream prices the projector off these two,
+ # including the drop probe below: it sees the lighter
+ # footprint and gives the drafter up only if the pin was not
+ # enough on its own.
+ mmproj_size = 0
+ model_size = gguf_size
+ # What the startup-recovery pin reports, so a CPU-resident
+ # projector is announced whether it was predicted or salvaged;
+ # otherwise image encoding just gets mysteriously slower. After
+ # the per-load reset, before the recovery paths, which override
+ # it with their more specific reason.
+ self._mmproj_fallback_reason = "cpu_offload"
+ logger.info(
+ "Auto: running the vision projector on the CPU "
+ "(--no-mmproj-offload); it does not fit in VRAM "
+ "alongside the model at %d context. Image encoding "
+ "gets slower, text generation is unaffected. Pass "
+ "--mmproj-offload in the advanced arguments to keep it "
+ "on the GPU.",
+ _mm_floor_ctx,
+ )
+
# Target pins but the drafter's reserve tips it over: Auto drops the
# drafter rather than pay for speed with context (or a --fit offload,
# where decode collapses ~3x). Priced over the SAME ranked subsets the
@@ -16327,37 +16689,6 @@ class LlamaCppBackend:
_probe_have / 1024,
)
- if _draft_cpu_no_embedded and mtp_overhead_fn is not None:
- # Nothing speculative is GPU-resident: the drafter that launches
- # is the separate CPU-offloaded one, and any embedded head it
- # displaced does not run. The flat fraction below is gated on
- # this; the byte-accurate callback was not, so the fit went on
- # charging VRAM no drafter allocates.
- # One term survives: a Hybrid Mamba target keeps its own
- # recurrent rollback snapshots for verification, and those sit
- # in the TARGET context, so pinning the drafter to the CPU does
- # not move them. Charge those alone rather than nothing. Flat in
- # ctx, the state being per-slot rather than per-token -- hence
- # the same _np/_n_ubatch keywords the replaced callback takes,
- # so _mtp_bytes can still re-price each slot candidate.
- def _cpu_draft_target_state(
- _ctx: int,
- _np: int = n_parallel,
- _n_ubatch: Optional[int] = _effective_ubatch,
- _n: int = _mtp_eff_n_max,
- _rollback: bool = _target_rollback,
- ) -> int:
- if not _rollback or _n <= 0:
- return 0
- return self._mamba_recurrent_state_bytes(_np) * _n
-
- mtp_overhead_fn = (
- _cpu_draft_target_state
- if _cpu_draft_target_state(effective_ctx) > 0
- else None
- )
- _mtp_kv_unsized = False
-
# Flat MTP reserve fraction: used only as the fallback when the
# byte-accurate mtp_overhead_fn can't size the draft KV (dims
# unavailable, or _mtp_kv_unsized = weights-only). A separate
@@ -16394,7 +16725,30 @@ class LlamaCppBackend:
_soft_overhead += int(mmproj_size * (self._MMPROJ_VRAM_SAFETY - 1.0))
if _mtp_reserves_gpu:
_soft_overhead += self._MTP_DRAFT_COMPUTE_BYTES
- model_size_fit = model_size + _compute_buffer_pipeline + _soft_overhead
+ # A CPU-pinned projector left model_size, which is right only where
+ # the bytes it gave up landed somewhere else. Shared memory -- an APU /
+ # iGPU pool, Apple unified memory, or a total the probe could not read
+ # -- has nowhere else, so the encoder sits in the very memory this fit
+ # measures and the context can spend those bytes twice.
+ #
+ # Near _discrete_vram's question but not the same one: that drops
+ # shared devices to ask whether the pin frees anything ANYWHERE, and
+ # one discrete card settles that. The fit asks what a candidate subset
+ # draws on, and the selection walks prefixes of `gpus`, so a shared
+ # device ranked first is a candidate alone. Measured: 9000 MiB of
+ # shared pool beside a nearly full discrete card fitted a 6 GiB model
+ # to 32000 tokens with a 1 GiB projector pinned into that same pool.
+ # So the charge follows the PRESENCE of shared memory, not its absence.
+ # On a mixed host that ends up purely discrete this over-charges by the
+ # projector, costing context rather than correctness.
+ _shared_pool_mmproj = (
+ _mmproj_pinned_bytes
+ if (not gpus or len(_mm_budgeted_gpus) < len(gpus))
+ else 0
+ )
+ model_size_fit = (
+ model_size + _compute_buffer_pipeline + _soft_overhead + _shared_pool_mmproj
+ )
def _subset_model_size(n_gpus: int) -> int:
return model_size_fit + max(0, n_gpus - 1) * _pipeline_overhead_bytes
@@ -16731,12 +17085,17 @@ class LlamaCppBackend:
_apple_fit_budget_mib = int(
_apple_budget_mib * max(0.0, 1.0 - _flat_mtp_reserve)
)
+ # A CPU-pinned projector is already carried by model_size_fit here:
+ # this arm is reached only with no GPU enumerated, so no device has
+ # a budget of its own and _shared_pool_mmproj charged those bytes.
+ # Adding them again would price the encoder twice.
+ _apple_model_size_fit = model_size_fit
def _apple_ctx_fit(target: int, min_ctx: int) -> int:
return self._fit_context_to_vram(
target,
_apple_fit_budget_mib,
- model_size_fit,
+ _apple_model_size_fit,
cache_type_kv,
min_ctx = min_ctx,
swa_full = swa_full,
@@ -16754,7 +17113,10 @@ class LlamaCppBackend:
def _apple_footprint_mib(ctx: int) -> float:
return (
- model_size_fit + _kv_bytes(ctx) + _mtp_bytes(ctx) + _cc_bytes(ctx)
+ _apple_model_size_fit
+ + _kv_bytes(ctx)
+ + _mtp_bytes(ctx)
+ + _cc_bytes(ctx)
) / (1024 * 1024)
if self._can_estimate_kv():
@@ -17038,7 +17400,11 @@ class LlamaCppBackend:
and self._amd_apu_wants_unified_memory(gpu_indices)
):
_ram_msg = self._apu_ram_shortfall_message(
- model_size, self._available_system_memory_mib()
+ # A pinned projector left model_size but not system RAM, and
+ # this guard exists to stop an oversize load being OOM-killed
+ # mid-read, so it has to weigh the projector either way.
+ model_size + _mmproj_pinned_bytes,
+ self._available_system_memory_mib(),
)
# gpu_indices is None for a launch nothing pinned, so the guard
# priced every visible card, including an APU the gate is about to
@@ -17064,6 +17430,11 @@ class LlamaCppBackend:
# but never one the unpinnable guard just dropped.
self._mmproj_has_audio = False
self._mmproj_accepts_image = True
+ # ...and never one the vision switch is about to scrub out of the
+ # child environment either. Reading it would record an audio encoder
+ # the launched server does not have, and _apply_detected_audio turns
+ # that into has_audio_input, so the composer would offer attachments
+ # the server cannot process.
_mmproj_probe = launch_mmproj_path or (
"" if _pv_mmproj_unpinnable else (os.environ.get("LLAMA_ARG_MMPROJ") or "")
)
@@ -17703,11 +18074,16 @@ class LlamaCppBackend:
# past the pass-through extras like the drafter pin, since
# --mmproj-offload is a real flag a user can pass and llama.cpp is
# last-wins.
- if _paravirtual_cpu_forced and _paravirtual_mmproj_pinnable(server_caps):
+ # One flag whichever reason pinned it: the corrupt paravirtual Metal
+ # device, or the fit deciding the projector does not fit in VRAM.
+ # Both already checked the capability.
+ if _mmproj_cpu_pinned:
_pv_mmproj_cpu_pin = ["--no-mmproj-offload"]
- logger.warning(
- "Disabling mmproj GPU offload: this Mac's Metal device is virtualised."
- )
+ if _paravirtual_cpu_forced:
+ logger.warning(
+ "Disabling mmproj GPU offload: this Mac's Metal "
+ "device is virtualised."
+ )
# Option C: --api-key for direct client access when enabled
import secrets as _secrets
@@ -17883,6 +18259,10 @@ class LlamaCppBackend:
cmd.extend(_pv_draft_cpu_pin)
if _pv_mmproj_cpu_pin:
cmd.extend(_pv_mmproj_cpu_pin)
+ # Also last, and for the same last-wins reason: suppressing Studio's own
+ # --mmproj and scrubbing the env vars still leaves a remembered
+ # --mmproj-auto in the extras above, and that flag asks llama-server to
+ # rediscover the adjacent projector by itself. Vision would come back on
# Also last: _zero_offload_keeps_gpu_visible reads the finished cmd, so
# the override must be in it before the env block below judges this a
# zero-VRAM server.
@@ -18073,6 +18453,13 @@ class LlamaCppBackend:
# it outranks even the --mmproj Unsloth emits. Unsloth always passes its
# own projector on the command line (with --no-mmproj-offload), so an
# inherited one is only ever the corrupt path.
+ # Turning vision off has the same blind spot, and it is the whole point
+ # of the switch: suppressing Studio's own --mmproj leaves an inherited
+ # LLAMA_ARG_MMPROJ / LLAMA_ARG_MMPROJ_URL untouched, so llama-server
+ # loads a projector anyway (arg.cpp sets params.mmproj.path / .url
+ # straight from those vars). The load would then report text-only over a
+ # server that is still multimodal, and the fit budget that gave the
+ # projector's bytes to context is short by exactly those bytes.
if _paravirtual_cpu_forced:
for _pv_mmproj_var in ("LLAMA_ARG_MMPROJ", "LLAMA_ARG_MMPROJ_URL"):
env.pop(_pv_mmproj_var, None)
@@ -18768,7 +19155,8 @@ class LlamaCppBackend:
# when the APU is picked first.
if model_size is not None and _retry_wants_unified:
_retry_ram_msg = self._apu_ram_shortfall_message(
- model_size, self._available_system_memory_mib()
+ model_size + _mmproj_pinned_bytes,
+ self._available_system_memory_mib(),
)
if _retry_ram_msg:
self._kill_process()
diff --git a/studio/backend/tests/test_gpu_memory_mode.py b/studio/backend/tests/test_gpu_memory_mode.py
index 51a6150273f..53cfa03d621 100644
--- a/studio/backend/tests/test_gpu_memory_mode.py
+++ b/studio/backend/tests/test_gpu_memory_mode.py
@@ -1380,25 +1380,30 @@ def test_zero_vram_chat_load_only_for_a_deliberate_cpu_only_offload(not_vulkan):
# Manual + gpu_layers=0 is the one shape that launches with the GPUs hidden from the child, so it is the one shape allowed
# to skip the GPU arbiter. Auto (or any pinned layer count) puts the model on the GPU and must still evict a pipeline.
zero = llama_cpp_module.zero_vram_chat_load
- assert zero("manual", 0) is True
- assert zero("auto", 0) is False
- assert zero("manual", 1) is False
- assert zero("manual", -1) is False
+ # Speculation named explicitly off: an ABSENT mode resolves to auto everywhere else
+ # in the module, so it is GPU-bearing and covered by its own test below.
+ assert zero("manual", 0, [], False, "off") is True
+ assert zero("auto", 0, [], False, "off") is False
+ assert zero("manual", 1, [], False, "off") is False
+ assert zero("manual", -1, [], False, "off") is False
def test_zero_vram_chat_load_refuses_every_gpu_companion(not_vulkan):
# The launch-time mask keeps the GPUs visible for a device pin, tensor mode, an mmproj or a drafter, so those loads DO hold
# VRAM. --mmproj and --model-draft are added by the backend, so their intent arrives as flags.
zero = llama_cpp_module.zero_vram_chat_load
- assert zero("manual", 0, ["--device", "CUDA0"]) is False
- assert zero("manual", 0, ["-dev", "CUDA0"]) is False
- assert zero("manual", 0, ["--split-mode", "tensor"]) is False
- assert zero("manual", 0, ["--model-draft", "/tmp/draft.gguf"]) is False
- assert zero("manual", 0, [], True) is False
+ assert zero("manual", 0, ["--device", "CUDA0"], False, "off") is False
+ assert zero("manual", 0, ["-dev", "CUDA0"], False, "off") is False
+ assert zero("manual", 0, ["--split-mode", "tensor"], False, "off") is False
+ assert zero("manual", 0, ["--model-draft", "/tmp/draft.gguf"], False, "off") is False
+ assert zero("manual", 0, [], True, "off") is False
assert zero("manual", 0, [], False, "model") is False
# A CPU-pinned device and a CPU-forced drafter keep it zero-VRAM.
- assert zero("manual", 0, ["--device", "none"]) is True
- assert zero("manual", 0, ["--model-draft", "/tmp/d.gguf", "--spec-draft-ngl", "0"]) is True
+ assert zero("manual", 0, ["--device", "none"], False, "off") is True
+ assert (
+ zero("manual", 0, ["--model-draft", "/tmp/d.gguf", "--spec-draft-ngl", "0"], False, "off")
+ is True
+ )
def test_zero_vram_chat_load_exempts_disabled_speculation(not_vulkan):
@@ -1407,7 +1412,9 @@ def test_zero_vram_chat_load_exempts_disabled_speculation(not_vulkan):
zero = llama_cpp_module.zero_vram_chat_load
assert zero("manual", 0, [], False, "off") is True
assert zero("manual", 0, [], False, " OFF ") is True
- assert zero("manual", 0, [], False, "") is True
+ # Empty is NOT off: it canonicalizes to None like an omitted mode, and every
+ # consumer resolves that to auto, which may launch a drafter on the GPU.
+ assert zero("manual", 0, [], False, "") is False
assert zero("manual", 0, [], False, "auto") is False
assert zero("manual", 0, [], False, "mtp") is False
assert zero("manual", 0, [], False, "default") is False
@@ -1465,3 +1472,20 @@ def test_cmd_companion_ignores_a_projector_pinned_off_the_gpu():
# llama.cpp assigns rather than accumulates for this one, so the last flag wins.
cmd = ["llama-server", "--mmproj", "p.gguf", "--no-mmproj-offload", "--mmproj-offload"]
assert has(cmd, {}) is True
+
+
+def test_zero_vram_chat_load_treats_an_absent_mode_as_auto(not_vulkan):
+ # _canonicalize_spec_mode returns None for None, "" and whitespace alike, and every
+ # consumer resolves that to "auto" (`... or "auto"` in load_model), where a remote or
+ # local sidecar can be discovered and launched with its default GPU offload. Reading
+ # an absent mode as "off" here let an API or defaulted load skip acquire_for(CHAT)
+ # while the launch-time mask, which reads the finished argv and so sees the drafter
+ # that got added, kept the GPUs visible: no arbiter, real VRAM, free to land on a
+ # resident image/video pipeline and OOM both.
+ zero = llama_cpp_module.zero_vram_chat_load
+ assert zero("manual", 0) is False
+ assert zero("manual", 0, [], False, None) is False
+ assert zero("manual", 0, [], False, "") is False
+ assert zero("manual", 0, [], False, " ") is False
+ # Only the canonical spelling still exempts it.
+ assert zero("manual", 0, [], False, "off") is True
diff --git a/studio/backend/tests/test_metal_explicit_context_guard.py b/studio/backend/tests/test_metal_explicit_context_guard.py
index 3474e9de2ef..7bf34458798 100644
--- a/studio/backend/tests/test_metal_explicit_context_guard.py
+++ b/studio/backend/tests/test_metal_explicit_context_guard.py
@@ -116,6 +116,7 @@ def _launch(
weights_bytes = 1024,
kv_per_token = 1024,
native = NATIVE,
+ mmproj_bytes = 0,
):
"""Drive the real load_model with no GPU enumerated (the Metal condition).
@@ -150,8 +151,12 @@ def _launch(
if not real_fit:
backend._fit_context_to_vram = lambda target, *a, **k: min(int(target), CEILING)
backend._get_gguf_size_bytes = lambda _path: weights_bytes
- backend._mmproj_vram_bytes = lambda _path: 0
- backend._resolve_launch_mmproj_path = lambda **kwargs: None
+ backend._mmproj_vram_bytes = lambda _path: mmproj_bytes
+ backend._resolve_launch_mmproj_path = (
+ (lambda **kwargs: str(_write_gguf(tmp_path / "mmproj-F16.gguf")))
+ if mmproj_bytes
+ else (lambda **kwargs: None)
+ )
backend._apu_ram_shortfall_message = lambda *a, **k: None
# This harness does not model host RAM, and None is the documented way to say so: both
# _apu_ram_shortfall_message and _host_offload_shortfall_message treat unknown
@@ -202,6 +207,7 @@ def _launch(
gpu_layers = gpu_layers,
extra_args = extra_args,
cache_type_kv = cache_type_kv,
+ is_vision = bool(mmproj_bytes),
)
)
captured["backend"] = backend
@@ -870,3 +876,67 @@ class TestAModelWhoseNativeLengthIsAtTheFloor:
kv_per_token = _FAT_KV,
)["cmd"]
assert _ctx_values(cmd)[-1] == "256"
+
+
+class TestACpuPinnedProjectorOnUnifiedMemory:
+ """--no-mmproj-offload moves the projector off a discrete card. On unified memory
+ there is nowhere to move it to: "host RAM" and "VRAM" are one pool, so its bytes
+ still sit in the budget this guard measures.
+
+ Dropping them overstates the context that fits and walks straight past the refusal
+ into an OOM, which is the one outcome the guard exists to prevent. The APU shortfall
+ guard already weighs a pinned projector for exactly this reason.
+
+ Sized so the projector alone decides it: budget 8192 MiB against 1024 of weights and
+ ~5120 of fixed overhead, with KV at 32 KiB per token. At 32768 the KV is 1024 MiB, so
+ without the projector 7168 fits and with its 1536 the footprint is 8704 and does not.
+ A KV rate any smaller and the pin is lost in the slack, which is how the first two
+ versions of this test passed against the bug.
+ """
+
+ _COMMON = dict(real_fit = True, weights_bytes = 1024**3, kv_per_token = 32 * 1024)
+
+ def test_the_pinned_projector_still_counts_against_the_budget(self, tmp_path, monkeypatch):
+ with pytest.raises(RuntimeError, match = "unified"):
+ _launch(
+ tmp_path,
+ monkeypatch,
+ n_ctx = 32768,
+ budget_bytes = 8 * 1024**3,
+ mmproj_bytes = int(1.5 * 1024**3),
+ extra_args = ["--no-mmproj-offload"],
+ **self._COMMON,
+ )
+
+ def test_the_same_load_without_the_projector_is_allowed(self, tmp_path, monkeypatch):
+ """The control, and the whole point: 32768 fits on this machine once the
+ projector is not in the pool, so the refusal above is about those bytes and not
+ about a budget too small for anything."""
+ captured = _launch(
+ tmp_path,
+ monkeypatch,
+ n_ctx = 32768,
+ budget_bytes = 8 * 1024**3,
+ **self._COMMON,
+ )
+ assert _ctx_values(captured["cmd"])[-1] == "32768"
+
+ def test_the_pinned_projector_is_charged_once_and_not_twice(self, tmp_path, monkeypatch):
+ """The other side of the same coin. The shared-pool charge now lives in the
+ common fit total, so an Apple-specific one on top of it prices the encoder
+ twice and refuses loads that do fit.
+
+ Sized so only the second charge decides it: 1024 of weights, ~5120 of fixed
+ overhead and 1280 of KV at 40960 tokens leave 768 MiB of the 8192 budget, and
+ a 512 MiB projector fits in that once but not twice.
+ """
+ captured = _launch(
+ tmp_path,
+ monkeypatch,
+ n_ctx = 40960,
+ budget_bytes = 8 * 1024**3,
+ mmproj_bytes = 512 * 1024**2,
+ extra_args = ["--no-mmproj-offload"],
+ **self._COMMON,
+ )
+ assert _ctx_values(captured["cmd"])[-1] == "40960"
diff --git a/studio/backend/tests/test_mmproj_placement_policy.py b/studio/backend/tests/test_mmproj_placement_policy.py
new file mode 100644
index 00000000000..93da6ee7588
--- /dev/null
+++ b/studio/backend/tests/test_mmproj_placement_policy.py
@@ -0,0 +1,830 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The vision-projector placement policy: GPU, CPU, or not loaded at all.
+
+Model + speculative decoding + projector + 4096 context in VRAM if they fit;
+otherwise pin the projector to the CPU; if that is still not enough, drop
+speculative decoding as well; and load no projector at all, on either device,
+when vision is switched off. Also covers the two fields the client reseeds the
+switch from, which no single-side test exercises.
+"""
+
+from __future__ import annotations
+
+import inspect
+import os
+import struct
+import subprocess
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import pytest
+
+from core.inference.llama_cpp import (
+ GgufLoadIntent,
+ LlamaCppBackend,
+ _resolved_mmproj_offload,
+)
+from models.inference import InferenceStatusResponse, LoadResponse
+from routes.inference import (
+ _estimate_gguf_required_gb,
+ _guard_chat_load_against_training,
+ _llama_runtime_fields,
+ _LoadPlacement,
+)
+
+MIB = 1024 * 1024
+GIB = 1024**3
+_REAL_POPEN = subprocess.Popen
+
+# Model + projector fit at 4096 but not at the native length: the placement loop
+# shrinks the context long before it would spill a layer, so pricing residency at
+# the native length is the bug this policy exists to avoid.
+NATIVE_CTX = 262144
+KV_PER_TOKEN = 64 * 1024 # 4096 ctx -> 256 MiB, NATIVE_CTX -> 16 GiB
+
+
+def _write_gguf(path: Path) -> Path:
+ def string(value: str) -> bytes:
+ data = value.encode()
+ return struct.pack("<Q", len(data)) + data
+
+ metadata = string("general.architecture") + struct.pack("<I", 8) + string("llama")
+ path.write_bytes(struct.pack("<IIQQ", 0x46554747, 3, 0, 1) + metadata)
+ return path
+
+
+def _backend(
+ tmp_path: Path,
+ *,
+ memory,
+ model_bytes: int = 6 * GIB,
+ mmproj_bytes: int = 1 * GIB,
+ drafter_bytes: int = 0,
+ native_ctx: int = NATIVE_CTX,
+):
+ """A GGUF vision load with the fit inputs pinned to known numbers.
+
+ ``native_ctx`` is lowered for the drafter tests: the drop probe prices the
+ reserve at the context the target alone would reach, so a 262144 native
+ length makes the draft KV, not the placement, decide every one of them.
+ """
+ backend = LlamaCppBackend()
+ gguf = _write_gguf(tmp_path / "model.gguf")
+ mmproj = _write_gguf(tmp_path / "mmproj-F16.gguf")
+ drafter = _write_gguf(tmp_path / "mtp.gguf")
+
+ def read_metadata(_path):
+ backend._context_length = native_ctx
+ backend._n_layers = 32
+ backend._n_heads = 32
+ backend._n_kv_heads = 8
+ backend._embedding_length = 4096
+ backend._vocab_size = 32000
+
+ backend._read_gguf_metadata = read_metadata
+ backend._get_gpu_memory = lambda _binary = None, **_kw: list(memory)
+ backend._get_gpu_free_memory = lambda _binary = None, **_kw: [
+ (index, free) for index, free, _total in memory
+ ]
+ backend._estimate_kv_cache_bytes = lambda ctx, *_a, **_kw: max(0, ctx) * KV_PER_TOKEN
+ backend._compute_buffer_ctx_bytes = lambda *_a, **_kw: 0
+ backend._estimate_compute_buffer_bytes = lambda **_kw: 256 * MIB
+ backend._get_gguf_size_bytes = lambda path: (
+ drafter_bytes if Path(path).name == "mtp.gguf" else model_bytes
+ )
+ backend._mmproj_vram_bytes = lambda _path: mmproj_bytes
+ backend._resolve_launch_mmproj_path = lambda **_kw: str(mmproj)
+ # Only the speculative-decoding test asks for a drafter; everywhere else the
+ # resolution has to come back empty or MTP engages behind the scenes.
+ backend._resolve_launch_mtp_path = lambda **_kw: str(drafter) if drafter_bytes else None
+ backend._apu_ram_shortfall_message = lambda *_a, **_kw: None
+ backend._amd_apu_wants_unified_memory = lambda *_a, **_kw: False
+ backend._find_llama_server_binary = lambda include_denied = False: "/fake/llama-server"
+ backend._is_vulkan_backend = lambda _binary = None: False
+ backend._wait_for_health = lambda timeout: True
+ backend._detect_audio_type_strict = lambda: None
+ backend._apply_detected_audio = lambda _detected: True
+ backend.probe_server_capabilities = lambda _binary = None: {
+ "supports_no_mmproj_offload": True,
+ "mtp_token": "draft-mtp",
+ "spec_draft_n_max_flag": "--spec-draft-n-max",
+ }
+ return backend, gguf
+
+
+def _launch(backend, gguf, **load_kwargs):
+ captured = {}
+
+ def fake_popen(cmd, **kwargs):
+ if not cmd or str(cmd[0]) != "/fake/llama-server":
+ return _REAL_POPEN(cmd, **kwargs)
+ captured["cmd"] = list(cmd)
+ captured["env"] = kwargs.get("env") or dict(os.environ)
+ return type(
+ "Process",
+ (),
+ {
+ "pid": 123,
+ "stdout": (),
+ "poll": lambda self: None,
+ "terminate": lambda self: None,
+ "wait": lambda self, timeout = None: 0,
+ "kill": lambda self: None,
+ },
+ )()
+
+ intent_kwargs = {
+ "is_vision": True,
+ # Auto context, the mode the policy is about: 0 resolves to the model's
+ # native length and lets the placement loop shrink it. A request pinned at
+ # 4096 would hide the whole floor question.
+ "n_ctx": 0,
+ **load_kwargs,
+ }
+ with patch.object(subprocess, "Popen", side_effect = fake_popen):
+ assert backend.load_model(
+ GgufLoadIntent(
+ gguf_path = str(gguf),
+ model_identifier = "test",
+ **intent_kwargs,
+ )
+ )
+ return captured
+
+
+def test_projector_stays_on_gpu_when_it_fits_at_the_floor(tmp_path):
+ """Model + projector fit at 4096 but not at the native 262144 context.
+
+ The placement loop shrinks the context, it does not spill layers, so both
+ arms are fully GPU-resident and pinning would buy nothing while costing
+ ~8.8x on every image encode.
+ """
+ backend, gguf = _backend(tmp_path, memory = [(0, 12_000, 24_000)])
+
+ cmd = _launch(backend, gguf)["cmd"]
+
+ assert "--mmproj" in cmd
+ assert "--no-mmproj-offload" not in cmd
+ # The premise the pin would have been traded against: every layer is already
+ # resident, so what the native length cost was context, not residency.
+ assert cmd[cmd.index("--fit") + 1] == "off"
+ assert int(cmd[cmd.index("-c") + 1]) < NATIVE_CTX
+
+
+def test_projector_pinned_to_cpu_when_it_does_not_fit(tmp_path):
+ """The 6 GiB model fits at 4096 on this card, the projector on top does not.
+
+ Vision is preserved rather than dropped: --mmproj still goes out, only the
+ offload is disabled. Sized so the _MMPROJ_VRAM_SAFETY surcharge decides it:
+ the budget is 8692 - 3% of 16384 = 8200 MiB, the footprint at 4096 is 6144
+ model + 1024 projector + 256 compute + 320 CUDA context + 256 KV = 8000 MiB,
+ and only the 409 MiB a projector costs beyond its file size puts it over.
+ """
+ backend, gguf = _backend(tmp_path, memory = [(0, 8_692, 16_384)])
+
+ cmd = _launch(backend, gguf)["cmd"]
+
+ assert "--mmproj" in cmd
+ assert "--no-mmproj-offload" in cmd
+ # And the trade was paid for: the model alone is fully resident, which is the
+ # only thing the slower image encode is bought with.
+ assert cmd[cmd.index("--fit") + 1] == "off"
+
+
+def test_user_owns_the_placement_when_they_name_either_spelling(tmp_path):
+ """llama.cpp is last-wins on the placement pair, so an explicit
+ --mmproj-offload must not be raced by the automatic pin."""
+ backend, gguf = _backend(tmp_path, memory = [(0, 8_692, 16_384)])
+
+ cmd = _launch(backend, gguf, extra_args = ["--mmproj-offload"])["cmd"]
+
+ assert cmd.count("--no-mmproj-offload") == 0
+
+
+ "memory,label",
+ [
+ ([], "apple_unified"),
+ ([(0, 7_600, 0)], "amd_apu_or_igpu"),
+ ],
+)
+def test_shared_memory_pools_are_not_charged_as_discrete(tmp_path, memory, label):
+ """Apple Silicon enumerates no GPU and an APU / iGPU reports free SYSTEM RAM
+ as its free VRAM with a total of 0. Moving the encoder inside one pool frees
+ nothing, so the same shortfall that pins a discrete card must not pin here."""
+ backend, gguf = _backend(tmp_path, memory = memory)
+
+ cmd = _launch(backend, gguf)["cmd"]
+
+ assert "--no-mmproj-offload" not in cmd, label
+
+
+# The drafter tests share one shape: a small native context so the drop probe
+# prices the reserve near the floor, and a 2 GiB drafter. Only the budget moves.
+DRAFTER_NATIVE_CTX = 8192
+
+
+def _drafter_backend(tmp_path, memory):
+ return _backend(
+ tmp_path,
+ memory = memory,
+ drafter_bytes = 2 * GIB,
+ native_ctx = DRAFTER_NATIVE_CTX,
+ )
+
+
+def _launch_with_drafter(backend, gguf, tmp_path):
+ return _launch(
+ backend,
+ gguf,
+ mtp_draft_path = str(tmp_path / "mtp.gguf"),
+ speculative_type = "auto",
+ )["cmd"]
+
+
+def test_the_projector_is_pinned_before_the_drafter_is_dropped(tmp_path):
+ """The projector is the first thing given up, not the last.
+
+ A bounded per-image cost is cheaper to concede than a per-token speedup, so pin
+ the projector and drop the drafter only if that was not enough. Here it is enough:
+ budget 12470 - 8% of 24000 = 10550 MiB, model + drafter + projector needs ~10682,
+ and the pin hands back the projector's 1434 so the drafter survives.
+
+ Deliberately tight: every term of the drafter's charge is decisive at this budget,
+ its 224 MiB decode graph included, so dropping one shows up here.
+ """
+ backend, gguf = _drafter_backend(tmp_path, [(0, 12_470, 24_000)])
+
+ cmd = _launch_with_drafter(backend, gguf, tmp_path)
+
+ assert "--no-mmproj-offload" in cmd
+ assert "--model-draft" in cmd
+
+
+def test_both_are_given_up_when_pinning_alone_is_not_enough(tmp_path):
+ """Step 3: the drafter goes too, but only after the projector has moved and
+ the load still does not fit. Budget 8200 MiB against about 9250 for model +
+ drafter with the projector already pinned."""
+ backend, gguf = _drafter_backend(tmp_path, [(0, 8_692, 16_384)])
+
+ cmd = _launch_with_drafter(backend, gguf, tmp_path)
+
+ assert "--no-mmproj-offload" in cmd
+ assert "--model-draft" not in cmd
+
+
+def test_the_drafters_vram_is_part_of_the_pin_decision(tmp_path):
+ """The pin runs with speculative decoding still live, so the drafter has to
+ be charged or the predicate answers for a machine that does not exist.
+
+ Differential, on one budget: the only thing that changes between the two
+ loads is whether a drafter is present. Model + projector alone is about 8410
+ MiB against a 10080 MiB budget and fits comfortably, so a predicate that
+ leaves the drafter out cannot pin either load, and the asymmetry below is
+ exactly the drafter's roughly 2272 MiB of weights and draft graph.
+ """
+ memory = [(0, 12_000, 24_000)]
+
+ with_drafter, gguf = _drafter_backend(tmp_path, memory)
+ pinned = _launch_with_drafter(with_drafter, gguf, tmp_path)
+
+ without_drafter, gguf2 = _backend(tmp_path, memory = memory, native_ctx = DRAFTER_NATIVE_CTX)
+ unpinned = _launch(without_drafter, gguf2)["cmd"]
+
+ assert "--no-mmproj-offload" in pinned
+ assert "--model-draft" in pinned
+ # Same card, same model, same projector: only the drafter differs.
+ assert "--no-mmproj-offload" not in unpinned
+
+
+_TOPOLOGIES = [
+ ([(0, 7_600, 8_192)], True, "linux_nvidia_discrete"),
+ ([(0, 7_600, 8_192)], True, "windows_nvidia_discrete"),
+ ([(0, 7_600, 8_192)], True, "wsl_nvidia_discrete"),
+ ([(0, 7_600, 8_192)], True, "linux_amd_discrete_rocm"),
+ ([(0, 7_600, 8_192)], True, "windows_amd_discrete_vulkan"),
+ ([(0, 7_600, 0)], False, "linux_amd_apu"),
+ ([(0, 7_600, 0)], False, "windows_amd_igpu"),
+ ([(0, 7_600, 0)], False, "wsl_amd_igpu"),
+ ([(0, 7_600, 0)], False, "linux_intel_igpu"),
+ ([], False, "mac_apple_silicon_unified"),
+ ([], False, "linux_cpu_only"),
+ ([], False, "windows_cpu_only"),
+ ([], False, "wsl_cpu_only"),
+ ([], False, "mac_cpu_only"),
+]
+
+
[email protected]("memory,expect_pin,label", _TOPOLOGIES)
+def test_the_platform_and_gpu_matrix_pins_only_where_memory_is_discrete(
+ tmp_path, memory, expect_pin, label
+):
+ """Moving the encoder out of a shared pool frees nothing, so only a card with
+ its own memory may be charged for the projector. An APU, an iGPU and a
+ virtualised Metal device all report free SYSTEM RAM as free VRAM."""
+ backend, gguf = _backend(tmp_path, memory = memory)
+
+ cmd = _launch(backend, gguf)["cmd"]
+
+ assert ("--no-mmproj-offload" in cmd) is expect_pin, label
+ # Vision survives either way: the pin moves the projector, it never drops it.
+ assert "--mmproj" in cmd, label
+
+
+ "memory,label",
+ [
+ ([(0, 7_600, 8_192), (1, 20_000, 24_576)], "big_card_second"),
+ ([(0, 20_000, 24_576), (1, 7_600, 8_192)], "big_card_first"),
+ ],
+)
+def test_a_heterogeneous_pair_is_ranked_before_the_projector_is_charged(tmp_path, memory, label):
+ """Enumeration order must not decide placement: the same two cards in either
+ order have to reach the same answer, or the pin is reading the device list
+ rather than the memory on it."""
+ backend, gguf = _backend(tmp_path, memory = memory)
+
+ cmd = _launch(backend, gguf)["cmd"]
+
+ assert "--mmproj" in cmd, label
+ assert ("--no-mmproj-offload" in cmd) is False, label
+
+
+def test_a_user_pinned_projector_is_not_charged_against_vram(tmp_path):
+ """--no-mmproj-offload puts the projector in host RAM, so its bytes are not on
+ the card. Charging them anyway shrank the context and spilled layers to make
+ room for VRAM nothing occupies, which is worse placement than Studio's own."""
+ backend, gguf = _backend(tmp_path, memory = [(0, 7_600, 8_192)])
+
+ cmd = _launch(backend, gguf, extra_args = ["--no-mmproj-offload"])["cmd"]
+
+ assert "--mmproj" in cmd
+ # Fully placed, exactly as an unpinned load on this card is.
+ assert "--fit" in cmd and cmd[cmd.index("--fit") + 1] == "off"
+ assert cmd[cmd.index("-c") + 1] == "9984"
+
+
+def test_a_user_demanding_gpu_offload_still_pays_for_it(tmp_path):
+ """The mirror: --mmproj-offload asks for the projector ON the card, so its bytes
+ stay in the budget and the context shrinks to fit them. Resolving the value is
+ what separates this from the case above; merely detecting ownership cannot."""
+ backend, gguf = _backend(tmp_path, memory = [(0, 7_600, 8_192)])
+
+ cmd = _launch(backend, gguf, extra_args = ["--mmproj-offload"])["cmd"]
+
+ assert cmd[cmd.index("-c") + 1] == "4096"
+
+
+def test_the_last_placement_spelling_is_what_gets_budgeted(tmp_path):
+ """llama.cpp folds the pair into one option and takes the last occurrence, so a
+ list ending in the disable form must budget as disabled however it starts."""
+ backend, gguf = _backend(tmp_path, memory = [(0, 7_600, 8_192)])
+
+ cmd = _launch(
+ backend,
+ gguf,
+ extra_args = ["--mmproj-offload", "--no-mmproj-offload"],
+ )["cmd"]
+
+ assert cmd[cmd.index("-c") + 1] == "9984"
+
+
+def test_the_projector_probe_agrees_with_the_layer_loop_it_gates(tmp_path):
+ """The probe answers "is the projector resident", and the layer placement that
+ follows must not then contradict it by spilling model layers. The context-compute
+ buffer is replicated per device, so a probe pricing it once could call a
+ multi-GPU split resident and hand the fit a load it cannot place. Whatever the
+ probe decides, the launch has to be self-consistent: either the projector went
+ to the CPU, or the model is fully placed."""
+ backend, gguf = _backend(
+ tmp_path,
+ memory = [(0, 6_000, 8_192), (1, 6_000, 8_192)],
+ model_bytes = 9 * GIB,
+ )
+
+ cmd = _launch(backend, gguf)["cmd"]
+
+ pinned = "--no-mmproj-offload" in cmd
+ fitted = "--fit" in cmd and cmd[cmd.index("--fit") + 1] == "off"
+ assert pinned or fitted, (
+ "the probe left the projector on the GPU and the fit then could not place "
+ f"the model: {[c for c in cmd if 'fit' in str(c) or 'mmproj' in str(c)]}"
+ )
+
+
+def test_an_explicit_context_is_priced_at_the_length_it_asked_for(tmp_path):
+ """The same card the auto test above leaves alone, with the context pinned.
+
+ Auto shrinks the CONTEXT and never spills a layer, which is why it is asked at the
+ 4096 floor. An explicit context is honored verbatim, so the only give left is
+ ``--fit on``, which offloads MODEL LAYERS: priced at the floor this load answers
+ "the projector fits" and pays in the one currency the policy refuses to spend.
+
+ Budget 12000 - 3% of 24000 = 11280 MiB. At 65536: 6144 model + 4096 KV + 256
+ compute + 320 CUDA context = 10816, and the projector's real 1433 puts it at
+ 12249, over. So the projector goes to host RAM and every layer stays resident.
+ """
+ backend, gguf = _backend(tmp_path, memory = [(0, 12_000, 24_000)])
+
+ cmd = _launch(backend, gguf, n_ctx = 65536)["cmd"]
+
+ assert "--mmproj" in cmd
+ assert "--no-mmproj-offload" in cmd
+ # What the pin bought, and the whole reason it was worth making: the requested
+ # context survives intact with the model fully resident.
+ assert cmd[cmd.index("--fit") + 1] == "off"
+ assert cmd[cmd.index("-c") + 1] == "65536"
+
+
+def test_an_explicit_context_that_fits_with_the_projector_keeps_it_on_the_gpu(tmp_path):
+ """The floor is not simply replaced by "always pin under an explicit context".
+
+ Same card, a context small enough that model + projector + KV all fit. Nothing
+ is bought by moving the encoder off the GPU here, so it stays and image encode
+ keeps its ~8.8x.
+ """
+ backend, gguf = _backend(tmp_path, memory = [(0, 12_000, 24_000)])
+
+ cmd = _launch(backend, gguf, n_ctx = 8192)["cmd"]
+
+ assert "--mmproj" in cmd
+ assert "--no-mmproj-offload" not in cmd
+ assert cmd[cmd.index("--fit") + 1] == "off"
+ assert cmd[cmd.index("-c") + 1] == "8192"
+
+
+def test_an_environment_owned_placement_is_not_reversed_by_the_pin(tmp_path, monkeypatch):
+ """common/arg.cpp applies every set_env option BEFORE argv, so an appended
+ --no-mmproj-offload does not lose to LLAMA_ARG_MMPROJ_OFFLOAD=1, it overwrites
+ it, and llama.cpp says so only in a stderr warning nobody reads. A user who set
+ the variable globally owns the placement exactly as one who passed the flag
+ does, which is already how the CPU-recovery gate reads it."""
+ monkeypatch.setenv("LLAMA_ARG_MMPROJ_OFFLOAD", "1")
+ # The card that pins when nobody has claimed the placement.
+ backend, gguf = _backend(tmp_path, memory = [(0, 8_692, 16_384)])
+
+ cmd = _launch(backend, gguf)["cmd"]
+
+ assert "--mmproj" in cmd
+ assert "--no-mmproj-offload" not in cmd
+
+
+def test_an_environment_pinned_projector_is_not_charged_against_vram(tmp_path, monkeypatch):
+ """The mirror of the flag case: LLAMA_ARG_MMPROJ_OFFLOAD=0 puts the projector in
+ host RAM just as --no-mmproj-offload does, so budgeting its bytes shrinks the
+ context for VRAM nothing occupies."""
+ monkeypatch.setenv("LLAMA_ARG_MMPROJ_OFFLOAD", "0")
+ backend, gguf = _backend(tmp_path, memory = [(0, 7_600, 8_192)])
+
+ cmd = _launch(backend, gguf)["cmd"]
+
+ assert "--mmproj" in cmd
+ assert cmd[cmd.index("--fit") + 1] == "off"
+ # The same context the flag spelling earns on this card.
+ assert cmd[cmd.index("-c") + 1] == "9984"
+
+
+def test_the_negative_environment_spelling_pins_on_presence_alone(tmp_path, monkeypatch):
+ """get_value_from_env checks the LLAMA_ARG_NO_ compatibility spelling first and
+ forces falsey on getenv returning non-null, so an empty value still pins. Read
+ any other way this charges VRAM the child never allocates."""
+ monkeypatch.setenv("LLAMA_ARG_NO_MMPROJ_OFFLOAD", "")
+ backend, gguf = _backend(tmp_path, memory = [(0, 7_600, 8_192)])
+
+ cmd = _launch(backend, gguf)["cmd"]
+
+ assert cmd[cmd.index("-c") + 1] == "9984"
+
+
+ ("extras", "env", "expected"),
+ [
+ # Silence on both sides is the only None: nobody has placed it.
+ ([], {}, None),
+ ([], {"LLAMA_ARG_MMPROJ_OFFLOAD": "1"}, True),
+ ([], {"LLAMA_ARG_MMPROJ_OFFLOAD": "enabled"}, True),
+ ([], {"LLAMA_ARG_MMPROJ_OFFLOAD": "off"}, False),
+ # arg.cpp raises on a value that is neither, so there is no side to budget.
+ ([], {"LLAMA_ARG_MMPROJ_OFFLOAD": "yes"}, None),
+ # Presence, not value, and it wins over the positive spelling.
+ ([], {"LLAMA_ARG_NO_MMPROJ_OFFLOAD": ""}, False),
+ ([], {"LLAMA_ARG_MMPROJ_OFFLOAD": "1", "LLAMA_ARG_NO_MMPROJ_OFFLOAD": "0"}, False),
+ # argv is parsed after the environment, so the flag wins either direction.
+ (["--mmproj-offload"], {"LLAMA_ARG_MMPROJ_OFFLOAD": "0"}, True),
+ (["--no-mmproj-offload"], {"LLAMA_ARG_MMPROJ_OFFLOAD": "1"}, False),
+ (["--mmproj-offload"], {"LLAMA_ARG_NO_MMPROJ_OFFLOAD": "1"}, True),
+ ],
+)
+def test_the_resolved_placement_follows_arg_cpps_own_precedence(extras, env, expected):
+ """Environment first, argv on top, the negative spelling short-circuiting on
+ presence. Anything else and Studio budgets for a placement the child does not
+ run."""
+ assert _resolved_mmproj_offload(extras, env) is expected
+
+
+def test_an_unparseable_environment_value_is_still_the_callers_placement(tmp_path, monkeypatch):
+ """No side to budget for, but the variable is set, so Studio must not append its
+ own spelling on top: common_params_parse throws on the value and the load fails
+ naming the caller's variable, not a Studio flag they never chose."""
+ monkeypatch.setenv("LLAMA_ARG_MMPROJ_OFFLOAD", "yes")
+ backend, gguf = _backend(tmp_path, memory = [(0, 8_692, 16_384)])
+
+ cmd = _launch(backend, gguf)["cmd"]
+
+ assert "--no-mmproj-offload" not in cmd
+
+
+def test_an_explicit_context_too_large_for_either_still_gives_the_projector_up_first(tmp_path):
+ """Same card, a context that does not fit even with the projector in host RAM.
+
+ The fit has to spill layers whatever happens here, which is exactly why the
+ projector should not be holding 1433 MiB of the card while it does: every byte
+ it gives back is a byte of model that stays resident. The order the policy is
+ built on does not change just because the pin alone was not enough, and this is
+ the same shape as dropping the drafter after the pin.
+ """
+ backend, gguf = _backend(tmp_path, memory = [(0, 12_000, 24_000)])
+
+ cmd = _launch(backend, gguf, n_ctx = 131072)["cmd"]
+
+ assert "--mmproj" in cmd
+ assert "--no-mmproj-offload" in cmd
+ assert cmd[cmd.index("--fit") + 1] == "on"
+
+
+# The context-compute buffer, at the shape the real one has: linear in context, and
+# _CTX_COMPUTE_SPLIT_MULT times larger PER DEVICE once the model is layer-split. The
+# shared _backend stubs it to a flat 0, which is fine for the single-GPU cases above
+# and is exactly why none of them can see a split-rate error.
+_CC_PER_TOKEN = 1536 # 6 MiB at 4096, the rate the bundled estimator produces
+
+
+def _split_rate_backend(tmp_path, *, memory, **kwargs):
+ backend, gguf = _backend(tmp_path, memory = memory, **kwargs)
+ backend._compute_buffer_ctx_bytes = (
+ lambda n_ctx, n_ubatch = None, cache_type_kv = None, *, layer_split = False: (
+ n_ctx * _CC_PER_TOKEN * (LlamaCppBackend._CTX_COMPUTE_SPLIT_MULT if layer_split else 1)
+ )
+ )
+ return backend, gguf
+
+
+def test_the_probe_prices_an_explicit_context_the_way_the_split_placement_does(tmp_path):
+ """Two cards, an explicit 65536, and a footprint that only a layer split can hold.
+
+ The explicit branch selects through `_select_gpus_split_aware`, charging the
+ context-compute buffer in the per-device overhead as well as the total and handing
+ the single-to-split step to the retry. A layer split does not just replicate that
+ buffer per card, it replicates a bigger one, so pricing it once understates the
+ real cost several-fold: 96 MiB charged against 768 MiB spent at this context on
+ two devices. That gap is wider than the projector surcharge being decided, so a
+ plain probe answers "the projector fits" on exactly the loads whose placement then
+ falls back to `--fit on` and spills model layers around the projector it kept.
+ """
+ backend, gguf = _split_rate_backend(tmp_path, memory = [(0, 7_200, 8_200), (1, 7_200, 8_200)])
+
+ cmd = _launch(backend, gguf, n_ctx = 65536)["cmd"]
+
+ assert "--mmproj" in cmd
+ assert "--no-mmproj-offload" in cmd
+ # The point of the pin: the requested context is placed on the two cards rather
+ # than the model being offloaded around a resident projector.
+ assert cmd[cmd.index("--fit") + 1] == "off"
+ assert cmd[cmd.index("-c") + 1] == "65536"
+
+
+def test_a_single_card_explicit_load_is_untouched_by_the_split_rate(tmp_path):
+ """No split, no replication, so the split-aware selector must reach the same
+ answer the plain one did. Guards the tightening from leaking onto one-GPU loads,
+ where `_select_gpus_split_aware` returns before its retry."""
+ backend, gguf = _split_rate_backend(tmp_path, memory = [(0, 12_000, 24_000)])
+
+ cmd = _launch(backend, gguf, n_ctx = 8192)["cmd"]
+
+ assert "--mmproj" in cmd
+ assert "--no-mmproj-offload" not in cmd
+ assert cmd[cmd.index("-c") + 1] == "8192"
+
+
+def test_auto_is_priced_at_the_split_rate_too_but_still_at_the_floor(tmp_path):
+ """The split rate and the floor are separate questions and only the floor is Auto's.
+
+ Auto's loop charges `_cc_bytes(ctx, n_gpus)` per card, so it is already stricter
+ than plain `_select_gpus` and a plainly priced probe is more optimistic than the
+ loop it gates. What keeps the pin honest under Auto is the FLOOR: a subset that
+ cannot hold the projector at 4096 is one Auto cannot rescue by shrinking, so
+ `--fit on` was coming either way.
+
+ Two cards where plain accounting says the projector fits at 4096 and the split
+ rate says it does not.
+ """
+ backend, gguf = _split_rate_backend(tmp_path, memory = [(0, 4_900, 5_900), (1, 4_900, 5_900)])
+
+ cmd = _launch(backend, gguf)["cmd"]
+
+ assert "--mmproj" in cmd
+ assert "--no-mmproj-offload" in cmd
+
+
+def test_auto_still_leaves_a_roomy_split_alone(tmp_path):
+ """The floor is what stops the split rate from turning into a blanket pin: on cards
+ with room at 4096 the projector stays on the GPU and Auto pays for the native
+ context in context, exactly as it does on one card."""
+ backend, gguf = _split_rate_backend(tmp_path, memory = [(0, 12_000, 16_000), (1, 12_000, 16_000)])
+
+ cmd = _launch(backend, gguf)["cmd"]
+
+ assert "--mmproj" in cmd
+ assert "--no-mmproj-offload" not in cmd
+
+
+def test_the_probe_reserves_the_compute_buffer_on_every_split_device(tmp_path):
+ """The buffer belongs in the per-device overhead as well as the total.
+
+ That is how the explicit branch charges it, and it is a separate term from the
+ retry's single-to-split step: the step re-prices the FOOTPRINT once the count is
+ known, while this is what makes each individual card carry its own copy. Drop it
+ and a subset whose cards cannot each hold one is accepted; the placement then makes
+ every device hold one anyway and falls back to `--fit on`, spilling model layers
+ around the projector the probe just kept. Verified reachable by sweeping the launch
+ path: without this term these numbers go from pinned with `--fit off` to unpinned
+ with `--fit on`.
+ """
+ backend, gguf = _split_rate_backend(tmp_path, memory = [(0, 6_000, 7_000), (1, 6_000, 7_000)])
+
+ cmd = _launch(backend, gguf, n_ctx = 32768)["cmd"]
+
+ assert "--mmproj" in cmd
+ assert "--no-mmproj-offload" in cmd
+ assert cmd[cmd.index("--fit") + 1] == "off"
+ assert cmd[cmd.index("-c") + 1] == "32768"
+
+
+def test_the_predicted_pin_is_reported_through_both_responses(tmp_path):
+ """A projector the fit moved to host RAM must say so, on the same channel the
+ startup-recovery pin uses.
+
+ Both routes end at the same placement and the same user-visible cost, so the
+ notice cannot depend on which one got there. Without this the predicted pin is
+ silent outside the server log: image encoding simply gets slower with nothing in
+ the UI to explain it, which is the complaint the recovery path exists to answer.
+ The card here is the one the pin fires on.
+ """
+ backend, gguf = _backend(tmp_path, memory = [(0, 8_692, 16_384)])
+ cmd = _launch(backend, gguf)["cmd"]
+
+ # Premise: this really is the predicted pin, not a post-crash recovery.
+ assert "--no-mmproj-offload" in cmd
+ assert backend.mmproj_fallback_reason == "cpu_offload"
+
+ fields = _llama_runtime_fields(backend)
+ load = LoadResponse(
+ status = "loaded", model = "test", display_name = "test", inference = {}, **fields
+ ).model_dump()
+ status = InferenceStatusResponse(active_model = "test", **fields).model_dump()
+ for payload, where in ((load, "load"), (status, "status")):
+ assert payload["mmproj_fallback_reason"] == "cpu_offload", where
+
+
+def test_a_load_that_keeps_the_projector_on_the_gpu_reports_nothing(tmp_path):
+ """The control: the reason is a report of something that happened, so a load that
+ never moved the projector must leave it None rather than always claiming CPU."""
+ backend, gguf = _backend(tmp_path, memory = [(0, 12_000, 24_000)])
+ cmd = _launch(backend, gguf)["cmd"]
+
+ assert "--no-mmproj-offload" not in cmd
+ assert backend.mmproj_fallback_reason is None
+
+
+ ("env", "expected_retry"),
+ [
+ # get_value_from_env checks the LLAMA_ARG_NO_ spelling first and forces falsey
+ # on presence alone, so the projector is already in host RAM either way.
+ ({"LLAMA_ARG_NO_MMPROJ_OFFLOAD": "1"}, False),
+ ({"LLAMA_ARG_NO_MMPROJ_OFFLOAD": ""}, False),
+ # It wins over the positive spelling, exactly as arg.cpp orders them.
+ ({"LLAMA_ARG_MMPROJ_OFFLOAD": "1", "LLAMA_ARG_NO_MMPROJ_OFFLOAD": "0"}, False),
+ # is_falsey accepts `disabled`; the spelling list alone does not.
+ ({"LLAMA_ARG_MMPROJ_OFFLOAD": "disabled"}, False),
+ # Still a GPU projector, so the recovery retry is real work.
+ ({"LLAMA_ARG_MMPROJ_OFFLOAD": "enabled"}, True),
+ ({}, True),
+ ],
+)
+def test_the_recovery_retry_sees_every_environment_pin(env, expected_retry):
+ """A projector the environment already pinned to CPU cannot be rescued by pinning
+ it again: the retry respawns a command identical in effect, cannot clear the
+ allocation failure, and costs the caller the real error, because the branch that
+ surfaces that OOM only runs when this returns None."""
+ cmd = ["llama-server", "-m", "/cache/model.gguf", "--mmproj", "/cache/mmproj.gguf"]
+ retry = LlamaCppBackend._with_mmproj_offload_disabled(cmd, env)
+
+ assert (retry is not None) is expected_retry
+ if expected_retry:
+ assert retry[-1] == "--no-mmproj-offload"
+
+
+def test_the_speculative_reserve_is_normalized_before_anything_prices_it(tmp_path):
+ """Ordering invariant: `_mtp_bytes` reads `mtp_overhead_fn` at call time, so the
+ CPU-drafter normalization has to run before the first thing that prices it.
+
+ It used to run after the projector probe, which is wrong on its face: a CPU-pinned
+ drafter allocates no VRAM, so charging the probe its full GPU footprint could pin
+ the projector and cost ~8.8x per image encode for memory nothing holds.
+
+ Asserted on the source rather than a launch, deliberately. No configuration I could
+ build makes the two orders decide differently -- a separate CPU-pinned drafter is
+ already excluded upstream, so `mtp_overhead_fn` is None at the probe either way.
+ Reaching it needs a target keeping its own reserve while a sidecar displaces an
+ embedded head. This locks the ordering that was fixed and claims no more.
+ """
+ source = Path(inspect.getsourcefile(LlamaCppBackend)).read_text()
+ normalize_at = source.index("if _draft_cpu_no_embedded and mtp_overhead_fn is not None:")
+ probe_at = source.index("_mm_mtp_on_gpu = _mtp_will_engage and not _draft_cpu_no_embedded")
+ assert (
+ normalize_at < probe_at
+ ), "the CPU-drafter reserve must be normalized before the projector probe prices it"
+
+
+def test_a_shared_device_beside_a_discrete_one_does_not_veto_the_pin(tmp_path):
+ """A laptop pairing a discrete card with an APU enumerates both.
+
+ Requiring EVERY enumerated device to have its own budget refused the pin there, so
+ a model that would have fitted the discrete card once the projector moved kept it
+ resident and either pulled the shared device into the split or went to `--fit on`.
+ The shared device is dropped from the question instead: bytes handed back land on a
+ card with its own pool.
+
+ The discrete card is the one the single-GPU pin test uses, with a shared device
+ (total 0) alongside it.
+ """
+ backend, gguf = _backend(tmp_path, memory = [(0, 8_692, 16_384), (1, 7_600, 0)])
+
+ cmd = _launch(backend, gguf)["cmd"]
+
+ assert "--mmproj" in cmd
+ assert "--no-mmproj-offload" in cmd
+
+
+def test_a_host_that_is_only_shared_memory_still_never_pins(tmp_path):
+ """The rule that survives: with no budgeted device anywhere, moving the projector
+ shuffles bytes inside one pool and frees nothing, so the 8.8x image-encode cost
+ buys exactly nothing. Unchanged by the mixed-host relaxation above."""
+ backend, gguf = _backend(tmp_path, memory = [(0, 7_600, 0), (1, 7_600, 0)])
+
+ cmd = _launch(backend, gguf)["cmd"]
+
+ assert "--mmproj" in cmd
+ assert "--no-mmproj-offload" not in cmd
+
+
+def test_a_user_pinned_projector_still_costs_a_shared_pool(tmp_path):
+ """--no-mmproj-offload on an APU moves the encoder inside one pool.
+
+ On a discrete card the flag really does take those bytes off the device, so
+ dropping them from the fit is right. A shared pool has nowhere to move them
+ to: the projector sits in the very memory the context is being fitted
+ against, and spending it on KV as well over-commits. The reference load
+ charges the same bytes as model weights with no projector at all, which is
+ exactly what a CPU-resident projector costs here, so the two must fit to the
+ same context.
+ """
+ memory = [(0, 9_000, 0)]
+
+ backend, gguf = _backend(tmp_path, memory = memory)
+ cmd = _launch(backend, gguf, extra_args = ["--no-mmproj-offload"])["cmd"]
+ pinned_ctx = int(cmd[cmd.index("-c") + 1])
+
+ reference, ref_gguf = _backend(tmp_path, memory = memory, model_bytes = 7 * GIB, mmproj_bytes = 0)
+ ref_cmd = _launch(reference, ref_gguf)["cmd"]
+ reference_ctx = int(ref_cmd[ref_cmd.index("-c") + 1])
+
+ assert pinned_ctx == reference_ctx
+
+
+def test_a_pinned_projector_costs_the_shared_pool_beside_a_discrete_card(tmp_path):
+ """The mixed host, where asking "is any device budgeted?" gets it backwards.
+
+ _discrete_vram drops shared devices to decide whether the pin frees anything
+ ANYWHERE, and one discrete card is enough for that. The fit is a different
+ question: the selection walks prefixes of the enumerated list, so a shared
+ device ranked first is a candidate subset on its own, and a context fitted
+ against that pool without the pinned projector over-commits it. The discrete
+ card here is nearly full, so the shared pool is what the load runs on.
+ """
+ memory = [(0, 9_000, 0), (1, 100, 16_384)]
+
+ backend, gguf = _backend(tmp_path, memory = memory)
+ cmd = _launch(backend, gguf, extra_args = ["--no-mmproj-offload"])["cmd"]
+ pinned_ctx = int(cmd[cmd.index("-c") + 1])
+
+ # Same reference as the single-device case: a CPU-resident projector in a
+ # shared pool costs exactly what the same bytes cost as model weights.
+ reference, ref_gguf = _backend(tmp_path, memory = memory, model_bytes = 7 * GIB, mmproj_bytes = 0)
+ ref_cmd = _launch(reference, ref_gguf)["cmd"]
+
+ assert pinned_ctx == int(ref_cmd[ref_cmd.index("-c") + 1])