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: add a Disable Vision toggle to a model's Advanced Settings (#9383)

Daniel Han91dad2384751
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 9e1bc8803b5..403c3b7ffdd 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -391,6 +391,10 @@ class GgufLoadIntent:
hf_variant: Optional[str] = None
hf_token: Optional[str] = None
is_vision: bool = False
+ # Load a vision GGUF as text-only: no projector on the GPU and none on the CPU
+ # either. The projector's VRAM is left for the model, and image input is off
+ # for the session.
+ disable_vision: bool = False
n_ctx: int = 4096
chat_template_override: Optional[str] = None
cache_type_kv: Optional[str] = None
@@ -3514,6 +3518,25 @@ def _paravirtual_mmproj_pinnable(server_caps: Mapping[str, object]) -> bool:
)
+def _mmproj_env_is_audio_only(path: Optional[str]) -> bool:
+ """True only when *path* names a readable projector with no vision tower.
+
+ Anything else -- unset, absent from disk, unreadable, or declaring images -- is
+ False, so the caller clears it. Deliberately asymmetric: keeping a projector the
+ user switched off is the worse mistake of the two, and an unknown declaration
+ reads image-capable upstream.
+ """
+ if not path:
+ return False
+ try:
+ from utils.models.gguf_metadata import mmproj_capabilities
+ has_audio, accepts_image = mmproj_capabilities(str(path))
+ except Exception as e:
+ logger.debug(f"inherited mmproj capability read failed: {e}")
+ return False
+ return has_audio and not accepts_image
+
+
# 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.
@@ -4583,6 +4606,15 @@ class LlamaCppBackend:
self._hf_variant: Optional[str] = None
self._is_vision: bool = False
# Vision deliberately left unloaded by the caller. Tracked so a reload that
+ # flips the toggle cannot be satisfied by the live server, which opened a
+ # different set of files, and echoed to the client so the switch can reseed
+ # from the load it actually ran.
+ self._disable_vision: bool = False
+ # Narrower than the raw request: image input is off because the user asked,
+ # not because the model has no usable projector. Only a model that HAS one
+ # can have had it switched off, and the client needs the distinction to point
+ # at the switch rather than at a missing file.
+ self._vision_disabled_by_user: bool = False
# 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
@@ -5405,6 +5437,12 @@ class LlamaCppBackend:
# 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
+ # diffusion path: _start_diffusion_server ignores the switch and records it
+ # False, so comparing it there makes every identical repeat request a
+ # mismatch and tears down a runtime that was already the one asked for.
+ if not self._is_diffusion and bool(self._disable_vision) != bool(intent.disable_vision):
+ return False
+
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
@@ -10813,6 +10851,10 @@ class LlamaCppBackend:
self._gguf_load_identity = self._gguf_load_source_identity(model_path)
self._hf_repo = hf_repo
self._is_vision = False
+ # Clear the prior GGUF's toggle too: a diffusion model must not report the
+ # last model's vision state.
+ self._disable_vision = False
+ self._vision_disabled_by_user = False
self._is_audio = False # clear any prior TTS/audio model's routing flag
self._model_identifier = model_identifier
self._cache_type_kv = None
@@ -14260,7 +14302,13 @@ class LlamaCppBackend:
return self._as_cpu_fallback_intent(intent)
def _apply_cpu_fallback_state(
- self, intent: GgufLoadIntent, *, is_vision: bool, mmproj_has_audio: bool
+ self,
+ intent: GgufLoadIntent,
+ *,
+ is_vision: bool,
+ mmproj_has_audio: bool,
+ disable_vision: bool,
+ vision_disabled_by_user: bool,
) -> GgufLoadIntent:
intent = self._as_cpu_fallback_intent(intent)
self._gpu_memory_mode = intent.gpu_memory_mode
@@ -14273,6 +14321,12 @@ class LlamaCppBackend:
self._layer_preserves_tensor_intent = False
self._is_vision = is_vision
self._mmproj_has_audio = mmproj_has_audio
+ # The caller returns straight after this, before the load's own assignment of
+ # these two, so a recovery that skipped them left the response describing the
+ # PREVIOUS load's Vision state: the control flips back on, and an unchanged
+ # disable_vision request then fails runtime matching and reloads the model.
+ self._disable_vision = bool(disable_vision)
+ self._vision_disabled_by_user = bool(vision_disabled_by_user)
self._cpu_fallback_reason = "vulkan_startup_crash"
return intent
@@ -14625,6 +14679,7 @@ class LlamaCppBackend:
hf_token = intent.hf_token
model_identifier = intent.model_identifier
is_vision = intent.is_vision
+ disable_vision = intent.disable_vision
n_ctx = intent.n_ctx
chat_template_override = intent.chat_template_override
cache_type_kv = intent.cache_type_kv
@@ -15489,11 +15544,54 @@ class LlamaCppBackend:
gpus: list[tuple[int, int]] = []
# Keep fit-budget and launch-flag mmproj resolution in sync.
launch_mmproj_path = None
+ # Set only where the SWITCH is what dropped a usable image projector.
+ # A None launch path does not mean that on its own: the resolve also
+ # returns None for a missing file or a family mismatch, and reporting
+ # the switch there tells the user to turn Vision back on when the same
+ # projector will just be rejected again.
+ _dv_dropped_image_projector = False
if not extra_args_disable_mmproj(extra_args):
launch_mmproj_path = self._resolve_launch_mmproj_path(
model_path = model_path,
mmproj_path = mmproj_path,
)
+ # The switch turns VISION off, and a projector is not always a
+ # vision tower: ultravox, Voxtral and Qwen3-ASR declare an audio
+ # encoder and no vision at all, so suppressing one takes the
+ # model's audio input away and gives no image VRAM back. Nothing
+ # there for the switch to turn off, so keep it. Resolution is a
+ # disk and family check with no download, so asking first is free.
+ if disable_vision and launch_mmproj_path:
+ _dv_has_audio, _dv_accepts_image = False, True
+ try:
+ from utils.models.gguf_metadata import mmproj_capabilities
+ _dv_has_audio, _dv_accepts_image = mmproj_capabilities(
+ launch_mmproj_path
+ )
+ except Exception as e:
+ # Unknown reads image-capable upstream, so honor the switch
+ # rather than quietly keep a projector the user turned off.
+ logger.debug(f"mmproj capability read failed: {e}")
+ if _dv_accepts_image:
+ if _dv_has_audio:
+ # One projector serves both modalities (Qwen2.5-Omni)
+ # and llama.cpp cannot load half of it, so audio input
+ # goes with vision. Say so: the switch only named images.
+ logger.warning(
+ "Vision is off for this load, so this model's audio "
+ "input goes too: its projector serves both and "
+ "llama.cpp cannot load one modality without the "
+ "other. Turn Vision back on to send audio."
+ )
+ launch_mmproj_path = None
+ _dv_dropped_image_projector = True
+ else:
+ logger.info(
+ "Vision is off for this load, but this model's projector "
+ "is audio-only (no vision tower), so it stays loaded: "
+ "dropping it would remove audio input and free no image "
+ "VRAM."
+ )
# A virtualised Metal device corrupts the vision encoder too, and
# --no-mmproj-offload is the only way to keep it off there (clip.cpp
# never reads --gpu-layers). Without that flag the choice is a projector
@@ -17435,8 +17533,25 @@ class LlamaCppBackend:
# 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.
+ #
+ # Unless the switch is going to keep it: an inherited audio-only
+ # encoder survives the scrub below, so the server really does have it
+ # and the same reasoning says to record it. One predicate for both, off
+ # the same inherited value, so the probe cannot describe a child the
+ # scrub did not build.
+ # ...and not on a virtualised Metal device, whose own scrub below
+ # takes BOTH projector vars unconditionally. It runs after the switch's
+ # block, so a file kept there is gone by launch, and a probe that still
+ # described it would report an audio encoder the child does not have.
+ _dv_env_mmproj_kept = (
+ disable_vision
+ and not _paravirtual_cpu_forced
+ and _mmproj_env_is_audio_only(os.environ.get("LLAMA_ARG_MMPROJ"))
+ )
_mmproj_probe = launch_mmproj_path or (
- "" if _pv_mmproj_unpinnable else (os.environ.get("LLAMA_ARG_MMPROJ") or "")
+ ""
+ if (_pv_mmproj_unpinnable or (disable_vision and not _dv_env_mmproj_kept))
+ else (os.environ.get("LLAMA_ARG_MMPROJ") or "")
)
if launch_mmproj_path or os.path.isfile(_mmproj_probe):
try:
@@ -18263,6 +18378,19 @@ class LlamaCppBackend:
# --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
+ # a load that reports it off and whose fit budget never charged the
+ # projector's VRAM. Only when the projector really was suppressed. Both
+ # ways of keeping an audio-only one are excluded: the resolved path keeps
+ # launch_mmproj_path set, and an inherited LLAMA_ARG_MMPROJ keeps neither
+ # that nor anything else this gate can see, so it needs the same predicate
+ # the env scrub used. --no-mmproj-auto does not actually unload either of
+ # them -- server-context.cpp gates the load on a non-empty mmproj.path and
+ # never reads no_mmproj, which only suppresses the HF auto-download and
+ # the router's capability report -- but advertising a model as text-only
+ # while loading its encoder is its own bug, and one flag away from a real
+ # one if that gate ever starts reading no_mmproj.
+ if disable_vision and not launch_mmproj_path and not _dv_env_mmproj_kept:
+ cmd.append("--no-mmproj-auto")
# 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.
@@ -18460,6 +18588,29 @@ class LlamaCppBackend:
# 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 disable_vision:
+ # With the same audio-only exception the resolved path gets, and for
+ # the same reason: a projector is not always a vision tower, so
+ # clearing an inherited ultravox / Voxtral / Qwen3-ASR encoder takes
+ # the model's audio input away and gives no image VRAM back. Asked of
+ # the file rather than assumed, and unknown still reads image-capable,
+ # so the switch is honored wherever it might mean anything.
+ _dv_env_mmproj = (env.get("LLAMA_ARG_MMPROJ") or "").strip()
+ if not _mmproj_env_is_audio_only(_dv_env_mmproj):
+ # Same signal the resolved path records, for the same reason:
+ # this one IS restored by turning Vision back on, so the composer
+ # must point at the switch rather than at a missing mmproj. Only
+ # for a file that exists -- a stale path drops nothing, and
+ # blaming the switch there sends the user to a control that
+ # cannot help. Unknown-but-present reads image-capable, matching
+ # the rule the scrub itself just used.
+ if _dv_env_mmproj and Path(_dv_env_mmproj).is_file():
+ _dv_dropped_image_projector = True
+ env.pop("LLAMA_ARG_MMPROJ", None)
+ # No such reprieve for the URL: it names a download that has not
+ # happened, so there is no file to classify and nothing to do but
+ # honor the switch.
+ env.pop("LLAMA_ARG_MMPROJ_URL", None)
if _paravirtual_cpu_forced:
for _pv_mmproj_var in ("LLAMA_ARG_MMPROJ", "LLAMA_ARG_MMPROJ_URL"):
env.pop(_pv_mmproj_var, None)
@@ -19006,6 +19157,12 @@ class LlamaCppBackend:
mmproj_has_audio = (
_launched_mmproj_has_audio if fallback_has_mmproj else False
),
+ disable_vision = disable_vision,
+ # The same expression the load's own assignment uses, since the
+ # replay carries the same switch and the same dropped projector.
+ vision_disabled_by_user = bool(
+ is_vision and disable_vision and _dv_dropped_image_projector
+ ),
)
gpu_memory_mode = intent.gpu_memory_mode
gpu_layers = intent.gpu_layers
@@ -19043,6 +19200,26 @@ class LlamaCppBackend:
else:
self._hf_variant = None
self._is_vision = effective_is_vision
+ self._disable_vision = bool(disable_vision)
+ # is_vision, NOT effective_is_vision: the latter means "a projector is
+ # attached", which this load deliberately made false, so it would report
+ # False for the one case this field exists to describe. The intent flag
+ # is the model's own capability.
+ #
+ # Three cases must NOT blame the switch, because turning it back on
+ # would not restore images: a text-only GGUF with a stale toggle, an
+ # audio-only projector (kept on purpose, no image encoder), and an
+ # advanced argument that drops the projector (nothing reads the file, so
+ # the capability default stays True). All three fall through to the
+ # generic "cannot accept images".
+ #
+ # So this is one signal recorded where the decision was made rather than
+ # re-derived from state that cannot tell the cases apart: True only where
+ # a usable image projector was resolved and the switch dropped it. None
+ # of the three reaches that assignment.
+ self._vision_disabled_by_user = bool(
+ is_vision and disable_vision and _dv_dropped_image_projector
+ )
self._model_identifier = model_identifier
# Store the effective (possibly capped) context separately; do
@@ -19082,6 +19259,10 @@ class LlamaCppBackend:
intent,
is_vision = self._is_vision,
mmproj_has_audio = self._mmproj_has_audio,
+ disable_vision = disable_vision,
+ vision_disabled_by_user = bool(
+ is_vision and disable_vision and _dv_dropped_image_projector
+ ),
)
gpu_memory_mode = intent.gpu_memory_mode
gpu_layers = intent.gpu_layers
@@ -20669,6 +20850,8 @@ class LlamaCppBackend:
self._mtp_runtime_fallback_active = False
self._hf_variant = None
self._is_vision = False
+ self._disable_vision = False
+ self._vision_disabled_by_user = False
self._is_audio = False
self._audio_type = None
self._audio_probed = False
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index c8891c280d8..7f2d445658b 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -188,6 +188,16 @@ class LoadRequest(BaseModel):
"No effect on a single GPU. Ignored for non-GGUF models."
),
)
+ disable_vision: bool = Field(
+ False,
+ description = (
+ "Load a vision-capable GGUF without its multimodal projector, as a "
+ "text-only model. Frees the VRAM the projector would hold, at the cost "
+ "of image input, which is off for the session; text generation is "
+ "unaffected. Ignored for models with no vision projector, and for "
+ "non-GGUF models."
+ ),
+ )
gpu_memory_mode: Literal["auto", "manual"] = Field(
"auto",
description = (
@@ -357,6 +367,10 @@ class ValidateModelRequest(BaseModel):
load_in_4bit: bool = Field(True)
cache_type_kv: Optional[str] = Field(None)
tensor_parallel: bool = Field(False)
+ # Sized with, like the other intended load settings above: the follow-up /load
+ # opens no projector when this is set, so a preflight that charges for one would
+ # refuse a load that then fits.
+ disable_vision: bool = Field(False)
gpu_ids: Optional[List[int]] = Field(None)
gpu_memory_mode: Literal["auto", "manual"] = Field(
"auto",
@@ -808,6 +822,23 @@ class _InferenceRuntimeFields(BaseModel):
False,
description = "Whether tensor-parallel split (--split-mode tensor) is active.",
)
+ disable_vision: bool = Field(
+ False,
+ description = (
+ "Whether the load ran with the vision projector deliberately left "
+ "unloaded. Echoes the request, so the Advanced Settings switch can "
+ "reseed from it even on a GGUF that never had a projector."
+ ),
+ )
+ vision_disabled_by_user: bool = Field(
+ False,
+ description = (
+ "Whether image input is off because the user asked, rather than because "
+ "the model has no usable mmproj. The two look identical to a client "
+ "otherwise and need different guidance, so this stays False for a model "
+ "that never had a projector to switch off."
+ ),
+ )
gpu_memory_mode: Literal["auto", "manual"] = Field(
"auto",
description = "Active GPU memory strategy ('auto' or 'manual').",
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index f0809a175a0..f44adf0eabc 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -6510,6 +6510,34 @@ def _effective_load_in_4bit(config: ModelConfig, requested: bool) -> bool:
return load_in_4bit
+def _load_keeps_a_projector(config, *, disable_vision: bool) -> bool:
+ """Whether the launch will actually open a projector for *config*.
+
+ The Vision switch turns IMAGES off, and llama_cpp.py keeps an audio-only
+ projector regardless because there is no image tower in it to drop. Only the
+ file's own metadata distinguishes the two, so this answers precisely when the
+ file is already on disk. A projector that is not (a remote repo, nothing
+ downloaded yet) reads as kept: the callers use this to decide whether the load
+ needs the GPU, and over-claiming is recoverable where under-claiming is not.
+ """
+ if not getattr(config, "is_vision", False):
+ return False
+ if not disable_vision:
+ return True
+ mmproj = getattr(config, "gguf_mmproj_file", None)
+ if not mmproj:
+ return True
+ try:
+ from utils.models.gguf_metadata import mmproj_accepts_image
+
+ # Image-capable means the switch really does suppress it. Unreadable reads
+ # as image-capable upstream, which matches what the loader will do with it.
+ return not mmproj_accepts_image(str(mmproj))
+ except Exception as exc:
+ logger.debug(f"mmproj capability read failed: {exc}")
+ return False
+
+
def _remote_gguf_companion_bytes(
repo: str,
*,
@@ -7052,6 +7080,7 @@ def _estimate_gguf_required_gb(
n_ubatch: Optional[int] = None,
n_devices: int = 1,
is_diffusion: bool = False,
+ disable_vision: bool = False,
) -> Optional[float]:
"""Approximate GGUF VRAM (GB): quantized weights + companions, plus the KV
cache for local files (unreadable pre-download for remote). None when nothing
@@ -7065,6 +7094,8 @@ def _estimate_gguf_required_gb(
_extra_args_requests_dflash,
_extra_args_requests_dspark,
_extra_args_set_spec_type,
+ _mmproj_env_is_audio_only,
+ extra_args_disable_mmproj,
)
_spec_mode = _canonicalize_spec_mode(speculative_type) or "auto"
@@ -7174,7 +7205,38 @@ def _estimate_gguf_required_gb(
# Only the drafter the launch will load: the modes are exclusive, and a
# 10 GB DSpark sidecar merely sitting on disk must not inflate the guard
# for a load that never opens it.
+ # Vision off means llama_cpp.py resolves no projector, so the guard must not
+ # refuse a chat load over bytes it provably does not take -- a constrained
+ # machine is where the switch gets used and where this guard bites. But the
+ # loader keeps an AUDIO-ONLY projector despite the switch, and dropping the
+ # bytes of one that does get opened would admit a load the running training job
+ # cannot afford. So ask the loader's own question of the same file, which is on
+ # disk here. Same gate as the remote branch's include_mmproj below.
_sized_attrs = ["gguf_mmproj_file"]
+ # Whether the CONFIGURED projector is one this launch opens. Bound before the
+ # switch so the inherited-projector gate below can read it either way.
+ _dv_opens_projector = True
+ if extra_args_disable_mmproj(llama_extra_args):
+ # llama_cpp.py skips the resolve entirely, so nothing of Studio's own goes
+ # on the command line and nothing is downloaded. (It does NOT unload an
+ # inherited path, which is charged below.)
+ _dv_opens_projector = False
+ _sized_attrs = []
+ elif disable_vision:
+ _dv_mmproj = getattr(config, "gguf_mmproj_file", None)
+ _dv_opens_projector = False
+ if _dv_mmproj:
+ try:
+ from utils.models.gguf_metadata import mmproj_accepts_image
+
+ # Kept for audio, so its bytes stay charged. An unreadable file
+ # reads as image-capable upstream, hence suppressed and uncharged,
+ # which matches what the loader will then do with it.
+ _dv_opens_projector = not mmproj_accepts_image(str(_dv_mmproj))
+ except Exception as _dv_exc:
+ logger.debug(f"mmproj capability read failed: {_dv_exc}")
+ if not _dv_opens_projector:
+ _sized_attrs = []
if not _charge_no_drafter:
if dspark_requested:
_sized_attrs.append("gguf_dspark_file")
@@ -7242,8 +7304,50 @@ def _estimate_gguf_required_gb(
# else: a local --model-draft that is not on disk, so no drafter loads and
# none is charged. A repository reserve there 409s a load over a typo.
+ # A projector this config never named: llama-server reads LLAMA_ARG_MMPROJ
+ # straight into params.mmproj.path, so an inherited one loads and takes VRAM
+ # that nothing above charged. Two things stop it, and only two. Studio's own
+ # --mmproj overrides the env, argv being applied after set_env, so exactly one
+ # file loads and charging both bills one projector twice. And under the vision
+ # switch the loader keeps only an audio-only file, asked through the loader's
+ # own helper so the two cannot answer differently.
+ #
+ # NOT the extras opt-out on its own. --no-mmproj / --no-mmproj-auto set
+ # params.no_mmproj, which stops Studio resolving a projector of its own and
+ # stops the HF auto-download, but server-context.cpp gates the load on a
+ # non-empty mmproj.path and never reads that field. So an inherited path loads
+ # straight through the opt-out. What the opt-out does do is empty the command
+ # line, which is why it feeds _studio_mmproj_on_argv rather than this gate.
+ #
+ # Added to the return rather than to total_bytes, which decides local-vs-remote
+ # above and must stay the main weight's verdict. The remote branch charges the
+ # repo's own projector instead; an inherited local file alongside a remote repo
+ # is charged nowhere, as before this.
+ #
+ # argv overrides the env, but only when there IS argv: a configured projector
+ # the switch suppressed, or extras that skipped the resolve, both leave the
+ # command line empty and let the inherited path load after all. So this asks
+ # what Studio actually emits, not merely what the config names -- the same
+ # answer _sized_attrs above was built from, so the two cannot disagree about
+ # which single projector this launch opens.
+ _studio_mmproj_on_argv = bool(
+ getattr(config, "gguf_mmproj_file", None) and _dv_opens_projector
+ )
+ _env_mmproj_bytes = 0
+ _env_mmproj = (os.environ.get("LLAMA_ARG_MMPROJ") or "").strip()
+ if (
+ _env_mmproj
+ and not _studio_mmproj_on_argv
+ and (not disable_vision or _mmproj_env_is_audio_only(_env_mmproj))
+ and Path(_env_mmproj).is_file()
+ and _same_file_key(_env_mmproj) not in _sized_keys
+ ):
+ _env_mmproj_bytes = LlamaCppBackend._get_gguf_size_bytes(_env_mmproj)
+
if total_bytes > 0:
- return (total_bytes + _extras_bytes) / (1024**3) + _estimate_gguf_kv_gb(
+ return (total_bytes + _extras_bytes + _env_mmproj_bytes) / (
+ 1024**3
+ ) + _estimate_gguf_kv_gb(
main,
max_seq_length,
llama_extra_args,
@@ -7269,6 +7373,12 @@ def _estimate_gguf_required_gb(
companions = _remote_gguf_companion_bytes(
repo,
hf_token = hf_token,
+ # Charged whenever the repo ships one, switch or no switch: the load
+ # fetches a remote projector either way, only the file's metadata
+ # separates an image tower from an audio encoder, and nothing here has
+ # the file to ask. Under-charging is what would admit a chat load over
+ # VRAM a training job needs, so an unknown projector is charged. The
+ # local branch, holding the file, asks instead.
include_mmproj = bool(has_vision),
# Remote, so which sidecar the repo ships is unknown until the
# listing. Under Auto size both: a repo has one kind or the other,
@@ -8135,6 +8245,9 @@ def _guard_chat_load_against_training(
n_devices = guard_n_devices,
# a confirmed diffusion runner ignores the batch flags, so no reserve for it
is_diffusion = diffusion_kind is True,
+ # getattr for the same reason as the batch flags above: an older caller
+ # hands this guard a bare request double that does not carry the field.
+ disable_vision = bool(getattr(request, "disable_vision", False)),
)
if is_gguf
else None
@@ -9294,6 +9407,11 @@ async def _load_model_impl(
_hub_download_blocks_gguf_load,
config.gguf_hf_repo,
config.gguf_variant,
+ # Same predicate as the marker's own check, and as the loader's
+ # download gate: the projector is fetched whenever the repo ships one
+ # and the extras have not opted out, so the switch must not relax this
+ # interlock. Relaxing it let a vision-off load bypass the 409 and then
+ # download into the shared Hub cache beside a running download job.
require_mmproj = bool(
config.is_vision and not extra_args_disable_mmproj(extra_llama_args)
),
@@ -9321,7 +9439,22 @@ async def _load_model_impl(
request.gpu_memory_mode,
request.gpu_layers,
extra_llama_args,
- bool(config.is_vision and not extra_args_disable_mmproj(extra_llama_args)),
+ # Vision off suppresses the projector, so it keeps no GPU visible and
+ # this load must not take the arbiter: acquire_for evicts a resident
+ # image/video pipeline and the confirmation cancels its running
+ # generations, both before the launch would have revealed it needed
+ # nothing. An audio-only projector is kept, and a kept projector does
+ # keep the GPUs visible, so ask the file when it is already on disk.
+ # A remote one is not, and claiming the GPU is the safe way to be
+ # wrong here: the stale claim is released right after the load.
+ bool(
+ config.is_vision
+ and not extra_args_disable_mmproj(extra_llama_args)
+ and _load_keeps_a_projector(
+ config,
+ disable_vision = bool(getattr(request, "disable_vision", False)),
+ )
+ ),
request.speculative_type,
)
)
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index 13f61dbc61a..785a2c37603 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -722,6 +722,7 @@ class ModelOverridePayload(BaseModel):
n_batch: Optional[int] = Field(default = None, ge = BATCH_SIZE_MIN, le = BATCH_SIZE_MAX)
n_ubatch: Optional[int] = Field(default = None, ge = BATCH_SIZE_MIN, le = BATCH_SIZE_MAX)
tensor_parallel: bool = False
+ disable_vision: bool = False
# Validated in bytes below: pydantic counts characters, so a multi-byte template would pass.
chat_template_override: Optional[str] = None
gpu_memory_mode: Optional[Literal["auto", "manual"]] = None
@@ -1457,9 +1458,18 @@ def update_openai_auto_switch_override(
if payload.remove is not None:
is_removal = payload.remove
else:
- is_removal = not payload.tensor_parallel and not {
- key: value for key, value in saved_fields.items() if key != "tensor_parallel"
- }
+ # Both booleans are carried, not just counted: they are stored only when
+ # true, so an override whose one setting is either of them has no other
+ # saved field and would otherwise read as a removal and be deleted.
+ is_removal = (
+ not payload.tensor_parallel
+ and not payload.disable_vision
+ and not {
+ key: value
+ for key, value in saved_fields.items()
+ if key not in ("tensor_parallel", "disable_vision")
+ }
+ )
if requested_extra_args is None and not is_removal:
stored = get_model_override(payload.model_id)
# A fill keeps the stored flags without echoing them back through validation: one
@@ -1575,6 +1585,7 @@ def update_openai_auto_switch_override(
n_batch = payload.n_batch,
n_ubatch = payload.n_ubatch,
tensor_parallel = payload.tensor_parallel,
+ disable_vision = payload.disable_vision,
chat_template_override = payload.chat_template_override,
gpu_memory_mode = payload.gpu_memory_mode,
gpu_layers = payload.gpu_layers,
diff --git a/studio/backend/tests/test_metal_paravirtual_guard.py b/studio/backend/tests/test_metal_paravirtual_guard.py
index 73554937dcb..66ce3c981a1 100644
--- a/studio/backend/tests/test_metal_paravirtual_guard.py
+++ b/studio/backend/tests/test_metal_paravirtual_guard.py
@@ -580,6 +580,9 @@ def _mmproj_gate(
),
"model_path": "/m.gguf",
"mmproj_path": None,
+ # This harness is about the paravirtual gate, so vision is on; the toggle's
+ # own effect on the same block is covered in test_mmproj_placement_policy.py.
+ "disable_vision": False,
"_paravirtual_cpu_forced": paravirtual,
"server_caps": caps,
"is_vision": is_vision,
diff --git a/studio/backend/tests/test_mmproj_placement_policy.py b/studio/backend/tests/test_mmproj_placement_policy.py
index 93da6ee7588..ed9c116921f 100644
--- a/studio/backend/tests/test_mmproj_placement_policy.py
+++ b/studio/backend/tests/test_mmproj_placement_policy.py
@@ -204,6 +204,22 @@ def test_user_owns_the_placement_when_they_name_either_spelling(tmp_path):
assert cmd.count("--no-mmproj-offload") == 0
+def test_vision_switched_off_loads_no_projector_anywhere(tmp_path, monkeypatch):
+ """Not on the GPU, not on the CPU, and not through an inherited env var:
+ common/arg.cpp reads LLAMA_ARG_MMPROJ straight into params.mmproj.path."""
+ monkeypatch.setenv("LLAMA_ARG_MMPROJ", "/ambient/mmproj.gguf")
+ monkeypatch.setenv("LLAMA_ARG_MMPROJ_URL", "https://example.invalid/mmproj.gguf")
+ backend, gguf = _backend(tmp_path, memory = [(0, 7_600, 8_192)])
+
+ result = _launch(backend, gguf, disable_vision = True)
+
+ assert "--mmproj" not in result["cmd"]
+ assert "--no-mmproj-offload" not in result["cmd"]
+ assert "LLAMA_ARG_MMPROJ" not in result["env"]
+ assert "LLAMA_ARG_MMPROJ_URL" not in result["env"]
+ assert backend.is_vision is False
+
+
@pytest.mark.parametrize(
"memory,label",
[
@@ -300,6 +316,159 @@ def test_the_drafters_vram_is_part_of_the_pin_decision(tmp_path):
assert "--no-mmproj-offload" not in unpinned
+ "is_vision,disable_vision,expect_disabled,expect_by_user",
+ [
+ # A vision GGUF with the switch on: the projector exists and the user
+ # turned it off, so both are true.
+ (True, True, True, True),
+ # A GGUF that never had a projector, switch on. The request still has to
+ # round-trip or the toggle reseeds itself to off after every load, but
+ # nothing was taken away from the user, so the narrow field stays false.
+ (False, True, True, False),
+ (True, False, False, False),
+ (False, False, False, False),
+ ],
+)
+def test_load_and_status_both_report_the_vision_toggle(
+ tmp_path, is_vision, disable_vision, expect_disabled, expect_by_user
+):
+ """Both fields must reach the client on both responses.
+
+ The frontend coalesces each with ``?? false``, so a field the backend omits
+ reads as "vision is on" instead of raising: the switch silently reseeds to
+ off after every load. Presence is therefore asserted on its own, not just
+ the value.
+ """
+ backend, gguf = _backend(tmp_path, memory = [(0, 12_000, 24_000)])
+ _launch(backend, gguf, is_vision = is_vision, disable_vision = disable_vision)
+
+ # The shared resolver both responses are built from, drift guard included.
+ 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 "disable_vision" in payload, where
+ assert "vision_disabled_by_user" in payload, where
+ assert payload["disable_vision"] is expect_disabled, where
+ assert payload["vision_disabled_by_user"] is expect_by_user, where
+
+
+def test_the_training_guard_does_not_charge_a_projector_the_load_will_not_open(tmp_path):
+ """The switch is used on constrained machines, which is exactly where this
+ guard bites: charging VRAM the load provably never takes would refuse a chat
+ load for the memory the user just freed."""
+ model = tmp_path / "model.gguf"
+ model.write_bytes(b"\x00" * (4 * MIB))
+ mmproj = tmp_path / "mmproj-F16.gguf"
+ mmproj.write_bytes(b"\x00" * (1 * MIB))
+ config = SimpleNamespace(
+ gguf_file = str(model),
+ gguf_mmproj_file = str(mmproj),
+ gguf_mtp_file = None,
+ gguf_dspark_file = None,
+ gguf_dflash_file = None,
+ gguf_hf_repo = None,
+ gguf_variant = None,
+ is_vision = True,
+ )
+
+ charged = _estimate_gguf_required_gb(config)
+ freed = _estimate_gguf_required_gb(config, disable_vision = True)
+
+ assert charged is not None and freed is not None
+ # Exactly the projector, and nothing else moved.
+ assert round((charged - freed) * 1024) == 1
+ assert freed < charged
+
+
+def test_the_training_guard_forwards_the_switch_to_its_estimator(tmp_path):
+ """The gate above is only worth having if the request reaches it.
+
+ Asserts on the keyword the guard hands the estimator, not on the verdict, so
+ the test stays about the wiring and not about the rest of the guard.
+ """
+ seen = {}
+
+ def capture(_config, **kwargs):
+ seen.update(kwargs)
+ return 0.0
+
+ training = SimpleNamespace(is_training_active = lambda: True)
+ request = SimpleNamespace(
+ hf_token = None,
+ max_seq_length = 0,
+ speculative_type = None,
+ cache_type_kv = None,
+ gpu_memory_mode = "auto",
+ gpu_layers = -1,
+ tensor_parallel = False,
+ n_parallel = 1,
+ disable_vision = True,
+ )
+ config = SimpleNamespace(is_gguf = True, gguf_file = None, gguf_hf_repo = None)
+ placement = _LoadPlacement(
+ requested_gpu_ids = None,
+ resolved_gpu_ids = None,
+ gpu_ids_are_vulkan_ordinals = False,
+ diffusion_kind = False,
+ )
+
+ with (
+ patch("core.training.get_training_backend", lambda: training),
+ patch("routes.inference._estimate_gguf_required_gb", side_effect = capture),
+ patch.object(LlamaCppBackend, "_find_llama_server_binary", lambda *_a, **_k: None),
+ patch.object(LlamaCppBackend, "_effective_gpu_count", lambda *_a, **_k: 1),
+ ):
+ try:
+ _guard_chat_load_against_training(
+ config, request, load_in_4bit = False, placement = placement
+ )
+ except Exception:
+ # The verdict is not what this test is about; the forwarded keyword is,
+ # and it is already captured by the time anything downstream can fail.
+ pass
+
+ assert seen.get("disable_vision") is True
+
+
+ "has_audio,accepts_image,projector_expected,label",
+ [
+ (True, False, True, "audio_only_keeps_the_projector"),
+ (True, True, False, "omni_honors_the_switch"),
+ (False, True, False, "vision_only_honors_the_switch"),
+ ],
+)
+def test_the_vision_switch_does_not_take_audio_only_projectors_away(
+ tmp_path, has_audio, accepts_image, projector_expected, label
+):
+ """A projector is not always a vision tower. ultravox, Voxtral and Qwen3-ASR
+ declare an audio encoder and no vision, so suppressing one would remove the
+ model's audio input and free no image VRAM: the switch has nothing to turn
+ off there and must leave it alone. A projector serving both modalities is
+ still suppressed, because llama.cpp cannot load one modality without the
+ other, and the switch is the user asking for the VRAM back."""
+ import utils.models.gguf_metadata as _meta
+
+ backend, gguf = _backend(tmp_path, memory = [(0, 7_600, 8_192)])
+ with patch.object(_meta, "mmproj_capabilities", lambda _p: (has_audio, accepts_image)):
+ cmd = _launch(backend, gguf, disable_vision = True)["cmd"]
+
+ assert ("--mmproj" in cmd) is projector_expected, label
+
+
+# The pin reads no platform flag. It sees the GPU probe's output, the Metal
+# budget, the paravirtual capability answer, tensor_parallel and the memory
+# mode, and nothing else, so an OS reaches it only through what its probe
+# reports. These are the probe signatures the supported pairs produce: what
+# varies between a Windows and a WSL RTX 4090 is nothing the decision reads.
+# Free VRAM is 7600 MiB against a footprint that needs more, i.e. the case that
+# pins on a discrete card, so any cell reporting "no pin" is doing so because
+# its memory is shared, not because it had room.
_TOPOLOGIES = [
([(0, 7_600, 8_192)], True, "linux_nvidia_discrete"),
([(0, 7_600, 8_192)], True, "windows_nvidia_discrete"),
@@ -353,6 +522,132 @@ def test_a_heterogeneous_pair_is_ranked_before_the_projector_is_charged(tmp_path
assert ("--no-mmproj-offload" in cmd) is False, label
+def test_a_remembered_mmproj_auto_does_not_survive_the_vision_switch(tmp_path):
+ """--mmproj-auto asks llama-server to find the adjacent projector on its own, so
+ suppressing Studio's --mmproj and the env vars is not enough: vision would come
+ back on a load that reports it off and never charged the projector's VRAM.
+ llama.cpp is last-wins on the pair, so the disable form has to follow the extras."""
+ backend, gguf = _backend(tmp_path, memory = [(0, 7_600, 8_192)])
+
+ cmd = _launch(backend, gguf, disable_vision = True, extra_args = ["--mmproj-auto"])["cmd"]
+
+ assert "--no-mmproj-auto" in cmd
+ assert cmd.index("--no-mmproj-auto") > cmd.index("--mmproj-auto")
+
+
+def test_an_audio_only_projector_is_not_taken_away_by_the_auto_override(tmp_path):
+ """The override exists to stop a projector coming back. An audio-only one is kept
+ on purpose, so --no-mmproj-auto must not follow it out the door."""
+ import utils.models.gguf_metadata as _meta
+
+ backend, gguf = _backend(tmp_path, memory = [(0, 7_600, 8_192)])
+ with patch.object(_meta, "mmproj_capabilities", lambda _p: (True, False)):
+ cmd = _launch(backend, gguf, disable_vision = True, extra_args = ["--mmproj-auto"])["cmd"]
+
+ assert "--mmproj" in cmd
+ assert "--no-mmproj-auto" not in cmd
+
+
+def test_an_audio_only_projector_does_not_blame_the_switch_for_images(tmp_path):
+ """vision_disabled_by_user drives the composer's "you turned it off" message, so
+ on a model with no image encoder it would promise a capability that turning the
+ switch back on cannot deliver."""
+ import utils.models.gguf_metadata as _meta
+
+ backend, gguf = _backend(tmp_path, memory = [(0, 7_600, 8_192)])
+ with patch.object(_meta, "mmproj_capabilities", lambda _p: (True, False)):
+ _launch(backend, gguf, disable_vision = True)
+
+ assert backend._disable_vision is True
+ assert backend._vision_disabled_by_user is False
+
+
+def test_the_training_guard_still_charges_an_audio_only_projector(tmp_path):
+ """The switch turns vision off, and the loader keeps an audio-only projector
+ anyway because there is no image tower to drop. Dropping its bytes here would
+ let the guard admit a chat load the running training job cannot afford, which
+ is the direction that costs someone else's job rather than merely annoying
+ this user."""
+ import utils.models.gguf_metadata as _meta
+
+ model = tmp_path / "model.gguf"
+ model.write_bytes(b"\x00" * (4 * MIB))
+ mmproj = tmp_path / "mmproj-F16.gguf"
+ mmproj.write_bytes(b"\x00" * (1 * MIB))
+ config = SimpleNamespace(
+ gguf_file = str(model),
+ gguf_mmproj_file = str(mmproj),
+ gguf_mtp_file = None,
+ gguf_dspark_file = None,
+ gguf_dflash_file = None,
+ gguf_hf_repo = None,
+ gguf_variant = None,
+ is_vision = True,
+ )
+
+ with patch.object(_meta, "mmproj_accepts_image", lambda _p: False):
+ audio_only = _estimate_gguf_required_gb(config, disable_vision = True)
+ with patch.object(_meta, "mmproj_accepts_image", lambda _p: True):
+ vision = _estimate_gguf_required_gb(config, disable_vision = True)
+ charged = _estimate_gguf_required_gb(config)
+
+ assert audio_only is not None and vision is not None and charged is not None
+ # Kept for audio, so it is charged exactly as an enabled projector would be.
+ assert audio_only == charged
+ # An image projector really is dropped, so the switch still frees its bytes.
+ assert vision < charged
+
+
+def test_the_download_interlock_is_not_relaxed_by_the_vision_switch(tmp_path):
+ """The load fetches a remote 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 interlock has to hold
+ for it: relaxing it let a vision-off load skip the 409 and then write into the
+ shared Hub cache beside a running download job, which is the race the check
+ exists to stop. The predicate must mirror the download gate, not the switch."""
+ from core.inference.llama_cpp import GgufLoadIntent, _with_gguf_load_marker
+
+ seen = {}
+
+ def fake_blocks(
+ repo,
+ variant,
+ *,
+ require_mmproj,
+ hf_token = None,
+ ):
+ seen["require_mmproj"] = require_mmproj
+ return False
+
+ def inner(
+ self,
+ intent,
+ load_cancel_event = None,
+ ):
+ return True
+
+ def _run(**intent_kwargs):
+ seen.clear()
+ _with_gguf_load_marker(inner)(
+ object(),
+ GgufLoadIntent(
+ gguf_path = str(tmp_path / "model.gguf"),
+ model_identifier = "test",
+ hf_repo = "unsloth/some-vl-GGUF",
+ is_vision = True,
+ **intent_kwargs,
+ ),
+ )
+ return seen["require_mmproj"]
+
+ with patch("core.inference.llama_cpp._hub_download_blocks_gguf_load", fake_blocks):
+ # Vision off still downloads, so the interlock still applies.
+ assert _run(disable_vision = True) is True
+ assert _run(disable_vision = False) is True
+ # The extras opting out is the one case that downloads nothing.
+ assert _run(disable_vision = True, extra_args = ["--no-mmproj"]) is False
+
+
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
@@ -415,6 +710,168 @@ def test_the_projector_probe_agrees_with_the_layer_loop_it_gates(tmp_path):
)
+def test_a_remote_projector_of_unknown_kind_is_charged_to_the_guard(tmp_path):
+ """Remote, so nothing here has the file to ask whether it is an image tower the
+ switch drops or an audio encoder the loader keeps. Under-charging is the
+ direction that admits a chat load over VRAM a running training job needs, so
+ the unknown one is charged."""
+ seen = {}
+
+ def fake_companions(repo, *, hf_token, include_mmproj, **kw):
+ seen["include_mmproj"] = include_mmproj
+ return 0
+
+ config = SimpleNamespace(
+ gguf_file = None,
+ gguf_mmproj_file = None,
+ gguf_mtp_file = None,
+ gguf_dspark_file = None,
+ gguf_dflash_file = None,
+ gguf_hf_repo = "unsloth/some-vl-GGUF",
+ gguf_variant = "UD-Q4_K_XL",
+ is_vision = True,
+ )
+ variant = SimpleNamespace(quant = "UD-Q4_K_XL", size_bytes = 4 * GIB)
+
+ with (
+ patch("routes.inference._remote_gguf_companion_bytes", fake_companions),
+ patch(
+ "utils.models.model_config.list_gguf_variants",
+ lambda *a, **k: ([variant], True),
+ ),
+ ):
+ _estimate_gguf_required_gb(config, disable_vision = True)
+
+ assert seen.get("include_mmproj") is True
+
+
+def _ambient_mmproj(tmp_path, monkeypatch):
+ ambient = tmp_path / "ambient-mmproj.gguf"
+ ambient.write_bytes(b"\x00" * (1 * MIB))
+ monkeypatch.setenv("LLAMA_ARG_MMPROJ", str(ambient))
+ backend, gguf = _backend(tmp_path, memory = [(0, 7_600, 8_192)])
+ backend._resolve_launch_mmproj_path = lambda **_kw: None
+ return backend, gguf
+
+
+def test_the_vision_switch_does_not_record_an_inherited_audio_encoder(tmp_path, monkeypatch):
+ """The capability probe falls back to the ambient LLAMA_ARG_MMPROJ, which the
+ switch then scrubs out of the child. Reading it anyway recorded an audio encoder
+ the launched server does not have, and that becomes has_audio_input, so the
+ composer would offer attachments the server cannot process.
+
+ A projector serving both modalities is the case that still scrubs: llama.cpp
+ cannot load half of it, so switching vision off takes the audio with it."""
+ backend, gguf = _ambient_mmproj(tmp_path, monkeypatch)
+
+ import utils.models.gguf_metadata as _meta
+
+ with patch.object(_meta, "mmproj_capabilities", lambda _p: (True, True)):
+ result = _launch(backend, gguf, disable_vision = True)
+
+ assert "LLAMA_ARG_MMPROJ" not in result["env"]
+ assert backend._mmproj_has_audio is False
+
+
+def test_the_vision_switch_keeps_an_inherited_audio_only_encoder(tmp_path, monkeypatch):
+ """The other half of the same rule, which the resolved path already had: an
+ ultravox / Voxtral / Qwen3-ASR projector declares audio and no vision, so there is
+ no image tower for the switch to turn off. Scrubbing it took the model's audio
+ input away and handed back no image VRAM, and the probe agreed with the scrub, so
+ the loss was silent on both sides.
+ """
+ backend, gguf = _ambient_mmproj(tmp_path, monkeypatch)
+
+ import utils.models.gguf_metadata as _meta
+
+ with patch.object(_meta, "mmproj_capabilities", lambda _p: (True, False)):
+ result = _launch(backend, gguf, disable_vision = True)
+
+ assert result["env"].get("LLAMA_ARG_MMPROJ")
+ # And the probe follows the scrub, so the composer is told what the child has.
+ assert backend._mmproj_has_audio is True
+ assert backend._mmproj_accepts_image is False
+ # --no-mmproj-auto does not unload it (server-context.cpp gates the load on a
+ # non-empty mmproj.path and never reads no_mmproj), but it does make the router
+ # advertise the model text-only, so a projector kept on purpose must not get it.
+ assert "--no-mmproj-auto" not in result["cmd"]
+
+
+def test_an_inherited_projector_that_reads_images_still_goes(tmp_path, monkeypatch):
+ """The asymmetry is deliberate: only a readable audio-only declaration is kept.
+ An image-capable one is exactly what the switch is for."""
+ backend, gguf = _ambient_mmproj(tmp_path, monkeypatch)
+
+ import utils.models.gguf_metadata as _meta
+
+ with patch.object(_meta, "mmproj_capabilities", lambda _p: (False, True)):
+ result = _launch(backend, gguf, disable_vision = True)
+
+ assert "LLAMA_ARG_MMPROJ" not in result["env"]
+
+
+def test_a_diffusion_runtime_is_not_torn_down_over_the_vision_switch(tmp_path):
+ """_start_diffusion_server ignores the switch and records it False, so comparing
+ it on that path makes every identical repeat request a mismatch and reloads a
+ runtime that was already the one asked for. The switch must not be what decides,
+ so both spellings of the request have to reach the same verdict."""
+ from core.inference.llama_cpp import (
+ GgufLoadIntent,
+ LlamaCppBackend,
+ _resolved_mmproj_offload,
+ )
+
+ backend = LlamaCppBackend()
+ backend._is_diffusion = True
+ backend._disable_vision = False
+ backend._gguf_path = str(tmp_path / "diffusion.gguf")
+ # Enough state for the comparison under test to be REACHED: the checks above it
+ # return early on their own, and a test where both calls fail for an unrelated
+ # reason passes whatever this line does (it did, until the mutant survived).
+ backend._requested_n_ctx = 4096
+ backend._cache_type_kv = None
+
+ def _intent(disable_vision: bool):
+ return GgufLoadIntent(
+ gguf_path = str(tmp_path / "diffusion.gguf"),
+ model_identifier = "test",
+ disable_vision = disable_vision,
+ )
+
+ assert backend._runtime_matches_intent(_intent(True), None) == (
+ backend._runtime_matches_intent(_intent(False), None)
+ )
+
+
+def test_an_advanced_argument_that_drops_the_projector_is_not_blamed_on_the_switch(tmp_path):
+ """vision_disabled_by_user drives the composer's "you turned it off" message. With
+ --no-mmproj in the extras the projector is suppressed by the ARGUMENT, resolution
+ is skipped so nothing reads the file and the capability default stays True, and
+ the switch would take the blame for images that turning it back on cannot
+ restore while the argument still applies."""
+ backend, gguf = _backend(tmp_path, memory = [(0, 7_600, 8_192)])
+
+ _launch(backend, gguf, disable_vision = True, extra_args = ["--no-mmproj"])
+
+ assert backend._disable_vision is True
+ assert backend._vision_disabled_by_user is False
+
+
+def test_a_projector_the_resolve_rejected_is_not_blamed_on_the_switch(tmp_path):
+ """A None launch path does not mean the switch dropped it. The resolve also
+ returns None for a missing file or a family mismatch, and reporting the switch
+ there tells the user to turn Vision back on when the same projector will just be
+ rejected again. Only a usable image projector the switch itself dropped counts."""
+ backend, gguf = _backend(tmp_path, memory = [(0, 7_600, 8_192)])
+ # What a family-check failure looks like from here.
+ backend._resolve_launch_mmproj_path = lambda **_kw: None
+
+ _launch(backend, gguf, disable_vision = True)
+
+ assert backend._disable_vision is True
+ assert backend._vision_disabled_by_user is False
+
+
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.
@@ -828,3 +1285,272 @@ def test_a_pinned_projector_costs_the_shared_pool_beside_a_discrete_card(tmp_pat
ref_cmd = _launch(reference, ref_gguf)["cmd"]
assert pinned_ctx == int(ref_cmd[ref_cmd.index("-c") + 1])
+
+
+def _estimator_config(model_path, mmproj_path = None):
+ return SimpleNamespace(
+ gguf_file = str(model_path),
+ gguf_mmproj_file = str(mmproj_path) if mmproj_path else None,
+ gguf_mtp_file = None,
+ gguf_dspark_file = None,
+ gguf_dflash_file = None,
+ gguf_hf_repo = None,
+ gguf_variant = None,
+ is_vision = True,
+ )
+
+
+def test_the_guard_charges_a_projector_only_the_environment_names(tmp_path, monkeypatch):
+ """The loader keeps an inherited audio-only LLAMA_ARG_MMPROJ when Vision is off.
+
+ It is GPU-resident like any other projector, and this config never names it, so
+ charging nothing let the coexistence guard admit a chat load the running
+ training job cannot afford -- the direction that costs someone else's job.
+ """
+ model = tmp_path / "model.gguf"
+ model.write_bytes(b"\x00" * (4 * MIB))
+ ambient = tmp_path / "ambient-mmproj.gguf"
+ ambient.write_bytes(b"\x00" * (1 * MIB))
+ config = _estimator_config(model)
+
+ bare = _estimate_gguf_required_gb(config, disable_vision = True)
+ monkeypatch.setenv("LLAMA_ARG_MMPROJ", str(ambient))
+
+ import utils.models.gguf_metadata as _meta
+
+ with patch.object(_meta, "mmproj_capabilities", lambda _p: (True, False)):
+ charged = _estimate_gguf_required_gb(config, disable_vision = True)
+ # An image-capable one is scrubbed out of the child, so it must stay uncharged.
+ with patch.object(_meta, "mmproj_capabilities", lambda _p: (False, True)):
+ dropped = _estimate_gguf_required_gb(config, disable_vision = True)
+
+ assert bare is not None and charged is not None and dropped is not None
+ assert round((charged - bare) * 1024) == 1
+ assert dropped == bare
+
+
+def test_studios_own_projector_outranks_the_inherited_one_in_the_estimate(tmp_path, monkeypatch):
+ """argv beats the environment (arg.cpp applies set_env first), so exactly one
+ projector loads. Charging both billed a single file twice and refused loads
+ that fit."""
+ model = tmp_path / "model.gguf"
+ model.write_bytes(b"\x00" * (4 * MIB))
+ resolved = tmp_path / "mmproj-F16.gguf"
+ resolved.write_bytes(b"\x00" * (1 * MIB))
+ ambient = tmp_path / "ambient-mmproj.gguf"
+ ambient.write_bytes(b"\x00" * (2 * MIB))
+
+ # What the launch really costs: weights plus the one projector argv names.
+ expected = _estimate_gguf_required_gb(_estimator_config(model, resolved))
+ monkeypatch.setenv("LLAMA_ARG_MMPROJ", str(ambient))
+ charged = _estimate_gguf_required_gb(_estimator_config(model, resolved))
+
+ assert expected is not None and charged is not None
+ # The 2 MiB ambient file is not in it, so the env changed nothing.
+ assert charged == expected
+
+
+def test_a_suppressed_image_projector_hands_the_budget_to_the_inherited_one(tmp_path, monkeypatch):
+ """The combination that slipped through: the CONFIGURED projector is
+ image-capable, so the switch drops it and Studio emits no --mmproj at all, while
+ the inherited one is audio-only and is kept. argv only beats the environment when
+ there IS argv, so the inherited projector is what loads, and it is what has to be
+ charged."""
+ model = tmp_path / "model.gguf"
+ model.write_bytes(b"\x00" * (4 * MIB))
+ configured = tmp_path / "mmproj-F16.gguf"
+ configured.write_bytes(b"\x00" * (1 * MIB))
+ ambient = tmp_path / "ambient-mmproj.gguf"
+ ambient.write_bytes(b"\x00" * (2 * MIB))
+
+ import utils.models.gguf_metadata as _meta
+
+ def _caps(path):
+ # Configured: images, so the switch drops it. Inherited: audio only, so it stays.
+ return (False, True) if str(path) == str(configured) else (True, False)
+
+ monkeypatch.delenv("LLAMA_ARG_MMPROJ", raising = False)
+ with (
+ patch.object(_meta, "mmproj_capabilities", _caps),
+ patch.object(_meta, "mmproj_accepts_image", lambda p: _caps(p)[1]),
+ ):
+ # Weights alone: the switch drops the image projector and no env one exists.
+ weights_only = _estimate_gguf_required_gb(
+ _estimator_config(model, configured), disable_vision = True
+ )
+ monkeypatch.setenv("LLAMA_ARG_MMPROJ", str(ambient))
+ charged = _estimate_gguf_required_gb(
+ _estimator_config(model, configured), disable_vision = True
+ )
+
+ assert charged is not None and weights_only is not None
+ # The 2 MiB inherited projector, not the 1 MiB configured one that never loads.
+ assert round((charged - weights_only) * 1024) == 2
+
+
+def test_the_extras_opt_out_does_not_excuse_an_inherited_projector(tmp_path, monkeypatch):
+ """--no-mmproj sets params.no_mmproj, which stops Studio resolving one of its own
+ and stops the HF download, but server-context.cpp gates the load on a non-empty
+ mmproj.path and never reads that field. The inherited projector loads straight
+ through the opt-out, so the guard has to keep charging it."""
+ model = tmp_path / "model.gguf"
+ model.write_bytes(b"\x00" * (4 * MIB))
+ ambient = tmp_path / "ambient-mmproj.gguf"
+ ambient.write_bytes(b"\x00" * (1 * MIB))
+ config = _estimator_config(model)
+
+ bare = _estimate_gguf_required_gb(config)
+ monkeypatch.setenv("LLAMA_ARG_MMPROJ", str(ambient))
+ charged = _estimate_gguf_required_gb(config, llama_extra_args = ["--no-mmproj"])
+
+ assert bare is not None and charged is not None
+ assert round((charged - bare) * 1024) == 1
+
+
+def test_the_extras_opt_out_moves_the_charge_to_the_inherited_projector(tmp_path, monkeypatch):
+ """--no-mmproj makes llama_cpp.py skip the resolve, so Studio emits no --mmproj
+ and the configured projector never loads. It does not unset an inherited path,
+ which then loads unopposed. The estimate has to move with the launch: drop the
+ configured file, charge the inherited one.
+ """
+ model = tmp_path / "model.gguf"
+ model.write_bytes(b"\x00" * (4 * MIB))
+ configured = tmp_path / "mmproj-F16.gguf"
+ configured.write_bytes(b"\x00" * (1 * MIB))
+ ambient = tmp_path / "ambient-mmproj.gguf"
+ ambient.write_bytes(b"\x00" * (2 * MIB))
+ config = _estimator_config(model, configured)
+
+ monkeypatch.delenv("LLAMA_ARG_MMPROJ", raising = False)
+ # The configured projector, charged, with no opt-out in play.
+ normal = _estimate_gguf_required_gb(config)
+ weights_only = _estimate_gguf_required_gb(_estimator_config(model))
+ opted_out = _estimate_gguf_required_gb(config, llama_extra_args = ["--no-mmproj"])
+
+ monkeypatch.setenv("LLAMA_ARG_MMPROJ", str(ambient))
+ inherited = _estimate_gguf_required_gb(config, llama_extra_args = ["--no-mmproj"])
+
+ for value in (normal, weights_only, opted_out, inherited):
+ assert value is not None
+ assert round((normal - weights_only) * 1024) == 1
+ # The opt-out drops the configured projector, because it never loads.
+ assert opted_out == weights_only
+ # And the inherited one takes its place at its own size.
+ assert round((inherited - weights_only) * 1024) == 2
+
+
+def _paravirtual(monkeypatch):
+ import core.inference.llama_cpp as _llama_cpp
+
+ monkeypatch.setattr(_llama_cpp, "_metal_device_is_paravirtual", lambda: True)
+
+
+def test_a_virtualised_metal_device_does_not_keep_the_inherited_projector(
+ tmp_path, monkeypatch
+):
+ """The paravirtual scrub runs after the switch's and takes BOTH projector vars
+ unconditionally, so a file the switch kept is gone by launch.
+
+ Two things went wrong when the "kept" answer did not know that: the capability
+ probe described an audio encoder the child does not have, and the --no-mmproj-auto
+ override was skipped, leaving a remembered --mmproj-auto free to rediscover an
+ adjacent image projector on a load the user asked to be text-only.
+ """
+ ambient = tmp_path / "ambient-mmproj.gguf"
+ ambient.write_bytes(b"\x00" * (1 * MIB))
+ monkeypatch.setenv("LLAMA_ARG_MMPROJ", str(ambient))
+ _paravirtual(monkeypatch)
+ backend, gguf = _backend(tmp_path, memory = [])
+ backend._resolve_launch_mmproj_path = lambda **_kw: None
+
+ import utils.models.gguf_metadata as _meta
+
+ with patch.object(_meta, "mmproj_capabilities", lambda _p: (True, False)):
+ result = _launch(
+ backend, gguf, disable_vision = True, extra_args = ["--mmproj-auto"]
+ )
+
+ assert "LLAMA_ARG_MMPROJ" not in result["env"]
+ # Nothing survives to rediscover a projector with.
+ assert "--no-mmproj-auto" in result["cmd"]
+ # And the probe describes the child that actually launched.
+ assert backend._mmproj_has_audio is False
+
+
+def test_dropping_an_inherited_image_projector_points_at_the_switch(
+ tmp_path, monkeypatch
+):
+ """Turning Vision back on restores an inherited image projector, so the composer
+ must name the switch rather than send the user hunting for a valid mmproj."""
+ ambient = tmp_path / "ambient-mmproj.gguf"
+ ambient.write_bytes(b"\x00" * (1 * MIB))
+ monkeypatch.setenv("LLAMA_ARG_MMPROJ", str(ambient))
+ backend, gguf = _backend(tmp_path, memory = [(0, 7_600, 8_192)])
+ backend._resolve_launch_mmproj_path = lambda **_kw: None
+
+ import utils.models.gguf_metadata as _meta
+
+ with patch.object(_meta, "mmproj_capabilities", lambda _p: (False, True)):
+ _launch(backend, gguf, disable_vision = True)
+
+ assert backend._vision_disabled_by_user is True
+
+
+def test_a_stale_inherited_path_does_not_blame_the_switch(tmp_path, monkeypatch):
+ """A path that names no file drops nothing, so turning Vision back on changes
+ nothing either. Blaming the switch there points at a control that cannot help."""
+ monkeypatch.setenv("LLAMA_ARG_MMPROJ", str(tmp_path / "not-on-disk.gguf"))
+ backend, gguf = _backend(tmp_path, memory = [(0, 7_600, 8_192)])
+ backend._resolve_launch_mmproj_path = lambda **_kw: None
+
+ _launch(backend, gguf, disable_vision = True)
+
+ assert backend._vision_disabled_by_user is False
+
+
+def test_a_cpu_recovery_records_the_vision_state_it_launched_with(tmp_path):
+ """_apply_cpu_fallback_state is the last thing a Vulkan-crash recovery runs: its
+ caller returns immediately after, before the load's own assignment of these two.
+
+ Leaving them behind meant the response described the PREVIOUS load's Vision state,
+ so the control flipped back on and an unchanged disable_vision request then failed
+ runtime matching and reloaded the model.
+ """
+ backend = LlamaCppBackend()
+ backend._disable_vision = False
+ backend._vision_disabled_by_user = False
+ intent = GgufLoadIntent(
+ gguf_path = str(_write_gguf(tmp_path / "model.gguf")),
+ model_identifier = "test",
+ is_vision = True,
+ disable_vision = True,
+ )
+
+ backend._apply_cpu_fallback_state(
+ intent,
+ is_vision = False,
+ mmproj_has_audio = False,
+ disable_vision = True,
+ vision_disabled_by_user = True,
+ )
+
+ assert backend._disable_vision is True
+ assert backend._vision_disabled_by_user is True
+ # The rest of the recovery state still lands, so this is additive.
+ assert backend._cpu_fallback_reason == "vulkan_startup_crash"
+
+
+def test_both_cpu_recovery_call_sites_pass_the_vision_state(tmp_path):
+ """Two call sites reach that helper and only one is on the common path, so a
+ keyword added to one and not the other is a silent half-fix. Checked at the source
+ because the second site needs a crash inside a replay this harness cannot stage."""
+ source = inspect.getsource(LlamaCppBackend.load_model)
+ calls = source.count("self._apply_cpu_fallback_state(")
+ assert calls == 2, f"expected 2 recovery call sites, found {calls}"
+ # The load's own `self._vision_disabled_by_user = ...` uses the same words, so
+ # subtract it rather than matching loosely and passing on the wrong occurrence.
+ keyword_uses = source.count("vision_disabled_by_user = bool(") - source.count(
+ "self._vision_disabled_by_user = bool("
+ )
+ assert keyword_uses == calls
+ assert source.count("disable_vision = disable_vision,") == calls
diff --git a/studio/backend/utils/openai_auto_switch_settings.py b/studio/backend/utils/openai_auto_switch_settings.py
index f3a78086476..5e93687cffa 100644
--- a/studio/backend/utils/openai_auto_switch_settings.py
+++ b/studio/backend/utils/openai_auto_switch_settings.py
@@ -540,6 +540,11 @@ def normalize_model_override(
if _coerce_bool(payload.get("tensor_parallel")):
entry["tensor_parallel"] = True
+ # Stored only when set, like tensor_parallel: absent means the default, so an
+ # override that never touched the switch does not pin it off for a later load.
+ if _coerce_bool(payload.get("disable_vision")):
+ entry["disable_vision"] = True
+
template = payload.get("chat_template_override")
if isinstance(template, str) and template.strip():
# A lone surrogate from JSON breaks encode() and can never render, so drop it.
@@ -641,6 +646,7 @@ def model_override_load_kwargs(override: dict[str, Any], *, is_gguf: bool) -> di
("speculative_type", "speculative_type"),
("spec_draft_n_max", "spec_draft_n_max"),
("tensor_parallel", "tensor_parallel"),
+ ("disable_vision", "disable_vision"),
("chat_template_override", "chat_template_override"),
):
if override.get(source) is not None:
diff --git a/studio/frontend/src/features/api-monitor/components/saved-model-settings.tsx b/studio/frontend/src/features/api-monitor/components/saved-model-settings.tsx
index a1d74a2b1cd..d6d52d5080f 100644
--- a/studio/frontend/src/features/api-monitor/components/saved-model-settings.tsx
+++ b/studio/frontend/src/features/api-monitor/components/saved-model-settings.tsx
@@ -43,6 +43,9 @@ function describeOverride(override: ApiModelOverride): string[] {
if (override.tensor_parallel) {
parts.push("tensor parallel");
}
+ if (override.disable_vision) {
+ parts.push("vision off");
+ }
if (override.gpu_memory_mode === "manual") {
parts.push("manual GPU memory");
}
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 00fc91b1fb6..d91a90b34b0 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -2029,6 +2029,9 @@ const VISIBLE_MODEL_RUNTIME_KEYS = [
"loadedNUbatch",
"tensorParallel",
"loadedTensorParallel",
+ "loadedDisableVision",
+ "disableVision",
+ "loadedVisionDisabledByUser",
"gpuMemoryMode",
"loadedGpuMemoryMode",
"loadedCpuFallback",
@@ -2724,6 +2727,9 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
gpu_memory_mode?: "auto" | "manual";
cache_type_kv?: string | null;
tensor_parallel?: boolean | null;
+ // The projector is part of what the guard has to size: a load that skips
+ // it needs ~1 GB less, and charging for it would refuse loads that fit.
+ disable_vision?: boolean | null;
// The estimate charges a drafter whose size differs by mode (a DSpark
// sidecar is ~11 GB, and Auto reaches it), so this preflight has to be told
// what the load will send or it sizes a different model.
@@ -2907,6 +2913,8 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
const effectiveTensorParallel = isDiffusion
? false
: config.tensorParallel;
+ // The diffusion runner has no projector to skip, so the toggle is inert there.
+ const effectiveDisableVision = isDiffusion ? false : config.disableVision;
const effectiveGpuIds =
config.selectedGpuIds !== undefined
? reconcilePersistedGpuIds(
@@ -2941,6 +2949,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
gguf_variant: candidate.ggufVariant,
cache_type_kv: config.kvCacheDtype,
tensor_parallel: effectiveTensorParallel,
+ disable_vision: effectiveDisableVision,
// The same values the load below sends.
speculative_type: effectiveSpeculativeType,
spec_draft_n_max: effectiveSpecDraftNMax,
@@ -2992,6 +3001,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
speculative_type: effectiveSpeculativeType,
spec_draft_n_max: effectiveSpecDraftNMax,
tensor_parallel: effectiveTensorParallel,
+ disable_vision: effectiveDisableVision,
// GGUF-only: the safetensors fallback loads via HF auto-placement (no
// explicit pins). The split ratio is deliberately never remembered
// (positionally bound to an exact GPU set), so auto-load leaves llama.cpp's
@@ -3135,6 +3145,13 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
: (resolvedExtraArgs ?? null),
tensorParallel: loadResp.tensor_parallel ?? false,
loadedTensorParallel: loadResp.tensor_parallel ?? false,
+ loadedDisableVision: loadResp.disable_vision ?? false,
+ // Repaired from the echo alongside tensorParallel: this load picked its
+ // own model and config, so a stale true would show Vision off over a
+ // loaded projector, and the next Apply would send it.
+ disableVision: loadResp.disable_vision ?? false,
+ loadedVisionDisabledByUser:
+ loadResp.vision_disabled_by_user ?? false,
...loadedGpuMemoryFields(loadResp),
loadedCustomContextLength: keepCustomCtx,
defaultChatTemplate: loadResp.chat_template ?? null,
@@ -3176,6 +3193,13 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
loadedLlamaExtraArgs: null,
tensorParallel: loadResp.tensor_parallel ?? false,
loadedTensorParallel: loadResp.tensor_parallel ?? false,
+ loadedDisableVision: loadResp.disable_vision ?? false,
+ // Cleared, not carried, like the GGUF-only knobs above: a safetensors
+ // load has no projector, and a stale true would stage it for the next
+ // model that has one.
+ disableVision: false,
+ loadedVisionDisabledByUser:
+ loadResp.vision_disabled_by_user ?? false,
// Non-GGUF response: clears any stale GPU baseline a prior manual-GPU
// GGUF load left, matching the interactive/status sibling load paths.
...loadedGpuMemoryFields(loadResp),
@@ -3496,6 +3520,11 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
loadedNUbatch: null,
tensorParallel: loadResp.tensor_parallel ?? false,
loadedTensorParallel: loadResp.tensor_parallel ?? false,
+ loadedDisableVision: loadResp.disable_vision ?? false,
+ // The request above omits disable_vision, so the echo is what the load
+ // ran with; adopting it stops a previous model's Vision-off carrying over.
+ disableVision: loadResp.disable_vision ?? false,
+ loadedVisionDisabledByUser: loadResp.vision_disabled_by_user ?? false,
...loadedGpuMemoryFields(loadResp),
// Drives the GPU Memory controls' diffusion gate; set alongside the
// GPU fields on every load path so the gate can't read stale.
@@ -4588,6 +4617,7 @@ export function createOpenAIStreamAdapter(
loadedIsMultimodal: runtime.loadedIsMultimodal,
modelLoaded: !!params.checkpoint && !runtime.modelLoading,
loadError: runtime.lastModelLoadError,
+ visionDisabledByUser: runtime.loadedVisionDisabledByUser,
mmprojFallbackReason: runtime.mmprojFallbackReason,
});
if (imageGateReason) {
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 88efd2d108b..1d04c8f0bf1 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -310,6 +310,7 @@ export async function validateModel(
load_in_4bit: payload.load_in_4bit,
cache_type_kv: payload.cache_type_kv ?? null,
tensor_parallel: payload.tensor_parallel ?? false,
+ disable_vision: payload.disable_vision ?? false,
gpu_ids: payload.gpu_ids,
// Manual placement is an explicit override: Auto layers use llama.cpp --fit, a pinned
// layer count is owned by the user. Tell validate so it applies the same policy as /load.
diff --git a/studio/frontend/src/features/chat/chat-settings-sheet.tsx b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
index 3be5edd7263..54176d1ecfb 100644
--- a/studio/frontend/src/features/chat/chat-settings-sheet.tsx
+++ b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
@@ -541,6 +541,7 @@ export function ChatSettingsPanel({
const gpuLayers = useChatRuntimeStore((s) => s.gpuLayers);
const nCpuMoe = useChatRuntimeStore((s) => s.nCpuMoe);
const tensorParallel = useChatRuntimeStore((s) => s.tensorParallel);
+ const disableVision = useChatRuntimeStore((s) => s.disableVision);
const specDraftNMax = useChatRuntimeStore((s) => s.specDraftNMax);
const nParallel = useChatRuntimeStore((s) => s.nParallel);
const nBatch = useChatRuntimeStore((s) => s.nBatch);
@@ -680,6 +681,7 @@ export function ChatSettingsPanel({
gpuLayers,
nCpuMoe,
tensorParallel,
+ disableVision,
speculativeType,
specDraftNMax,
nParallel,
@@ -702,6 +704,7 @@ export function ChatSettingsPanel({
gpuLayers,
nCpuMoe,
tensorParallel,
+ disableVision,
speculativeType,
specDraftNMax,
nParallel,
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
index d35de359f45..f6e412c1e27 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
@@ -450,6 +450,7 @@ async function syncInferenceStatusToStore(options?: {
residentCheckpoint: null,
modelRequiresTrustRemoteCode: false,
loadedIsMultimodal: false,
+ loadedVisionDisabledByUser: null,
loadedIsDiffusion: false,
});
// Known resident a moment ago, and nothing loading now. Both matter: a
@@ -1179,6 +1180,29 @@ export function useChatModelRuntime() {
? false
: (pendingLoadConfig?.tensorParallel ??
stateBeforeUnload.tensorParallel);
+ // The diffusion runner has no projector to skip, so the toggle is inert
+ // there for the same reason tensorParallel is.
+ //
+ // Unlike tensorParallel, this does NOT survive a model switch: it is
+ // per-model config defaulting to vision on, so a target that saved none gets
+ // that default, not the outgoing model's setting. Carrying it over loaded the
+ // new model text-only and silently, because the dedupe comparison above
+ // already builds its own view of an unconfigured switch from
+ // DEFAULT_PER_MODEL_CONFIG. resetsPerModelSettings cannot repair it: this
+ // constant is captured before that block runs.
+ const loadSwitchesModelOrVariant = Boolean(
+ currentCheckpoint &&
+ (currentCheckpoint !== modelId ||
+ (stateBeforeUnload.activeGgufVariant ?? null) !==
+ (ggufVariant ?? null)) &&
+ !keepSpeculative,
+ );
+ const loadDisableVision = targetIsDiffusion
+ ? false
+ : (pendingLoadConfig?.disableVision ??
+ (loadSwitchesModelOrVariant
+ ? DEFAULT_PER_MODEL_CONFIG.disableVision
+ : stateBeforeUnload.disableVision));
const loadActivePresetSource = stateBeforeUnload.activePresetSource;
const loadActiveGgufVariant = stateBeforeUnload.activeGgufVariant;
const loadGpuMemoryMode =
@@ -1296,6 +1320,7 @@ export function useChatModelRuntime() {
gguf_variant: ggufVariant ?? null,
cache_type_kv: loadKvCacheDtype,
tensor_parallel: loadTensorParallel,
+ disable_vision: loadDisableVision,
gpu_ids: validateGpuIds ?? undefined,
...(isGguf
? {
@@ -1530,6 +1555,7 @@ export function useChatModelRuntime() {
? { n_ubatch: loadNUbatch }
: {}),
tensor_parallel: loadTensorParallel,
+ disable_vision: loadDisableVision,
gpu_memory_mode: loadGpuMemoryMode,
gpu_layers: loadGpuLayers,
n_cpu_moe: loadNCpuMoe,
@@ -1707,6 +1733,16 @@ export function useChatModelRuntime() {
...mlxRuntimeStateFrom(loadResponse),
tensorParallel: loadedTp,
loadedTensorParallel: loadedTp,
+ loadedDisableVision: loadResponse.disable_vision ?? false,
+ // Repaired from the echo like the knob above: loadDisableVision
+ // forces the flag off for a diffusion target without writing the
+ // store, so a Vision-off GGUF followed by a diffusion load would
+ // otherwise leave the switch off over a load that never sent it.
+ disableVision: loadResponse.disable_vision ?? false,
+ // Set alongside loadedIsMultimodal so the composer can say WHY
+ // images are unavailable.
+ loadedVisionDisabledByUser:
+ loadResponse.vision_disabled_by_user ?? false,
...loadedGpuMemoryFields(loadResponse),
speculativeType: loadedSpec,
loadedSpeculativeType: loadedSpec,
@@ -1864,6 +1900,14 @@ export function useChatModelRuntime() {
// Restore the previous model in the split mode it was running,
// not the default layer split.
tensor_parallel: stateBeforeUnload.loadedTensorParallel ?? false,
+ // What the PREVIOUS server was loaded with. Not the control field:
+ // applyPerModelConfigToRuntime writes disableVision before this
+ // baseline is captured, so it holds the TARGET's setting. Not
+ // loadedVisionDisabledByUser either: that is narrowed to models that
+ // can do images, so a non-vision GGUF would come back with vision on
+ // while the control restored to off. Same separately tracked baseline
+ // tensor_parallel uses above.
+ disable_vision: stateBeforeUnload.loadedDisableVision ?? false,
// Restore the previous model's GPU Memory placement, not backend defaults.
gpu_memory_mode: stateBeforeUnload.loadedGpuMemoryMode ?? "auto",
gpu_layers: stateBeforeUnload.loadedGpuLayers ?? GPU_LAYERS_AUTO,
@@ -1913,6 +1957,18 @@ export function useChatModelRuntime() {
tensorParallel: rollbackResponse.tensor_parallel ?? false,
loadedTensorParallel:
rollbackResponse.tensor_parallel ?? false,
+ loadedDisableVision:
+ rollbackResponse.disable_vision ?? false,
+ // The rolled-back model's own loaded value, matching the request
+ // above field for field. Not stateBeforeUnload.disableVision, which
+ // holds the TARGET's value by now and would show Vision off over a
+ // restored projector, arming the next Apply to switch it off for real.
+ // Not the echo either: the replayed request is gated on the model
+ // having a projector, so a text-only GGUF switched off echoes false
+ // and would flip Vision back on.
+ disableVision: stateBeforeUnload.loadedDisableVision ?? false,
+ loadedVisionDisabledByUser:
+ rollbackResponse.vision_disabled_by_user ?? false,
customContextLength:
stateBeforeUnload.loadedCustomContextLength,
loadedCustomContextLength:
diff --git a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
index a417ae919fc..41ac07bc329 100644
--- a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
+++ b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
@@ -32,6 +32,7 @@ import { resolveQwenThinkingParams } from "../utils/qwen-params";
import { sameGpuSelection } from "@/hooks/gpu-selection";
import { resolveBatchSizeSeed } from "./resolve-batch-size-seed";
import { resolveChatTemplateSeed } from "./resolve-chat-template-seed";
+import { shouldSeedVisionSwitch } from "./resolve-vision-switch-seed";
type LocalReasoningEffort = Extract<ReasoningEffort, "low" | "medium" | "high">;
@@ -403,6 +404,38 @@ export function applyActiveModelStatusToStore(
tensorParallel: status.tensor_parallel,
loadedTensorParallel: status.tensor_parallel,
}),
+ // A load knob like tensorParallel above. Without a reseed a tab that never
+ // performed the load shows Vision ON over a model running with its projector
+ // off, and the next Reload silently puts the projector back. Seeded from
+ // disable_vision -- the request the load ran with -- not
+ // vision_disabled_by_user, which is also gated on the model HAVING a projector
+ // and so cannot round-trip a text-only GGUF.
+ //
+ // Unlike tensorParallel the guard is not just "unseeded": the baseline below is
+ // unguarded, so an external reload of the same model would move it and the image
+ // gate while leaving this control behind. See shouldSeedVisionSwitch.
+ ...(seedLoadParams &&
+ status.disable_vision !== undefined &&
+ shouldSeedVisionSwitch({
+ incoming: status.disable_vision,
+ previous: prevState,
+ hydratingExistingModel,
+ }) && {
+ disableVision: status.disable_vision,
+ }),
+ // The rollback baseline, and unguarded like the mirror below rather than
+ // seeded once: it has to track the RUNNING server, or a switch that fails
+ // after a poll restores whatever the last seed happened to see.
+ ...(seedLoadParams &&
+ status.disable_vision !== undefined && {
+ loadedDisableVision: status.disable_vision,
+ }),
+ // Unguarded, unlike the seed above: this mirrors the live load for the
+ // composer's image gate, not a user setting, so every poll must land.
+ ...(seedLoadParams &&
+ status.vision_disabled_by_user !== undefined && {
+ loadedVisionDisabledByUser: status.vision_disabled_by_user,
+ }),
// Hydration only, so a steady poll never rewrites settings the store owns.
// Width, verdict and request move together; a late reply can overwrite a newer one.
...(seedLoadParams &&
diff --git a/studio/frontend/src/features/chat/lib/resident-config-match.ts b/studio/frontend/src/features/chat/lib/resident-config-match.ts
index 8124b70da2d..0fe1e346cd9 100644
--- a/studio/frontend/src/features/chat/lib/resident-config-match.ts
+++ b/studio/frontend/src/features/chat/lib/resident-config-match.ts
@@ -24,6 +24,7 @@ type ResidentRuntime = Pick<
| "requested_n_batch"
| "requested_n_ubatch"
| "tensor_parallel"
+ | "disable_vision"
| "chat_template_override"
| "requested_llama_extra_args"
| "gpu_memory_mode"
@@ -351,6 +352,14 @@ const SETTING_CHECKS: SettingCheck[] = [
s.tensor_parallel !== true &&
s.tensor_parallel_dropped_by_arch_gate === true),
},
+ {
+ // Not nullable, so it always has an opinion; a status omitting it ran with the
+ // projector. The backend reloads when this disagrees, so adopting a resident
+ // server that disagrees would drop the setting and keep the VRAM spent.
+ chatOnly: true,
+ pinned: () => true,
+ agrees: (c, s) => c.disableVision === (s.disable_vision ?? false),
+ },
{
// Blank-trimmed on both ends: the applier and the load both send "" as null.
mlxComparable: true,
diff --git a/studio/frontend/src/features/chat/lib/resolve-vision-switch-seed.ts b/studio/frontend/src/features/chat/lib/resolve-vision-switch-seed.ts
new file mode 100644
index 00000000000..d928e62cc96
--- /dev/null
+++ b/studio/frontend/src/features/chat/lib/resolve-vision-switch-seed.ts
@@ -0,0 +1,44 @@
+// 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 three store fields the Vision switch is decided from. */
+export interface VisionSwitchSeedState {
+ /** The editable control: what the next load or Apply will send. */
+ disableVision: boolean;
+ /** What the RUNNING server was loaded with; null before the first status. */
+ loadedDisableVision: boolean | null;
+ /** Set once the pair has been seeded at all; null means never. */
+ loadedVisionDisabledByUser: boolean | null;
+}
+
+/**
+ * Whether a status poll may write the incoming value into the editable control.
+ *
+ * Three cases say yes:
+ *
+ * 1. Never seeded, so the control holds a default nobody chose.
+ * 2. The model or variant changed under this tab, so the control belongs to the
+ * model that just left.
+ * 3. The RUNNING server's value moved while this tab was idle -- another tab or
+ * an API client reloaded the same model with the opposite setting. Without
+ * this, `loadedDisableVision` and the image gate follow the new server while
+ * the control keeps the old value, so Advanced Settings shows the opposite of
+ * the running projector and the next Apply quietly undoes the external change.
+ *
+ * The exception to case 3 is a genuinely pending local edit: a control that has
+ * been moved away from its loaded baseline is the user's unapplied intent, and a
+ * poll must not overwrite it. That is why "no pending edit" is `disableVision ===
+ * loadedDisableVision` against the OLD baseline, not against the incoming value.
+ */
+export function shouldSeedVisionSwitch(args: {
+ incoming: boolean;
+ previous: VisionSwitchSeedState;
+ hydratingExistingModel: boolean;
+}): boolean {
+ const { incoming, previous, hydratingExistingModel } = args;
+ if (previous.loadedVisionDisabledByUser === null) return true;
+ if (hydratingExistingModel) return true;
+ if (previous.loadedDisableVision === null) return false;
+ if (previous.loadedDisableVision === incoming) return false;
+ return previous.disableVision === previous.loadedDisableVision;
+}
diff --git a/studio/frontend/src/features/chat/presets/preset-load-config.ts b/studio/frontend/src/features/chat/presets/preset-load-config.ts
index 7815204ea1b..d8d5f703926 100644
--- a/studio/frontend/src/features/chat/presets/preset-load-config.ts
+++ b/studio/frontend/src/features/chat/presets/preset-load-config.ts
@@ -42,6 +42,7 @@ export type PresetLoadConfig = Pick<
| "nBatch"
| "nUbatch"
| "tensorParallel"
+ | "disableVision"
| "gpuMemoryMode"
| "gpuLayers"
| "nCpuMoe"
@@ -61,6 +62,7 @@ export const EMPTY_PRESET_LOAD_CONFIG: PresetLoadConfig = {
nBatch: null,
nUbatch: null,
tensorParallel: false,
+ disableVision: false,
};
function toComparablePerModelConfig(
@@ -147,6 +149,10 @@ export function normalizePresetLoadConfig(
typeof partial.tensorParallel === "boolean"
? partial.tensorParallel
: false,
+ disableVision:
+ typeof partial.disableVision === "boolean"
+ ? partial.disableVision
+ : false,
...(gpuMemoryMode ? { gpuMemoryMode } : {}),
...(gpuLayers !== undefined ? { gpuLayers } : {}),
...(nCpuMoe !== undefined ? { nCpuMoe } : {}),
@@ -193,6 +199,7 @@ export function capturePresetLoadConfig(): PresetLoadConfig | undefined {
nBatch: snapshot.nBatch ?? null,
nUbatch: snapshot.nUbatch ?? null,
tensorParallel: snapshot.tensorParallel ?? false,
+ disableVision: snapshot.disableVision ?? false,
...(snapshot.gpuMemoryMode === "manual"
? { gpuMemoryMode: "manual" as const }
: {}),
@@ -251,6 +258,7 @@ export function applyPresetLoadConfig(
nBatch: config.nBatch ?? null,
nUbatch: config.nUbatch ?? null,
tensorParallel: config.tensorParallel ?? false,
+ disableVision: config.disableVision ?? false,
chatTemplateOverride: null,
gpuMemoryMode: config.gpuMemoryMode,
gpuLayers: config.gpuLayers,
@@ -297,5 +305,8 @@ export function formatPresetLoadConfigSummary(
if (config.tensorParallel) {
parts.push("TP");
}
+ if (config.disableVision) {
+ parts.push("No vision");
+ }
return parts.length > 0 ? parts.join(" · ") : null;
}
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index d9425f6984c..1f2073efcf7 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -219,6 +219,7 @@ class VisionImageAdapter implements AttachmentAdapter {
loadedIsMultimodal: state.loadedIsMultimodal,
modelLoaded,
loadError: state.lastModelLoadError,
+ visionDisabledByUser: state.loadedVisionDisabledByUser,
mmprojFallbackReason: state.mmprojFallbackReason,
});
if (unavailableReason) {
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index a9b11abf77c..8c00e00c934 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -92,6 +92,7 @@ import { useChatProjects } from "./hooks/use-chat-projects";
import { confirmRemoteCodeIfNeeded } from "@/features/security";
import {
DEFAULT_MAX_SEQ_LENGTH,
+ DEFAULT_PER_MODEL_CONFIG,
normalizeMaxSeqLength,
resolveInitialConfig,
type PerModelConfig,
@@ -594,6 +595,9 @@ export function SharedComposer({
);
const lastModelLoadError = useChatRuntimeStore((s) => s.lastModelLoadError);
const loadedIsMultimodal = useChatRuntimeStore((s) => s.loadedIsMultimodal);
+ const loadedVisionDisabledByUser = useChatRuntimeStore(
+ (s) => s.loadedVisionDisabledByUser,
+ );
const mmprojFallbackReason = useChatRuntimeStore(
(s) => s.mmprojFallbackReason,
);
@@ -676,6 +680,7 @@ export function SharedComposer({
loadedIsMultimodal,
modelLoaded,
loadError: lastModelLoadError,
+ visionDisabledByUser: loadedVisionDisabledByUser,
mmprojFallbackReason,
});
const isCompareMode = Boolean(model1?.id || model2?.id);
@@ -1368,6 +1373,18 @@ export function SharedComposer({
: ownRemembered
? ownConfig.tensorParallel
: fallbackTensorParallel;
+ // The diffusion runner has no projector to skip, so the toggle is inert
+ // there for the same reason tensorParallel is.
+ //
+ // A pane with no saved config gets the per-model DEFAULT, not the store's
+ // current value, which belongs to whichever model is loaded. Where this parts
+ // company with tensorParallel: that one deliberately stands across models,
+ // while an unconfigured model is a model with vision on.
+ const effectiveDisableVision = resolvedIsDiffusion
+ ? false
+ : ownRemembered
+ ? ownConfig.disableVision
+ : DEFAULT_PER_MODEL_CONFIG.disableVision;
if (ownConfig.selectedGpuIds != null) {
await ensureGpuDeviceCache();
}
@@ -1435,6 +1452,7 @@ export function SharedComposer({
chat_template_override: effectiveChatTemplateOverride,
cache_type_kv: ownConfig.kvCacheDtype ?? null,
tensor_parallel: effectiveTensorParallel,
+ disable_vision: effectiveDisableVision,
// Scope the validate to the picked GPUs. GGUF-only, like the load
// below: a non-GGUF target must not inherit a hidden GGUF GPU pick.
...(targetIsGguf
@@ -1524,6 +1542,7 @@ export function SharedComposer({
speculative_type: effectiveSpeculativeType,
spec_draft_n_max: effectiveSpecDraftNMax,
tensor_parallel: effectiveTensorParallel,
+ disable_vision: effectiveDisableVision,
force_cancel_active:
compareStopDecision?.forceCancelActive ?? false,
...(targetIsGguf
@@ -1626,6 +1645,11 @@ export function SharedComposer({
: (ownConfig.llamaExtraArgs ?? null),
tensorParallel: resp.tensor_parallel ?? false,
loadedTensorParallel: resp.tensor_parallel ?? false,
+ loadedDisableVision: resp.disable_vision ?? false,
+ // Adopted from the echo like the knob above: this pane loaded its own
+ // model, so the editable value must follow it or Advanced Settings
+ // shows the other pane's Vision state.
+ disableVision: resp.disable_vision ?? false,
defaultChatTemplate: resp.chat_template ?? null,
chatTemplateOverride: effectiveChatTemplateOverride,
loadedChatTemplateOverride: effectiveChatTemplateOverride,
@@ -1640,7 +1664,9 @@ export function SharedComposer({
// GPU fields on every load path so the gate can't read stale.
loadedIsDiffusion: resp.is_diffusion ?? false,
loadedIsMultimodal: isMultimodalResponse(resp),
-
+ // Set alongside loadedIsMultimodal so the composer can say WHY images
+ // are unavailable in compare mode too.
+ loadedVisionDisabledByUser: resp.vision_disabled_by_user ?? false,
mmprojFallbackReason: resp.mmproj_fallback_reason ?? null,
activeModelIsLocal: resp.is_local_model ?? false,
// Record the context this pane loaded with (like the single-model path)
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
index e514eaa507f..0175468a27d 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -2624,6 +2624,15 @@ type ChatRuntimeStore = {
tensorParallel: boolean;
/** Backend-reported tensor-parallel state; null until first hydrated. */
loadedTensorParallel: boolean | null;
+ /** What the RUNNING server was loaded with, as opposed to what the control now
+ * shows: a pending per-model config is applied to disableVision before a switch
+ * captures its rollback baseline, so only this survives to restore. */
+ loadedDisableVision: boolean | null;
+ /** Load a vision GGUF without its mmproj, freeing the projector's VRAM. */
+ disableVision: boolean;
+ /** Backend-reported: image input is off by request, not by absence of a
+ * projector. Null until first hydrated. */
+ loadedVisionDisabledByUser: boolean | null;
/** GPU memory strategy for GGUF loads. "auto" = Unsloth picks GPUs and context
* to fit; "manual" = you own the offload (gpuLayers < 0 = Auto/--fit, >= 0
* pins layers + nCpuMoe). */
@@ -3721,6 +3730,9 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
loadedNUbatch: null,
tensorParallel: false,
loadedTensorParallel: null,
+ loadedDisableVision: null,
+ disableVision: false,
+ loadedVisionDisabledByUser: null,
gpuMemoryMode: readPersistedGpuMemoryMode(),
loadedGpuMemoryMode: null,
loadedCpuFallback: false,
@@ -4478,6 +4490,9 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
loadedNUbatch: null,
tensorParallel: false,
loadedTensorParallel: null,
+ loadedDisableVision: null,
+ disableVision: false,
+ loadedVisionDisabledByUser: null,
// Standing preference: survives unload, unlike the per-model knobs above.
gpuMemoryMode: readPersistedGpuMemoryMode(),
loadedGpuMemoryMode: null,
diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.ts
index 81aba150069..c9f65729e58 100644
--- a/studio/frontend/src/features/chat/types/api.ts
+++ b/studio/frontend/src/features/chat/types/api.ts
@@ -105,6 +105,12 @@ export interface LoadModelRequest {
* of by layer for GGUF models. Multi-GPU only; no effect on a single GPU.
*/
tensor_parallel?: boolean | null;
+ /**
+ * Load a vision-capable GGUF without its mmproj, freeing the VRAM the
+ * projector would occupy. Image input is unavailable for the session;
+ * text generation is unaffected.
+ */
+ disable_vision?: boolean | null;
/** GPU memory strategy for GGUF models. "auto" (default): Unsloth selects GPUs
* and caps context to fit VRAM. "manual": you own the offload -- gpu_layers
* -1 (Auto) hands sizing to llama.cpp's --fit, >= 0 pins layers/n_cpu_moe. */
@@ -254,6 +260,12 @@ export interface LoadModelResponse {
spec_draft_n_max?: number | null;
/** Whether tensor-parallel split (--split-mode tensor) is active. */
tensor_parallel?: boolean;
+ /** The load ran with the vision projector deliberately left unloaded. Echoes the
+ * request, so it round-trips the Advanced Settings switch even on a GGUF that
+ * never had a projector -- unlike vision_disabled_by_user below. */
+ disable_vision?: boolean;
+ /** Image input is off because the user asked, not because the mmproj is missing. */
+ vision_disabled_by_user?: boolean;
gpu_memory_mode?: "auto" | "manual";
gpu_layers?: number;
/** Set when an automatic Vulkan startup crash was recovered by loading on CPU. */
@@ -347,6 +359,12 @@ export interface InferenceStatusResponse {
spec_draft_n_max?: number | null;
/** Whether tensor-parallel split (--split-mode tensor) is active. */
tensor_parallel?: boolean;
+ /** The load ran with the vision projector deliberately left unloaded. Echoes the
+ * request, so it round-trips the Advanced Settings switch even on a GGUF that
+ * never had a projector -- unlike vision_disabled_by_user below. */
+ disable_vision?: boolean;
+ /** Image input is off because the user asked, not because the mmproj is missing. */
+ vision_disabled_by_user?: boolean;
gpu_memory_mode?: "auto" | "manual";
gpu_layers?: number;
/** Set while the active model is a recovered CPU-only Vulkan load. */
diff --git a/studio/frontend/src/features/chat/utils/image-input-support.ts b/studio/frontend/src/features/chat/utils/image-input-support.ts
index 54d2873a4bf..7b75817de32 100644
--- a/studio/frontend/src/features/chat/utils/image-input-support.ts
+++ b/studio/frontend/src/features/chat/utils/image-input-support.ts
@@ -25,6 +25,7 @@ export function getImageInputUnavailableReason({
loadedIsMultimodal,
modelLoaded,
loadError,
+ visionDisabledByUser,
mmprojFallbackReason,
}: {
activeModel?: ChatModelSummary;
@@ -39,6 +40,9 @@ export function getImageInputUnavailableReason({
modelLoaded: boolean;
// Runtime lastModelLoadError; lets the no-model branch flag a failed load.
loadError?: string | null;
+ // Backend-reported: image input is off because Vision was switched off for this
+ // model, not because no projector could be found.
+ visionDisabledByUser?: boolean | null;
mmprojFallbackReason?: MmprojFallbackReason | null;
}): string | null {
if (isExternalModel) {
@@ -86,6 +90,12 @@ export function getImageInputUnavailableReason({
}
}
const label = activeModel?.name || activeModel?.id || "Current model";
+ // Before the generic message below, which would otherwise send someone who
+ // switched Vision off hunting for a vision model with a valid mmproj. The
+ // model is capable and the projector is fine; the setting is what is in the way.
+ if (visionDisabledByUser) {
+ return `Vision is turned off for ${label}. Turn it back on in the model's Advanced Settings to attach images.`;
+ }
const suffix = activeModel?.isGguf
? " with a valid mmproj before attaching images."
: " before attaching images.";
diff --git a/studio/frontend/src/features/chat/utils/mmproj-fallback.ts b/studio/frontend/src/features/chat/utils/mmproj-fallback.ts
index 30558c566b1..6afc9bbc89f 100644
--- a/studio/frontend/src/features/chat/utils/mmproj-fallback.ts
+++ b/studio/frontend/src/features/chat/utils/mmproj-fallback.ts
@@ -14,8 +14,15 @@ export const CPU_FALLBACK_MESSAGE =
"The auto-selected Vulkan backend crashed during startup, so GPU acceleration is disabled for this model session.";
const MMPROJ_FALLBACK_MESSAGES: Record<MmprojFallbackReason, string> = {
+ // Three routes reach this one placement: the fit estimate predicting the
+ // projector will not fit in VRAM, a GPU allocation failure at startup, and a
+ // bare signal crash with no non-projector diagnostic. So the message names the
+ // outcome and no cause. "Could not start on the GPU" is untrue of the predicted
+ // route, which never attempts a GPU load, and "does not fit in VRAM" is untrue
+ // of the crash routes -- and that one is worse than vague, because it sends
+ // someone whose GPU runtime is broken off to cut context and offload layers.
cpu_offload:
- "The vision projector could not start on the GPU, so Studio moved it to system memory. Image input remains available, but image processing may be slower.",
+ "Studio is running the vision projector in system memory rather than on the GPU. Image input remains available, but image processing may be slower.",
projector_incompatible:
"The vision projector is incompatible with the installed llama.cpp build, so Studio reloaded this model in text-only mode. Update Studio, then reload the model to restore image input.",
projector_startup_failure:
diff --git a/studio/frontend/src/features/model-picker/api/model-overrides.ts b/studio/frontend/src/features/model-picker/api/model-overrides.ts
index f717791831a..e614938f690 100644
--- a/studio/frontend/src/features/model-picker/api/model-overrides.ts
+++ b/studio/frontend/src/features/model-picker/api/model-overrides.ts
@@ -41,6 +41,8 @@ export interface ApiModelOverride {
// biome-ignore lint/style/useNamingConvention: API schema
tensor_parallel?: boolean;
// biome-ignore lint/style/useNamingConvention: API schema
+ disable_vision?: boolean;
+ // biome-ignore lint/style/useNamingConvention: API schema
chat_template_override?: string;
// biome-ignore lint/style/useNamingConvention: API schema
gpu_memory_mode?: "auto" | "manual";
@@ -304,6 +306,9 @@ export function toApiOverride(config: PerModelConfig | null): ApiModelOverride {
if (config.tensorParallel) {
payload.tensor_parallel = true;
}
+ if (config.disableVision) {
+ payload.disable_vision = true;
+ }
if (config.chatTemplateOverride?.trim()) {
payload.chat_template_override = config.chatTemplateOverride;
}
diff --git a/studio/frontend/src/features/model-picker/components/model-config-page.tsx b/studio/frontend/src/features/model-picker/components/model-config-page.tsx
index 3f3c0eb1c81..d9cd1fa588b 100644
--- a/studio/frontend/src/features/model-picker/components/model-config-page.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-config-page.tsx
@@ -181,6 +181,7 @@ function hasNonDefaultAdvanced(config: PerModelConfig): boolean {
config.nBatch != null ||
config.nUbatch != null ||
config.tensorParallel ||
+ config.disableVision ||
config.chatTemplateOverride != null ||
// Hidden flags can change what the model does, so a panel that opens collapsed
// over them says "defaults" about a load that is anything but.
@@ -205,6 +206,7 @@ function withoutUnsupportedDiffusionSettings(
config.gpuLayers == null &&
config.nCpuMoe == null &&
!config.tensorParallel &&
+ !config.disableVision &&
config.nBatch == null &&
config.nUbatch == null &&
(config.llamaExtraArgs == null || config.llamaExtraArgs.length === 0) &&
@@ -218,6 +220,7 @@ function withoutUnsupportedDiffusionSettings(
gpuLayers: undefined,
nCpuMoe: undefined,
tensorParallel: false,
+ disableVision: false,
// the diffusion runner ignores the llama-server batch flags
nBatch: null,
nUbatch: null,
@@ -1216,6 +1219,29 @@ function GgufAdvancedSettings({
/>
</div>
+ {/* withoutUnsupportedDiffusionSettings forces disableVision back to false on a
+ diffusion model and the diffusion runner never reads it, so the switch would
+ flip back under the pointer. Gated for the same reason the batch rows are. */}
+ {!isDiffusion && (
+ <div className={ROW_CLASS}>
+ <div className="flex min-w-0 items-center gap-1.5">
+ <span className={LABEL_CLASS}>Vision</span>
+ <InfoHint>
+ Loads the vision projector so the model can read images. Turning it
+ off frees the VRAM the projector would use, which can leave room for
+ more layers on the GPU. Text generation is unaffected either way.
+ Models that ship no projector have nothing to load, so the setting
+ does nothing for them.
+ </InfoHint>
+ </div>
+ <Switch
+ className="panel-switch shrink-0"
+ checked={!config.disableVision}
+ onCheckedChange={(checked) => update({ disableVision: !checked })}
+ />
+ </div>
+ )}
+
<GpuMemorySettings
config={config}
update={update}
diff --git a/studio/frontend/src/features/model-picker/hooks/use-active-model-config.ts b/studio/frontend/src/features/model-picker/hooks/use-active-model-config.ts
index a05aa33afec..92ad1975141 100644
--- a/studio/frontend/src/features/model-picker/hooks/use-active-model-config.ts
+++ b/studio/frontend/src/features/model-picker/hooks/use-active-model-config.ts
@@ -29,6 +29,7 @@ export function useActiveModelConfig(): ActiveModelConfigState {
const nBatch = useChatRuntimeStore((s) => s.nBatch);
const nUbatch = useChatRuntimeStore((s) => s.nUbatch);
const tensorParallel = useChatRuntimeStore((s) => s.tensorParallel);
+ const disableVision = useChatRuntimeStore((s) => s.disableVision);
const chatTemplateOverride = useChatRuntimeStore(
(s) => s.chatTemplateOverride,
);
@@ -66,6 +67,7 @@ export function useActiveModelConfig(): ActiveModelConfigState {
nBatch: nBatch ?? null,
nUbatch: nUbatch ?? null,
tensorParallel: tensorParallel ?? false,
+ disableVision: disableVision ?? false,
chatTemplateOverride: chatTemplateOverride ?? null,
};
if (!isGguf) {
@@ -92,6 +94,7 @@ export function useActiveModelConfig(): ActiveModelConfigState {
nBatch,
nUbatch,
tensorParallel,
+ disableVision,
chatTemplateOverride,
gpuMemoryMode,
gpuLayers,
diff --git a/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts b/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts
index 4290841f3e3..ce5892b17e2 100644
--- a/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts
+++ b/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts
@@ -62,6 +62,11 @@ export function applyPerModelConfigToRuntime(
tensorParallel: options.isDiffusion
? false
: (config.tensorParallel ?? false),
+ // The diffusion runner has no projector to skip, so the toggle is inert
+ // there for the same reason tensorParallel is.
+ disableVision: options.isDiffusion
+ ? false
+ : (config.disableVision ?? false),
chatTemplateOverride: cleanTemplate(config.chatTemplateOverride),
// GPU Memory knobs are per-model (GGUF-only). Absent = defaults; the mode is
// a standing preference so an absent mode falls back to the persisted one.
@@ -111,6 +116,7 @@ export function currentRuntimePerModelConfig(
nBatch: s.nBatch ?? null,
nUbatch: s.nUbatch ?? null,
tensorParallel: s.tensorParallel ?? false,
+ disableVision: s.disableVision ?? false,
chatTemplateOverride: cleanTemplate(s.chatTemplateOverride),
// Snapshot the live GPU knobs too so a failed switch rolls the previous
// model's GPU Memory settings back (see applyPerModelConfigToRuntime). The
@@ -140,6 +146,7 @@ export function perModelConfigsEqual(
(a.nBatch ?? null) === (b.nBatch ?? null) &&
(a.nUbatch ?? null) === (b.nUbatch ?? null) &&
Boolean(a.tensorParallel) === Boolean(b.tensorParallel) &&
+ Boolean(a.disableVision) === Boolean(b.disableVision) &&
cleanTemplate(a.chatTemplateOverride) ===
cleanTemplate(b.chatTemplateOverride) &&
extraArgsSignature(a.llamaExtraArgs) === extraArgsSignature(b.llamaExtraArgs) &&
diff --git a/studio/frontend/src/features/model-picker/model-config/config-signature.ts b/studio/frontend/src/features/model-picker/model-config/config-signature.ts
index 8d3d1cf8348..fcf0d71d341 100644
--- a/studio/frontend/src/features/model-picker/model-config/config-signature.ts
+++ b/studio/frontend/src/features/model-picker/model-config/config-signature.ts
@@ -58,6 +58,7 @@ export function loadedConfigSignature(
config.nBatch ?? "",
config.nUbatch ?? "",
config.tensorParallel ? "1" : "0",
+ config.disableVision ? "1" : "0",
config.chatTemplateOverride == null
? ""
: `${config.chatTemplateOverride.length}:${hashString(config.chatTemplateOverride)}`,
diff --git a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts b/studio/frontend/src/features/model-picker/model-config/per-model-config.ts
index e2f9ba353ae..e6cfadf6646 100644
--- a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts
+++ b/studio/frontend/src/features/model-picker/model-config/per-model-config.ts
@@ -24,6 +24,8 @@ export interface PerModelConfig {
nBatch: number | null;
nUbatch: number | null;
tensorParallel: boolean;
+ /** Load a vision GGUF without its mmproj, freeing the projector's VRAM. */
+ disableVision: boolean;
chatTemplateOverride: string | null;
/**
* Pass-through llama-server args, one argv token per entry, appended after
@@ -57,6 +59,7 @@ export const DEFAULT_PER_MODEL_CONFIG: PerModelConfig = {
nBatch: null,
nUbatch: null,
tensorParallel: false,
+ disableVision: false,
chatTemplateOverride: null,
};
@@ -162,9 +165,11 @@ export {
const STORAGE_KEY = "unsloth_model_configs";
const LEGACY_STORAGE_KEY = "unsloth_load_settings";
const LEGACY_MIGRATION_FLAG = "unsloth_model_configs_migrated";
-// v2 added nBatch / nUbatch and v3 llamaExtraArgs; a client from before either
-// would normalize the field it does not know straight back out of the record.
-const STORAGE_SCHEMA_VERSION = 3;
+// v2 added nBatch / nUbatch, v3 llamaExtraArgs and v4 disableVision; a client
+// from before any of them would normalize the field it does not know straight
+// back out of the record.
+const STORAGE_SCHEMA_VERSION = 4;
+const PRE_VISION_SCHEMA_VERSION = 3;
const PRE_EXTRA_ARGS_SCHEMA_VERSION = 2;
const PRE_BATCH_SCHEMA_VERSION = 1;
const MAX_ENTRIES = 500;
@@ -189,6 +194,7 @@ const STORED_CONFIG_FIELDS = new Set([
"nBatch",
"nUbatch",
"tensorParallel",
+ "disableVision",
"chatTemplateOverride",
"llamaExtraArgs",
"gpuMemoryMode",
@@ -515,6 +521,8 @@ function legacyEntryToConfig(raw: Record<string, unknown>): PerModelConfig {
nParallel: null,
tensorParallel:
typeof raw.tensorParallel === "boolean" ? raw.tensorParallel : false,
+ disableVision:
+ typeof raw.disableVision === "boolean" ? raw.disableVision : false,
chatTemplateOverride: null,
// Absent, not null: a legacy blob predates the editor, and the server may well
// hold flags set from the CLI. Reading that as "cleared" would wipe them on the
@@ -711,6 +719,10 @@ function normalizeV1(partial: RawConfig): PerModelConfig {
typeof partial.tensorParallel === "boolean"
? partial.tensorParallel
: DEFAULT_PER_MODEL_CONFIG.tensorParallel,
+ disableVision:
+ typeof partial.disableVision === "boolean"
+ ? partial.disableVision
+ : DEFAULT_PER_MODEL_CONFIG.disableVision,
chatTemplateOverride:
typeof partial.chatTemplateOverride === "string" &&
isChatTemplateWithinLimit(partial.chatTemplateOverride)
@@ -746,9 +758,14 @@ function toStoredConfig(config: PerModelConfig): StoredPerModelConfig {
// Stamped with the OLDEST version that still understands every field present, so
// a record an older client can safely rewrite is not needlessly locked away from
// it. Only a record carrying a newer field is put out of that client's reach.
- const version =
- normalized.llamaExtraArgs != null && normalized.llamaExtraArgs.length > 0
- ? STORAGE_SCHEMA_VERSION
+ // Only a TRUE disableVision needs the v4 stamp. The default is false, which
+ // is what a pre-vision client reconstructs anyway, so a record that merely
+ // carries the key at its default loses nothing by staying in that client's
+ // reach -- and stamping every record v4 would put the whole store out of it.
+ const version = normalized.disableVision
+ ? STORAGE_SCHEMA_VERSION
+ : normalized.llamaExtraArgs != null && normalized.llamaExtraArgs.length > 0
+ ? PRE_VISION_SCHEMA_VERSION
: normalized.nBatch != null || normalized.nUbatch != null
? PRE_EXTRA_ARGS_SCHEMA_VERSION
: PRE_BATCH_SCHEMA_VERSION;
@@ -869,6 +886,8 @@ export function isDefaultConfig(config: PerModelConfig): boolean {
config.nUbatch == null &&
Boolean(config.tensorParallel) ===
Boolean(DEFAULT_PER_MODEL_CONFIG.tensorParallel) &&
+ Boolean(config.disableVision) ===
+ Boolean(DEFAULT_PER_MODEL_CONFIG.disableVision) &&
(config.chatTemplateOverride ?? null) === null &&
// Or a config whose only change is Extra Arguments reads as default, and
// savePerModelConfig deletes the entry it was asked to remember.
diff --git a/studio/frontend/tests/adopt-legacy-config-key.test.ts b/studio/frontend/tests/adopt-legacy-config-key.test.ts
index 16ee3686981..df582b1b813 100644
--- a/studio/frontend/tests/adopt-legacy-config-key.test.ts
+++ b/studio/frontend/tests/adopt-legacy-config-key.test.ts
@@ -41,6 +41,7 @@ function config(
nBatch: null,
nUbatch: null,
tensorParallel: false,
+ disableVision: false,
chatTemplateOverride,
};
}
diff --git a/studio/frontend/tests/batch-schema-version.test.ts b/studio/frontend/tests/batch-schema-version.test.ts
index 0c12d7572be..85c009c891d 100644
--- a/studio/frontend/tests/batch-schema-version.test.ts
+++ b/studio/frontend/tests/batch-schema-version.test.ts
@@ -29,6 +29,7 @@ function config(nBatch: number | null, nUbatch: number | null = null) {
nBatch,
nUbatch,
tensorParallel: false,
+ disableVision: false,
chatTemplateOverride: null,
};
}
diff --git a/studio/frontend/tests/batch-upgrade-downgrade-compat.test.ts b/studio/frontend/tests/batch-upgrade-downgrade-compat.test.ts
index c4f1ae7604e..5a37d3b1afd 100644
--- a/studio/frontend/tests/batch-upgrade-downgrade-compat.test.ts
+++ b/studio/frontend/tests/batch-upgrade-downgrade-compat.test.ts
@@ -41,6 +41,7 @@ function config(overrides: Record<string, unknown> = {}) {
nBatch: null,
nUbatch: null,
tensorParallel: false,
+ disableVision: false,
chatTemplateOverride: null,
...overrides,
};
diff --git a/studio/frontend/tests/mmproj-fallback.test.ts b/studio/frontend/tests/mmproj-fallback.test.ts
index d356ca2b27f..175b21fbd33 100644
--- a/studio/frontend/tests/mmproj-fallback.test.ts
+++ b/studio/frontend/tests/mmproj-fallback.test.ts
@@ -121,6 +121,19 @@ test("attachment and send gates forward projector fallback state", () => {
assert.match(interactiveLoad, /force_reload:\s*forceReload/);
});
+// cpu_offload has three producers: the fit estimate predicting the projector will not
+// fit in VRAM, a GPU allocation failure at startup, and a bare signal crash with no
+// non-projector diagnostic. So the message names the outcome and no cause at all.
+test("the CPU projector message describes the placement, not one route to it", () => {
+ const message = mmprojFallbackMessage("cpu_offload");
+ assert.match(message, IMAGE_INPUT_AVAILABLE);
+ // Untrue of the predicted pin, which never attempts a GPU load.
+ assert.doesNotMatch(message, /could not start|failed|crash/i);
+ // Untrue of both crash routes, and worse than vague there: it sends someone whose
+ // GPU runtime is broken off to cut context and offload layers.
+ assert.doesNotMatch(message, /VRAM|fit|memory pressure|out of memory/i);
+});
+
// The combination neither load path handled. Both wrote
// `mmproj ? mmprojMessage : cpu ? cpuMessage : undefined`, so a session that lost GPU
// acceleration AND vision reported only the vision loss, and the user was never told
diff --git a/studio/frontend/tests/model-config-instance-key.test.ts b/studio/frontend/tests/model-config-instance-key.test.ts
index eab3613872e..f70c05d85bb 100644
--- a/studio/frontend/tests/model-config-instance-key.test.ts
+++ b/studio/frontend/tests/model-config-instance-key.test.ts
@@ -21,6 +21,7 @@ const LIVE: PerModelConfig = {
nBatch: 4096,
nUbatch: 1024,
tensorParallel: true,
+ disableVision: false,
chatTemplateOverride: null,
gpuMemoryMode: "manual",
gpuLayers: 24,
@@ -39,6 +40,7 @@ const SAVED: PerModelConfig = {
nBatch: null,
nUbatch: null,
tensorParallel: false,
+ disableVision: false,
chatTemplateOverride: null,
gpuMemoryMode: "auto",
gpuLayers: -1,
diff --git a/studio/frontend/tests/model-identity.test.ts b/studio/frontend/tests/model-identity.test.ts
index 004d332e2ea..2219d622550 100644
--- a/studio/frontend/tests/model-identity.test.ts
+++ b/studio/frontend/tests/model-identity.test.ts
@@ -55,6 +55,7 @@ function config(maxSeqLength: number, kvCacheDtype: string | null = null) {
nBatch: null,
nUbatch: null,
tensorParallel: false,
+ disableVision: false,
chatTemplateOverride: null,
};
}
diff --git a/studio/frontend/tests/resident-config-match-accelerator-matrix.test.ts b/studio/frontend/tests/resident-config-match-accelerator-matrix.test.ts
index df46797528d..664c21ea717 100644
--- a/studio/frontend/tests/resident-config-match-accelerator-matrix.test.ts
+++ b/studio/frontend/tests/resident-config-match-accelerator-matrix.test.ts
@@ -72,6 +72,7 @@ const BLANK = {
nBatch: null,
nUbatch: null,
tensorParallel: false,
+ disableVision: false,
chatTemplateOverride: null,
};
@@ -231,6 +232,12 @@ const FIELDS: FieldCase[] = [
same: true,
different: false,
},
+ {
+ key: "disableVision",
+ statusKey: "disable_vision",
+ same: true,
+ different: false,
+ },
];
for (const [accelerator, base] of Object.entries(ACCELERATORS)) {
diff --git a/studio/frontend/tests/resident-config-match.test.ts b/studio/frontend/tests/resident-config-match.test.ts
index b6f7cf01a11..941d68f5a5c 100644
--- a/studio/frontend/tests/resident-config-match.test.ts
+++ b/studio/frontend/tests/resident-config-match.test.ts
@@ -33,6 +33,7 @@ const DEFAULT_ISH = {
nBatch: null,
nUbatch: null,
tensorParallel: false,
+ disableVision: false,
chatTemplateOverride: null,
} as const;
@@ -47,6 +48,7 @@ const BLANK = {
nBatch: null,
nUbatch: null,
tensorParallel: false,
+ disableVision: false,
chatTemplateOverride: null,
};
diff --git a/studio/frontend/tests/resident-remembered-config.test.ts b/studio/frontend/tests/resident-remembered-config.test.ts
index b88c0e4bb1c..dfeb56147b8 100644
--- a/studio/frontend/tests/resident-remembered-config.test.ts
+++ b/studio/frontend/tests/resident-remembered-config.test.ts
@@ -38,6 +38,7 @@ function config(nParallel: number | null, maxSeqLength: number | null = null) {
nBatch: null,
nUbatch: null,
tensorParallel: false,
+ disableVision: false,
chatTemplateOverride: null,
};
}
diff --git a/studio/frontend/tests/vision-switch-seed.test.ts b/studio/frontend/tests/vision-switch-seed.test.ts
new file mode 100644
index 00000000000..c1f10be56e7
--- /dev/null
+++ b/studio/frontend/tests/vision-switch-seed.test.ts
@@ -0,0 +1,145 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// When /api/inference/status may write the Vision switch. The control is what the
+// next load or Apply sends; the loaded baseline is what the resident server is
+// running. They are seeded on different rules, which is what lets them diverge.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const { shouldSeedVisionSwitch } = await import(
+ "../src/features/chat/lib/resolve-vision-switch-seed.ts"
+);
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const APPLIER = readFileSync(
+ path.join(
+ HERE,
+ "..",
+ "src/features/chat/lib/apply-inference-status-to-store.ts",
+ ),
+ "utf8",
+);
+
+function seed(
+ incoming: boolean,
+ previous: {
+ disableVision: boolean;
+ loadedDisableVision: boolean | null;
+ loadedVisionDisabledByUser: boolean | null;
+ },
+ hydratingExistingModel = false,
+): boolean {
+ return shouldSeedVisionSwitch({ incoming, previous, hydratingExistingModel });
+}
+
+test("an unseeded pair takes the running value", () => {
+ assert.equal(
+ seed(true, {
+ disableVision: false,
+ loadedDisableVision: null,
+ loadedVisionDisabledByUser: null,
+ }),
+ true,
+ );
+});
+
+test("a model or variant change reseeds the control it just left behind", () => {
+ assert.equal(
+ seed(
+ true,
+ {
+ disableVision: false,
+ loadedDisableVision: false,
+ loadedVisionDisabledByUser: false,
+ },
+ true,
+ ),
+ true,
+ );
+});
+
+test("a steady poll that agrees with the baseline writes nothing", () => {
+ assert.equal(
+ seed(false, {
+ disableVision: true,
+ loadedDisableVision: false,
+ loadedVisionDisabledByUser: false,
+ }),
+ false,
+ );
+});
+
+test("a poll that agrees with the baseline is not a reseed", () => {
+ // Nothing moved and nothing is pending, so the answer is "no reseed needed".
+ // Writing the incoming value anyway would be a no-op in the store, which is why
+ // this is asserted on the resolver's answer rather than on a store effect: the
+ // contract is what a future caller branches on.
+ assert.equal(
+ seed(false, {
+ disableVision: false,
+ loadedDisableVision: false,
+ loadedVisionDisabledByUser: false,
+ }),
+ false,
+ );
+});
+
+test("an external reload of the same model resyncs the control", () => {
+ // Another tab or an API client loaded this model with the opposite setting.
+ // loadedDisableVision and the image gate follow it unguarded, so leaving the
+ // control behind shows Advanced Settings the opposite of the running projector
+ // and arms the next Apply to undo the external change.
+ assert.equal(
+ seed(true, {
+ disableVision: false,
+ loadedDisableVision: false,
+ loadedVisionDisabledByUser: false,
+ }),
+ true,
+ );
+});
+
+test("a pending local edit survives an external reload", () => {
+ // The control has been moved off its baseline and not applied yet. That is the
+ // user's unapplied intent and a poll must not overwrite it, even though the
+ // running server moved underneath.
+ assert.equal(
+ seed(true, {
+ disableVision: true,
+ loadedDisableVision: false,
+ loadedVisionDisabledByUser: false,
+ }),
+ false,
+ );
+});
+
+test("a seeded pair with no baseline yet is left alone", () => {
+ // Nothing to compare against, so there is no evidence the server moved.
+ assert.equal(
+ seed(true, {
+ disableVision: false,
+ loadedDisableVision: null,
+ loadedVisionDisabledByUser: false,
+ }),
+ false,
+ );
+});
+
+test("the applier routes the control through the resolver", () => {
+ // Re-inlining the old `loadedVisionDisabledByUser === null` guard would restore
+ // the divergence without failing any of the cases above.
+ assert.match(APPLIER, /shouldSeedVisionSwitch\(\{/);
+ assert.doesNotMatch(
+ APPLIER,
+ /\(prevState\.loadedVisionDisabledByUser === null \|\|\s*\n?\s*hydratingExistingModel\) && \{\s*\n\s*disableVision:/,
+ );
+});
diff --git a/studio/frontend/tests/vision-toggle-config.test.ts b/studio/frontend/tests/vision-toggle-config.test.ts
new file mode 100644
index 00000000000..722c43972c3
--- /dev/null
+++ b/studio/frontend/tests/vision-toggle-config.test.ts
@@ -0,0 +1,142 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Persistence for the Disable Vision toggle. The per-model config store has no
+// migration step, so a new field has to survive both directions on its own: a
+// blob written before the field existed must still load, and a blob carrying it
+// must not be silently erased by a build that has never heard of it.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import type { PerModelConfig } from "../src/features/model-picker/model-config/per-model-config.ts";
+import {
+ installLocalStorageFake,
+ registerBundlerResolver,
+} from "./helpers/kit.ts";
+
+registerBundlerResolver();
+const { store } = installLocalStorageFake();
+
+const {
+ DEFAULT_PER_MODEL_CONFIG,
+ normalizePerModelConfig,
+ resolveInitialConfig,
+ savePerModelConfig,
+} = await import(
+ "../src/features/model-picker/model-config/per-model-config.ts"
+);
+const { loadedConfigSignature } = await import(
+ "../src/features/model-picker/model-config/config-signature.ts"
+);
+
+const STORAGE_KEY = "unsloth_model_configs";
+// Ceiling shipped by the last build BEFORE the toggle. A record stamped at or
+// below it is readable, and therefore erasable, by that build.
+const PRE_VISION_CEILING = 3;
+
+function config(overrides: Partial<PerModelConfig> = {}): PerModelConfig {
+ return { ...DEFAULT_PER_MODEL_CONFIG, ...overrides };
+}
+
+function storedRecord(): Record<string, unknown> {
+ const raw = store.get(STORAGE_KEY);
+ assert.ok(raw, "nothing was persisted");
+ const map = JSON.parse(raw) as Record<string, Record<string, unknown>>;
+ const keys = Object.keys(map);
+ assert.equal(keys.length, 1, `expected one record, got ${keys.length}`);
+ return map[keys[0]];
+}
+
+test("vision is on by default", () => {
+ assert.equal(DEFAULT_PER_MODEL_CONFIG.disableVision, false);
+});
+
+test("a blob written before the toggle existed still loads", () => {
+ // The key is genuinely absent, not present-and-undefined, the way an older
+ // build's JSON would have it.
+ const { disableVision: _omitted, ...legacy } = DEFAULT_PER_MODEL_CONFIG;
+ assert.equal(
+ normalizePerModelConfig(legacy as Record<string, unknown>).disableVision,
+ false,
+ );
+ // And junk in the slot must not silently drop the projector.
+ for (const bad of ["true", 1, null, {}]) {
+ assert.equal(
+ normalizePerModelConfig({
+ ...DEFAULT_PER_MODEL_CONFIG,
+ disableVision: bad,
+ }).disableVision,
+ false,
+ `for ${JSON.stringify(bad)}`,
+ );
+ }
+});
+
+test("the toggle round-trips through save and load", () => {
+ store.clear();
+ savePerModelConfig(
+ "some/vision-gguf",
+ "Q4_K_M",
+ config({ disableVision: true }),
+ );
+ assert.equal(
+ resolveInitialConfig("some/vision-gguf", "Q4_K_M").config.disableVision,
+ true,
+ );
+});
+
+test("an older build cannot reach a vision-off record and erase it", () => {
+ store.clear();
+ savePerModelConfig(
+ "some/vision-gguf",
+ "Q4_K_M",
+ config({ disableVision: true }),
+ );
+ const record = storedRecord();
+ assert.equal(record.disableVision, true);
+ assert.ok(
+ (record.version as number) > PRE_VISION_CEILING,
+ `stamped v${record.version}; a pre-feature build (ceiling ${PRE_VISION_CEILING}) ` +
+ "would accept this record, drop disableVision, and erase it on its next save",
+ );
+
+ // Replay what that build actually does: read every record it is allowed to
+ // interpret, drop the key it does not know, write the result back.
+ const map = JSON.parse(store.get(STORAGE_KEY) as string) as Record<
+ string,
+ Record<string, unknown>
+ >;
+ let rewrote = false;
+ for (const key of Object.keys(map)) {
+ const version =
+ typeof map[key].version === "number" ? (map[key].version as number) : 0;
+ if (version > PRE_VISION_CEILING) continue;
+ const { disableVision: _dropped, ...known } = map[key];
+ map[key] = known;
+ rewrote = true;
+ }
+ store.set(STORAGE_KEY, JSON.stringify(map));
+ assert.equal(rewrote, false, "the old build was able to rewrite the record");
+ assert.equal(
+ resolveInitialConfig("some/vision-gguf", "Q4_K_M").config.disableVision,
+ true,
+ );
+});
+
+test("a record with no new field stays inside an older build's reach", () => {
+ // The other half of the rule: only a record carrying a NEWER field is put out
+ // of reach. Stamping every record v4 would quarantine the whole store.
+ store.clear();
+ savePerModelConfig("some/gguf", "Q4_K_M", config({ kvCacheDtype: "q8_0" }));
+ assert.ok((storedRecord().version as number) <= PRE_VISION_CEILING);
+});
+
+test("flipping the toggle changes the signature, so a reload is not deduped away", () => {
+ // Without this the server stays up with the projector resident while the UI
+ // shows Vision as off.
+ assert.notEqual(
+ loadedConfigSignature(config({ disableVision: false })),
+ loadedConfigSignature(config({ disableVision: true })),
+ );
+});
diff --git a/studio/frontend/tests/vision-toggle-gating.test.ts b/studio/frontend/tests/vision-toggle-gating.test.ts
new file mode 100644
index 00000000000..7deb31a11d1
--- /dev/null
+++ b/studio/frontend/tests/vision-toggle-gating.test.ts
@@ -0,0 +1,319 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// What the Disable Vision toggle is allowed to reach: the status reseed that
+// teaches a fresh tab the running model has no projector, the MLX half of
+// Advanced Settings which must never show the row, and the composer's refusal
+// message when the toggle is what is in the way.
+//
+// The reseed and the MLX row are checked at the source. The applier is one large
+// object literal with no seam to call, and the config page cannot be rendered
+// (the repo has no render harness, and importing it pulls a directory import
+// Node cannot resolve). Both follow the chat-template and llama-extra-args seed
+// tests next door.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { getImageInputUnavailableReason } from "../src/features/chat/utils/image-input-support.ts";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const read = (relative: string) =>
+ readFileSync(path.join(HERE, "..", relative), "utf8");
+
+const APPLIER = read(
+ "src/features/chat/lib/apply-inference-status-to-store.ts",
+);
+const API_TYPES = read("src/features/chat/types/api.ts");
+const CONFIG_PAGE = read(
+ "src/features/model-picker/components/model-config-page.tsx",
+);
+
+test("both response types carry the raw disable_vision echo", () => {
+ // vision_disabled_by_user is additionally gated on the model HAVING a
+ // projector, so it cannot round-trip the switch on a text-only GGUF. The seed
+ // needs the request the load actually ran with, on the load response and the
+ // status poll alike.
+ assert.equal(
+ API_TYPES.match(/^ {2}disable_vision\?: boolean;$/gm)?.length,
+ 2,
+ );
+});
+
+test("the applier seeds the switch from status, through the seed resolver", () => {
+ // Unguarded it would fight the user: every poll would stamp the running model's
+ // value over a switch that was flipped but not yet applied. The rule is in
+ // shouldSeedVisionSwitch, which vision-switch-seed.test.ts pins case by case;
+ // this only checks the applier still routes through it.
+ assert.match(
+ APPLIER,
+ /status\.disable_vision !== undefined &&\s*\n\s*shouldSeedVisionSwitch\(\{/,
+ );
+ // An older backend that omits the field must change nothing at all, so no
+ // `?? false` may creep in here.
+ assert.doesNotMatch(
+ APPLIER,
+ /disableVision: status\.disable_vision \?\? false/,
+ );
+});
+
+test("the composer's own mirror of the flag stays unguarded", () => {
+ // loadedVisionDisabledByUser is what the image gate reads. It mirrors the live
+ // load rather than a user setting, so every poll must land on it; the seed
+ // guard here would freeze the refusal string at the first read.
+ assert.match(
+ APPLIER,
+ /status\.vision_disabled_by_user !== undefined && \{\s*\n\s*loadedVisionDisabledByUser: status\.vision_disabled_by_user,/,
+ );
+});
+
+test("the Vision row exists only in the GGUF half of Advanced Settings", () => {
+ // MLX is a separate engine with no mmproj to skip, so the row must not render
+ // for it. Checked by exact wiring, so a second switch added elsewhere fails
+ // here rather than quietly widening the control's reach.
+ const lines = CONFIG_PAGE.split("\n");
+ const bodyOf = (name: string): string => {
+ const start = lines.findIndex((line) =>
+ line.startsWith(`function ${name}(`),
+ );
+ assert.notEqual(start, -1, `no top-level function ${name}`);
+ let end = lines.length;
+ for (let i = start + 1; i < lines.length; i++) {
+ if (/^(export )?function \w+\(/.test(lines[i])) {
+ end = i;
+ break;
+ }
+ }
+ return lines.slice(start, end).join("\n");
+ };
+ const gguf = bodyOf("GgufAdvancedSettings");
+ const mlx = bodyOf("MlxAdvancedSettings");
+ const wiring = "checked={!config.disableVision}";
+
+ assert.equal(
+ CONFIG_PAGE.split(wiring).length - 1,
+ 1,
+ "expected exactly one Vision switch in the file",
+ );
+ assert.ok(
+ gguf.includes(wiring),
+ "Vision switch is not in GgufAdvancedSettings",
+ );
+ assert.ok(
+ !mlx.includes(wiring),
+ "Vision switch leaked into MlxAdvancedSettings",
+ );
+ assert.ok(
+ !mlx.includes("disableVision"),
+ "MlxAdvancedSettings reads disableVision, which it cannot act on",
+ );
+ assert.ok(gguf.includes(">Vision</span>"));
+
+ // And the GGUF half only renders under target.isGguf, so a non-GGUF target
+ // shows no Vision switch at all.
+ const gateAbove = (index: number): string => {
+ for (let i = index; i >= 0; i--) {
+ const line = lines[i].trim();
+ if (line === "{target.isGguf && (") return "isGguf";
+ if (line === "{!target.isGguf && (") return "!isGguf";
+ }
+ return "none";
+ };
+ const ggufAt = lines.findIndex((l) => l.includes("<GgufAdvancedSettings"));
+ const mlxAt = lines.findIndex((l) => l.includes("<MlxAdvancedSettings"));
+ assert.ok(ggufAt > 0 && mlxAt > 0, "one of the panels is never rendered");
+ assert.equal(gateAbove(ggufAt), "isGguf");
+ assert.equal(gateAbove(mlxAt), "!isGguf");
+});
+
+const VISION_GGUF = {
+ id: "local/qwen3.5-4b",
+ name: "Qwen3.5 4B",
+ isLora: false,
+ isVision: true,
+ isGguf: true,
+ isAudio: false,
+ audioType: null,
+ hasAudioInput: false,
+};
+
+function reason(overrides: Record<string, unknown> = {}) {
+ return getImageInputUnavailableReason({
+ activeModel: VISION_GGUF,
+ isExternalModel: false,
+ loadedIsMultimodal: false,
+ modelLoaded: true,
+ ...overrides,
+ });
+}
+
+test("switching Vision off points at the switch, not at a missing mmproj", () => {
+ const message = reason({ visionDisabledByUser: true });
+ assert.ok(message, "attaching images should still be blocked");
+ assert.match(message, /Advanced Settings/);
+ assert.match(message, /Qwen3\.5 4B/);
+ // The generic copy would send someone who turned the toggle off hunting for a
+ // vision model with a valid mmproj, a problem they do not have.
+ assert.doesNotMatch(message, /valid mmproj/);
+ assert.doesNotMatch(message, /Load a vision-capable model/);
+});
+
+test("every other refusal is untouched by the new branch", () => {
+ const missing = reason({ visionDisabledByUser: false });
+ assert.match(missing ?? "", /valid mmproj/);
+ assert.doesNotMatch(missing ?? "", /Advanced Settings/);
+ // An absent flag behaves exactly as before the toggle existed.
+ assert.equal(reason(), missing);
+ assert.equal(reason({ visionDisabledByUser: null }), missing);
+ // No model loaded still reports the load, not the toggle.
+ assert.match(
+ reason({ modelLoaded: false, visionDisabledByUser: true }) ?? "",
+ /Load a model before adding images/,
+ );
+ // And a stale echo must not disable attach for a session that DID load its
+ // projector.
+ assert.equal(
+ reason({ loadedIsMultimodal: true, visionDisabledByUser: true }),
+ null,
+ );
+});
+
+// The rollback replays the previous load's settings after a failed switch. It must
+// send the baseline that tracks the RUNNING server, not the control field: a pending
+// per-model config is written to disableVision before the switch captures its
+// baseline, so that holds the TARGET's setting and a failed switch would roll the old
+// model back with the new model's Vision choice. Nor the narrowed image-gating field,
+// which is false for a model that cannot do images. Source-level for the same reason
+// as the reseed above: the replay sits inside one large object literal.
+test("the rollback replays the loaded vision baseline, not the control or the gate", () => {
+ const runtime = read("src/features/chat/hooks/use-chat-model-runtime.ts");
+ const replay = runtime.slice(
+ runtime.indexOf("tensor_parallel: stateBeforeUnload.loadedTensorParallel"),
+ );
+ const line = replay.slice(
+ replay.indexOf("disable_vision:"),
+ replay.indexOf("gpu_memory_mode:"),
+ );
+ assert.ok(
+ line.includes("stateBeforeUnload.loadedDisableVision"),
+ `rollback must replay the loaded baseline, got: ${line.trim()}`,
+ );
+ assert.ok(
+ !line.includes("loadedVisionDisabledByUser"),
+ "rollback must not replay the narrowed image-gating field",
+ );
+ assert.ok(
+ !/stateBeforeUnload\.disableVision\b/.test(line),
+ "rollback must not replay the control field, which the pending config overwrites",
+ );
+});
+
+// The other half of the same rollback: the store assignment that follows the replayed
+// request. Getting the request right is not enough, because the control the user sees
+// is seeded separately, and applyPerModelConfigToRuntime(pendingLoadConfig) runs BEFORE
+// stateBeforeUnload is captured, so the snapshot's control field already holds the
+// TARGET's setting. Seeding from it leaves the Vision row reading "off" over a restored
+// model whose projector is running, and arms the next Apply to switch it off for real.
+// Source-level for the same reason as the replay above.
+test("the rollback seeds the Vision control from the restored model, not the target", () => {
+ const runtime = read("src/features/chat/hooks/use-chat-model-runtime.ts");
+ const assignment = runtime.slice(
+ runtime.indexOf("loadedSpeculativeType: rollbackSpeculativeType"),
+ );
+ const line = assignment.slice(
+ assignment.indexOf("disableVision:"),
+ assignment.indexOf("loadedVisionDisabledByUser:"),
+ );
+ assert.ok(
+ line.includes("stateBeforeUnload.loadedDisableVision"),
+ `the control must be seeded from the restored model's loaded value, got: ${line.trim()}`,
+ );
+ assert.ok(
+ !/stateBeforeUnload\.disableVision\b/.test(line),
+ "the control must not be seeded from the snapshot the pending config overwrote",
+ );
+ assert.ok(
+ !/rollbackResponse\.disable_vision/.test(line),
+ "the control must not be seeded from the echo, which is false for a text-only GGUF",
+ );
+});
+
+// Vision is per-model config with a default of ON, so switching to a model that saved
+// no config must give it that default rather than the outgoing model's setting. It
+// used to inherit, which loaded the new model text-only and did it silently: the
+// dedupe comparison builds its own view of an unconfigured switch out of
+// DEFAULT_PER_MODEL_CONFIG, so the two halves disagreed about the same load. This is
+// where it parts company with tensorParallel, which is deliberately standing across
+// models. Source-level for the same reason as the tests above.
+test("an unconfigured target gets the default Vision value, not the outgoing model's", () => {
+ const runtime = read("src/features/chat/hooks/use-chat-model-runtime.ts");
+ const decl = runtime.slice(
+ runtime.indexOf("const loadDisableVision ="),
+ runtime.indexOf("const loadActivePresetSource"),
+ );
+ assert.ok(
+ decl.includes("DEFAULT_PER_MODEL_CONFIG.disableVision"),
+ `a model switch must fall back to the per-model default, got: ${decl.trim()}`,
+ );
+ assert.ok(
+ decl.includes("loadSwitchesModelOrVariant"),
+ "the default must apply on a model or variant switch specifically",
+ );
+});
+
+test("a compare pane with no saved config does not inherit the live Vision value", () => {
+ const composer = read("src/features/chat/shared-composer.tsx");
+ const decl = composer.slice(
+ composer.indexOf("const effectiveDisableVision ="),
+ composer.indexOf("if (ownConfig.selectedGpuIds != null)"),
+ );
+ assert.ok(
+ decl.includes("DEFAULT_PER_MODEL_CONFIG.disableVision"),
+ `an unremembered pane must take the per-model default, got: ${decl.trim()}`,
+ );
+ assert.ok(
+ !/fallbackDisableVision/.test(composer),
+ "the store-derived fallback should be gone entirely, not just unused",
+ );
+});
+
+test("the Vision row is gated out for diffusion models", () => {
+ // withoutUnsupportedDiffusionSettings forces disableVision back to false and the
+ // diffusion runner never reads it, so an ungated row is a switch that flips back
+ // under the pointer and changes nothing if it did not. The batch rows above it are
+ // gated for exactly this reason.
+ assert.match(
+ CONFIG_PAGE,
+ /disableVision: false,/,
+ "withoutUnsupportedDiffusionSettings no longer clears disableVision",
+ );
+
+ const lines = CONFIG_PAGE.split("\n");
+ const visionAt = lines.findIndex((line) =>
+ line.includes("checked={!config.disableVision}"),
+ );
+ assert.notEqual(visionAt, -1, "no Vision switch to gate");
+
+ // The nearest JSX conditional boundary above the switch. A `)}` first means the
+ // gate closed before the row, i.e. the row is not inside it.
+ let nearest = "none";
+ for (let i = visionAt; i >= 0; i--) {
+ const line = lines[i].trim();
+ if (line === "{!isDiffusion && (") {
+ nearest = "!isDiffusion";
+ break;
+ }
+ if (line === ")}") {
+ nearest = "closed";
+ break;
+ }
+ }
+ assert.equal(
+ nearest,
+ "!isDiffusion",
+ "the Vision row is not inside a !isDiffusion gate",
+ );
+});