Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: warn instead of refusing to load a model bigger than VRAM plus RAM (#9822)
Daniel Han2c69e1d294a4
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex c51da2a7742..623f3f624b5 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -85,6 +85,7 @@ from core.inference.llama_server_args import (extra_args_disable_mmproj,extra_args_select_load_mode,fit_is_enabled_in,+ force_pageable_load,memory_env_selects_load_mode,memory_state_satisfies_settings,fit_is_effectively_on,@@ -3028,12 +3029,36 @@ _CTX_FIT_VRAM_FRACTION = 0.97# 0.85 MLX uses in mlx_inference.py (_configure_memory_limits); not kept in sync._APPLE_UNIFIED_MEMORY_FRACTION = 0.85-# _fit_context_to_vram's floor, and llama.cpp's (common_params.fit_params_min_ctx), so a-# 4096 from either is that floor rather than a measurement. The Metal branch re-prices+# _fit_context_to_vram's floor: the shortest context the search will settle for, so a+# value equal to it is that floor rather than a measurement. The Metal branch re-prices# from _FIT_FLOOR_MIN_CTX (the search's 256 alignment step) before trusting it.-_FIT_MIN_CTX = 4096+#+# 8192, not llama.cpp's own 4096 (common_params.fit_params_min_ctx). 4096 is too short+# to be useful for chat once tools and a system prompt are in the window, and the fit+# search would settle there rather than spilling weights it could spill instead. The two+# floors are now deliberately different numbers: llama.cpp's still governs ITS fitter,+# and Unsloth does not pass -fitc, so a launch that hands llama.cpp an explicit -c can+# still be reduced below this by the child's own fit step.+#+# Every arm now floors here, Metal included. The Apple arm used to hold a separate+# hardcoded 4096, which made a Mac publish half the context a discrete GPU published+# for the same model. Being BELOW llama.cpp's own floor is what made that safe to+# raise: -c 8192 is a request the child's --fit can still reduce, down to its 4096,+# so the arm hands over a ceiling rather than a commitment. The one arm still on a+# bare 4096 is _plan_tensor_parallel's no-KV fallback, which cannot prove a safe cap+# at all and is a different question from this floor.+_FIT_MIN_CTX = 8192_FIT_FLOOR_MIN_CTX = 256+# llama.cpp's OWN reduction floor: common_params.fit_params_min_ctx, 4096+# (common/common.h), the smallest context its --fit step will shrink a request to.+# Named because the paragraph above spends the whole justification for _FIT_MIN_CTX on+# it: -c 8192 is safe to hand a Mac only as a ceiling the child's fitter can still come+# down from, and this is how far down. A launch that hands over 8192 with the fitter+# NOT running has no such backstop, so it must hand over this number itself rather than+# the ceiling that assumed one.+_LLAMA_FIT_MIN_CTX = 4096+# Auto only reaches this path when no discrete-GPU subset can hold the model.# llama.cpp must offload layers to host RAM either way, so prefer a context that# remains useful for chat. Separate from _FIT_MIN_CTX: that value is also a search@@ -4922,6 +4947,26 @@ def _report_live_llama_timings(callback, chunk) -> None:# system RAM, so hold back the same margin rather than inventing a larger one._IGPU_HOST_RESERVE_MIB = 1024_HOST_RAM_HEADROOM_MIB = 2048+# Appended to whichever shortfall warning an oversized non-pageable launch produced,+# after _page_an_oversized_unmapped_load rewrote the mode. One string, so the three+# call sites cannot describe the same override differently.+_PAGEABLE_OVERRIDE_NOTE = (+ " This model was set to load without memory mapping, which reads every byte into "+ "RAM up front and cannot complete at this size, so Unsloth loaded it with memory "+ "mapping instead."+)+# What memory_warning says when the text-only fallback removed the CPU-pinned projector+# whose bytes were what made the load oversized, on a launch that had already had its+# unmapped load mode overridden for that shortfall. The override is REPORTED and not+# taken back: the argv was rewritten and spawned, and force_pageable_load rewrote the+# shared child env in place, so the running server is memory-mapped whatever this says.+_PAGEABLE_OVERRIDE_TEXT_ONLY_NOTICE = (+ "This model was set to load without memory mapping, and with its vision projector "+ "in system RAM it was too large to load that way, so Unsloth loaded it with memory "+ "mapping instead. The projector then failed to start and this session is text-only, "+ "which the weights alone would have fit. The running server keeps the memory "+ "mapping it started with; load the model again to run it as you asked."+)_CGROUP_ROOT = "/sys/fs/cgroup"_PROC_SELF_CGROUP = "/proc/self/cgroup"@@ -5200,6 +5245,10 @@ class LlamaCppBackend:"""self._process: Optional[subprocess.Popen] = Noneself._port: Optional[int] = None+ # Advisory memory notice from the load in flight, handed back on LoadResponse.+ # Reset by _begin_load_warnings so one load's notice is never reported against+ # the next.+ self._last_load_warning: Optional[str] = Noneself._model_identifier: Optional[str] = Noneself._gguf_path: Optional[str] = None# Snapshot of the exact file(s) handed to the resident process. A local@@ -8084,6 +8133,8 @@ class LlamaCppBackend:caller_owns_budget: bool,native_ctx: Optional[int],max_available_ctx: Optional[int] = None,+ *,+ fitter_runs: bool = True,) -> int:"""Context to start at when Metal would otherwise be sent "-c 0", else 0.@@ -8100,24 +8151,41 @@ class LlamaCppBackend:Either way the child over-commits unified memory, surfacing asllama-server's "Compute error." at decode (#5118, #6529). Floor to the- same 4096 the cap falls back to without a KV estimate.+ same ``_FIT_MIN_CTX`` the cap falls back to without a KV estimate.++ ``fitter_runs`` is whether the child's own --fit step will actually run, and+ both the exemption and the floor VALUE depend on it. _FIT_MIN_CTX sits above+ llama.cpp's own ``fit_params_min_ctx`` on purpose: 8192 is defensible on a Mac+ only because it is a request the fitter can still reduce, down to 4096. Turn+ the fitter off and that backstop is gone, and this arm would hand a machine+ with room for 4096 but not 8192 a context nothing can bring down -- a startup+ failure or a "Compute error." at decode, the very thing the floor exists to+ prevent. So a launch with no fitter is floored at ``_LLAMA_FIT_MIN_CTX``, the+ number the fitter would have reduced to, rather than at the ceiling that+ assumed one. Conservative on purpose: --fit off is a flag the user typed, and+ overriding it to keep our own invented floor would be Unsloth taking back a+ setting the user asked for, on the path where they most likely asked for it+ because the fitter misbehaves on their host.Exemptions: no Metal budget (0 off Apple Silicon, so this is inert- there); ``auto_fit``, which omits -c so --fit sizes it, and which the- caller passes only while --fit will actually run; and+ there); ``auto_fit``, which omits -c so --fit sizes it, and which is+ therefore honoured only while ``fitter_runs`` -- the conjunction is taken+ here rather than trusted to the caller, since without it the exemption hands+ the child no -c and no fitter, which is llama.cpp's native length; and``caller_owns_budget``, a manual mode with a fixed layer count where theuser owns memory management. That last is read off the REQUEST, becausethe paravirtual CPU pin rewrites every placement to manual/0 first andwould make a plain Auto request look caller-owned."""- if effective_ctx > 0 or auto_fit or caller_owns_budget:+ if effective_ctx > 0 or (auto_fit and fitter_runs) or caller_owns_budget:return 0if not LlamaCppBackend._apple_metal_memory_budget_bytes():return 0+ floor = _FIT_MIN_CTX if fitter_runs else _LLAMA_FIT_MIN_CTX# Never above a ceiling the cap already worked out: on the exception path# max_available_ctx survives the reset, and its KV-based answer can sit- # below 4096. Floating back up would re-create the over-commit.- return min(4096, native_ctx or 4096, max_available_ctx or 4096)+ # below the floor. Floating back up would re-create the over-commit.+ return min(floor, native_ctx or floor, max_available_ctx or floor)@staticmethoddef _metal_drops_zero_ctx_override(@@ -9093,6 +9161,29 @@ class LlamaCppBackend:n_layers = self.n_layersreturn requested == -1 or (bool(n_layers) and requested > n_layers)+ @staticmethod+ def _rows_the_child_can_reach(detected_gpus, pinned_ids) -> list:+ """``detected_gpus`` narrowed to the cards THIS launch pinned the child to.++ ``_launch_host_shortfall_message`` sums free VRAM over every row it is handed,+ which is right for an advisory about the host and wrong for a decision about+ one launch: a child pinned to a subset cannot spend the VRAM on the cards it+ cannot see, so crediting them prices the spill too low and can leave an+ unmapped oversized load unrewritten, which is an OOM rather than a slow load.++ ``pinned_ids`` is the narrowing this load performed, not the visibility mask+ in ``env``. An inherited CUDA_VISIBLE_DEVICES is already applied: the probe+ only ever reported the cards it left visible, so re-applying it here would+ subtract the same pin twice and price a single-card host as having none.+ None means nothing narrowed the launch, which is not the same as an empty+ pin, and physical ids match ``row[0]``.+ """+ rows = list(detected_gpus or ())+ if pinned_ids is None:+ return rows+ visible = set(pinned_ids)+ return [row for row in rows if row[0] in visible]+def _shared_heap_budget(self,gpus: Iterable[tuple],@@ -9157,14 +9248,17 @@ class LlamaCppBackend:child_has_no_gpu: bool = False,avail_mib: Optional[int] = None,shared_gpu_ids: Iterable[int] = (),+ honor_opt_out: bool = True,) -> Optional[str]:- """Refusal when the weights alone cannot fit in free VRAM plus available RAM.+ """Warning when the weights alone do not fit in free VRAM plus available RAM.++ Advisory only. Nothing here blocks a load: callers log this and launch anyway.Weights only, against the whole free pool, is a strict lower bound on what thelaunch must hold: the KV cache, projector, drafter and compute buffers all addto it, and a layer or device pin only narrows the VRAM actually reachable. Soevery term this leaves out moves the estimate down, never up, and no missing- term can turn an allowed load into a refused one. That is what keeps the check+ term can turn a quiet load into a warned one. That is what keeps the checka floor with no placement modelling to keep in step with llama.cpp.Read from the finished argv, so the model path is the one the child opens. An@@ -9173,8 +9267,14 @@ class LlamaCppBackend:placement it already knows reaches no card, rather than one it could not read:there the whole model is host-resident and takes no VRAM credit.- UNSLOTH_ALLOW_HOST_OFFLOAD=1 abstains outright, so a user who accepts the- paging can still load a variant the picker offers.+ UNSLOTH_ALLOW_HOST_OFFLOAD=1 abstains outright. DEPRECATED: it was the opt-out+ from the old refusal, so all it does now is silence the warning. Still honoured+ so existing scripts and docs keep working.++ ``honor_opt_out=False`` prices the shortfall with that variable ignored, for a+ caller that needs the FACT rather than the warning. Silencing the message must+ never disable the pageable-load override, which is what lets an oversized+ unmapped load finish at all: see ``_page_an_oversized_unmapped_load``.``avail_mib`` overrides the host figure for a caller that runs before the residentowners are released; the launch reads what is available now. ``shared_gpu_ids``@@ -9187,12 +9287,7 @@ class LlamaCppBackend:model_path = _extra_args_device(argv, self._ARGV_MODEL)if not model_path:return None- # the user's own opt-out, so read the real environment, not the curated child env- if os.environ.get("UNSLOTH_ALLOW_HOST_OFFLOAD", "").strip().lower() in (- "1",- "true",- "yes",- ):+ if honor_opt_out and self._host_offload_warning_opted_out():logger.info("UNSLOTH_ALLOW_HOST_OFFLOAD set: skipping the host-RAM preflight.")return None# rpc places layers on remote devices this cannot size, in either spelling@@ -9233,10 +9328,14 @@ class LlamaCppBackend:avail_mib: Optional[int],headroom_mib: int = _HOST_RAM_HEADROOM_MIB,) -> Optional[str]:- """On a unified-memory APU, return a user-facing refusal when the weights- cannot fit in available system RAM (else None). Weights only: KV/context- auto-reduce, so counting them too would refuse loads that would succeed.- None avail (unknown RAM) never refuses."""+ """On a unified-memory APU, return a user-facing WARNING when the weights+ do not fit in available system RAM (else None). Weights only: KV/context+ auto-reduce, so counting them too would warn about loads that are fine.+ None avail (unknown RAM) never warns.++ Advisory, never a refusal: the load goes ahead and llama.cpp reports what+ actually happens rather than Studio pre-empting a failure it predicted.+ """if avail_mib is None:return Noneneed_mib = model_size_bytes / (1024 * 1024)@@ -9245,9 +9344,10 @@ class LlamaCppBackend:return (f"This model needs about {need_mib / 1024:.0f} GB but only about "f"{avail_mib / 1024:.0f} GB of memory is available. On a unified-memory "- "APU the weights load into system RAM, so a larger model is stopped by "- "the OS mid-load. Use a smaller or more quantized GGUF, or free memory "- "(on WSL, raise the memory limit in .wslconfig)."+ "APU the weights load into system RAM, so the OS may stop the load. "+ "Loading anyway. If it does not complete, use a smaller or more "+ "quantized GGUF, or free memory (on WSL, raise the memory limit in "+ ".wslconfig).")@staticmethod@@ -9256,12 +9356,17 @@ class LlamaCppBackend:avail_mib: Optional[int],headroom_mib: int = _HOST_RAM_HEADROOM_MIB,) -> Optional[str]:- """On a discrete GPU, return a user-facing refusal when the part of a load- that misses VRAM cannot fit in available system RAM (else None). The spill is- mmap'd, so an oversized one thrashes the mapping instead of failing, until the- OS kills the app. Priced against free VRAM with no margin subtracted, so it- under-states the spill and only an unambiguous shortfall refuses. None avail- (unknown RAM), and anything VRAM-resident, never refuse."""+ """On a discrete GPU, return a user-facing WARNING when the part of a load+ that misses VRAM does not fit in available system RAM (else None). Priced+ against free VRAM with no margin subtracted, so it under-states the spill and+ only an unambiguous shortfall warns. None avail (unknown RAM), and anything+ VRAM-resident, never warn.++ Advisory, never a refusal. The spill is mmap'd, so the weights page in from disk+ rather than failing: off fast storage that is a deliberate way to run a quant+ larger than the machine's fast memory, and this check cannot tell how fast the+ backing store is. It reports the cost; the user decides.+ """if offload_bytes <= 0 or avail_mib is None:return Noneneed_mib = offload_bytes / (1024 * 1024)@@ -9275,9 +9380,278 @@ class LlamaCppBackend:f"from system RAM. Only about {avail_mib / 1024:.0f} GB is available and "f"{headroom_mib / 1024:.0f} GB of that is kept free for the rest of the "f"system, leaving about {usable_gb} GB usable. The weights are memory-mapped, "- "so the machine pages them in and out until it stops responding and the OS "- "kills the app. Use a smaller or more quantized GGUF, free memory, or set "- "UNSLOTH_ALLOW_HOST_OFFLOAD=1 to load it anyway."+ "so the machine pages them in from disk as it runs. Loading anyway: expect "+ "slow generation, and slower still on a hard disk than on an SSD. A smaller "+ "or more quantized GGUF, or more free memory, would run faster."+ )++ @staticmethod+ def _host_offload_warning_opted_out() -> bool:+ """Whether UNSLOTH_ALLOW_HOST_OFFLOAD silences the host-RAM warning.++ The user's own opt-out, so it reads the REAL environment rather than the+ curated child env. DEPRECATED and warning-scoped: it was the escape from a+ refusal that no longer exists, so all it may do is suppress a message. It must+ never reach a decision that changes what the child runs.+ """+ return os.environ.get("UNSLOTH_ALLOW_HOST_OFFLOAD", "").strip().lower() in (+ "1",+ "true",+ "yes",+ )++ def _page_an_oversized_unmapped_load(+ self, cmd: Iterable[str], env: Optional[dict], oversized+ ) -> tuple[list, Optional[str]]:+ """Rewrite a launch that is BOTH oversized and non-pageable into a pageable one.++ Returns ``(cmd, note)``: the argv to launch, and the sentence to append to+ whatever warning is emitted, or None when nothing was overridden and ``cmd``+ comes back unchanged.++ The host-RAM shortfall is survivable only because the weights are mmap'd: the+ whole premise is that the spill pages in from disk as the model runs. Modes+ "none" and "mlock" have no such fallback -- upstream sets use_mmap for+ mmap/mmap+mlock/auto and nothing else (llama-model-loader.cpp), so those two+ read the weights into a buffer llama.cpp allocates. The same shortfall is then+ an allocation failure or an OOM kill during loading, not slow generation.+ Reached by ``--load-mode``, by the deprecated ``--no-mmap`` / ``--no-direct-io``+ spellings, and by the LLAMA_ARG_* twins llama.cpp reads before argv, so the+ EFFECTIVE state is what decides, not the tokens Unsloth happens to have emitted.++ This never blocks a load, so the unmapped request is OVERRIDDEN rather than+ refused: the pageable equivalent goes in (a lock is kept, as mmap+mlock) so the+ load the user asked for can actually finish. Only on a real shortfall -- an+ unmapped load that fits is exactly what was asked for and is left byte for byte+ as written. Said out loud, since a silent override is its own surprise: in the+ returned note when a warning is emitted, and in the log either way, so a load+ whose warning was silenced is still traceable.++ One helper for every launch that can discover a shortfall (the APU preflight,+ the discrete host guard, the arch-crash retry), because the decision belongs to+ the CONDITION and not to any one warning: a site that only recorded, or a+ warning the environment suppressed, would otherwise skip the remap and hand the+ child a load it cannot complete. ``oversized`` is the per-site shortfall+ predicate, called only once the cheap non-pageable test has passed, so a+ comfortable launch pays for no pricing.+ """+ # The caller's own list back on every no-op path, not a rebuilt copy: an+ # untouched launch must stay byte for byte, and the same token objects, as+ # whatever built it.+ original = cmd if isinstance(cmd, list) else list(cmd or ())+ _mlock_now, _reserves_ram_now = resolve_effective_memory_state(original, env)+ if not _reserves_ram_now:+ return original, None+ try:+ if not (oversized() if callable(oversized) else oversized):+ return original, None+ except Exception:+ # Advisory pricing: an unreadable host or GGUF leaves the launch alone.+ logger.debug("Could not price the load for a pageable override.", exc_info = True)+ return original, None+ paged, overridden = force_pageable_load(original, env)+ if not overridden:+ return original, None+ logger.warning(+ "Overriding the unmapped load mode (%s) for an oversized model: it would "+ "allocate the whole model in host RAM instead of paging it in.",+ ", ".join(overridden),+ )+ return paged, _PAGEABLE_OVERRIDE_NOTE++ @property+ def last_load_warning(self) -> Optional[str]:+ """Advisory notice from the most recent load, or None. Read by the route."""+ return self._last_load_warning++ def _begin_load_warnings(self) -> None:+ """Drop the previous load's advisory notice, at the point a load commits to+ replacing the resident server. Without it a warned load followed by a+ comfortable one would report the first load's notice against the second.++ Called from the Phase 1 teardown, not from the top of ``load_model``: an+ attempt rejected before that point leaves the old child serving, and its+ advisory has to survive with it (the route still answers ``already_loaded``+ from that child). The arch-crash retry calls it again for the same reason in+ reverse -- the placement everything was priced against is the one that just+ died."""+ self._last_load_warning = None++ def _record_load_warning(self, message: Optional[str]) -> None:+ """Log an advisory memory notice and keep it for the route to hand back.++ Never raises: these replace what used to be a refusal, and an oversized GGUF+ pages from disk instead of failing, so the load is the user's call. First notice+ wins, since the earliest priced the whole pool and later ones see a narrowed+ selection.+ """+ if not message:+ return+ logger.warning(message)+ if self._last_load_warning is None:+ self._last_load_warning = message++ def _amend_load_warning(self, note: Optional[str]) -> None:+ """Append to the notice already recorded for this load, if there is one.++ The pageable-load override can be settled after an earlier guard has already+ recorded its warning: the APU preflight runs long before ``cmd`` and ``env``+ exist, which is where the override has to be applied. First notice wins, so+ that earlier text is what the route hands back, and appending is what keeps the+ override named in the message the user actually sees. A load whose warning was+ suppressed has nothing to amend and keeps the log line as its only record.+ """+ if note and self._last_load_warning:+ self._last_load_warning += note++ def _reprice_after_dropping_pinned_projector(+ self,+ *,+ apu_msg: Optional[str],+ host_msg: Optional[str],+ model_size: Optional[int],+ pinned_bytes: int,+ avail_mib: Optional[int],+ ) -> None:+ """Re-price the APU RAM advisory once a text-only retry drops a CPU-pinned+ vision projector.++ The APU preflight charges ``model_size + _mmproj_pinned_bytes``, because a+ projector pinned to the CPU loads into the same system RAM as the weights. When+ that projector then fails to start and the retry strips ``--mmproj``, the child+ that came up healthy never read those bytes: the recorded shortfall describes a+ load nothing is running. Priced again without them, so the notice matches what+ the serving process actually holds -- rewritten to the smaller need if the+ weights alone still do not fit, handed to the discrete guard's notice if that+ one also found a shortfall, and otherwise dropped.++ What is NOT undone is the pageable-load override. It rewrote the argv and, in+ ``force_pageable_load``, the shared child env in place, and the child was+ spawned from both long before this runs, so the server IS memory-mapped and+ nothing here can change that; reverting it would need yet another respawn of a+ process that just came up healthy, on the recovery rung that exists because this+ model has already failed to start once. So an override that the reprice shows+ was not needed is reported rather than reverted: whatever note the message+ carried is kept, and a load whose only remaining news is the override says that+ and nothing else.++ A no-op unless the projector was actually charged and the APU advisory is+ actually what the route would hand back -- an opt-out that silenced it, or any+ other notice that first-notice-wins kept, is left exactly as it is.+ """+ if not apu_msg or pinned_bytes <= 0 or model_size is None or avail_mib is None:+ return+ current = self._last_load_warning+ if not current or not current.startswith(apu_msg):+ return+ # Whatever _amend_load_warning appended (the pageable-override note), carried+ # over rather than rebuilt, so a reprice cannot describe the override in+ # different words than the launch site did.+ suffix = current[len(apu_msg) :]+ # ``avail_mib`` is the figure the PREFLIGHT read, carried down rather than taken+ # again here. By this point the text-only child is healthy and holding the+ # weights, so a fresh reading is the pool minus the very model being priced:+ # it would charge ``model_size`` against ``avail - model_size`` and report a+ # shortfall for a load that demonstrably just started. Same pool, one term+ # removed, is the only comparison that answers the question being asked.+ repriced = self._apu_ram_shortfall_message(model_size, avail_mib)+ if repriced:+ self._last_load_warning = repriced + suffix+ elif host_msg:+ # The discrete guard priced the same launch and lost first-notice-wins.+ # It reads the model path off the argv and never charged the projector,+ # so dropping the projector leaves its verdict standing.+ self._last_load_warning = host_msg + suffix+ elif suffix.strip():+ self._last_load_warning = _PAGEABLE_OVERRIDE_TEXT_ONLY_NOTICE+ else:+ self._last_load_warning = None+ logger.info(+ "Text-only fallback dropped the CPU-pinned vision projector (%.0f MiB); "+ "re-priced the host memory advisory against the weights alone.",+ pinned_bytes / (1024 * 1024),+ )++ def _reprice_after_cpu_only_fallback(+ self,+ *,+ host_msg: Optional[str],+ cpu_cmd: Iterable[str],+ env: Optional[Mapping[str, str]],+ avail_mib: Optional[int],+ pageable_note: Optional[str] = None,+ ) -> None:+ """Re-price the host memory advisory once a Vulkan crash is replayed on CPU.++ The replay launches with ``--gpu-layers 0 --device none``, so no VRAM is+ credited to it at all: the child that serves the session holds the WHOLE model+ in system RAM and pages it from disk. Two things follow, and the preflight+ notice gets neither right.++ A load that was warned about its spill was warned about the spill of the GPU+ placement that just died. The replay's spill is the whole model, which is+ strictly larger, so the recorded figure understates what the running child+ actually pages. And a load that FIT in VRAM was never warned at all, yet it is+ the one the user most needs told: it now runs entirely from host RAM on a host+ that may not hold it, and ``memory_warning`` was null for it.++ Priced against ``avail_mib``, the figure the PREFLIGHT read, for the same reason+ the projector reprice carries its own snapshot down: this runs after+ ``_spawn_and_wait`` reports the CPU child healthy, so a fresh reading is the+ pool minus the model being priced and would report a shortfall for a load that+ demonstrably just started.++ Called only where the replay is known healthy, never where it is chosen. A+ failed replay is not terminal on every rung -- the drafter replay reports "not+ recovered" and the caller tries the drafterless argv next -- so pricing at the+ decision would describe a placement about to be abandoned.++ The pageable-load override is NOT re-decided here, and nothing claims it was+ reverted. ``force_pageable_load`` rewrote the argv and the shared child env in+ place before the first spawn, and ``_cpu_isolated_replay`` strips placement+ alone, so the replay inherits both and the CPU child really is memory-mapped.+ Whatever note the preflight message carried is carried over verbatim onto the+ re-priced text rather than rebuilt, so a reprice cannot describe the override in+ different words than the launch site did.++ ``pageable_note`` is the override ``_prepare_cpu_fallback_launch`` decided on+ the REPLAY, which the preflight message cannot have carried: a launch that fit+ in VRAM was priced as pageable-enough and left the user's unmapped mode alone,+ and only the replay's own footprint (no VRAM credited) turns it into a full+ host allocation. Both notes cannot be set at once -- if the preflight had+ already overridden, the replay it built from is mapped and the second pricing+ finds nothing to rewrite -- so this appends rather than replaces. Priced against+ the same ``avail_mib`` the rewrite used, so the advisory cannot describe an+ unmapped load the same pool reading has just made mapped.++ A no-op unless the notice the route would hand back is the one this path can+ speak for: an opt-out that silenced it (the re-pricing call honours it too), or+ any other notice first-notice-wins kept, is left exactly as it is. The note+ follows the message: an override on a silenced load stays in the log alone,+ exactly as it does on the main launch path.+ """+ repriced = self._launch_host_shortfall_message(+ cpu_cmd,+ (),+ env,+ child_has_no_gpu = True,+ avail_mib = avail_mib,+ )+ note = pageable_note or ""+ current = self._last_load_warning+ if current is None:+ # The model fit in VRAM, so nothing warned; on CPU it fits nowhere but disk.+ self._record_load_warning((repriced + note) if repriced else None)+ return+ if not host_msg or not current.startswith(host_msg) or not repriced:+ # Nothing here can be re-priced, but an override still changed the child:+ # say so on whatever notice first-notice-wins kept.+ self._amend_load_warning(pageable_note)+ return+ self._last_load_warning = repriced + current[len(host_msg) :] + note+ logger.info(+ "Re-priced the host memory advisory for the CPU replay: it runs with no "+ "GPU, so the whole model is charged to system RAM.")def _fits_without_paging(@@ -10202,7 +10576,7 @@ class LlamaCppBackend:ctx: int,usable_mib: Iterable[float],reserve_bytes_fn: Callable[[int], int],- min_ctx: int = 4096,+ min_ctx: int = 8192,) -> int:"""Largest context in [``min_ctx``, ``ctx``] whose replicated per-device reservestill fits the SMALLEST card of a layer-split subset; 0 when even ``min_ctx``@@ -10924,7 +11298,7 @@ class LlamaCppBackend:# Context the projector's residency is priced at. The placement loop shrinks the# context to this floor long before it would spill a layer, so this is the length# at which "does it fit" means "does every layer stay on the GPU".- _MMPROJ_FIT_FLOOR_CTX = 4096+ _MMPROJ_FIT_FLOOR_CTX = 8192_MTP_DRAFT_COMPUTE_BYTES = 224 * 1024 * 1024 # MTP draft decode graph beyond its KV# Draft depth to budget when the extras own the spec block and the probe cannot# read the build's own default off its --help. Shipped values are 3@@ -11180,7 +11554,7 @@ class LlamaCppBackend:available_mib: int,model_size_bytes: int,cache_type_kv: Optional[str] = None,- min_ctx: int = 4096,+ min_ctx: int = 8192,*,swa_full: bool = False,n_parallel: int = 1,@@ -11579,24 +11953,25 @@ class LlamaCppBackend:logger.debug("Non-chat GGUF preflight failed for the route: %s", e)return None- def host_offload_refusal_for_intent(self, intent) -> Optional[str]:- """The host-RAM verdict for a resolved load intent, or None.+ def host_offload_warning_for_intent(self, intent) -> Optional[str]:+ """The host-RAM advisory for a resolved load intent, or None.- ``_launch_host_shortfall_message`` stays authoritative, since it reads the finished- argv, but it runs after the ROUTE has evicted a resident Images/Video pipeline via- ``acquire_for(CHAT)`` and cancelled the running generations. Asking here first spares- both, exactly as the non-chat header check above does.+ Advisory, never a refusal: the route LOGS this and loads anyway. It does not+ reach the load response -- it records nothing, and ``load_model`` clears the+ previous notice at its teardown anyway; the response carries the launch-time+ notice instead. What this buys is a line in the log before ``acquire_for(CHAT)``+ evicts a resident Images/Video pipeline, rather than only from deep inside+ ``load_model`` once that teardown has happened.Both capacities are read as PHYSICAL TOTALS, not as what is free right now. Theresident llama-server, Unsloth model and Images/Video pipeline hold VRAM and, througha host KV cache, CPU-offloaded weights and locked mappings, host RAM as well, and theroute and ``load_model`` reclaim all of it after this runs. Pricing against the free- readings would refuse a switch to a model the reclaimed machine holds easily. Each+ readings would warn about a switch to a model the reclaimed machine holds easily. Eachtotal is the ceiling on what the launch can ever see, and every narrowing the launchapplies to the pool (the ROCm arch gate, the Vulkan discrete preference, a ``gpu_ids``pin) only shrinks it further, so this charges no more than the launch copy and can- refuse nothing the launch would allow. What survives is the pick no reclaim can- rescue, which is the one worth catching before the teardown.+ warn about nothing the launch would call comfortable.Only a local path is priced. An HF repo may not be downloaded yet, and resolving onehere would start a download the route has not committed to.@@ -15948,7 +16323,19 @@ class LlamaCppBackend:server_caps: Mapping[str, object],*,drop_full_offload_threads: bool = False,- ) -> Optional[tuple[list[str], Optional[str]]]:+ avail_mib: Optional[int] = None,+ ) -> Optional[tuple[list[str], Optional[str], Optional[str]]]:+ """Build the CPU replay, or None when this install cannot host one.++ Returns ``(argv, cwd, pageable_note)``. The note is the sentence+ ``_page_an_oversized_unmapped_load`` produces when it had to override an+ unmapped load mode, for the caller to put in front of the user; None when+ nothing was rewritten.++ ``avail_mib`` is the host pool the preflight read, carried down so the rewrite+ below and ``_reprice_after_cpu_only_fallback`` price the replay against the same+ number and cannot reach opposite conclusions about the same child.+ """# Staging only removes GPU backends; a non-Vulkan install would report a# Vulkan crash that never happened.if not self._is_vulkan_backend(binary):@@ -15967,6 +16354,33 @@ class LlamaCppBackend:"Load mode: dropping the fit's --load-mode none for the CPU ""fallback; it runs entirely from host RAM.")+ # A user's own "--load-mode none" / "--no-mmap" survives that strip, by design,+ # and on this rung it is no longer the mode they were priced for: the replay+ # appends "--gpu-layers 0 --fit off --device none", so nothing credits VRAM and+ # the child holds the WHOLE model in host RAM. Unmapped that is one allocation+ # of the whole file rather than a mapping the kernel pages, i.e. an OOM kill on+ # a host that cannot hold it -- which the main launch path would have rewritten+ # before spawning. So price the replay on its OWN footprint (never the preflight+ # verdict, which credited a GPU placement this argv has just deleted) and apply+ # the same override.+ _priced_replay = replay+ replay, pageable_note = self._page_an_oversized_unmapped_load(+ replay,+ env,+ # honor_opt_out=False for the same reason _launch_is_oversized reads it that+ # way: UNSLOTH_ALLOW_HOST_OFFLOAD silences a message and must never withdraw+ # the rewrite that makes the load possible.+ lambda: bool(+ self._launch_host_shortfall_message(+ _priced_replay,+ (),+ env,+ child_has_no_gpu = True,+ avail_mib = avail_mib,+ honor_opt_out = False,+ )+ ),+ )cpu_binary = self._cpu_isolated_binary(binary)if cpu_binary is None:return None@@ -15976,7 +16390,7 @@ class LlamaCppBackend:replay[0] = cpu_binary# Staging covers only the executable and libraries, so keep Unsloth's working# directory: relative paths in user extra args resolve against it.- return replay, None+ return replay, None, pageable_notedef _cpu_isolated_binary(self, binary: Optional[str]) -> Optional[str]:"""Stage managed llama.cpp without GPU backend libraries.@@ -16638,8 +17052,22 @@ class LlamaCppBackend:return False# ── Phase 1: kill old process (under lock, fast) ──────────+ # The previous load's advisory is dropped HERE, at the one point this call+ # commits to replacing the resident server, rather than on the first line of+ # load_model. Everything above can stand down with that server still serving+ # (the update-in-progress refusal, the duplicate-load fast path, an+ # unenumerated Vulkan pin, a diffusion or non-chat refusal, a cancel), and+ # clearing on the way past retired the advisory of a child that keeps+ # running -- so the next `already_loaded` answered memory_warning: null for+ # an oversized model that is still paging from disk. Placing the reset at+ # the teardown rather than restoring it on each rejected path is what keeps+ # that true for early returns added later: this is the line that separates+ # "the old child survives" from "the old child is gone", so a new stand-down+ # above it is covered by construction and needs no bookkeeping of its own.+ # Nothing between the top of load_model and this point records a warning._replaying_cpu_fallback = intent.cpu_fallbackwith self._lock:+ self._begin_load_warnings()self._kill_process()if not _replaying_cpu_fallback:self._cpu_fallback_reason = None@@ -17200,6 +17628,18 @@ class LlamaCppBackend:# the same reason as _detected_gpus: the except path (--fit on) falls# through to the launch, which reads it._arch_gate_forced_cpu = False+ # The GPUs THIS launch pinned the child to, or None when it pinned+ # nothing. Set where the pin is emitted, and read by the pageable+ # override so it prices against VRAM the child can actually spend.+ # Not derived from env: an inherited mask is already applied by the+ # probe, so re-reading it there would subtract the same pin twice.+ _launch_pinned_ids: Optional[list] = None+ # The pageable rewrite a CPU replay applied, kept across attempts: the+ # env is shared, so only the first replay to need it produces a note.+ _replay_pageable_override: Optional[str] = None+ # Set by the restored cpu_fallback path, consumed once the launch is+ # healthy: str carries that replay's override note, True means none.+ _restored_cpu_reprice: Union[str, bool, None] = None# Whether Unsloth's placement planner actually RAN and came back# unable to fit the model. `use_fit` alone cannot answer that: it# starts True at its declaration below and is also what the except@@ -18080,9 +18520,9 @@ class LlamaCppBackend:# An EXPLICIT context gets its requested length, because there# the reasoning points the other way: the loop honors a pinned# context verbatim, so the only give left is `--fit on`, which- # spills MODEL LAYERS and collapses decode ~3x. Asking at 4096- # would answer "fits", keep the projector, and pay in offloaded- # weights -- this probe's trade at its worst rate.+ # spills MODEL LAYERS and collapses decode ~3x. Asking at the+ # floor instead would answer "fits", keep the projector, and pay+ # in offloaded weights -- this probe's trade at its worst rate.## The drafter IS charged: this runs before the drop probe, so# speculative decoding is still in the footprint. Priced exactly@@ -18840,6 +19280,18 @@ class LlamaCppBackend:# ggml-metal's free-memory report, blind to Unsloth's own footprint# and the wired limit. See _metal_context_overcommit_message.native_ctx_for_cap = self._context_length or effective_ctx+ # This arm's floor, which is _FIT_MIN_CTX only while the child's+ # fitter can come down from it. With --fit off (argv or+ # LLAMA_ARG_FIT) nothing reduces what we emit, so hand over the+ # number llama.cpp's own fitter would have reduced to instead.+ # _metal_zero_ctx_floor draws the same distinction but never sees+ # these paths: they assign a POSITIVE context, and its first+ # condition returns 0 for any positive effective_ctx.+ _metal_floor_ctx = (+ _FIT_MIN_CTX+ if fit_is_effectively_on(extra_args, os.environ)+ else _LLAMA_FIT_MIN_CTX+ )# Only a ceiling backed by a real KV estimate may refuse; the 4096# fallback below is a guess and would block working loads._apple_measured_ceiling: Optional[int] = None@@ -18892,7 +19344,8 @@ class LlamaCppBackend:cap = _apple_ctx_fit(native_ctx_for_cap, _FIT_MIN_CTX)_cap_footprint_mib = _apple_footprint_mib(cap)# Fit returns the request unchanged when it fits OR weights- # exceed budget; only the latter over-commits, so floor to 4096.+ # exceed budget; only the latter over-commits, so floor to+ # _FIT_MIN_CTX.if _cap_footprint_mib <= _apple_fit_budget_mib:max_available_ctx = cap_apple_measured_ceiling = cap@@ -18900,12 +19353,15 @@ class LlamaCppBackend:# Two states land here, only one unmeasurable. Weights# alone over budget: the fit returned the request# untouched, priced nothing, and no context rescues it.- # Or the weights fit and it is the helper's own 4096 floor- # that does not -- a floor, not a measurement, so re-price- # under it before concluding nothing was measured. Without- # that pass a Mac with room for no tested context skipped- # the refusal and reached llama-server, whose --fit cannot- # reduce below 4096 either.+ # Or the weights fit and it is the helper's own+ # _FIT_MIN_CTX floor that does not -- a floor, not a+ # measurement, so re-price under it before concluding+ # nothing was measured. Without that pass a Mac with room+ # for no tested context skipped the refusal and reached+ # llama-server, whose own --fit stops at LLAMA.CPP's+ # fit_params_min_ctx (4096, a different number from ours+ # since this arm's floor became _FIT_MIN_CTX) and so+ # cannot rescue it either._floor_cap = _apple_ctx_fit(native_ctx_for_cap, _FIT_FLOOR_MIN_CTX)# Ask the budget directly rather than inferring the# weights-only state from the two fits disagreeing: both@@ -18923,7 +19379,7 @@ class LlamaCppBackend:# whose weights alone miss the budget, and that is the# host-RAM guard's failure. Floor for the UI, but do# not refuse against a number the fit never vouched for.- max_available_ctx = min(4096, native_ctx_for_cap)+ max_available_ctx = min(_metal_floor_ctx, native_ctx_for_cap)elif _apple_footprint_mib(_floor_cap) <= _apple_fit_budget_mib:max_available_ctx = _floor_cap_apple_measured_ceiling = _floor_cap@@ -18933,15 +19389,16 @@ class LlamaCppBackend:# too, and the strongest available: nothing fits, so# there is no number to lower to and every explicit# request over-commits. Auto is untouched as everywhere- # else here -- it keeps the 4096 floor it has always- # launched at, since changing that is a larger claim- # than this guard makes.- max_available_ctx = min(4096, native_ctx_for_cap)+ # else here -- it keeps this arm's floor, which is now+ # _FIT_MIN_CTX like every other arm, rather than the+ # separate 4096 Metal used to hold.+ max_available_ctx = min(_metal_floor_ctx, native_ctx_for_cap)_apple_nothing_fits = Trueelse:# No KV estimate: mirror the discrete file-size-only fallback- # and floor to 4096 rather than launch at native and over-commit.- max_available_ctx = min(4096, native_ctx_for_cap)+ # and floor to _FIT_MIN_CTX rather than launch at native and+ # over-commit.+ max_available_ctx = min(_metal_floor_ctx, native_ctx_for_cap)if not explicit_ctx:effective_ctx = max_available_ctxelif (@@ -18978,11 +19435,12 @@ class LlamaCppBackend:):_extended_ceiling = _apple_ctx_fit(effective_ctx, _FIT_MIN_CTX)if _apple_footprint_mib(_extended_ceiling) > _apple_fit_budget_mib:- # 4096 is the helper's floor, not a measurement, and- # the cap above re-prices under it for the same reason.+ # _FIT_MIN_CTX is the helper's floor, not a+ # measurement, and the cap above re-prices under it+ # for the same reason.# It bites here whenever native is below the floor: the# request is above native and the floor above what- # fits, so the probe hands back a non-fitting 4096, the+ # fits, so the probe hands back a non-fitting floor, the# check discards it, and the refusal keeps naming the# native-sized cap -- "the largest that fits is 2,048"# on a 2048-native model whose machine launches 3,072@@ -19565,6 +20023,26 @@ class LlamaCppBackend:else:self._gpu_ids = None+ # Did the APU preflight below find a shortfall. Carried to the launch+ # site, which is where `cmd` and `env` first exist and so the only place+ # the pageable-load override can be applied. Without it an oversized+ # unmapped load on an APU is never remapped: _shared_gpu_ids is+ # populated for Vulkan alone, so the discrete guard downstream credits+ # the APU's reported GPU pool against the weights, finds no spill and+ # abstains, while the RAM this launch actually loads into cannot hold+ # them. "none" and "mlock" do not mmap, so that is an OOM kill.+ _apu_ram_oversized = False+ # The two shortfall notices this load recorded, kept verbatim (and+ # un-amended) so the text-only fallback further down can re-price them+ # once it drops the CPU-pinned projector whose bytes they charged. Both+ # are re-stated by the arch-crash retry, which starts its own warning+ # scope, so what these hold is always the pair behind the notice the+ # route would hand back right now.+ _apu_ram_msg: Optional[str] = None+ _host_ram_msg: Optional[str] = None+ # The RAM figure those notices were priced against, kept with them.+ _apu_avail_mib: Optional[int] = None+# Unified-memory APUs load weights into system RAM (under WSL the VM# cap, not the ROCm-reported VRAM, is the real ceiling); refuse an# oversize load the OS would otherwise kill mid-flight. Base model@@ -19575,30 +20053,52 @@ class LlamaCppBackend:and not is_vulkan_backendand self._amd_apu_wants_unified_memory(gpu_indices)):+ # Read ONCE and kept, because the text-only fallback re-prices this+ # same decision much later, with the weights already resident. A+ # second live reading there would be the pool MINUS the model the+ # reprice is asking about, which double-charges it.+ _apu_avail_mib = self._available_system_memory_mib()_ram_msg = self._apu_ram_shortfall_message(# A pinned projector left model_size but not system RAM, and# this guard exists to stop an oversize load being OOM-killed# mid-read, so it has to weigh the projector either way.model_size + _mmproj_pinned_bytes,- self._available_system_memory_mib(),+ _apu_avail_mib,)# gpu_indices is None for a launch nothing pinned, so the guard# priced every visible card, including an APU the gate is about to# drop and whose shared pool the narrowed child never touches.- # Re-ask for the set the child will actually see. Refusal branch+ # Re-ask for the set the child will actually see. Warned branch# only, so a passing launch pays for no probe; an empty answer- # keeps the refusal.+ # keeps the warning.if _ram_msg and gpu_indices is None and not gpu_ids:_gated_pin = self._arch_gate_survivors(binary)if _gated_pin and not self._amd_apu_wants_unified_memory(_gated_pin):logger.info(- "Skipping the APU RAM refusal: the arch gate pins "+ "Skipping the APU RAM warning: the arch gate pins ""this launch to discrete GPU(s) %s.",_gated_pin,)_ram_msg = None- if _ram_msg:- raise RuntimeError(_ram_msg)+ # The condition, not the message: read after the arch-gate skip+ # above, so a launch the gate moves onto discrete cards is not+ # remapped for a shortfall it no longer has. Independent of+ # UNSLOTH_ALLOW_HOST_OFFLOAD, which this preflight never consulted.+ _apu_ram_oversized = bool(_ram_msg)+ # ...and the MESSAGE is the one thing the deprecated opt-out may+ # take away. _apu_ram_shortfall_message prices RAM and never reads+ # it, so without this UNSLOTH_ALLOW_HOST_OFFLOAD silenced the+ # discrete guard next door and left the APU advisory in+ # memory_warning, against a contract that is only ever "silences+ # the warning". Read AFTER the verdict above, so the rewrite the+ # verdict drives is untouched.+ if _ram_msg and self._host_offload_warning_opted_out():+ logger.info(+ "UNSLOTH_ALLOW_HOST_OFFLOAD set: not recording the APU RAM advisory."+ )+ _ram_msg = None+ _apu_ram_msg = _ram_msg+ self._record_load_warning(_ram_msg)# Audio input straight from the mmproj (clip.has_audio_encoder),# independent of token names. A projector passed only via@@ -19662,15 +20162,19 @@ class LlamaCppBackend:)_metal_floor = self._metal_zero_ctx_floor(effective_ctx,- # Auto-layers earns its exemption by leaving the context to --fit,- # so it only holds while --fit actually runs. Extras land after- # Unsloth's own "--fit on" and win, and a "--fit off" there would- # otherwise leave a command with no -c and no fitter, which is- # llama.cpp's native context.- auto_fit and fit_is_effectively_on(extra_args),+ auto_fit,_caller_owns_budget,self._context_length,max_available_ctx,+ # Whether the child's own fitter runs at all, which decides both the+ # Auto-layers exemption and how far the floor may reach. Every branch+ # that can reach the floor emits "--fit on" or nothing (llama.cpp+ # defaults it on); the one branch that emits "--fit off" is manual+ # with a fixed layer count, which _caller_owns_budget exempts. So the+ # only ways off here are the user's own, and both are read: extras+ # land after Unsloth's flag and win, and LLAMA_ARG_FIT is applied+ # before argv when argv sets nothing.+ fitter_runs = fit_is_effectively_on(extra_args, os.environ),)if _metal_floor:effective_ctx = _metal_floor@@ -21006,6 +21510,7 @@ class LlamaCppBackend:self._emit_child_gpu_visibility(env, ",".join(str(i) for i in gpu_indices), prefer_rocr = True)+ _launch_pinned_ids = list(gpu_indices)elif not is_vulkan_backend and not gpu_ids:# Nothing above pinned the child. Two shapes land here and the gate# breaks both the same way, so they share one probe: `--fit on`@@ -21077,6 +21582,8 @@ class LlamaCppBackend:self._emit_child_gpu_visibility(env, ",".join(str(i) for i in _survivors), prefer_rocr = True)+ # Narrower than any pin above, so it replaces it.+ _launch_pinned_ids = list(_survivors)elif manual_tensor_split_emitted:# A manual per-GPU ratio across ALL GPUs (no explicit pick, so# no mask above): the UI built --tensor-split in ascending@@ -21084,28 +21591,106 @@ class LlamaCppBackend:# The whole visible set stays in use, only its order is fixed.self._pin_visible_gpu_order_for_split(env)+ _child_has_no_gpu = (+ # each names a device present but unusable, so it owns the empty pool+ _arch_gate_forced_cpu+ or _paravirtual_cpu_forced+ # neither says a device exists, so an empty pool stays unreadable+ or (+ bool(_detected_gpus)+ and (+ _cpu_only_zero_offload or self._binary_ships_no_gpu_backend(binary, env)+ )+ )+ )+ # The host pool as it stands before ANYTHING spawns, kept for the Vulkan+ # CPU replay to re-price against. That replay only runs once a CPU-only+ # child is healthy and holding the whole model in system RAM, where a+ # live reading is the pool minus the very model being priced. Taken+ # here, and handed to the guard below as well, so the two verdicts+ # differ in exactly one term -- the VRAM credit the replay loses -- and+ # never in the pool they were read against. Only on the path that can+ # use it: a load with no CPU replay available pays for no probe, and+ # None restores the guard's own live reading.+ _preflight_avail_mib = (+ self._available_system_memory_mib() if _cpu_fallback_eligible else None+ )+ # Only the cards this child can reach. VRAM on a card this launch+ # pinned away is not VRAM it can spend: crediting it prices the spill+ # too low and leaves an unmapped oversized load unrewritten, which is+ # an OOM rather than the slow load the override exists to produce.+ _reachable_gpus = self._rows_the_child_can_reach(_detected_gpus, _launch_pinned_ids)# reads the argv the child gets, not the mid-fit state that produced it_offload_msg = self._launch_host_shortfall_message(cmd,- _detected_gpus,+ _reachable_gpus,env,- child_has_no_gpu = (- # each names a device present but unusable, so it owns the empty pool- _arch_gate_forced_cpu- or _paravirtual_cpu_forced- # neither says a device exists, so an empty pool stays unreadable- or (- bool(_detected_gpus)- and (- _cpu_only_zero_offload- or self._binary_ships_no_gpu_backend(binary, env)- )- )- ),+ child_has_no_gpu = _child_has_no_gpu,+ avail_mib = _preflight_avail_mib,shared_gpu_ids = _shared_gpu_ids,)- if _offload_msg:- raise RuntimeError(_offload_msg)+ # Snapshotted BEFORE the override note is appended below, so a re-price+ # that promotes this notice appends that note once rather than twice.+ _host_ram_msg = _offload_msg++ def _launch_is_oversized() -> bool:+ """Whether SOMETHING about to launch does not fit, warning aside.++ Three readings, because one alone misses a shape the override has+ to cover. The APU preflight, whose shortfall this guard cannot see:+ _shared_gpu_ids covers Vulkan only, so a ROCm APU's reported pool is+ credited here as if it were dedicated VRAM and the spill prices out+ at zero. The warning just produced, which is the discrete case. And,+ only when the deprecated opt-out silenced that warning, the same+ pricing with the opt-out ignored: the variable's contract is that it+ hides a message, and hiding a message must not withdraw the rewrite+ that makes the load possible.+ """+ if _apu_ram_oversized or _offload_msg:+ return True+ if not self._host_offload_warning_opted_out():+ return False+ return bool(+ self._launch_host_shortfall_message(+ cmd,+ _reachable_gpus,+ env,+ child_has_no_gpu = _child_has_no_gpu,+ shared_gpu_ids = _shared_gpu_ids,+ honor_opt_out = False,+ )+ )++ cmd, _pageable_note = self._page_an_oversized_unmapped_load(+ cmd, env, _launch_is_oversized+ )+ if _pageable_note:+ # Only onto a warning that is actually emitted; when the opt-out+ # suppressed it the override still went to the log, which is what+ # keeps a silenced load traceable.+ if _offload_msg:+ _offload_msg += _pageable_note+ # And onto whatever is already recorded, which is not the same+ # thing. First notice wins, so when the APU preflight also warned+ # its text is what the route hands back and the _offload_msg+ # amended just above is dropped by _record_load_warning below --+ # leaving memory_warning silent about an override that did change+ # the child's argv. A no-op when nothing was recorded, including a+ # load the opt-out silenced, and it cannot double-append: the note+ # reaches at most one of the two strings.+ self._amend_load_warning(_pageable_note)+ # The recorded state has to describe the argv that launches, or the+ # reload comparator judges this child against a mode it no longer+ # runs. The snapshot too: the arch-crash retry restores it over+ # `cmd`, which now carries the override.+ self._memory_state = resolve_effective_memory_state(cmd, env)+ _mem_policy_for_cmd = (+ _mem_host_resident,+ self._memory_state,+ self._memory_policy_active,+ self._memory_mlock_applicable,+ )+ self._record_load_warning(_offload_msg)# Captured before any text-only fallback strips it from cmd.launched_with_mmproj = "--mmproj" in cmd@@ -21471,6 +22056,7 @@ class LlamaCppBackend:worth replaying."""nonlocal intent, gpu_memory_mode, gpu_layers, n_cpu_moe+ nonlocal _replay_pageable_overridenonlocal tensor_parallel, tensor_split, gpu_indices, use_fit, _spawn_cwd# GGML_ASSERT is a signal on POSIX and a CRT abort (exit 3) on# MSVC, so Windows needs both. Cancel-checked like every retry@@ -21487,6 +22073,9 @@ class LlamaCppBackend:env,server_caps,drop_full_offload_threads = _drop_full_offload_threads,+ # The same host pool the preflight and the reprice below read,+ # so the rewrite and the advisory answer one question once.+ avail_mib = _preflight_avail_mib,)if prepared is None:return False@@ -21496,7 +22085,16 @@ class LlamaCppBackend:# remove; take it back here.self._cleanup_cpu_fallback_runtime()return False- replay, _spawn_cwd = prepared+ replay, _spawn_cwd, _cpu_pageable_note = prepared+ # The rewrite mutates the SHARED env in place, so it happens once+ # even when several argvs are replayed. A non-terminal failure+ # below returns without the note, and the next replay then finds an+ # already-pageable env and produces none of its own -- so whichever+ # attempt finally comes up would report ordinary paging and never+ # say the user's load mode had been overridden. Carried instead.+ if _cpu_pageable_note:+ _replay_pageable_override = _cpu_pageable_note+ _cpu_pageable_note = _cpu_pageable_note or _replay_pageable_overridelogger.warning("The auto-selected Vulkan backend hard-crashed during "@@ -21529,7 +22127,12 @@ class LlamaCppBackend:# make, and a later "Don't reserve system RAM" would demand a# pointless reload. From _last_spawn_cmd, the argv that really# started, so this cannot undo a record a --fit retry wrote.- if self._fit_load_mode_flags:+ #+ # Or the pageable override rewrote a mode this replay no longer runs+ # with: the record has to describe the argv that started, whichever+ # of the two changed it, or the reload comparator judges this child+ # against a mode it does not have.+ if self._fit_load_mode_flags or _cpu_pageable_note:self._memory_state = resolve_effective_memory_state(_last_spawn_cmd, env)intent = self._apply_cpu_fallback_state(intent,@@ -21551,6 +22154,17 @@ class LlamaCppBackend:tensor_split = intent.tensor_splitgpu_indices = Noneuse_fit = False+ # Everything above records that this session runs on no GPU; the+ # advisory has to say so too. Here and not at the decision above,+ # because only a child that came up is evidence of what is running+ # and a failed replay can still fall through to another argv.+ self._reprice_after_cpu_only_fallback(+ host_msg = _host_ram_msg,+ cpu_cmd = _last_spawn_cmd,+ env = env,+ avail_mib = _preflight_avail_mib,+ pageable_note = _cpu_pageable_note,+ )logger.warning("llama-server loaded successfully on CPU after the ""auto-selected Vulkan backend crashed. GPU acceleration "@@ -21625,19 +22239,37 @@ class LlamaCppBackend:env,server_caps,drop_full_offload_threads = _drop_full_offload_threads,+ avail_mib = _preflight_avail_mib,)if prepared is None:_raise_terminal_load_failure("The prior Vulkan CPU fallback could not be reconstructed; run ""`unsloth studio update` to repair the managed llama.cpp runtime.")- cmd, _spawn_cwd = prepared+ cmd, _spawn_cwd, _replay_pageable_note = prepared# Same reason as the crash path, recomputed from the stripped# `cmd` before anything spawns. The arch-crash rung re-derives it# from `cmd` too, so the _mem_policy_for_cmd snapshot it restores- # cannot put the stale pair back.- if self._fit_load_mode_flags:+ # cannot put the stale pair back. The pageable override rewrites+ # the same field, so either one having fired makes the record stale.+ if self._fit_load_mode_flags or _replay_pageable_note:self._memory_state = resolve_effective_memory_state(cmd, env)+ # The preflight above priced and, where needed, rewrote the argv+ # this replay was built FROM; an override settled here is news it+ # could not have carried. Appended to whatever notice is recorded,+ # the same way the APU preflight's override reaches the message,+ # and a no-op on a load whose warning the opt-out silenced, which+ # keeps the log line as its only record.+ self._amend_load_warning(_replay_pageable_note)+ # This replay is CPU-only by construction (--device none), so+ # the advisory has to describe the whole model in host RAM. The+ # amend above can only add to a notice that already exists, and+ # on a restored fallback there often is none: an empty Vulkan+ # probe leaves _child_has_no_gpu False, so the preflight+ # abstained and memory_warning was null for a session paging+ # everything from disk. Deferred rather than priced here,+ # because only a child that came up is evidence of what runs.+ _restored_cpu_reprice = _replay_pageable_note or True# Same normalization the crash path applies, so a client that# sent only the flag cannot leave a CPU-only server reporting# an Auto/GPU placement (which then fails holds_no_vram).@@ -21731,30 +22363,53 @@ class LlamaCppBackend:)if _remaining:_retry_wants_unified = self._amd_apu_wants_unified_memory(_remaining)+ # Everything recorded so far priced the CRASHED selection, and+ # that placement is gone: the canonical #7624 shape pins the APU+ # whose shared-pool "free memory" outranked the dGPU, warns that+ # system RAM cannot hold the weights, then crashes and respawns+ # on the discrete sibling that holds them in VRAM. First notice+ # wins, so without this the served child reports a shortfall on+ # a device it never touches. The two checks below price exactly+ # the set the respawn reaches, and both are wider than their+ # upstream twins (the same weights against a NARROWED pool), so+ # a shortfall that still stands is re-recorded here.+ #+ # Both are also kept in a variable: the pageable-load override+ # at the END of this block, after every rewrite `cmd` still has+ # coming, reads them as its shortfall condition and amends+ # whichever one first-notice-wins recorded.+ self._begin_load_warnings()+ # ...and the re-price snapshots go with the scope they describe:+ # the preflight's pair priced the crashed placement, so leaving+ # them standing would let the text-only fallback re-price the+ # notice this block is about to record against the wrong pool.+ _apu_ram_msg = None+ _host_ram_msg = None+ _apu_avail_mib = None# The APU RAM preflight upstream ran against the CRASHED- # selection, discrete on this arm by construction, so it never- # fired. The mirror shape (crash on the dGPU, retry on the+ # selection. The mirror shape (crash on the dGPU, retry on the# unified-memory sibling) makes the respawn the first load into- # system RAM. Unchecked, an oversized GGUF is OOM-killed- # mid-load instead of getting the refusal the same host gives- # when the APU is picked first.+ # system RAM, so price it here too. Advisory: the respawn goes+ # ahead either way.+ _retry_apu_msg = Noneif model_size is not None and _retry_wants_unified:- _retry_ram_msg = self._apu_ram_shortfall_message(+ _apu_avail_mib = self._available_system_memory_mib()+ _retry_apu_msg = self._apu_ram_shortfall_message(model_size + _mmproj_pinned_bytes,- self._available_system_memory_mib(),+ _apu_avail_mib,)- if _retry_ram_msg:- self._kill_process()- raise RuntimeError(_retry_ram_msg)+ # Same contract as the preflight above: the opt-out takes+ # the message and nothing else. _retry_apu_msg itself stays+ # set, so _retry_is_oversized below still sees the+ # shortfall and the pageable rewrite still happens.+ if not self._host_offload_warning_opted_out():+ _apu_ram_msg = _retry_apu_msg+ self._record_load_warning(_retry_apu_msg)# host guard credited the whole pool; the respawn reaches only _remaining- _retry_offload_msg = self._launch_host_shortfall_message(- cmd,- [row for row in _detected_gpus if row[0] in set(_remaining)],- env,- )- if _retry_offload_msg:- self._kill_process()- raise RuntimeError(_retry_offload_msg)+ _retry_rows = [row for row in _detected_gpus if row[0] in set(_remaining)]+ _retry_host_msg = self._launch_host_shortfall_message(cmd, _retry_rows, env)+ _host_ram_msg = _retry_host_msg+ self._record_load_warning(_retry_host_msg)logger.warning(f"llama-server crashed with a HIP kernel-image error on "f"GPU(s) {_crashed} -- the llama.cpp build has no kernels "@@ -21919,6 +22574,37 @@ class LlamaCppBackend:"recomputed Model Memory (%s)."," ".join(_retry_managed) if _retry_managed else "no page-lock",)++ # Last, because everything above still rewrites `cmd`: the+ # tensor-split drop, the split-mode drop, the fit's load-mode+ # strip and the re-armed page-lock. The narrowed pool is where a+ # load that FIT its first placement can meet its first shortfall,+ # and nothing upstream remapped it, so an unmapped respawn would+ # allocate the whole model in host RAM and be OOM-killed. Same+ # condition, same helper, before the respawn rather than after.+ def _retry_is_oversized() -> bool:+ if _retry_apu_msg or _retry_host_msg:+ return True+ # The opt-out silences the message, never the rewrite.+ if not self._host_offload_warning_opted_out():+ return False+ return bool(+ self._launch_host_shortfall_message(+ cmd, _retry_rows, env, honor_opt_out = False+ )+ )++ cmd, _retry_pageable_note = self._page_an_oversized_unmapped_load(+ cmd, env, _retry_is_oversized+ )+ if _retry_pageable_note:+ # Onto whichever notice first-notice-wins kept above; a+ # suppressed one leaves the log line as the only record,+ # which is the intended contract for the opt-out.+ self._amend_load_warning(_retry_pageable_note)+ # From the argv, like the fit-strip above: `cmd` is what+ # the respawn runs, and the record has to match it.+ self._memory_state = resolve_effective_memory_state(cmd, env)healthy = _spawn_and_wait(cmd, label = "-archfallback")# Flash-attention kernels hard-crash at startup on some ROCm/GPU@@ -22292,6 +22978,21 @@ class LlamaCppBackend:self._start_llama_process(cmd, env)if self._wait_for_health(timeout = 600.0):healthy = True+ # The child that serves this session never read the+ # CPU-pinned projector, so the host-memory advisory the+ # APU preflight charged it against is now describing a+ # load nothing is running. Priced again here, and not at+ # the strip above, because a failed text-only retry can+ # still replay the ORIGINAL vision argv on CPU further+ # down -- projector and all -- and that child does load+ # the bytes. Only a healthy text-only server is evidence.+ self._reprice_after_dropping_pinned_projector(+ apu_msg = _apu_ram_msg,+ host_msg = _host_ram_msg,+ model_size = model_size,+ pinned_bytes = _mmproj_pinned_bytes,+ avail_mib = _apu_avail_mib,+ )else:# Read the exit code before _kill_process() clears it, so# an OS-killed text-only retry still gets the OOM message.@@ -22369,6 +23070,22 @@ class LlamaCppBackend:))+ if _restored_cpu_reprice is not None:+ # The child that answered is the CPU-only replay, so price the+ # advisory against the whole model in system RAM, against the pool+ # the preflight read rather than a live one taken with the weights+ # already resident.+ self._reprice_after_cpu_only_fallback(+ host_msg = _host_ram_msg,+ cpu_cmd = _last_spawn_cmd or cmd,+ env = env,+ avail_mib = _preflight_avail_mib,+ pageable_note = (+ _restored_cpu_reprice+ if isinstance(_restored_cpu_reprice, str)+ else None+ ),+ )self._healthy = Trueself._commit_effective_parallel_slots(n_parallel)self._swa_full = swa_fulldiff --git a/studio/backend/core/inference/llama_server_args.py b/studio/backend/core/inference/llama_server_args.pyindex 0fe84b7f0da..71ce448d966 100644--- a/studio/backend/core/inference/llama_server_args.py+++ b/studio/backend/core/inference/llama_server_args.py@@ -1620,6 +1620,161 @@ def scrub_memory_env(env: dict) -> list[str]:return removed+# The pageable twin of each mode that reads the weights into a buffer it allocates.+# Upstream sets use_mmap for mmap / mmap+mlock / auto only (llama-model-loader.cpp),+# so `mlock` is a full host copy that is also locked, and `mmap+mlock` is the same+# lock over a mapping. `none` has no lock to preserve, so it goes back to the default.+_PAGEABLE_LOAD_MODE: dict[str, Optional[str]] = {"none": None, "mlock": "mmap+mlock"}+# Modes that already map, so the rewrite has no unmapped copy of its own to fix and+# leaves them alone. It reaches them only when a LATER reserving selector shadowed the+# lock (``--load-mode mmap+mlock --no-mmap`` runs unlocked and unmapped, last-wins), and+# there dropping only the selector hands the child back the lock it had lost -- over the+# full-size mapping the override just restored, which is the one outcome it exists to+# prevent. So they are stripped in that state and in no other.+_SHADOWED_LOCK_LOAD_MODE = frozenset({"mmap+mlock"})+++def _pageable_mode_replacement(+ normalized: str, drop_shadowed_mlock: bool+) -> tuple[bool, Optional[str]]:+ """``(rewrite, replacement)`` for one ``--load-mode`` value, argv or env alike.++ ``replacement`` None removes the selector, leaving llama.cpp's default mapping.+ """+ if normalized in _PAGEABLE_LOAD_MODE:+ return True, None if drop_shadowed_mlock else _PAGEABLE_LOAD_MODE[normalized]+ if normalized in _SHADOWED_LOCK_LOAD_MODE:+ return drop_shadowed_mlock, None+ return False, None+++def _pageable_env_value(+ name: str,+ value: str,+ drop_shadowed_mlock: bool = False,+) -> tuple[bool, Optional[str]]:+ """``(rewrite, new_value)`` for an inherited var that disables mmap.++ ``rewrite`` False leaves the var alone. ``new_value`` None means remove it; a+ string replaces it, which is how a locked mode keeps its lock. ``LLAMA_ARG_MLOCK``+ is otherwise left alone: on its own it sets the lock bit over the default mapping+ and holds no unmapped copy.++ ``drop_shadowed_mlock`` says the launch is NOT locked before the rewrite, because+ a later selector reset the mlock bit -- llama.cpp resolves these last-wins, so+ ``LLAMA_ARG_MLOCK=1`` beside ``LLAMA_ARG_NO_MMAP`` leaves the child unlocked. There+ is then no lock to carry, so the var goes and a ``mlock`` mode is dropped rather+ than promoted to ``mmap+mlock``.+ """+ normalized = value.strip().lower()+ if name == "LLAMA_ARG_MLOCK":+ # Only when it is already shadowed: resurrecting it would page-lock the+ # oversized mapping into the RAM this override exists to keep pageable.+ return drop_shadowed_mlock and normalized in _ENV_TRUE_VALUES, None+ if name in {"LLAMA_ARG_NO_MMAP", "LLAMA_ARG_NO_DIO"}:+ # Presence alone selects mode "none", whatever the value says.+ return True, None+ if name in {"LLAMA_ARG_MMAP", "LLAMA_ARG_DIO"}:+ # Falsy selects "none"; truthy selects mmap / dio, neither of which+ # holds a full copy.+ return normalized in _ENV_FALSE_VALUES, None+ if name == "LLAMA_ARG_LOAD_MODE":+ return _pageable_mode_replacement(normalized, drop_shadowed_mlock)+ return False, None+++def force_pageable_load(+ argv: Optional[Iterable[str]], env: Optional[dict] = None+) -> tuple[list[str], list[str]]:+ """Rewrite a launch that would hold a full unmapped host copy into a pageable one.++ Returns ``(argv, overridden)``, naming the argv tokens and env vars that were+ dropped or rewritten, for the log line and the warning. Empty means the launch was+ already pageable and ``argv`` comes back unchanged.++ Modes ``none`` and ``mlock`` read the weights into a buffer llama.cpp allocates+ (``use_mmap`` is set for ``mmap``/``mmap+mlock``/``auto`` and nothing else), so a+ model larger than free RAM cannot load at all rather than paging in slowly. Both+ sides of llama.cpp's env-then-argv resolution are rewritten, since the environment+ supplies the default the argv only overrides when it names the same option.++ A lock that is EFFECTIVE is preserved rather than dropped: ``mlock`` becomes+ ``mmap+mlock`` and ``--no-mmap --mlock`` keeps its lock through the strip, so "keep+ this in RAM" still holds -- over a mapping the kernel can fall back on. ``none`` has+ no lock to keep and needs no replacement flag at all, mmap being the default, so a+ build predating ``--load-mode`` is handed nothing it cannot parse.++ A SHADOWED lock is not resurrected. These options resolve last-wins, so+ ``--mlock --no-mmap`` (and the ``LLAMA_ARG_`` twins, where the negative alias is+ read after the affirmative one) runs unlocked and unmapped: the reserving selector+ already cleared the lock bit, which is what ``resolve_effective_memory_state``+ reports. Dropping only the selector and leaving the earlier ``--mlock`` standing+ would hand the child ``mmap+mlock`` and page-lock the whole oversized mapping into+ the RAM this override exists to keep pageable -- worse than the load it fixes. So+ the pre-rewrite state decides, not the tokens that happen to be present.+ """+ tokens = [str(a) for a in (argv or [])]+ # What the child runs TODAY, across env and argv in llama.cpp's own resolution+ # order. Only a launch that reserves RAM is rewritten at all, so a pageable one+ # (``dio``, plain ``mmap``) keeps every token it was given, mlock included.+ _mlock_now, _reserves_now = resolve_effective_memory_state(tokens, env)+ drop_shadowed_mlock = _reserves_now and not _mlock_now+ overridden: list[str] = []+ out: list[str] = []+ i, n = 0, len(tokens)+ while i < n:+ token = tokens[i]+ flag = _flag_name(token)+ # --no-mmap / --no-direct-io: upstream's deprecated spellings for "none".+ # Valueless, so the token goes and nothing follows it out.+ if flag in _RAM_RESERVING_FLAGS:+ overridden.append(token)+ i += 1+ continue+ # A lock a later selector already cleared. Valueless like the above, and+ # named in `overridden` so the log line describes the whole rewrite.+ if drop_shadowed_mlock and flag in _MLOCK_FLAGS:+ overridden.append(token)+ i += 1+ continue+ if flag in _LOAD_MODE_FLAGS:+ if "=" in token:+ value, step = token.split("=", 1)[1], 1+ elif i + 1 < n and _flag_name(tokens[i + 1]) is None:+ value, step = tokens[i + 1], 2+ else:+ value, step = "", 1+ normalized = value.strip().lower()+ # `--load-mode mlock --no-mmap` is unlocked by the time the child parses+ # it, so mmap+mlock would ADD a lock; `mmap+mlock --no-mmap` is the same+ # shape one spelling further on, and there the selector itself is the lock.+ rewrite_mode, replacement = _pageable_mode_replacement(normalized, drop_shadowed_mlock)+ if rewrite_mode:+ overridden.append(" ".join(tokens[i : i + step]))+ if replacement is not None:+ out.extend([tokens[i].split("=", 1)[0], replacement])+ i += step+ continue+ out.extend(tokens[i : i + step])+ i += step+ continue+ out.append(token)+ i += 1+ if env is not None:+ for name in MEMORY_ENV_VARS:+ if name not in env:+ continue+ rewrite, new_value = _pageable_env_value(name, str(env[name]), drop_shadowed_mlock)+ if not rewrite:+ continue+ if new_value is None:+ env.pop(name, None)+ else:+ env[name] = new_value+ overridden.append(name)+ return out, overridden++# Mirrors llama_cpp's _LLAMA_ARG_TRUE/FALSE_VALUES; duplicated so this module# stays dependency-free (llama_cpp imports from here, not the other way)._ENV_TRUE_VALUES = frozenset({"on", "enabled", "true", "1"})diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 027b61c614b..9b2addd5b70 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -1330,6 +1330,12 @@ class LoadResponse(_InferenceRuntimeFields):inference: dict = Field(..., description = "Inference parameters (temperature, top_p, top_k, min_p)")+ memory_warning: Optional[str] = Field(+ None,+ description = "Non-blocking advisory about this load, or null. Set when the "+ "weights do not fit in free VRAM plus available system RAM, so llama.cpp pages "+ "them in from disk and generation will be slow. The model still loaded.",+ )class UnloadResponse(BaseModel):diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 3c020f426eb..124b875e7e2 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -6017,6 +6017,10 @@ def _gguf_load_response(inference = load_inference_config(inference_identifier or llama_backend.model_identifier or model),+ # Advisory, and None on nearly every load. Recorded by load_model when the+ # weights outgrow fast memory, so the client can say why generation is slow.+ # getattr: older/custom backend doubles predate this additive field.+ memory_warning = getattr(llama_backend, "last_load_warning", None),**_llama_runtime_fields(llama_backend),)@@ -12420,13 +12424,15 @@ async def _load_model_impl(if _non_chat:logger.error("Refusing non-chat GGUF before the GPU handoff: %s", _non_chat)raise HTTPException(status_code = 400, detail = _non_chat)- # same reason: the host-RAM guard reads the finished argv, so it answers too late- _host_offload = await asyncio.to_thread(- llama_backend.host_offload_refusal_for_intent, gguf_intent- )- if _host_offload:- logger.error("Refusing an oversized GGUF before the GPU handoff: %s", _host_offload)- raise HTTPException(status_code = 400, detail = _host_offload)+ # Advisory, not a gate: an oversized GGUF mmaps and pages from disk rather+ # than failing, which off fast storage is a deliberate way to run a quant+ # bigger than fast memory, so the load goes ahead. Asked here as well as at+ # launch because load_model's copy runs too deep to reach the response.+ _host_offload_warning = await asyncio.to_thread(+ llama_backend.host_offload_warning_for_intent, gguf_intent+ )+ if _host_offload_warning:+ logger.warning("Loading an oversized GGUF: %s", _host_offload_warning)if chat_load_needs_gpu:gpu_acquire_kwargs = {} if allow_gpu_owner_eviction else {"allow_evict": False}diff --git a/studio/backend/tests/test_auto_offload_ctx_fit_floor_coupling.py b/studio/backend/tests/test_auto_offload_ctx_fit_floor_coupling.pyindex 56b75615d8a..17e048d15f3 100644--- a/studio/backend/tests/test_auto_offload_ctx_fit_floor_coupling.py+++ b/studio/backend/tests/test_auto_offload_ctx_fit_floor_coupling.py@@ -30,6 +30,7 @@ from __future__ import annotationsimport importlib.utilimport inspect+import refrom pathlib import Pathimport pytest@@ -227,6 +228,20 @@ def test_the_projector_residency_floor_is_the_fit_floor_and_not_the_offload_contPinned here because the two constants were the same literal before this change,so a reader could reasonably assume they still move together.++ The value check is on the fit floor only. Raising ``_FIT_MIN_CTX`` to 8192 put it+ on the same number as ``_AUTO_OFFLOAD_CTX`` again, so ``!=`` on the values no+ longer separates the two concepts: it would fail on a correct tree and pass on a+ wrong one the moment the offload fallback moved. Assert instead that the projector+ floor is DERIVED from the fit floor and never from the offload fallback, which is+ the mistake this test exists to catch and holds whatever the two numbers are."""assert LlamaCppBackend._MMPROJ_FIT_FLOOR_CTX == _FIT_MIN_CTX- assert LlamaCppBackend._MMPROJ_FIT_FLOOR_CTX != _AUTO_OFFLOAD_CTX+ source = inspect.getsource(LlamaCppBackend)+ assignment = re.search(r"^\s*_MMPROJ_FIT_FLOOR_CTX\s*=\s*(.+)$", source, re.MULTILINE)+ assert assignment, "_MMPROJ_FIT_FLOOR_CTX is no longer a class attribute of the backend"+ assert "_AUTO_OFFLOAD_CTX" not in assignment.group(1), (+ "_MMPROJ_FIT_FLOOR_CTX is being set from _AUTO_OFFLOAD_CTX. It must track the FIT "+ "floor: the projector probe asks for the lowest context at which placement can "+ f"still award GPU residency, which the offload fallback is past. Got {assignment.group(1)!r}."+ )diff --git a/studio/backend/tests/test_auto_offload_ctx_platform_matrix.py b/studio/backend/tests/test_auto_offload_ctx_platform_matrix.pyindex ecf1ba5ab9f..9b51ec6642c 100644--- a/studio/backend/tests/test_auto_offload_ctx_platform_matrix.py+++ b/studio/backend/tests/test_auto_offload_ctx_platform_matrix.py@@ -17,7 +17,9 @@ The chain under test, in source order:subset loop's ``else:`` plus its residency re-check3. file-size-only -- gpus, no KV metadata; holds SITE B, which onlyrelabels the context ``--fit`` was already given- 4. Apple unified memory -- no gpus, a Metal budget; hardcoded 4096s, untouched+ 4. Apple unified memory -- no gpus, a Metal budget; floors at _FIT_MIN_CTX+ like every other arm, since its four hardcoded+ 4096s were replaced by the constant5. (no arm) -- no gpus and no Metal budget: CPU, no context mathEach cell records the arm taken, the emitted context, ``--fit`` and the pinned@@ -421,19 +423,25 @@ def test_the_file_size_only_arm_relabels_the_context_without_moving_a_device(assert outcome.ctx == _AUTO_OFFLOAD_CTX-# ── G3: the Metal asymmetry, measured ────────────────────────────────────────+# ── G3: the Metal arm, measured against the discrete one ─────────────────────@pytest.mark.parametrize("platform", PLATFORMS, ids = [p[0] for p in PLATFORMS])def test_metal_auto_still_floors_at_the_fit_minimum(tmp_path, monkeypatch, platform):"""G3. Pins the CURRENT Metal behaviour so it cannot drift silently.- The Apple arm keeps its own floor and never reads ``_AUTO_OFFLOAD_CTX``, so an- offloading model gets ``_FIT_MIN_CTX`` here and ``_AUTO_OFFLOAD_CTX`` on a- discrete GPU: half the context on the same model. That asymmetry is deliberate- (unified memory is shared with the OS, so a larger KV is charged to the same- pool the weights and the compositor live in) and this test exists to make any- future change to it explicit rather than incidental.+ This used to measure an ASYMMETRY: the Apple arm held four hardcoded 4096s while+ a discrete GPU got ``_AUTO_OFFLOAD_CTX``, so the same offloading model published+ half the context on a Mac. Those four sites now read ``_FIT_MIN_CTX``, the+ asymmetry is gone by design, and what is worth pinning is the symmetry -- the two+ arms agreeing is the property that regresses if anyone re-introduces a separate+ Metal literal.++ The equality is asserted against the CONSTANTS on both sides rather than against+ 8192, so the pair keeps agreeing through the next floor move instead of failing+ here. The old form asserted ``on_discrete.ctx == 2 * on_metal.ctx``, which was a+ correct reading of the ratio at the time and is exactly the shape that turns a+ deliberate change into a puzzling failure.Parametrised over every platform on purpose: the arm is gated on a non-zeroMetal budget, not on ``sys.platform``, and that is worth having on record.@@ -447,7 +455,8 @@ def test_metal_auto_still_floors_at_the_fit_minimum(tmp_path, monkeypatch, platfdiscrete = next(a for a in ACCELERATORS if a.label == "nvidia-single")on_discrete = run_cell(_subdir(tmp_path, "discrete"), monkeypatch, platform, discrete)assert on_discrete.ctx == _AUTO_OFFLOAD_CTX- assert on_discrete.ctx == 2 * on_metal.ctx+ # Same model, same published context, whichever kind of memory it lands in.+ assert on_discrete.ctx == on_metal.ctx# ── G7: manual memory mode ───────────────────────────────────────────────────@@ -585,12 +594,20 @@ def test_the_windows_rocm_cap_is_what_pushes_a_load_into_the_fallback(tmp_path,hardware where Linux AMD users never see it. Not a regression the constantintroduced -- the same asymmetry sent them to 4096 before -- but it is the cellwhere the new value is most often visible.++ The weights are 10 GiB rather than the 12 GiB this started at. At 12 GiB both+ sides offload now: 12288 + 320 MiB leaves 2900 of a 15508 MiB Linux budget,+ which held a 4096 context and does not hold an 8192 one, so the cell stopped+ contrasting anything the moment the fit floor moved. 10 GiB restores the+ contrast and leaves it a measurement rather than a floor -- Linux pins at 9728,+ 1536 above the floor -- so the next floor move shows up as this test failing+ only once it would really have changed the placement."""windows = next(p for p in PLATFORMS if p[0] == "windows")linux = next(p for p in PLATFORMS if p[0] == "linux")- # 12 GiB of weights: inside a 16000 MiB budget with room for a KV, outside the- # 10384 MiB one before any context is priced at all.- model_mib = 12 * 1024+ # 10 GiB of weights: inside a 16000 MiB budget with room for a KV at the fit+ # floor, outside the 10384 MiB one before any context is priced at all.+ model_mib = 10 * 1024def _run(platform, free_mib, subdir):accelerator = Accelerator("amd-rocm", False, ((0, free_mib, 16_384),), is_rocm = True)diff --git a/studio/backend/tests/test_compute_buffer.py b/studio/backend/tests/test_compute_buffer.pyindex 4b2ba88acb0..16381ece51b 100644--- a/studio/backend/tests/test_compute_buffer.py+++ b/studio/backend/tests/test_compute_buffer.py@@ -908,26 +908,39 @@ class TestPerDeviceSplitReserve:return sorted(idx for idx, _ in subset), ctxreturn None, 0+ def _card_at_floor_reserve(self, b, total_mib, margin_mib):+ """Free VRAM leaving card 1 exactly ``margin_mib`` from the reserve it+ replicates AT THE FIT FLOOR, which is the context ``_drive_reduced`` runs.++ Derived rather than written out: the whole point of these two cases is a+ card sized one MiB either side of that reserve, so the number has to follow+ the floor. Spelled 4096 it silently stopped straddling anything when the+ floor moved to 8192 -- the card was built against reserve(4096) == 1120 MiB+ while the driver charged reserve(8192) == 1216.+ """+ reserve_mib = (+ self._OH + b._compute_buffer_ctx_bytes(_FIT_MIN_CTX, self._UB, "f16", layer_split = True)+ ) / MIB+ return round(reserve_mib + margin_mib + 0.03 * total_mib)+def test_reduced_context_fallback_enforces_the_same_reserve(self):- # Card 1 sized one MiB under the reserve it replicates at 4096 ctx: the pooled- # budget still admits the pair, so dropping to 4096 pinned a card that OOMs.+ # Card 1 sized one MiB under the reserve it replicates at the floor: the+ # pooled budget still admits the pair, so dropping to the floor pinned a+ # card that OOMs.b = self._fit_backend()totals = {0: 49_152, 1: 24_576}- reserve_mib = (- self._OH + b._compute_buffer_ctx_bytes(4096, self._UB, "f16", layer_split = True)- ) / MIB- gpus = [(0, 40_000), (1, round(reserve_mib - 1 + 0.03 * totals[1]))]- assert self._drive_reduced(b, gpus, totals, 20_480, enforce = False) == ([0, 1], 4096)+ gpus = [(0, 40_000), (1, self._card_at_floor_reserve(b, totals[1], -1))]+ assert self._drive_reduced(b, gpus, totals, 20_480, enforce = False) == (+ [0, 1],+ _FIT_MIN_CTX,+ )assert self._drive_reduced(b, gpus, totals, 20_480) == (None, 0)def test_reduced_context_fallback_keeps_a_card_that_holds_it(self):b = self._fit_backend()totals = {0: 49_152, 1: 24_576}- reserve_mib = (- self._OH + b._compute_buffer_ctx_bytes(4096, self._UB, "f16", layer_split = True)- ) / MIB- gpus = [(0, 40_000), (1, round(reserve_mib + 1 + 0.03 * totals[1]))]- assert self._drive_reduced(b, gpus, totals, 20_480) == ([0, 1], 4096)+ gpus = [(0, 40_000), (1, self._card_at_floor_reserve(b, totals[1], +1))]+ assert self._drive_reduced(b, gpus, totals, 20_480) == ([0, 1], _FIT_MIN_CTX)def test_pooled_budget_hides_the_small_cards_shortfall(self):# Pre-fix: the pair is admitted at native context even though card 1 has@@ -1034,18 +1047,21 @@ class TestPerDeviceReserveCap:gpus, totals = self._HOMOGENEOUSassert self._drive(b, gpus, totals, 20_480, 262144) == ([0, 1], 262144)- def test_cap_floors_at_4096_and_still_rejects_below_it(self):- # usable 1118.72 < reserve(4096) == 1120.0: nothing to salvage.+ _card_at_floor_reserve = TestPerDeviceSplitReserve._card_at_floor_reserve++ def test_cap_floors_at_the_fit_minimum_and_still_rejects_below_it(self):+ # Card 1 one MiB under reserve(_FIT_MIN_CTX): the cap has nothing to salvage,+ # so it returns 0 rather than handing back the floor it could not price.b = self._fit_backend()- assert self._drive(- b, [(0, 40_000), (1, 1_856)], {0: 49_152, 1: 24_576}, 20_480, 262144- ) == (None, 0)+ totals = {0: 49_152, 1: 24_576}+ gpus = [(0, 40_000), (1, self._card_at_floor_reserve(b, totals[1], -1))]+ assert self._drive(b, gpus, totals, 20_480, 262144) == (None, 0)- def test_cap_keeps_a_card_that_holds_exactly_4096(self):+ def test_cap_keeps_a_card_that_holds_exactly_the_fit_minimum(self):b = self._fit_backend()- assert self._drive(- b, [(0, 40_000), (1, 1_858)], {0: 49_152, 1: 24_576}, 20_480, 262144- ) == ([0, 1], 4096)+ totals = {0: 49_152, 1: 24_576}+ gpus = [(0, 40_000), (1, self._card_at_floor_reserve(b, totals[1], +1))]+ assert self._drive(b, gpus, totals, 20_480, 262144) == ([0, 1], _FIT_MIN_CTX)def test_flat_arch_term_is_not_rate_inverted(self):# deepseek4 carries a flat indexer term, so inverting the per-token ratediff --git a/studio/backend/tests/test_gpu_arch_gate_os_matrix_7624.py b/studio/backend/tests/test_gpu_arch_gate_os_matrix_7624.pyindex f11e808bfb7..00eaa7fd1b9 100644--- a/studio/backend/tests/test_gpu_arch_gate_os_matrix_7624.py+++ b/studio/backend/tests/test_gpu_arch_gate_os_matrix_7624.py@@ -1247,11 +1247,123 @@ class TestArchCrashRetryEnv:capture = capture,)- assert launches, "the first launch was refused, so the retry is not what was tested"- assert not [- env for _c, env in launches if env.get("ROCR_VISIBLE_DEVICES") == "1"- ], "the respawn on the narrowed pool was not refused"- assert "does not fit in GPU memory" in str(capture.get("error"))+ assert launches, "the first launch never ran, so the retry is not what was tested"+ # The repricing is the point, not a block: the respawn goes ahead and carries+ # the advisory the narrowed pool produced.+ assert "does not fit in GPU memory" in (+ capture["backend"].last_load_warning or ""+ ), "the retry did not reprice the spill against the narrowed pool"++ def _arch_retry_launches(self, tmp_path, monkeypatch, capture, **kwargs):+ """The narrowed-pool retry above, plus whatever the caller asks the load for.++ Returns ``(first_argv, retry_argv)``: the crashed launch and the respawn, told+ apart by the mask, since the unrelated --fit off retry spawns each twice."""+ torch = self._big_then_small_discrete(monkeypatch)+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ None,+ returncode = 1,+ output = "ROCm error: device kernel image is invalid",+ host_offload_stub = LlamaCppBackend._host_offload_shortfall_message,+ capture = capture,+ **kwargs,+ )+ assert launches, "the first launch never ran, so the retry is not what was tested"+ _retry = [cmd for cmd, env in launches if env.get("ROCR_VISIBLE_DEVICES") == "1"]+ assert _retry, "the arch-crash retry did not fire"+ return launches[0][0], _retry[0]++ @pytest.mark.parametrize(+ "extra_args",+ [["--no-mmap"], ["--load-mode", "none"], ["--load-mode=none"], ["--no-direct-io"]],+ ids = ["no-mmap", "load-mode-none", "load-mode-none-equals", "no-direct-io"],+ )+ def test_the_narrowed_retry_pages_an_unmapped_respawn(+ self, tmp_path, monkeypatch, probe_env, extra_args+ ):+ """The shortfall the retry discovers is its FIRST one, so nothing upstream+ remapped the load: the original placement held the model in VRAM and the+ discrete guard abstained. "none" and "mlock" do not mmap, so respawning that+ argv unchanged allocates the whole 30 GB in a 20 GB host and is OOM-killed+ rather than paged. The override belongs to the condition, so it runs here too,+ before the respawn."""+ capture = {}+ first, retry = self._arch_retry_launches(+ tmp_path,+ monkeypatch,+ capture,+ model_bytes = 30 * 1024**3,+ intent_kwargs = {"extra_args": list(extra_args)},+ )++ # The first launch fit the card it pinned, so it is left exactly as asked --+ # which is what makes the retry the first place the shortfall can be found.+ assert _unmapped_tokens(first) == list(extra_args), f"the fitting launch changed: {first}"+ assert not _unmapped_tokens(retry), f"the respawn still loads unmapped: {retry}"+ assert "memory mapping instead" in (capture["backend"].last_load_warning or "")++ @pytest.mark.parametrize(+ "extra_args",+ [["--no-mmap"], ["--load-mode", "none"], ["--load-mode=none"], ["--no-direct-io"]],+ ids = ["no-mmap", "load-mode-none", "load-mode-none-equals", "no-direct-io"],+ )+ def test_a_narrowed_retry_that_fits_keeps_the_mode_it_was_given(+ self, tmp_path, monkeypatch, probe_env, extra_args+ ):+ """The control. Same crash and same narrowing, on a model the 4000 MiB survivor+ plus a 20 GB host holds comfortably: no shortfall, so both argvs keep the+ unmapped mode the user chose."""+ capture = {}+ first, retry = self._arch_retry_launches(+ tmp_path,+ monkeypatch,+ capture,+ model_bytes = 2 * 1024**3,+ intent_kwargs = {"extra_args": list(extra_args)},+ )++ assert _unmapped_tokens(first) == list(extra_args), f"the first launch changed: {first}"+ assert _unmapped_tokens(retry) == list(extra_args), f"the respawn changed: {retry}"+ assert capture["backend"].last_load_warning is None++ def test_the_retry_pages_an_unmapped_respawn_the_opt_out_silenced(+ self, tmp_path, monkeypatch, probe_env+ ):+ """UNSLOTH_ALLOW_HOST_OFFLOAD hides the retry's warning. It must not also hand+ the respawn back the load mode that cannot complete."""+ monkeypatch.setenv("UNSLOTH_ALLOW_HOST_OFFLOAD", "1")+ capture = {}+ _first, retry = self._arch_retry_launches(+ tmp_path,+ monkeypatch,+ capture,+ model_bytes = 30 * 1024**3,+ intent_kwargs = {"extra_args": ["--no-mmap"]},+ )++ assert not _unmapped_tokens(retry), f"the silenced respawn still loads unmapped: {retry}"+ assert capture["backend"].last_load_warning is None+++def _unmapped_tokens(cmd):+ """The tokens in ``cmd`` that select a mode llama.cpp does not mmap.++ Copied from test_llama_cpp_placement.py rather than imported: these two files are+ separate harnesses and neither imports the other."""+ out = []+ for i, token in enumerate(cmd):+ if token in ("--no-mmap", "-no-mmap", "--no-direct-io", "-ndio"):+ out.append(token)+ elif token in ("--load-mode", "-lm") and i + 1 < len(cmd):+ if cmd[i + 1].strip().lower() in ("none", "mlock"):+ out.extend([token, cmd[i + 1]])+ elif token.split("=", 1)[0] in ("--load-mode", "-lm") and "=" in token:+ if token.split("=", 1)[1].strip().lower() in ("none", "mlock"):+ out.append(token)+ return outclass TestManualSplitLaunchesRespectTheGate:@@ -1737,9 +1849,9 @@ class TestGatedNarrowingRechecksTheApuRamGuard:_cmd, env = launches[0]assert _visibility(env) == {"ROCR_VISIBLE_DEVICES": "0", "CUDA_VISIBLE_DEVICES": "0"}- def test_a_surviving_apu_still_refuses(self, tmp_path, monkeypatch, probe_env):+ def test_a_surviving_apu_still_warns(self, tmp_path, monkeypatch, probe_env):"""The waiver is scoped to survivors that are all discrete. A build- covering both cards leaves the APU in play, so the refusal stands."""+ covering both cards leaves the APU in play, so the warning stands."""torch = self._apu_and_dgpu(monkeypatch)calls: list = []capture: dict = {}@@ -1754,12 +1866,12 @@ class TestGatedNarrowingRechecksTheApuRamGuard:apu_ram_stub = self._shortfall_stub(calls),)assert len(calls) == 1, f"the RAM guard ran {len(calls)} times, expected once"- assert launches == [], "an oversized APU load reached the child"- assert "only about 8 GB" in str(capture.get("error"))+ assert launches, "the oversized APU load never reached the child"+ assert "only about 8 GB" in (capture["backend"].last_load_warning or "")- def test_the_forced_cpu_host_still_refuses(self, tmp_path, monkeypatch, probe_env):- """Every card gated out means the weights load into system RAM after all,- so the guard the gate has no survivor to answer with keeps its refusal."""+ def test_the_forced_cpu_host_still_warns(self, tmp_path, monkeypatch, probe_env):+ """Every card gated out means the weights load into system RAM after all, so+ the guard the gate has no survivor to answer with still prices it."""torch = self._apu_and_dgpu(monkeypatch)calls: list = []capture: dict = {}@@ -1774,8 +1886,8 @@ class TestGatedNarrowingRechecksTheApuRamGuard:apu_ram_stub = self._shortfall_stub(calls),)assert len(calls) == 1, f"the RAM guard ran {len(calls)} times, expected once"- assert launches == [], "an oversized CPU-bound load reached the child"- assert "only about 8 GB" in str(capture.get("error"))+ assert launches, "the oversized CPU-bound load never reached the child"+ assert "only about 8 GB" in (capture["backend"].last_load_warning or "")class TestArchCrashRetryOntoAnApu:@@ -2023,9 +2135,7 @@ class TestArchCrashRetryRechecksTheApuRamGuard:vendor = "amd",)- def test_an_oversized_model_is_refused_instead_of_respawned(- self, tmp_path, monkeypatch, probe_env- ):+ def test_an_oversized_model_is_respawned_with_a_warning(self, tmp_path, monkeypatch, probe_env):torch = self._dgpu_then_apu(monkeypatch)# Counted, not raised: this runs inside the launch path's own# except-Exception arms, which would swallow an AssertionError and leave@@ -2051,15 +2161,16 @@ class TestArchCrashRetryRechecksTheApuRamGuard:# The dGPU is pinned first, so the pre-launch guard never asks (it is# gated on the selection wanting unified memory) and the crash happens.assert launches, "the first spawn never ran"- assert all(- env.get("ROCR_VISIBLE_DEVICES") != "1" for _c, env in launches- ), "the retry respawned onto the APU without the RAM preflight"+ # The preflight still runs against the APU the retry lands on and still prices+ # the projector with the weights; it just no longer stops the respawn.assert len(calls) == 1, f"the RAM guard ran {len(calls)} times, expected once"assert calls[0][0] == 20 * 1024**3- assert "only about 8 GB" in str(capture.get("error"))+ assert "only about 8 GB" in (capture["backend"].last_load_warning or "")+ # capture["error"] is now the simulated HIP crash, not the RAM guard, so+ # asserting the guard's text there would only re-test the mock.def test_a_model_that_fits_still_retries_onto_the_apu(self, tmp_path, monkeypatch, probe_env):- """The guard refuses a shortfall, it does not block the fallback. With+ """The guard warns on a shortfall, it does not block the fallback. Withroom to spare the retry runs exactly as before."""torch = self._dgpu_then_apu(monkeypatch)calls: list = []@@ -2083,6 +2194,176 @@ class TestArchCrashRetryRechecksTheApuRamGuard:assert _retry, "the arch-crash retry did not fire"assert all(env.get("GGML_CUDA_ENABLE_UNIFIED_MEMORY") == "1" for env in _retry)+ @staticmethod+ def _override_log(monkeypatch):+ """Collect the pageable-override log line. structlog, so caplog cannot see it."""+ lines: list = []+ monkeypatch.setattr(+ llama_cpp.logger,+ "warning",+ lambda msg, *a, **kw: lines.append(msg % a if a else msg),+ )+ return lines++ def _respawn_unmapped_and_oversized(self, tmp_path, monkeypatch, capture):+ """The respawn lands on the APU, is oversized there, and was asked to load+ without mmap -- the one shape where the override is what lets it finish."""+ torch = self._dgpu_then_apu(monkeypatch)+ return _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ None, # no marker: the proactive gate fails open, so the crash path runs+ returncode = 1,+ output = "ROCm error: device kernel image is invalid",+ model_bytes = 20 * 1024**3,+ capture = capture,+ apu_ram_stub = lambda *_a, **_kw: (+ "This model needs about 20 GB but only about 8 GB of memory is available."+ ),+ intent_kwargs = {"extra_args": ["--no-mmap"]},+ )++ def test_the_opt_out_silences_the_retrys_apu_advisory_and_keeps_the_override(+ self, tmp_path, monkeypatch, probe_env+ ):+ """UNSLOTH_ALLOW_HOST_OFFLOAD is documented as silencing the warning and+ nothing else, but this site recorded the APU advisory without consulting it, so+ a user who opted out still got a memory_warning back. The verdict stays: the+ respawn is still remapped, or "none" would allocate the whole model in the RAM+ that cannot hold it."""+ monkeypatch.setenv("UNSLOTH_ALLOW_HOST_OFFLOAD", "1")+ capture: dict = {}+ logged = self._override_log(monkeypatch)++ launches = self._respawn_unmapped_and_oversized(tmp_path, monkeypatch, capture)++ _retry = [cmd for cmd, env in launches if env.get("ROCR_VISIBLE_DEVICES") == "1"]+ assert _retry, "the arch-crash retry did not fire"+ assert all("--no-mmap" not in cmd for cmd in _retry), _retry+ assert capture["backend"].last_load_warning is None, (+ "the opt-out left the retry's APU advisory in memory_warning: "+ f"{capture['backend'].last_load_warning}"+ )+ assert [line for line in logged if "Overriding the unmapped load mode" in line], logged++ def test_without_the_opt_out_the_retrys_advisory_still_names_the_override(+ self, tmp_path, monkeypatch, probe_env+ ):+ """The control. Nothing silenced, so the same respawn warns as before and the+ override is named in the text the route hands back."""+ monkeypatch.delenv("UNSLOTH_ALLOW_HOST_OFFLOAD", raising = False)+ capture: dict = {}++ launches = self._respawn_unmapped_and_oversized(tmp_path, monkeypatch, capture)++ _retry = [cmd for cmd, env in launches if env.get("ROCR_VISIBLE_DEVICES") == "1"]+ assert _retry, "the arch-crash retry did not fire"+ assert all("--no-mmap" not in cmd for cmd in _retry), _retry+ warning = capture["backend"].last_load_warning or ""+ assert "only about 8 GB" in warning, warning+ assert "memory mapping instead" in warning, warning+++class TestArchCrashRetryReplacesTheCrashedSelectionsWarning:+ """The canonical #7624 shape, priced. The APU's shared-pool "free memory"+ outranks the dGPU, so auto pins it; the APU RAM guard warns that system RAM+ cannot hold the weights; the child then dies with a kernel-image error and the+ retry respawns on the discrete sibling, which holds the model in VRAM.++ ``_record_load_warning`` keeps the FIRST notice, so the crashed selection's+ verdict outlived the placement it described: the served response told the user+ the OS might stop a load running entirely on a discrete card. The retry prices+ the set it actually reaches, so that answer -- not the dead one -- is the load's.+ """++ def _apu_then_dgpu(self, monkeypatch, *, dgpu_free_mib):+ # Device 0 is the APU and outranks the dGPU on free memory, so auto pins it and+ # the pre-launch APU guard DOES ask (the mirror of+ # TestArchCrashRetryRechecksTheApuRamGuard, where the dGPU is pinned first and+ # the guard never asks). The APU's usable figure is its shared pool capped by+ # available system RAM minus a host reserve, so the RAM stub has to stay high+ # enough to leave the APU on top; the shortfall itself is the stubbed verdict,+ # which is how every APU-guard cell in this file drives it -- the arithmetic+ # belongs to test_host_offload_ram_guard.py, the plumbing is what is at stake.+ _apply_os(monkeypatch, "linux", is_rocm = True)+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: {0})+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 60000)+ )+ return _fake_torch(+ [+ _device("gfx1151", free_mib = 47000, is_integrated = 1),+ _device("gfx1030", free_mib = dgpu_free_mib),+ ],+ vendor = "amd",+ )++ @staticmethod+ def _apu_stub(calls):+ # Counted, not raised: this runs inside the launch path's own+ # except-Exception arms, which would swallow an AssertionError.+ def _shortfall(model_size_bytes, avail_mib, *_a, **_kw):+ calls.append((model_size_bytes, avail_mib))+ return "This model needs about 20 GB but only about 8 GB of memory is available."++ return _shortfall++ def test_a_comfortable_retry_clears_the_dead_selections_warning(+ self, tmp_path, monkeypatch, probe_env+ ):+ # 30000MiB free holds the 20GB model outright, so the respawn spills nothing.+ torch = self._apu_then_dgpu(monkeypatch, dgpu_free_mib = 30000)+ calls: list = []+ capture: dict = {}+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ None, # no marker: the proactive gate fails open, so the crash path runs+ returncode = 1,+ output = "ROCm error: device kernel image is invalid",+ model_bytes = 20 * 1024**3,+ capture = capture,+ apu_ram_stub = self._apu_stub(calls),+ )+ assert calls, "the pre-launch APU RAM guard never ran, so nothing was warned"+ _retry = [env for _c, env in launches if env.get("ROCR_VISIBLE_DEVICES") == "1"]+ assert _retry, "the arch-crash retry did not fire"+ assert capture["backend"].last_load_warning is None, (+ "the response still carries the crashed APU's shortfall for a child that "+ "runs on the discrete card"+ )++ def test_a_shortfall_that_still_stands_survives_the_retry(+ self, tmp_path, monkeypatch, probe_env+ ):+ """Scoped: clearing the dead verdict must not silence a live one. The respawn+ prices the same weights against a NARROWER pool, so a real spill is re-warned.+ """+ # 4000MiB free leaves most of the 20GB model in host RAM on the respawn.+ torch = self._apu_then_dgpu(monkeypatch, dgpu_free_mib = 4000)+ capture: dict = {}+ launches = _run_auto_load(+ monkeypatch,+ tmp_path,+ torch,+ None,+ returncode = 1,+ output = "ROCm error: device kernel image is invalid",+ model_bytes = 20 * 1024**3,+ capture = capture,+ apu_ram_stub = self._apu_stub([]),+ host_offload_stub = (+ lambda *_a, **_kw: "About 16 GB of this model does not fit in GPU memory."+ ),+ )+ _retry = [env for _c, env in launches if env.get("ROCR_VISIBLE_DEVICES") == "1"]+ assert _retry, "the arch-crash retry did not fire"+ assert "does not fit in GPU memory" in (capture["backend"].last_load_warning or "")+class TestHsaOverrideGfxVersion:"""``HSA_OVERRIDE_GFX_VERSION`` is the long-standing AMD workaround for an archdiff --git a/studio/backend/tests/test_host_offload_ram_guard.py b/studio/backend/tests/test_host_offload_ram_guard.pyindex 892ef9cec1d..229bcf26956 100644--- a/studio/backend/tests/test_host_offload_ram_guard.py+++ b/studio/backend/tests/test_host_offload_ram_guard.py@@ -1,10 +1,14 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""A GGUF that misses VRAM spills into host RAM under `--fit on`, unpriced. When-that spill is larger than available RAM the mmap'd weights thrash rather than-fail, the desktop stops responding and the OS kills the app, so the load must be-refused before llama-server is spawned."""+"""A GGUF that misses VRAM spills into host RAM under `--fit on`, unpriced. When that+spill is larger than available RAM the weights page in from disk as the model runs, so+generation is slow.++This used to REFUSE the load. It no longer does: the spill is mmap'd, so an oversized+model pages rather than failing, and running a quant larger than fast memory off an SSD+is deliberate and supported, which this check cannot tell apart from a mistake. Same+arithmetic, different consequence -- it warns, and the load proceeds."""from __future__ import annotations@@ -51,12 +55,14 @@ class TestHostOffloadShortfall:assert _shortfall(20 * _GB, 23 * _MIB_PER_GB) is Noneassert _shortfall(20 * _GB, 21 * _MIB_PER_GB) is not None- def test_a_refusal_names_the_escape(self):- """The picker still offers a variant this refuses, so the message has to say how- to load it anyway."""+ def test_the_warning_says_the_load_goes_ahead(self):+ """Nothing here blocks a load any more, so the message must not read as a+ refusal or send the user hunting for an env var. It states the cost and says+ the load continues."""msg = _shortfall(20 * _GB, 21 * _MIB_PER_GB)assert msg is not None- assert "UNSLOTH_ALLOW_HOST_OFFLOAD=1" in msg+ assert "Loading anyway" in msg+ assert "UNSLOTH_ALLOW_HOST_OFFLOAD" not in msgdef test_a_refusal_never_prints_a_need_at_or_under_the_usable_figure(self):"""A spill inside available RAM but inside the headroom too is still refused, sodiff --git a/studio/backend/tests/test_kv_cache_estimation.py b/studio/backend/tests/test_kv_cache_estimation.pyindex 4a2409d742b..c1b54b52798 100644--- a/studio/backend/tests/test_kv_cache_estimation.py+++ b/studio/backend/tests/test_kv_cache_estimation.py@@ -76,7 +76,7 @@ except ImportError:)sys.modules["httpx"] = _httpx_stub-from core.inference.llama_cpp import _CTX_FIT_VRAM_FRACTION, LlamaCppBackend+from core.inference.llama_cpp import _CTX_FIT_VRAM_FRACTION, _FIT_MIN_CTX, LlamaCppBackend# Helpers@@ -1668,7 +1668,11 @@ class TestServerFlags:def test_fit_threads_swa_full_through_estimator(self):# SWA model, generous budget; both should fit but cache size differs.b = self._swa_backend()- ctx = 8192+ # Above the fit floor, so the search has somewhere to shrink TO. Spelled+ # 8192 this sat exactly on the floor once it moved there, and the assert+ # below stopped testing that swa_full costs more: the fit could not return+ # anything smaller than the request, whatever the estimator said.+ ctx = 2 * _FIT_MIN_CTXkv_default = b._estimate_kv_cache_bytes(ctx, "f16")kv_full = b._estimate_kv_cache_bytes(ctx, "f16", swa_full = True)assert kv_full > kv_defaultdiff --git a/studio/backend/tests/test_llama_admission_kv_budget_media_and_tools.py b/studio/backend/tests/test_llama_admission_kv_budget_media_and_tools.pyindex 16209bd63f3..b27c202f851 100644--- a/studio/backend/tests/test_llama_admission_kv_budget_media_and_tools.py+++ b/studio/backend/tests/test_llama_admission_kv_budget_media_and_tools.py@@ -107,12 +107,12 @@ class TestMediaIsCharged:inline_cost = _openai_llama_admission_tokens(inline, budget = 1_000_000, capacity = 4)assert dual_cost == inline_cost- assert dual_cost < 2 * _OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS, (- "the echo must be charged once, not once per spelling"- )- assert dual_cost >= _OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS, (- "image bytes must be bounded but still charged"- )+ assert (+ dual_cost < 2 * _OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS+ ), "the echo must be charged once, not once per spelling"+ assert (+ dual_cost >= _OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS+ ), "image bytes must be bounded but still charged"def test_every_builder_forwards_exactly_what_admission_charged(self):"""The reservation is only a bound if it counts the images actually sent.@@ -218,9 +218,9 @@ class TestMediaIsCharged:"""measured_worst_case = {"qwen3-vl-4b": 4098, "gemma-3-4b": 258}for model, tokens in measured_worst_case.items():- assert _OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS >= tokens, (- f"per-image allowance under-reserves {model}"- )+ assert (+ _OPENAI_LLAMA_ADMISSION_IMAGE_TOKENS >= tokens+ ), f"per-image allowance under-reserves {model}"def test_the_allowance_follows_a_raised_image_token_cap(self):"""A load can raise the projector ceiling, and the reservation has to follow it.diff --git a/studio/backend/tests/test_llama_cpp_placement.py b/studio/backend/tests/test_llama_cpp_placement.pyindex 471f6063dea..02ce12736fe 100644--- a/studio/backend/tests/test_llama_cpp_placement.py+++ b/studio/backend/tests/test_llama_cpp_placement.py@@ -9,6 +9,7 @@ import osimport structimport subprocessimport sys+import threadingimport typesfrom pathlib import Pathfrom unittest.mock import patch@@ -67,7 +68,7 @@ if "httpx" not in sys.modules:)sys.modules["httpx"] = module-from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend+from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend, _loader_path_var_REAL_POPEN = subprocess.Popen@@ -139,6 +140,18 @@ def _launch(backend, gguf, **load_kwargs):return captured+def _launch_warns(backend, gguf, **load_kwargs):+ """A load whose weights outgrow fast memory: it LAUNCHES, and says so.++ These cases used to raise. The spill is mmap'd, so refusing cost users a load+ llama.cpp itself supports. The advisory is the whole remaining contract, so assert+ it rather than only that the launch survived.+ """+ captured = _launch(backend, gguf, **load_kwargs)+ assert "does not fit in GPU memory" in (backend.last_load_warning or "")+ return captured++def test_vulkan_selection_uses_ordinals_and_owns_device_flags(tmp_path):backend, gguf = _backend(tmp_path,@@ -703,7 +716,7 @@ def _hybrid_reserve_backend(tmp_path: Path, *, caps = None):backend, gguf = _backend(tmp_path, vulkan = False, memory = [(0, 24_576, 24_576)])sidecar = tmp_path / "dflash-model-Q8_0.gguf"sidecar.write_bytes(b"draft")- backend._get_gguf_size_bytes = lambda path: (0 if str(path) == str(sidecar) else 8 * gb)+ backend._get_gguf_size_bytes = lambda path: 0 if str(path) == str(sidecar) else 8 * gbbackend._can_estimate_kv = lambda: Truebackend._compute_buffer_ctx_bytes = lambda *args, **kwargs: 0backend._estimate_compute_buffer_bytes = lambda **kwargs: 1@@ -726,15 +739,18 @@ def _hybrid_reserve_backend(tmp_path: Path, *, caps = None):backend._ssm_conv_kernel = 4backend._read_gguf_metadata = read_metadata- backend.probe_server_capabilities = lambda _binary = None: caps or {- "mtp_token": "draft-mtp",- "supports_dflash": True,- "supports_ngram_mod": True,- "spec_draft_n_max_flag": "--spec-draft-n-max",- # Or the launch clamps the four slots to one and the per-slot state,- # which is what these tests measure, shrinks with them.- "supports_kv_unified": True,- }+ backend.probe_server_capabilities = lambda _binary = None: (+ caps+ or {+ "mtp_token": "draft-mtp",+ "supports_dflash": True,+ "supports_ngram_mod": True,+ "spec_draft_n_max_flag": "--spec-draft-n-max",+ # Or the launch clamps the four slots to one and the per-slot state,+ # which is what these tests measure, shrinks with them.+ "supports_kv_unified": True,+ }+ )return backend, gguf, sidecar@@ -1541,14 +1557,15 @@ def test_a_cpu_offloaded_sidecar_reserves_no_gpu_despite_an_embedded_head(tmp_paassert not any(reserved), f"mtp_engaged should be False throughout, got {reserved}"-def test_a_subset_that_can_shrink_to_hold_both_is_where_the_decision_lands(tmp_path):- """The placement loop does not walk past a subset that fails with the drafter.+def _shrink_to_hold_both_backend(+ tmp_path, *, model_gb, native_ctx, kv_mib_per_tok, mtp_mib_per_tok+):+ """Two 24 GiB cards and a DSpark sidecar, with every VRAM term context-linear.- It re-caps the context WITH the drafter charged and accepts that subset at- whatever is left, so a smaller context holding both here IS the placement the- load takes, and the drafter gets paid for in context. Believing a later,- larger subset would rescue it keeps the drafter and shrinks the context, which- is the trade this exists to refuse.+ ``kv_mib_per_tok`` prices the target's cache and ``mtp_mib_per_tok`` the whole+ drafter reserve, weights included: the stub replaces+ ``_estimate_mtp_overhead_bytes`` outright, so the sidecar's file size never+ reaches the arithmetic and only these rates decide what holds what."""gb = 1024**3backend, gguf = _backend(@@ -1556,20 +1573,51 @@ def test_a_subset_that_can_shrink_to_hold_both_is_where_the_decision_lands(tmp_p)sidecar = tmp_path / "dspark-model-Q8_0.gguf"sidecar.write_bytes(b"draft")- backend._get_gguf_size_bytes = lambda path: 8 * gb if str(path) == str(sidecar) else 16 * gb- backend._read_gguf_metadata = lambda _path: setattr(backend, "_context_length", 8192)+ backend._get_gguf_size_bytes = lambda path: (+ 8 * gb if str(path) == str(sidecar) else int(model_gb * gb)+ )+ backend._read_gguf_metadata = lambda _path: setattr(backend, "_context_length", native_ctx)backend._can_estimate_kv = lambda: True- # Context-linear throughout, so GPU0 alone can shrink its way to holding both.- backend._estimate_kv_cache_bytes = lambda ctx, *a, **k: int(ctx * 0.5 * 1024**2)+ backend._estimate_kv_cache_bytes = lambda ctx, *a, **k: int(ctx * kv_mib_per_tok * 1024**2)backend._compute_buffer_ctx_bytes = lambda *a, **k: 0backend._estimate_compute_buffer_bytes = lambda **k: 1backend._mtp_draft_kv_bytes = lambda *a, **k: 0- backend._estimate_mtp_overhead_bytes = lambda ctx, *a, **k: int(ctx * 0.75 * 1024**2)+ backend._estimate_mtp_overhead_bytes = lambda ctx, *a, **k: int(ctx * mtp_mib_per_tok * 1024**2)backend.probe_server_capabilities = lambda _binary = None: {"supports_dspark": True,"supports_ngram_mod": True,"spec_draft_n_max_flag": "--spec-draft-n-max",}+ return backend, gguf, sidecar+++def test_a_subset_that_can_shrink_to_hold_both_is_where_the_decision_lands(tmp_path):+ """The placement loop does not walk past a subset that fails with the drafter.++ It re-caps the context WITH the drafter charged and accepts that subset at+ whatever is left, so a smaller context holding both here IS the placement the+ load takes, and the drafter gets paid for in context. Believing a later,+ larger subset would rescue it keeps the drafter and shrinks the context, which+ is the trade this exists to refuse.++ The shrink has to land ABOVE the fit floor to be a measurement rather than the+ floor itself, which is what makes this scenario 32768-native rather than 8192.+ On one card, budget 23838 MiB: the target alone is 14336 + 320 = 14656 MiB and+ holds 32768 (+8192 MiB of cache) with room to spare, the drafter's 8192 MiB on+ top does not, and 14336 + 544 leaves 8958 MiB, which at 0.5 MiB/token both ways+ re-caps to 17664. That is the shrink the loop takes and the drafter is refused+ for. Two cards WOULD have held both at the full 32768 (32288 of 47677 MiB+ pooled), so the refusal is a choice and not an absence of alternatives; see+ test_widening_beats_shrinking_below_the_fit_floor for the case where the shrink+ is not available and widening is what happens instead.+ """+ backend, gguf, sidecar = _shrink_to_hold_both_backend(+ tmp_path,+ model_gb = 14,+ native_ctx = 32_768,+ kv_mib_per_tok = 0.25,+ mtp_mib_per_tok = 0.25,+ )result = _launch(backend,@@ -1582,7 +1630,49 @@ def test_a_subset_that_can_shrink_to_hold_both_is_where_the_decision_lands(tmp_pcmd = result["cmd"]assert "--model-draft" not in cmdassert backend.spec_fallback_reason == "drafter_no_vram"+ assert cmd[cmd.index("-c") + 1] == "32768"+ # One card: the point is that the loop stopped here rather than widening.+ assert result["env"].get("CUDA_VISIBLE_DEVICES") == "0"+++def test_widening_beats_shrinking_below_the_fit_floor(tmp_path):+ """The other side of the same branch: no shrink is on offer, so the loop widens.++ Same machine, sized so one card can only hold both BELOW the fit floor. The+ re-cap with the drafter charged is bounded by that floor, so it cannot return+ the shrink, the caller re-prices its answer and rejects it, and the loop walks+ on to the two-card subset that holds the target AND the drafter at the full+ context. Keeping the drafter for free is the whole reason the floor exists, and+ the placement is a real fit rather than a floored one: 17952 MiB of weights and+ overhead plus 4096 of cache plus 6144 of drafter is 28192 of a 47677 MiB pool,+ about 14 GiB on each 24 GiB card.++ Pinning it because the shape that would flip it back is silent: the re-cap+ helper returns ``min_ctx`` rather than 0 when even ``min_ctx`` does not fit, so+ the only thing standing between this and a one-card placement that OOMs is the+ caller's own footprint re-check.+ """+ backend, gguf, sidecar = _shrink_to_hold_both_backend(+ tmp_path,+ model_gb = 16,+ native_ctx = 8192,+ kv_mib_per_tok = 0.5,+ mtp_mib_per_tok = 0.75,+ )++ result = _launch(+ backend,+ gguf,+ dspark_draft_path = str(sidecar),+ speculative_type = "auto",+ n_ctx = 0,+ )++ cmd = result["cmd"]+ assert "--model-draft" in cmd+ assert backend.spec_fallback_reason is Noneassert cmd[cmd.index("-c") + 1] == "8192"+ assert result["env"].get("CUDA_VISIBLE_DEVICES") == "0,1"def _restore_host_guard(backend):@@ -1607,16 +1697,15 @@ def _offload_backend(tmp_path, *, gguf_gb, free_mib, avail_mib, monkeypatch, **kreturn backend, gguf-def test_weights_larger_than_vram_plus_ram_are_refused(tmp_path, monkeypatch):+def test_weights_larger_than_vram_plus_ram_still_load_with_a_warning(tmp_path, monkeypatch):"""The field case: a 13.3 GB GGUF on a 6 GB laptop card holding 4877 MiB free needs- about 8.5 GB of host RAM, which a 10 GB host cannot hold. Unrefused, the mmap'd- remainder thrashes until the OS kills Unsloth and the desktop session."""+ about 8.5 GB of host RAM, which a 10 GB host cannot hold. It loads anyway, paging+ the remainder from disk, and says so."""backend, gguf = _offload_backend(tmp_path, gguf_gb = 13.3, free_mib = 4877, avail_mib = 10_000, monkeypatch = monkeypatch)- with pytest.raises(RuntimeError, match = "does not fit in GPU memory"):- _launch(backend, gguf)+ _launch_warns(backend, gguf)def test_the_same_load_on_a_large_ram_host_still_launches(tmp_path, monkeypatch):@@ -1662,8 +1751,7 @@ def test_vulkan_igpu_shared_memory_is_not_counted_twice(tmp_path, monkeypatch, m)monkeypatch.setattr(LlamaCppBackend, "_cgroup_available_memory_mib", staticmethod(lambda: None))- with pytest.raises(RuntimeError, match = "does not fit in GPU memory"):- _launch(backend, gguf)+ _launch_warns(backend, gguf)def test_vulkan_igpu_heap_can_hold_weights_missing_from_host_available(tmp_path, monkeypatch):@@ -1697,8 +1785,8 @@ def test_vulkan_igpu_backing_bound_preserves_placement_and_host_headroom("""The raw planner reading never lets host-backed credit lose system headroom."""backend, gguf = _backend(tmp_path, vulkan = True, memory = [(0, 15 * 1024, 0)])_restore_host_guard(backend)- backend._get_gpu_memory = (- lambda _binary = None, **_kw: LlamaCppBackend._get_gpu_free_memory_vulkan(_binary)+ backend._get_gpu_memory = lambda _binary = None, **_kw: (+ LlamaCppBackend._get_gpu_free_memory_vulkan(_binary))backend._get_gguf_size_bytes = lambda _path: gguf_mib * 1024**2monkeypatch.setattr(@@ -1725,8 +1813,7 @@ def test_vulkan_igpu_backing_bound_preserves_placement_and_host_headroom(monkeypatch.setattr(LlamaCppBackend, "_cgroup_available_memory_mib", staticmethod(lambda: None))if not admitted:- with pytest.raises(RuntimeError, match = "does not fit in GPU memory"):- _launch(backend, gguf)+ _launch_warns(backend, gguf)returncmd = _launch(backend, gguf)["cmd"]@@ -1760,8 +1847,7 @@ def test_vulkan_igpu_heap_is_not_credited_to_a_host_resident_launch()monkeypatch.setattr(LlamaCppBackend, "_cgroup_available_memory_mib", staticmethod(lambda: None))- with pytest.raises(RuntimeError, match = "does not fit in GPU memory"):- _launch(backend, gguf, **placement)+ _launch_warns(backend, gguf, **placement)def test_a_device_pin_decides_whether_the_shared_heap_is_reachable(tmp_path, monkeypatch):@@ -1787,8 +1873,7 @@ def test_a_device_pin_decides_whether_the_shared_heap_is_reachable(tmp_path, monmanual = {"gpu_memory_mode": "manual", "gpu_layers": 33}backend, gguf = _mixed()- with pytest.raises(RuntimeError, match = "does not fit in GPU memory"):- _launch(backend, gguf, extra_args = ["--device", "Vulkan0"], **manual)+ _launch_warns(backend, gguf, extra_args = ["--device", "Vulkan0"], **manual)backend, gguf = _mixed()assert _launch(backend, gguf, extra_args = ["--device", "Vulkan1"], **manual)["cmd"]@@ -1810,14 +1895,13 @@ def test_an_unselected_card_does_not_shrink_what_the_shared_heap_must_hold(tmp_p)monkeypatch.setattr(LlamaCppBackend, "_cgroup_available_memory_mib", staticmethod(lambda: None))- with pytest.raises(RuntimeError, match = "does not fit in GPU memory"):- _launch(- backend,- gguf,- gpu_memory_mode = "manual",- gpu_layers = 33,- extra_args = ["--device", "Vulkan1"],- )+ _launch_warns(+ backend,+ gguf,+ gpu_memory_mode = "manual",+ gpu_layers = 33,+ extra_args = ["--device", "Vulkan1"],+ )@pytest.mark.parametrize(@@ -1839,15 +1923,14 @@ def test_an_explicit_tensor_split_leaves_the_shared_heap_uncredited(tmp_path, mo)monkeypatch.setattr(LlamaCppBackend, "_cgroup_available_memory_mib", staticmethod(lambda: None))- with pytest.raises(RuntimeError, match = "does not fit in GPU memory"):- _launch(- backend,- gguf,- gpu_memory_mode = "manual",- gpu_layers = 33,- gpu_ids = [0, 1],- **split,- )+ _launch_warns(+ backend,+ gguf,+ gpu_memory_mode = "manual",+ gpu_layers = 33,+ gpu_ids = [0, 1],+ **split,+ )def _mixed_vulkan(tmp_path, monkeypatch, memory):@@ -1876,14 +1959,13 @@ def test_split_mode_none_leaves_a_second_device_heap_uncredited(tmp_path, monkeybackend, gguf = _mixed_vulkan(tmp_path, monkeypatch, [(0, 6 * 1024, 8 * 1024), (1, 94641, 0)])# Both devices pinned, so the split mode is the only thing left to decide.- with pytest.raises(RuntimeError, match = "does not fit in GPU memory"):- _launch(- backend,- gguf,- gpu_memory_mode = "manual",- gpu_layers = 33,- extra_args = ["--device", "Vulkan0,Vulkan1", *extras],- )+ _launch_warns(+ backend,+ gguf,+ gpu_memory_mode = "manual",+ gpu_layers = 33,+ extra_args = ["--device", "Vulkan0,Vulkan1", *extras],+ )def test_an_unpinned_launch_beside_a_discrete_card_leaves_the_heap_uncredited(@@ -1892,8 +1974,7 @@ def test_an_unpinned_launch_beside_a_discrete_card_leaves_the_heap_uncredited("""llama.cpp drops integrated GPUs when its own device list finds a discrete one."""backend, gguf = _mixed_vulkan(tmp_path, monkeypatch, [(0, 94641, 0), (1, 6 * 1024, 8 * 1024)])- with pytest.raises(RuntimeError, match = "does not fit in GPU memory"):- _launch(backend, gguf, gpu_memory_mode = "manual", gpu_layers = 33)+ _launch_warns(backend, gguf, gpu_memory_mode = "manual", gpu_layers = 33)def test_a_pin_still_reaches_the_heap_beside_a_discrete_card(tmp_path, monkeypatch):@@ -1939,8 +2020,10 @@ def test_vulkan_igpu_heap_does_not_bypass_a_cgroup_limit(tmp_path, monkeypatch):LlamaCppBackend, "_cgroup_available_memory_mib", staticmethod(lambda: 8 * 1024))- with pytest.raises(RuntimeError, match = "unified-memory APU"):- _launch(backend, gguf)+ # The cgroup ceiling still governs what the message prices, it just no longer+ # stops the load.+ _launch(backend, gguf)+ assert "unified-memory APU" in (backend.last_load_warning or "")def test_a_card_resident_model_is_not_refused_by_a_container_ceiling(tmp_path, monkeypatch):@@ -2015,21 +2098,22 @@ def test_the_guard_reads_the_model_the_child_opens(tmp_path, monkeypatch):return real_size(path)backend._get_gguf_size_bytes = _record- with pytest.raises(RuntimeError, match = "does not fit in GPU memory"):- _launch(backend, gguf)+ _launch_warns(backend, gguf)assert str(gguf) in seen-def test_the_env_escape_loads_a_variant_the_guard_refuses(tmp_path, monkeypatch):- """The picker still offers a variant `classifyGgufFit` calls "oom", and no load- field carries a force, so an unconditional refusal leaves that selection with no way- through. UNSLOTH_ALLOW_HOST_OFFLOAD=1 abstains, and the refusal names it."""- refused, gguf = _offload_backend(+def test_the_env_escape_is_now_a_no_op_that_only_silences_the_warning(tmp_path, monkeypatch):+ """UNSLOTH_ALLOW_HOST_OFFLOAD was the opt-out from a refusal that no longer exists.++ Both arms must load. Unset, the load carries the advisory; set, it loads just the+ same and says nothing. Kept honoured so existing scripts and docs keep working."""+ warned, gguf = _offload_backend(tmp_path, gguf_gb = 13.3, free_mib = 4877, avail_mib = 10_000, monkeypatch = monkeypatch)- with pytest.raises(RuntimeError, match = "UNSLOTH_ALLOW_HOST_OFFLOAD=1"):- _launch(refused, gguf)+ monkeypatch.delenv("UNSLOTH_ALLOW_HOST_OFFLOAD", raising = False)+ assert "--fit" in _launch(warned, gguf)["cmd"]+ assert "does not fit in GPU memory" in (warned.last_load_warning or "")allowed_dir = tmp_path / "allowed"allowed_dir.mkdir()@@ -2038,6 +2122,239 @@ def test_the_env_escape_loads_a_variant_the_guard_refuses(tmp_path, monkeypatch))monkeypatch.setenv("UNSLOTH_ALLOW_HOST_OFFLOAD", "1")assert "--fit" in _launch(allowed, gguf2)["cmd"]+ assert allowed.last_load_warning is None+++def test_a_wildly_oversized_model_still_loads(tmp_path, monkeypatch):+ """The regression this change exists for.++ A 67.6 GB quant on a 14.5 GiB card with 51 GB of RAM (the measured Colab T4+ high-RAM shape) used to come back as HTTP 400 from /api/inference/load, on a model+ llama.cpp itself will run straight off the mmap. No shortfall may block a load+ again, however large the gap: the cost is reported, not enforced."""+ backend, gguf = _offload_backend(+ tmp_path,+ gguf_gb = 67.6,+ free_mib = 14_848,+ avail_mib = 51_000,+ monkeypatch = monkeypatch,+ )+ monkeypatch.delenv("UNSLOTH_ALLOW_HOST_OFFLOAD", raising = False)++ assert _launch(backend, gguf)["cmd"], "the oversized load never spawned llama-server"+ assert "does not fit in GPU memory" in (backend.last_load_warning or "")+++# An unmapped load is the one shape the advisory's premise does not cover. The spill+# is only survivable because the weights are mmap'd; upstream sets use_mmap for+# mmap/mmap+mlock/auto alone (llama-model-loader.cpp), so `none` and `mlock` read every+# byte into a buffer llama.cpp allocates and an oversized model fails outright instead+# of paging. The guard still never refuses: it overrides the mode and says so.+_UNMAPPED_ARGV = [+ ["--no-mmap"],+ ["--load-mode", "none"],+ ["--load-mode=none"],+ ["--no-direct-io"],+]+_UNMAPPED_IDS = ["no-mmap", "load-mode-none", "load-mode-none-equals", "no-direct-io"]++[email protected]("extra_args", _UNMAPPED_ARGV, ids = _UNMAPPED_IDS)+def test_an_oversized_unmapped_load_is_remapped_instead_of_refused(+ tmp_path, monkeypatch, extra_args+):+ """It launches, the argv the child gets is pageable, and the warning names the+ override -- a silent one would leave the user's own setting quietly undone."""+ backend, gguf = _offload_backend(+ tmp_path, gguf_gb = 13.3, free_mib = 4877, avail_mib = 10_000, monkeypatch = monkeypatch+ )+ monkeypatch.delenv("UNSLOTH_ALLOW_HOST_OFFLOAD", raising = False)++ cmd = _launch(backend, gguf, extra_args = extra_args)["cmd"]++ assert cmd, "the unmapped oversized load never spawned llama-server"+ assert not _unmapped_tokens(cmd), f"the child still loads unmapped: {cmd}"+ assert "memory mapping instead" in (backend.last_load_warning or "")++[email protected]("extra_args", _UNMAPPED_ARGV, ids = _UNMAPPED_IDS)+def test_an_unmapped_load_that_fits_is_left_exactly_as_asked(tmp_path, monkeypatch, extra_args):+ """The control. Same request on a host with room: no shortfall, so nothing is+ overridden and no warning is invented. Loading unmapped is a legitimate choice."""+ backend, gguf = _offload_backend(+ tmp_path, gguf_gb = 13.3, free_mib = 4877, avail_mib = 64_000, monkeypatch = monkeypatch+ )++ cmd = _launch(backend, gguf, extra_args = extra_args)["cmd"]++ assert _unmapped_tokens(cmd) == list(+ extra_args+ ), f"the fitting load lost the mode it asked for: {cmd}"+ assert backend.last_load_warning is None+++def test_the_override_keeps_a_lock_rather_than_dropping_it(tmp_path, monkeypatch):+ """`mlock` is unmapped too, but it also says "keep this in RAM". The pageable+ equivalent is `mmap+mlock`, which upstream mmaps, so the request survives the+ override instead of being silently discarded."""+ backend, gguf = _offload_backend(+ tmp_path, gguf_gb = 13.3, free_mib = 4877, avail_mib = 10_000, monkeypatch = monkeypatch+ )+ monkeypatch.delenv("UNSLOTH_ALLOW_HOST_OFFLOAD", raising = False)++ cmd = _launch(backend, gguf, extra_args = ["--load-mode", "mlock"])["cmd"]++ assert cmd, "the unmapped oversized load never spawned llama-server"+ _modes = [cmd[i + 1] for i, tok in enumerate(cmd) if tok == "--load-mode" and i + 1 < len(cmd)]+ assert _modes == ["mmap+mlock"], f"the lock was not carried onto a mapping: {cmd}"+ assert "memory mapping instead" in (backend.last_load_warning or "")+++def test_the_override_reaches_the_env_twin_llama_cpp_reads_first(tmp_path, monkeypatch):+ """llama.cpp resolves LLAMA_ARG_* before argv, so an inherited selector survives+ stripping the tokens. Unsloth emits no load-mode flag of its own here, so without+ the env half the child would still load unmapped with nothing in the argv to show+ it."""+ backend, gguf = _offload_backend(+ tmp_path, gguf_gb = 13.3, free_mib = 4877, avail_mib = 10_000, monkeypatch = monkeypatch+ )+ monkeypatch.delenv("UNSLOTH_ALLOW_HOST_OFFLOAD", raising = False)+ monkeypatch.setenv("LLAMA_ARG_NO_MMAP", "1")++ launched = _launch(backend, gguf)++ assert launched["cmd"], "the unmapped oversized load never spawned llama-server"+ assert "LLAMA_ARG_NO_MMAP" not in launched["env"]+ assert "memory mapping instead" in (backend.last_load_warning or "")+++def _override_log(monkeypatch):+ """Collect the pageable-override log line. structlog, so caplog cannot see it."""+ import core.inference.llama_cpp as llama_cpp++ lines = []+ monkeypatch.setattr(+ llama_cpp.logger,+ "warning",+ lambda msg, *a, **kw: lines.append(msg % a if a else msg),+ )+ return lines++[email protected]("extra_args", _UNMAPPED_ARGV, ids = _UNMAPPED_IDS)+def test_the_warning_opt_out_never_disables_the_pageable_override(+ tmp_path, monkeypatch, extra_args+):+ """UNSLOTH_ALLOW_HOST_OFFLOAD silences the warning and nothing else.++ The override is what lets an oversized unmapped load finish at all: "none" and+ "mlock" allocate the whole model in host RAM, so the same shortfall is an OOM kill+ rather than slow paging. Gating it on the message meant setting the deprecated+ escape turned a load that works into one that is killed, which is the opposite of+ what an opt-out from a REFUSAL was ever meant to do. The message goes; the rewrite+ stays, and the log still names it so the load is traceable."""+ backend, gguf = _offload_backend(+ tmp_path, gguf_gb = 13.3, free_mib = 4877, avail_mib = 10_000, monkeypatch = monkeypatch+ )+ monkeypatch.setenv("UNSLOTH_ALLOW_HOST_OFFLOAD", "1")+ logged = _override_log(monkeypatch)++ cmd = _launch(backend, gguf, extra_args = extra_args)["cmd"]++ assert cmd, "the unmapped oversized load never spawned llama-server"+ assert not _unmapped_tokens(cmd), f"the opt-out left the child loading unmapped: {cmd}"+ # The opt-out did its one job, and only that job.+ assert backend.last_load_warning is None+ assert [line for line in logged if "Overriding the unmapped load mode" in line], logged++[email protected]("extra_args", _UNMAPPED_ARGV, ids = _UNMAPPED_IDS)+def test_the_opt_out_on_a_fitting_unmapped_load_changes_nothing(tmp_path, monkeypatch, extra_args):+ """The control for the case above. Silenced or not, a load with room to run is+ left exactly as asked and nothing is logged about an override."""+ backend, gguf = _offload_backend(+ tmp_path, gguf_gb = 13.3, free_mib = 4877, avail_mib = 64_000, monkeypatch = monkeypatch+ )+ monkeypatch.setenv("UNSLOTH_ALLOW_HOST_OFFLOAD", "1")+ logged = _override_log(monkeypatch)++ cmd = _launch(backend, gguf, extra_args = extra_args)["cmd"]++ assert _unmapped_tokens(cmd) == list(extra_args), f"the fitting load lost its mode: {cmd}"+ assert backend.last_load_warning is None+ assert not [line for line in logged if "Overriding the unmapped load mode" in line], logged+++def _apu_backend(tmp_path, *, gguf_gb, avail_mib, monkeypatch):+ """A ROCm unified-memory APU: the weights load into system RAM, and the APU's+ reported GPU pool IS that RAM.++ The discrete host guard is left stubbed off, as it effectively is on this host:+ ``_shared_gpu_ids`` is populated for Vulkan alone (the Vulkan probe is what reports+ an iGPU), so on ROCm the APU's pool is credited against the weights as if it were+ dedicated VRAM, the spill prices out at zero and the guard abstains. The APU+ preflight is the only reading that sees the shortfall."""+ backend, gguf = _backend(tmp_path, vulkan = False, memory = [(0, 60_000, 60_000)])+ backend._get_gguf_size_bytes = lambda _path: int(gguf_gb * 1024**3)+ backend._amd_apu_wants_unified_memory = lambda *_a, **_kw: True+ backend._apu_ram_shortfall_message = LlamaCppBackend._apu_ram_shortfall_message+ # nothing pinned, so the preflight re-asks the gate; no marker here, so it abstains+ backend._arch_gate_survivors = lambda _binary = None: []+ backend._select_gpus = lambda *args, **kw: (None, True)+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: avail_mib)+ )+ monkeypatch.delenv("UNSLOTH_ALLOW_HOST_OFFLOAD", raising = False)+ return backend, gguf++[email protected]("extra_args", _UNMAPPED_ARGV, ids = _UNMAPPED_IDS)+def test_an_oversized_unmapped_apu_load_is_paged_before_it_launches(+ tmp_path, monkeypatch, extra_args+):+ """The APU preflight only RECORDED its shortfall, and the discrete guard next door+ cannot re-find it (the APU's reported pool covers the weights), so an unmapped+ oversized APU load reached the child unchanged and was OOM-killed. It is the+ condition that drives the override, not whichever guard happened to word it."""+ backend, gguf = _apu_backend(+ tmp_path, gguf_gb = 64.6, avail_mib = 46 * 1024, monkeypatch = monkeypatch+ )++ cmd = _launch(backend, gguf, extra_args = extra_args)["cmd"]++ assert cmd, "the unmapped oversized APU load never spawned llama-server"+ assert not _unmapped_tokens(cmd), f"the APU child still loads unmapped: {cmd}"+ assert "unified-memory APU" in (backend.last_load_warning or "")+ assert "memory mapping instead" in (backend.last_load_warning or "")++[email protected]("extra_args", _UNMAPPED_ARGV, ids = _UNMAPPED_IDS)+def test_an_unmapped_apu_load_that_fits_is_left_exactly_as_asked(tmp_path, monkeypatch, extra_args):+ """The control. Same APU, same request, room to run: no shortfall, so the mode the+ user chose survives untouched and no warning is invented."""+ backend, gguf = _apu_backend(+ tmp_path, gguf_gb = 64.6, avail_mib = 92 * 1024, monkeypatch = monkeypatch+ )++ cmd = _launch(backend, gguf, extra_args = extra_args)["cmd"]++ assert _unmapped_tokens(cmd) == list(extra_args), f"the fitting APU load lost it: {cmd}"+ assert backend.last_load_warning is None+++def _unmapped_tokens(cmd):+ """The tokens in ``cmd`` that select a mode llama.cpp does not mmap."""+ out = []+ for i, token in enumerate(cmd):+ if token in ("--no-mmap", "-no-mmap", "--no-direct-io", "-ndio"):+ out.append(token)+ elif token in ("--load-mode", "-lm") and i + 1 < len(cmd):+ if cmd[i + 1].strip().lower() in ("none", "mlock"):+ out.extend([token, cmd[i + 1]])+ elif token.split("=", 1)[0] in ("--load-mode", "-lm") and "=" in token:+ if token.split("=", 1)[1].strip().lower() in ("none", "mlock"):+ out.append(token)+ return outdef _load_intent(gguf, **kwargs):@@ -2071,7 +2388,7 @@ def test_the_route_precheck_refuses_before_the_gpu_handoff(tmp_path, monkeypatch)_host_totals(monkeypatch, backend, vram_total_mib = 24_000, ram_total_mib = 32_000)- verdict = backend.host_offload_refusal_for_intent(_load_intent(gguf))+ verdict = backend.host_offload_warning_for_intent(_load_intent(gguf))assert verdict is not None and "does not fit in GPU memory" in verdict@@ -2092,7 +2409,7 @@ def test_the_route_precheck_credits_capacity_the_handoff_is_about_to_reclaim(tmpmonkeypatch, backend, vram_total_mib = 24_000, ram_total_mib = 64_000, vram_free_mib = 900)- assert backend.host_offload_refusal_for_intent(_load_intent(gguf)) is None+ assert backend.host_offload_warning_for_intent(_load_intent(gguf)) is Nonedef test_the_route_precheck_only_refuses_what_the_launch_would(tmp_path, monkeypatch):@@ -2104,17 +2421,17 @@ def test_the_route_precheck_only_refuses_what_the_launch_would(tmp_path, monkeyp)_host_totals(monkeypatch, backend, vram_total_mib = 24_000, ram_total_mib = 32_000)- assert backend.host_offload_refusal_for_intent(_load_intent(gguf, hf_repo = "org/repo")) is None+ assert backend.host_offload_warning_for_intent(_load_intent(gguf, hf_repo = "org/repo")) is None# an igpu or a MIG/vGPU line reports total 0, so the ceiling is unknownbackend._get_gpu_memory = lambda _binary = None, **_kw: [(0, 20_000, 0)]- assert backend.host_offload_refusal_for_intent(_load_intent(gguf)) is None+ assert backend.host_offload_warning_for_intent(_load_intent(gguf)) is Nonebackend._get_gpu_memory = lambda _binary = None, **_kw: []- assert backend.host_offload_refusal_for_intent(_load_intent(gguf)) is None+ assert backend.host_offload_warning_for_intent(_load_intent(gguf)) is None_host_totals(monkeypatch, backend, vram_total_mib = 24_000, ram_total_mib = None)- assert backend.host_offload_refusal_for_intent(_load_intent(gguf)) is None+ assert backend.host_offload_warning_for_intent(_load_intent(gguf)) is None_host_totals(monkeypatch, backend, vram_total_mib = 24_000, ram_total_mib = 32_000)monkeypatch.setenv("UNSLOTH_ALLOW_HOST_OFFLOAD", "1")- assert backend.host_offload_refusal_for_intent(_load_intent(gguf)) is None+ assert backend.host_offload_warning_for_intent(_load_intent(gguf)) is Nonedef test_an_arch_gated_cpu_launch_prices_the_whole_model(tmp_path, monkeypatch):@@ -2246,8 +2563,7 @@ def test_the_launch_reports_a_cpu_only_build_to_the_guard(tmp_path, monkeypatch)monkeypatch = monkeypatch,)cpu_build._binary_ships_no_gpu_backend = lambda _binary = None, _env = None: True- with pytest.raises(RuntimeError, match = "does not fit in GPU memory"):- _launch(cpu_build, gguf2)+ _launch_warns(cpu_build, gguf2)def test_an_empty_gpu_pool_abstains(tmp_path, monkeypatch):@@ -2516,3 +2832,729 @@ def test_tensor_mode_keeps_an_inherited_quantized_kv_env(tmp_path, monkeypatch):# Budget-only adoption: the env stays the source of truth for the child.assert "--cache-type-k" not in cmdassert "--cache-type-v" not in cmd+++# ── UNSLOTH_ALLOW_HOST_OFFLOAD is warning-scoped on the APU path too ────────+# The variable's whole remaining contract is that it silences a message. The APU+# preflight priced RAM with a helper that never reads it, so setting the deprecated+# escape silenced the discrete guard and left the APU advisory in memory_warning.++[email protected]("extra_args", _UNMAPPED_ARGV, ids = _UNMAPPED_IDS)+def test_the_opt_out_silences_the_apu_advisory_and_keeps_the_override(+ tmp_path, monkeypatch, extra_args+):+ """Both halves at once, because they pull in opposite directions: the message goes,+ and the pageable rewrite that makes the load survivable stays. The verdict is read+ before the opt-out, so only the recording is suppressed."""+ backend, gguf = _apu_backend(+ tmp_path, gguf_gb = 64.6, avail_mib = 46 * 1024, monkeypatch = monkeypatch+ )+ monkeypatch.setenv("UNSLOTH_ALLOW_HOST_OFFLOAD", "1")+ logged = _override_log(monkeypatch)++ cmd = _launch(backend, gguf, extra_args = extra_args)["cmd"]++ assert cmd, "the unmapped oversized APU load never spawned llama-server"+ assert not _unmapped_tokens(cmd), f"the opt-out left the APU child unmapped: {cmd}"+ assert backend.last_load_warning is None, (+ "UNSLOTH_ALLOW_HOST_OFFLOAD is documented as silencing the warning, but the "+ f"APU advisory came back: {backend.last_load_warning}"+ )+ # Silenced, not invisible: the log is what keeps an overridden load traceable.+ assert [line for line in logged if "Overriding the unmapped load mode" in line], logged+++def test_the_opt_out_leaves_a_fitting_apu_load_alone(tmp_path, monkeypatch):+ """The control. Nothing to say and nothing to override, so the mode the user asked+ for survives and no warning is invented either way."""+ backend, gguf = _apu_backend(+ tmp_path, gguf_gb = 64.6, avail_mib = 92 * 1024, monkeypatch = monkeypatch+ )+ monkeypatch.setenv("UNSLOTH_ALLOW_HOST_OFFLOAD", "1")++ cmd = _launch(backend, gguf, extra_args = ["--no-mmap"])["cmd"]++ assert _unmapped_tokens(cmd) == ["--no-mmap"], cmd+ assert backend.last_load_warning is None+++def _apu_and_discrete_shortfall_backend(tmp_path, monkeypatch, *, avail_mib):+ """A unified-memory APU whose reported VRAM pool does NOT cover the weights, so the+ APU preflight and the discrete host guard both find a shortfall on the same load.++ The overlap is the point: two guards, two messages, and _record_load_warning keeps+ the first."""+ backend, gguf = _offload_backend(+ tmp_path,+ gguf_gb = 13.3,+ free_mib = 4877,+ avail_mib = avail_mib,+ monkeypatch = monkeypatch,+ _amd_apu_wants_unified_memory = lambda *_a, **_kw: True,+ _apu_ram_shortfall_message = LlamaCppBackend._apu_ram_shortfall_message,+ # nothing pinned, so the preflight re-asks the gate; no marker, so it abstains+ _arch_gate_survivors = lambda _binary = None: [],+ )+ monkeypatch.delenv("UNSLOTH_ALLOW_HOST_OFFLOAD", raising = False)+ return backend, gguf+++def _host_guard_spy(backend):+ """Record what the discrete host guard returned, so a test can pin that it really+ did fire rather than assuming the overlap it is about."""+ seen = []+ real = backend._launch_host_shortfall_message++ def _spy(*args, **kwargs):+ message = real(*args, **kwargs)+ seen.append(message)+ return message++ backend._launch_host_shortfall_message = _spy+ return seen++[email protected]("extra_args", _UNMAPPED_ARGV, ids = _UNMAPPED_IDS)+def test_the_override_note_reaches_the_warning_the_route_returns(tmp_path, monkeypatch, extra_args):+ """When BOTH guards warn, the APU preflight recorded first and first notice wins,+ so appending the override note to the launch guard's message alone wrote it onto a+ string _record_load_warning then discards. The user was told nothing about Unsloth+ undoing the non-mmap mode they chose, on a load whose argv really did change."""+ backend, gguf = _apu_and_discrete_shortfall_backend(tmp_path, monkeypatch, avail_mib = 10_000)+ seen = _host_guard_spy(backend)++ cmd = _launch(backend, gguf, extra_args = extra_args)["cmd"]++ assert cmd, "the unmapped oversized load never spawned llama-server"+ assert not _unmapped_tokens(cmd), f"the child still loads unmapped: {cmd}"+ # The precondition this cell exists for: two shortfalls on one load.+ assert any(msg and "does not fit in GPU memory" in msg for msg in seen), seen+ warning = backend.last_load_warning or ""+ assert "unified-memory APU" in warning, warning+ assert (+ "memory mapping instead" in warning+ ), f"the override never reached the warning the route returns: {warning}"+++def test_the_note_is_appended_once_when_only_the_launch_guard_warned(tmp_path, monkeypatch):+ """The control against a double append. With no APU notice recorded there is+ nothing to amend, so the note arrives exactly once, through the launch guard's own+ message."""+ backend, gguf = _offload_backend(+ tmp_path, gguf_gb = 13.3, free_mib = 4877, avail_mib = 10_000, monkeypatch = monkeypatch+ )+ monkeypatch.delenv("UNSLOTH_ALLOW_HOST_OFFLOAD", raising = False)++ _launch(backend, gguf, extra_args = ["--no-mmap"])++ warning = backend.last_load_warning or ""+ assert "does not fit in GPU memory" in warning+ assert warning.count("memory mapping instead") == 1, warning+++# ── Repricing after the text-only fallback drops a CPU-pinned projector ────────+# The APU preflight charges model_size + the projector the launch pinned to CPU,+# because both land in the same system RAM. When llama-server then fails on the+# projector and the retry strips --mmproj, the child that serves the session never+# reads those bytes: the advisory the route hands back described a load that is not+# running, and could have been the only reason an unmapped launch was remapped.+_PROJECTOR_ABORT_OUT = (+ "srv load_model: loading model 'model.gguf'\nclip.cpp:4391: Unknown projector type\n"+)+++def _apu_pinned_projector_backend(tmp_path, monkeypatch, *, gguf_gb, mmproj_gb, avail_mib):+ """An APU whose weights fit in RAM on their own and only overflow it once the+ CPU-pinned vision projector is charged alongside them."""+ backend, gguf = _apu_backend(+ tmp_path, gguf_gb = gguf_gb, avail_mib = avail_mib, monkeypatch = monkeypatch+ )+ mmproj = _write_gguf(tmp_path / "mmproj.gguf", architecture = "clip")+ backend._resolve_launch_mmproj_path = lambda **_kw: str(mmproj)+ backend._mmproj_vram_bytes = lambda _path: int(mmproj_gb * 1024**3)+ return backend, gguf+++def _launch_with_text_only_fallback(backend, gguf, **load_kwargs):+ """Every spawn that still carries --mmproj aborts on the projector; the text-only+ retry comes up healthy. Mirrors the real recovery: the session ends up serving a+ child that loaded the weights and nothing else."""+ captured = {"cmds": []}++ def fake_popen(cmd, **kwargs):+ if not cmd or str(cmd[0]) != "/fake/llama-server":+ return _REAL_POPEN(cmd, **kwargs)+ captured["cmds"].append(list(cmd))+ captured["cmd"] = list(cmd)+ captured["env"] = kwargs.get("env") or dict(os.environ)+ return type(+ "Process",+ (),+ {+ "pid": 123,+ "stdout": (),+ "poll": lambda self: None,+ "terminate": lambda self: None,+ "wait": lambda self, timeout = None: 0,+ "kill": lambda self: None,+ },+ )()++ def fake_health(timeout = None):+ launched = captured["cmds"][-1] if captured["cmds"] else []+ if "--mmproj" in launched:+ backend._stdout_lines = _PROJECTOR_ABORT_OUT.splitlines()+ return False+ backend._stdout_lines = []+ return True++ backend._wait_for_health = fake_health++ with patch.object(subprocess, "Popen", side_effect = fake_popen):+ assert backend.load_model(+ GgufLoadIntent(+ gguf_path = str(gguf),+ model_identifier = "test",+ is_vision = True,+ **load_kwargs,+ )+ )+ return captured++[email protected]("unmapped", [False, True], ids = ["pageable", "unmapped"])+def test_the_text_only_fallback_reprices_the_projector_it_dropped(tmp_path, monkeypatch, unmapped):+ """40 GB of weights fit the 44 GB this APU can spare; the 8 GB projector pinned+ beside them does not, so the preflight warns (and, unmapped, remaps the load).+ The projector then fails to start and the session serves text-only, holding only+ the weights -- which fit. The advisory has to describe THAT child.++ The override is not taken back. Its argv and its env reached the child long before+ this point, so the running server is memory-mapped whatever the message says; an+ override that turns out to have been unnecessary is reported, not un-reported.+ """+ backend, gguf = _apu_pinned_projector_backend(+ tmp_path, monkeypatch, gguf_gb = 40.0, mmproj_gb = 8.0, avail_mib = 46 * 1024+ )+ extra_args = ["--no-mmproj-offload"] + (["--no-mmap"] if unmapped else [])++ captured = _launch_with_text_only_fallback(backend, gguf, extra_args = extra_args)++ assert "--mmproj" in captured["cmds"][0], captured["cmds"][0]+ assert "--mmproj" not in captured["cmds"][-1], captured["cmds"][-1]+ warning = backend.last_load_warning or ""+ assert "unified-memory APU" not in warning, (+ "the response still warns about a shortfall the resident model does not have: " f"{warning}"+ )+ if unmapped:+ # The one thing that IS still true of the running child.+ assert "memory mapping instead" in warning, warning+ else:+ assert backend.last_load_warning is None, warning+++def test_the_reprice_reads_the_pool_the_preflight_saw_not_the_one_the_model_is_in(+ tmp_path, monkeypatch+):+ """The reprice asks "would the weights alone have fit?", so it has to weigh them+ against the RAM that was free BEFORE they were loaded.++ By the time it runs, the text-only child is healthy and holding the weights, so+ system RAM has fallen by roughly their size. Re-reading it there charges+ ``model_size`` against ``avail - model_size`` and finds a shortfall for a model+ that demonstrably just started: the load would keep an advisory saying it does not+ fit while it is serving. Modelled here by dropping the pool between the preflight+ and the fallback, which a fixed ``avail_mib`` in the other tests cannot express.+ """+ backend, gguf = _apu_pinned_projector_backend(+ tmp_path, monkeypatch, gguf_gb = 40.0, mmproj_gb = 8.0, avail_mib = 46 * 1024+ )+ # 46 GB free at the preflight; the resident 40 GB of weights leave 6 GB by the time+ # the text-only retry is healthy. Only the first reading is the one being repriced.+ readings = iter([46 * 1024])+ monkeypatch.setattr(+ LlamaCppBackend,+ "_available_system_memory_mib",+ staticmethod(lambda: next(readings, 6 * 1024)),+ )++ _launch_with_text_only_fallback(backend, gguf, extra_args = ["--no-mmproj-offload"])++ assert backend.last_load_warning is None, (+ "the reprice charged the weights against a pool they are already occupying, so "+ f"a model that started fine still warns it does not fit: {backend.last_load_warning}"+ )+++def test_a_projector_the_weights_alone_still_outgrow_keeps_its_warning(tmp_path, monkeypatch):+ """The control. Same fallback, but the weights on their own are already too big+ for this APU, so dropping the projector changes nothing the user needs to know and+ the advisory stays."""+ backend, gguf = _apu_pinned_projector_backend(+ tmp_path, monkeypatch, gguf_gb = 64.6, mmproj_gb = 8.0, avail_mib = 46 * 1024+ )++ _launch_with_text_only_fallback(backend, gguf, extra_args = ["--no-mmproj-offload"])++ assert "unified-memory APU" in (backend.last_load_warning or "")+++# ── The resident advisory outlives an attempt that never touched the server ───+def _load_rejected(backend, intent, **load_kwargs):+ """Run a load that is expected to stand down before the Phase 1 teardown, and+ report nothing about it: what the caller asserts is the server left behind."""+ try:+ return backend.load_model(intent, **load_kwargs)+ except (RuntimeError, ValueError, FileNotFoundError):+ return False+++def test_a_rejected_load_leaves_the_resident_advisory_alone(tmp_path, monkeypatch):+ """An oversized model is serving, and its advisory is the only thing telling the+ user why generation crawls. A load that is refused before the teardown leaves that+ child running, so retiring its notice reported memory_warning: null for a model+ that is still paging -- including on the very next already_loaded answer."""+ backend, gguf = _apu_backend(+ tmp_path, gguf_gb = 64.6, avail_mib = 46 * 1024, monkeypatch = monkeypatch+ )++ resident = _launch(backend, gguf)+ assert resident["cmd"]+ warned = backend.last_load_warning+ assert "unified-memory APU" in (warned or "")++ # 1. The in-app update refusal: the first check in load_model, above everything.+ backend._llama_update_in_progress = True+ assert not _load_rejected(+ backend, GgufLoadIntent(gguf_path = str(gguf), model_identifier = "other")+ )+ backend._llama_update_in_progress = False+ assert backend.last_load_warning == warned, (+ "the update refusal retired the advisory of a server it never touched: "+ f"{backend.last_load_warning}"+ )++ # 2. A cancel that lands before the teardown, on a different model.+ cancelled = threading.Event()+ cancelled.set()+ assert not _load_rejected(+ backend,+ GgufLoadIntent(gguf_path = str(gguf), model_identifier = "other"),+ load_cancel_event = cancelled,+ )+ assert (+ backend.last_load_warning == warned+ ), f"the cancelled load retired the resident advisory: {backend.last_load_warning}"++ # 3. ...and the already_loaded fast path still carries it, which is what the route+ # reads for memory_warning on a repeat /load.+ assert backend.load_model(GgufLoadIntent(gguf_path = str(gguf), model_identifier = "test"))+ assert (+ backend.last_load_warning == warned+ ), f"already_loaded answered with no memory_warning: {backend.last_load_warning}"+++# ── Repricing after an auto-selected Vulkan backend is replayed on CPU ─────────+# The replay launches with --gpu-layers 0 --device none, so the child that serves the+# session is credited no VRAM at all and pages the whole model from system RAM. The+# preflight priced a GPU placement that is now dead: its spill figure understates what+# the running child holds, and a model that FIT in VRAM was never priced against host+# RAM at all, which is the case the user most needs told about.+def _vulkan_cpu_replay_backend(tmp_path, monkeypatch, *, gguf_gb, free_mib, avail_mib):+ """A host whose auto-selected Vulkan build hard-crashes at startup, with a discrete+ card (Vulkan reports total 0 only for an iGPU, so this pool is real VRAM) and a+ staged CPU runtime for the replay."""+ backend, gguf = _backend(tmp_path, vulkan = True, memory = [(0, free_mib, free_mib)])+ _restore_host_guard(backend)+ backend._get_gguf_size_bytes = lambda _path: int(gguf_gb * 1024**3)+ backend._select_gpus = lambda *_a, **_kw: (None, True)+ backend.probe_server_capabilities = lambda _binary: {"found": True}+ # The real _prepare_cpu_fallback_launch and _cpu_isolated_replay run: what is being+ # asserted is how the REPLAY argv prices, so it has to be the argv the code builds.+ backend._cpu_isolated_binary = lambda _binary: "/fake/llama-server"+ backend._llama_server_env_for_binary = lambda _binary: {_loader_path_var(): ""}+ backend._record_server_pid = lambda _pid: None+ backend._clear_server_pid = lambda: None+ monkeypatch.setattr(+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _binary = None: True)+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_vulkan_prebuilt_was_auto_selected", staticmethod(lambda _binary: True)+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: avail_mib)+ )+ monkeypatch.delenv("UNSLOTH_ALLOW_HOST_OFFLOAD", raising = False)+ return backend, gguf+++def _launch_with_vulkan_cpu_replay(+ backend,+ gguf,+ *,+ crash = True,+ **load_kwargs,+):+ """Every launch that can still reach a GPU dies of a signal, which is what a broken+ Vulkan backend does; only the device-less replay comes up healthy. Written against+ the argv rather than the attempt number so the intermediate rungs (the --flash-attn+ off retry) crash too instead of masking the fallback under test.++ ``crash=False`` is the control: the same host, the same model, one launch that+ works, so nothing is repriced.+ """+ captured = {"cmds": []}++ def _is_cpu_replay(cmd):+ return "--device" in cmd and cmd[cmd.index("--device") + 1] == "none"++ def fake_popen(cmd, **kwargs):+ if not cmd or str(cmd[0]) != "/fake/llama-server":+ return _REAL_POPEN(cmd, **kwargs)+ rc = -11 if (crash and not _is_cpu_replay(list(cmd))) else None+ captured["cmds"].append(list(cmd))+ captured["env"] = kwargs.get("env") or dict(os.environ)+ return type(+ "Process",+ (),+ {+ "pid": 123,+ "stdout": (),+ "returncode": rc,+ "poll": lambda self: rc,+ "terminate": lambda self: None,+ "wait": lambda self, timeout = None: rc,+ "kill": lambda self: None,+ },+ )()++ def fake_health(timeout = None):+ if crash and not _is_cpu_replay(captured["cmds"][-1] if captured["cmds"] else []):+ backend._stdout_lines = ["ggml_vulkan: Device memory allocation failed"]+ return False+ backend._stdout_lines = []+ return True++ backend._wait_for_health = fake_health++ with patch.object(subprocess, "Popen", side_effect = fake_popen):+ assert backend.load_model(+ GgufLoadIntent(+ gguf_path = str(gguf),+ model_identifier = "test",+ **load_kwargs,+ )+ )+ if crash:+ assert len(captured["cmds"]) > 1, captured["cmds"]+ assert backend._cpu_fallback_reason == "vulkan_startup_crash"+ assert _is_cpu_replay(captured["cmds"][-1]), captured["cmds"][-1]+ return captured+++def test_a_model_that_fits_vram_but_not_ram_is_warned_once_it_lands_on_cpu(tmp_path, monkeypatch):+ """20 GB of weights on a 24 GB card: nothing spills, so the preflight has nothing+ to say. The Vulkan backend then crashes and the replay runs on no GPU at all, so+ the whole 20 GB has to come out of a 12 GB host and pages from disk for the rest of+ the session -- and memory_warning was null for exactly that load."""+ backend, gguf = _vulkan_cpu_replay_backend(+ tmp_path, monkeypatch, gguf_gb = 20.0, free_mib = 24 * 1024, avail_mib = 12 * 1024+ )++ _launch_with_vulkan_cpu_replay(backend, gguf)++ warning = backend.last_load_warning or ""+ assert "does not fit in GPU memory" in warning, (+ "the CPU-only child pages the whole model from disk and says nothing about it: "+ f"{warning!r}"+ )+ assert "About 20 GB" in warning, warning+++def test_a_gpu_placement_warning_does_not_survive_onto_the_cpu_child(tmp_path, monkeypatch):+ """20 GB of weights on an 8 GB card spill 12 GB, which a 13 GB host cannot hold, so+ the preflight warns about 12 GB. That placement then dies. The child that serves the+ session holds all 20 GB in RAM, so the figure it inherited describes an offload it+ no longer performs -- and understates the one it does."""+ backend, gguf = _vulkan_cpu_replay_backend(+ tmp_path, monkeypatch, gguf_gb = 20.0, free_mib = 8 * 1024, avail_mib = 13 * 1024+ )++ _launch_with_vulkan_cpu_replay(backend, gguf)++ warning = backend.last_load_warning or ""+ assert (+ "About 20 GB" in warning+ ), f"the CPU-only child still reports the dead GPU placement's spill: {warning!r}"+ assert "About 12 GB" not in warning, warning+++def test_a_vulkan_load_that_never_falls_back_keeps_its_own_advisory(tmp_path, monkeypatch):+ """The control. Same host and same model as above, but the GPU launch comes up:+ nothing is replayed, so the advisory is the GPU placement's own spill, untouched."""+ backend, gguf = _vulkan_cpu_replay_backend(+ tmp_path, monkeypatch, gguf_gb = 20.0, free_mib = 8 * 1024, avail_mib = 13 * 1024+ )++ captured = _launch_with_vulkan_cpu_replay(backend, gguf, crash = False)++ assert len(captured["cmds"]) == 1, captured["cmds"]+ assert backend._cpu_fallback_reason is None+ warning = backend.last_load_warning or ""+ assert "About 12 GB" in warning, warning+ assert "About 20 GB" not in warning, warning+++def test_the_cpu_reprice_carries_the_pageable_override_note_it_did_not_revert(+ tmp_path, monkeypatch+):+ """An unmapped oversized load is remapped before the first spawn: force_pageable_load+ rewrites the argv and the shared child env in place. The replay is built from that+ argv and that env and strips placement alone, so the CPU child really is+ memory-mapped -- the note stays true and is carried onto the repriced text verbatim,+ not rebuilt and not taken back."""+ backend, gguf = _vulkan_cpu_replay_backend(+ tmp_path, monkeypatch, gguf_gb = 20.0, free_mib = 8 * 1024, avail_mib = 13 * 1024+ )++ captured = _launch_with_vulkan_cpu_replay(backend, gguf, extra_args = ["--no-mmap"])++ replay = captured["cmds"][-1]+ assert not _unmapped_tokens(replay), f"the CPU child loads unmapped: {replay}"+ warning = backend.last_load_warning or ""+ assert "About 20 GB" in warning, warning+ assert warning.count("memory mapping instead") == 1, warning++[email protected]("extra_args", _UNMAPPED_ARGV, ids = _UNMAPPED_IDS)+def test_a_replay_that_loses_its_vram_is_repaged_before_it_spawns(+ tmp_path, monkeypatch, extra_args+):+ """20 GB of weights on a 24 GB card, loaded unmapped by request, on a 12 GB host.++ The preflight leaves the mode alone and is right to: nothing spills, so there is no+ shortfall and an unmapped load that fits is exactly what was asked for. Then Vulkan+ hard-crashes and the replay appends "--gpu-layers 0 --fit off --device none", which+ credits it no VRAM at all. The same 20 GB now has to come out of a 12 GB host, and+ unmapped that is one allocation of the whole file rather than a mapping that pages:+ an OOM kill, not a slow load. So the replay is priced on its own footprint and+ repaged before it spawns, exactly as the main launch path would have done.+ """+ backend, gguf = _vulkan_cpu_replay_backend(+ tmp_path, monkeypatch, gguf_gb = 20.0, free_mib = 24 * 1024, avail_mib = 12 * 1024+ )++ captured = _launch_with_vulkan_cpu_replay(backend, gguf, extra_args = extra_args)++ gpu_attempt, replay = captured["cmds"][0], captured["cmds"][-1]+ assert _unmapped_tokens(gpu_attempt) == list(+ extra_args+ ), f"the fitting GPU launch lost the mode it asked for: {gpu_attempt}"+ assert not _unmapped_tokens(+ replay+ ), f"the CPU replay holds the whole model in host RAM unmapped: {replay}"+ # The advisory has to describe the child that is running: the whole model against+ # host RAM, and the override that is why it can page at all.+ warning = backend.last_load_warning or ""+ assert "About 20 GB" in warning, warning+ assert warning.count("memory mapping instead") == 1, warning+ # And the record the reload comparator reads, or the next Apply judges this child+ # against a mode it no longer runs.+ assert backend._memory_state == (False, False), backend._memory_state++[email protected]("extra_args", _UNMAPPED_ARGV, ids = _UNMAPPED_IDS)+def test_a_replay_the_host_can_actually_hold_keeps_the_mode_it_was_asked_for(+ tmp_path, monkeypatch, extra_args+):+ """The control. Same crash, same replay with no VRAM credited, but a 64 GB host+ holds all 20 GB outright. Nothing is oversized, so loading unmapped is the+ legitimate choice it always was and no override and no warning are invented."""+ backend, gguf = _vulkan_cpu_replay_backend(+ tmp_path, monkeypatch, gguf_gb = 20.0, free_mib = 24 * 1024, avail_mib = 64 * 1024+ )++ captured = _launch_with_vulkan_cpu_replay(backend, gguf, extra_args = extra_args)++ replay = captured["cmds"][-1]+ assert _unmapped_tokens(replay) == list(+ extra_args+ ), f"the CPU replay lost the mode the user asked for: {replay}"+ assert backend.last_load_warning is None, backend.last_load_warning+++def test_the_opt_out_silences_the_replay_warning_without_licensing_the_oom(tmp_path, monkeypatch):+ """UNSLOTH_ALLOW_HOST_OFFLOAD is warning-scoped, the same contract the main launch+ path holds it to: it hides the message, it does not hand the child a load it cannot+ complete. So the replay is still repaged and the override is still logged."""+ backend, gguf = _vulkan_cpu_replay_backend(+ tmp_path, monkeypatch, gguf_gb = 20.0, free_mib = 24 * 1024, avail_mib = 12 * 1024+ )+ monkeypatch.setenv("UNSLOTH_ALLOW_HOST_OFFLOAD", "1")++ captured = _launch_with_vulkan_cpu_replay(backend, gguf, extra_args = ["--no-mmap"])++ assert not _unmapped_tokens(captured["cmds"][-1]), captured["cmds"][-1]+ assert backend.last_load_warning is None, backend.last_load_warning+++def test_an_effective_lock_survives_the_replay_override_as_a_mapped_one(tmp_path, monkeypatch):+ """force_pageable_load's own rule, reached through this rung: "keep this in RAM" is+ honoured over a mapping the kernel can fall back on, so --load-mode mlock becomes+ mmap+mlock rather than losing the lock."""+ backend, gguf = _vulkan_cpu_replay_backend(+ tmp_path, monkeypatch, gguf_gb = 20.0, free_mib = 24 * 1024, avail_mib = 12 * 1024+ )++ captured = _launch_with_vulkan_cpu_replay(backend, gguf, extra_args = ["--load-mode", "mlock"])++ replay = captured["cmds"][-1]+ assert not _unmapped_tokens(replay), replay+ assert "mmap+mlock" in replay, replay+++def test_a_shadowed_lock_is_not_resurrected_by_the_replay_override(tmp_path, monkeypatch):+ """The other half of that rule. "--mlock --no-mmap" already runs unlocked, so+ dropping only the selector would page-lock the whole oversized mapping into the RAM+ this override exists to keep pageable."""+ backend, gguf = _vulkan_cpu_replay_backend(+ tmp_path, monkeypatch, gguf_gb = 20.0, free_mib = 24 * 1024, avail_mib = 12 * 1024+ )++ captured = _launch_with_vulkan_cpu_replay(backend, gguf, extra_args = ["--mlock", "--no-mmap"])++ replay = captured["cmds"][-1]+ assert not _unmapped_tokens(replay), replay+ assert "--mlock" not in replay and "mmap+mlock" not in replay, replay+++def test_the_cpu_reprice_reads_the_pool_the_preflight_saw_not_the_one_the_model_is_in(+ tmp_path, monkeypatch+):+ """The reprice asks "does the whole model fit in host RAM?", so it has to weigh it+ against the RAM that was free BEFORE the replay loaded it.++ By the time it runs, the CPU child is healthy and holding every byte, so a fresh+ reading is the pool minus the model being priced: it would charge 20 GB against the+ 4 GB left over and warn that a model which demonstrably just started does not fit.+ """+ backend, gguf = _vulkan_cpu_replay_backend(+ tmp_path, monkeypatch, gguf_gb = 20.0, free_mib = 24 * 1024, avail_mib = 24 * 1024+ )+ # 24 GB free at the preflight, 4 GB once the 20 GB of weights are resident.+ readings = iter([24 * 1024])+ monkeypatch.setattr(+ LlamaCppBackend,+ "_available_system_memory_mib",+ staticmethod(lambda: next(readings, 4 * 1024)),+ )++ _launch_with_vulkan_cpu_replay(backend, gguf)++ assert backend.last_load_warning is None, (+ "the reprice charged the weights against a pool they already occupy, so a model "+ f"that started fine still warns it does not fit: {backend.last_load_warning!r}"+ )++[email protected]("extra_args", _UNMAPPED_ARGV, ids = _UNMAPPED_IDS)+def test_an_unmapped_load_is_priced_against_the_cards_the_pin_left_it(+ tmp_path, monkeypatch, extra_args+):+ """VRAM on a card this launch pinned away is not VRAM the child can spend.++ Two 24 GB cards, and Unsloth pins the child to one of them. A 25 GB model is+ smaller than the pair and larger than the card it actually gets, so the spill+ is real and the 3 GB host cannot hold it. Summing both cards prices that spill+ at zero, leaves the unmapped request standing, and the child then allocates the+ offloaded weights in host RAM and is OOM-killed: the override exists to turn+ exactly that into a slow load.+ """+ backend, gguf = _backend(+ tmp_path, vulkan = False, memory = [(0, 20_000, 24_576), (1, 20_000, 24_576)]+ )+ _restore_host_guard(backend)+ backend._get_gguf_size_bytes = lambda _path: int(25 * 1024**3)+ backend._select_gpus = lambda *args, **kw: ([0], False)+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 3_000)+ )+ monkeypatch.delenv("UNSLOTH_ALLOW_HOST_OFFLOAD", raising = False)++ result = _launch(backend, gguf, extra_args = extra_args)+ cmd = result["cmd"]++ assert cmd, "the pinned unmapped load never spawned llama-server"+ assert not _unmapped_tokens(+ cmd+ ), f"the child still loads unmapped, priced against a card the pin hid: {cmd}"+ assert "memory mapping instead" in (backend.last_load_warning or "")+++def test_a_pinned_load_that_fits_the_card_it_got_keeps_its_mode(tmp_path, monkeypatch):+ """The control, and the one that stops the fix double-counting a pin.++ Same pin, same single reachable card, but the model fits it. Nothing is+ oversized, so the request survives untouched and no warning is invented. This+ is also what fails if the reachable set is ever derived from an INHERITED+ CUDA_VISIBLE_DEVICES: the probe has already applied that mask, so subtracting+ it again would price a card the child really does have as absent.+ """+ backend, gguf = _backend(+ tmp_path, vulkan = False, memory = [(0, 20_000, 24_576), (1, 20_000, 24_576)]+ )+ _restore_host_guard(backend)+ backend._get_gguf_size_bytes = lambda _path: int(8 * 1024**3)+ backend._select_gpus = lambda *args, **kw: ([0], False)+ monkeypatch.setattr(+ LlamaCppBackend, "_available_system_memory_mib", staticmethod(lambda: 3_000)+ )+ monkeypatch.delenv("UNSLOTH_ALLOW_HOST_OFFLOAD", raising = False)++ cmd = _launch(backend, gguf, extra_args = ["--no-mmap"])["cmd"]++ assert _unmapped_tokens(cmd) == ["--no-mmap"], f"the fitting load lost its mode: {cmd}"+ assert backend.last_load_warning is None+++def test_a_restored_cpu_fallback_is_priced_against_host_ram(tmp_path, monkeypatch):+ """A persisted cpu_fallback load reconstructs the CPU-only replay directly, with+ no crash to price around, so nothing upstream ever warned about it.++ The Vulkan probe returns an empty pool on this shape, which leaves+ `_child_has_no_gpu` False and makes the preflight abstain, so there is no notice+ for the amend on that path to add to. The child then serves the whole model out of+ system RAM and `memory_warning` came back null for it, which is the session that+ most needs the advisory.+ """+ backend, gguf = _vulkan_cpu_replay_backend(+ tmp_path, monkeypatch, gguf_gb = 20.0, free_mib = 4_000, avail_mib = 12_000+ )+ # The probe comes back EMPTY, which is the shape that makes the preflight abstain:+ # _child_has_no_gpu credits _cpu_only_zero_offload only when a device was detected,+ # so with no rows it stays False and the guard cannot tell an unreadable pool from+ # a host with no GPU. A row reporting zero free is a different, already-warned case.+ backend._get_gpu_memory = lambda _binary = None, **_kw: []+ backend._get_gpu_free_memory = lambda _binary = None, **_kw: []++ _launch_with_vulkan_cpu_replay(backend, gguf, crash = False, cpu_fallback = True)++ warning = backend.last_load_warning or ""+ assert (+ "20 GB" in warning+ ), f"a restored CPU-only session reported nothing about paging the model: {warning!r}"+++def test_a_restored_cpu_fallback_the_host_can_hold_says_nothing(tmp_path, monkeypatch):+ """The control. Same restored path, a host with room: no shortfall, so no advisory+ is invented for a session that is running comfortably."""+ backend, gguf = _vulkan_cpu_replay_backend(+ tmp_path, monkeypatch, gguf_gb = 20.0, free_mib = 4_000, avail_mib = 64_000+ )+ backend._get_gpu_memory = lambda _binary = None, **_kw: []+ backend._get_gpu_free_memory = lambda _binary = None, **_kw: []++ _launch_with_vulkan_cpu_replay(backend, gguf, crash = False, cpu_fallback = True)++ assert backend.last_load_warning is Nonediff --git a/studio/backend/tests/test_llama_server_args.py b/studio/backend/tests/test_llama_server_args.pyindex 6c468d0d3a4..57e43e0a2d6 100644--- a/studio/backend/tests/test_llama_server_args.py+++ b/studio/backend/tests/test_llama_server_args.py@@ -1251,3 +1251,164 @@ def test_matching_ctx_override_is_total_over_stored_junk():assert not _lsa.matches_explicit_ctx_override(["--ctx-size", "100352"], n_ctx), n_ctx# A malformed flag raises in parse_ctx_override; the matcher answers False.assert not _lsa.matches_explicit_ctx_override(["--ctx-size", "--top-k"], 100352)+++# ── The pageable override never resurrects a shadowed lock ──────────────────+# force_pageable_load rewrites an oversized non-mmap launch so the weights page in+# from disk instead of being allocated whole in host RAM. llama.cpp resolves these+# options last-wins, so `--mlock --no-mmap` runs UNLOCKED and unmapped: the strip has+# to read the EFFECTIVE state, not the tokens. Dropping only the selector and leaving+# the earlier --mlock standing hands the child mmap+mlock and page-locks the whole+# oversized mapping into the RAM the override exists to keep pageable.+++def _rewritten_state(argv, env = None):+ """``((mlock, reserves_ram), argv, env)`` after the pageable rewrite."""+ env = dict(env or {})+ out, overridden = _lsa.force_pageable_load(list(argv), env)+ return _lsa.resolve_effective_memory_state(out, env), out, env, overridden+++ "argv",+ [+ ["--mlock", "--no-mmap"],+ ["--mlock", "--no-direct-io"],+ ["--mlock", "--load-mode", "none"],+ ["--load-mode", "mlock", "--no-mmap"],+ ["--load-mode=mlock", "--no-mmap"],+ # The mapped spelling of the lock. It holds no unmapped copy of its own, so+ # the rewrite has no reason to touch it -- until a later reserving selector+ # shadows it, where leaving it standing is what re-locks the mapping.+ ["--load-mode", "mmap+mlock", "--no-mmap"],+ ["--load-mode=mmap+mlock", "--no-mmap"],+ ["--load-mode", "mmap+mlock", "--no-direct-io"],+ ],+ ids = [+ "no-mmap",+ "no-dio",+ "load-mode-none",+ "load-mode-mlock",+ "load-mode-mlock-equals",+ "load-mode-mmap-mlock",+ "load-mode-mmap-mlock-equals",+ "load-mode-mmap-mlock-no-dio",+ ],+)+def test_a_shadowed_lock_is_not_resurrected_by_the_pageable_rewrite(argv):+ # The pre-rewrite child is already unlocked, so there is no lock to carry.+ assert _lsa.resolve_effective_memory_state(argv) == (False, True)++ (mlock, reserves), out, _env, overridden = _rewritten_state(argv)++ assert overridden, f"the unmapped launch was not rewritten at all: {out}"+ assert not reserves, f"the child still holds a full unmapped copy: {out}"+ assert not mlock, f"the rewrite page-locked the oversized mapping: {out}"+++ "argv, expect_tokens",+ [+ (["--no-mmap", "--mlock"], ["--mlock"]),+ (["--load-mode", "mlock"], ["--load-mode", "mmap+mlock"]),+ (["--load-mode=mlock"], ["--load-mode", "mmap+mlock"]),+ ],+ ids = ["no-mmap-then-mlock", "load-mode-mlock", "load-mode-mlock-equals"],+)+def test_an_effective_lock_survives_the_pageable_rewrite(argv, expect_tokens):+ """The control. "Keep this in RAM" is a real request when nothing shadowed it, so+ it is carried onto a mapping (mmap+mlock) rather than discarded."""+ assert _lsa.resolve_effective_memory_state(argv) == (True, True)++ (mlock, reserves), out, _env, overridden = _rewritten_state(argv)++ assert overridden, f"the unmapped launch was not rewritten at all: {out}"+ assert (mlock, reserves) == (True, False), f"the lock was dropped or kept unmapped: {out}"+ assert out == expect_tokens, out+++def test_the_env_twin_of_a_shadowed_lock_goes_too():+ """llama.cpp reads LLAMA_ARG_* before argv and the negative alias after the+ affirmative one, so LLAMA_ARG_MLOCK=1 beside LLAMA_ARG_NO_MMAP is shadowed exactly+ as the argv pair is. Leaving the var behind locks the child through the environment+ with nothing in the argv to show it."""+ env = {"LLAMA_ARG_MLOCK": "1", "LLAMA_ARG_NO_MMAP": "1"}+ assert _lsa.resolve_effective_memory_state([], env) == (False, True)++ (mlock, reserves), _out, out_env, overridden = _rewritten_state([], env)++ assert "LLAMA_ARG_NO_MMAP" not in out_env+ assert "LLAMA_ARG_MLOCK" not in out_env, out_env+ assert "LLAMA_ARG_MLOCK" in overridden, overridden+ assert (mlock, reserves) == (False, False)+++def test_the_env_mapped_lock_mode_shadowed_by_an_argv_selector_goes_too():+ """The env half of the mapped spelling. llama.cpp reads LLAMA_ARG_* before argv,+ so an inherited LLAMA_ARG_LOAD_MODE=mmap+mlock followed by --no-mmap on the command+ line is shadowed exactly as the all-argv pair is, and leaving the var behind locks+ the restored mapping through the environment with nothing in the argv to show it."""+ env = {"LLAMA_ARG_LOAD_MODE": "mmap+mlock"}+ assert _lsa.resolve_effective_memory_state(["--no-mmap"], env) == (False, True)++ (mlock, reserves), _out, out_env, overridden = _rewritten_state(["--no-mmap"], env)++ assert "LLAMA_ARG_LOAD_MODE" not in out_env, out_env+ assert overridden, "the unmapped launch was not rewritten at all"+ assert (mlock, reserves) == (+ False,+ False,+ ), f"the rewrite page-locked the oversized mapping: {out_env}"+++def test_an_unshadowed_mapped_lock_is_left_entirely_alone():+ """The control that keeps the strip above scoped. ``mmap+mlock`` on its own already+ maps, so it holds no full unmapped copy and is not this override's business: it must+ come back untouched and, with nothing rewritten, report no override at all. Without+ that, a launch that was always pageable would be reported as having been remapped."""+ argv = ["--load-mode", "mmap+mlock"]+ assert _lsa.resolve_effective_memory_state(argv) == (True, False)++ (mlock, reserves), out, _env, overridden = _rewritten_state(argv)++ assert out == argv, out+ assert not overridden, f"an already-mapped launch was reported as overridden: {overridden}"+ assert (mlock, reserves) == (True, False)+++def test_the_env_mlock_mode_that_is_not_shadowed_keeps_its_lock():+ """The control for the env half: LLAMA_ARG_LOAD_MODE=mlock with nothing after it+ really is locked, so it becomes the mapped twin instead of being dropped."""+ env = {"LLAMA_ARG_LOAD_MODE": "mlock"}+ assert _lsa.resolve_effective_memory_state([], env) == (True, True)++ (mlock, reserves), _out, out_env, _overridden = _rewritten_state([], env)++ assert out_env["LLAMA_ARG_LOAD_MODE"] == "mmap+mlock"+ assert (mlock, reserves) == (True, False)+++def test_an_argv_lock_that_overrides_an_inherited_selector_survives():+ """The cross case, and the reason the rewrite cannot read either side alone: argv+ is resolved after the environment, so --mlock beats an inherited LLAMA_ARG_NO_MMAP+ and the lock is the user's live request."""+ env = {"LLAMA_ARG_NO_MMAP": "1"}+ argv = ["--mlock"]+ assert _lsa.resolve_effective_memory_state(argv, env) == (True, True)++ (mlock, reserves), out, out_env, _overridden = _rewritten_state(argv, env)++ assert "LLAMA_ARG_NO_MMAP" not in out_env+ assert out == ["--mlock"], out+ assert (mlock, reserves) == (True, False)+++def test_a_pageable_launch_keeps_every_token_including_its_lock():+ """Nothing here reserves RAM, so the override does not apply and the launch comes+ back byte for byte -- the mlock strip is scoped to a rewrite, not to any --mlock."""+ argv = ["--mlock", "--load-mode", "dio"]+ assert _lsa.resolve_effective_memory_state(argv) == (False, False)++ out, overridden = _lsa.force_pageable_load(list(argv), {})++ assert out == argv and overridden == []diff --git a/studio/backend/tests/test_load_mode_fit_matrix.py b/studio/backend/tests/test_load_mode_fit_matrix.pyindex 7fcbbbc37b6..21d89d4d633 100644--- a/studio/backend/tests/test_load_mode_fit_matrix.py+++ b/studio/backend/tests/test_load_mode_fit_matrix.py@@ -735,7 +735,7 @@ def test_the_cpu_fallback_drops_the_fits_load_mode(monkeypatch):return_value = {lc._loader_path_var(): "/staged"},),):- out, _reason = backend._prepare_cpu_fallback_launch("llama-server", replay, {}, {})+ out, _reason, _note = backend._prepare_cpu_fallback_launch("llama-server", replay, {}, {})assert "--load-mode" not in outassert "none" not in out[: out.index("--gpu-layers")]# The placement flags the replay itself adds are untouched.@@ -761,7 +761,7 @@ def test_the_cpu_fallback_keeps_a_load_mode_the_user_asked_for(monkeypatch):return_value = {lc._loader_path_var(): "/staged"},),):- out, _reason = backend._prepare_cpu_fallback_launch("llama-server", replay, {}, {})+ out, _reason, _note = backend._prepare_cpu_fallback_launch("llama-server", replay, {}, {})assert out[-2:] == ["--load-mode", "none"]@@ -2247,7 +2247,9 @@ def test_the_cpu_replay_and_the_launch_record_disagree(monkeypatch):return_value = {lc._loader_path_var(): "/staged"},),):- replay, _reason = backend._prepare_cpu_fallback_launch("llama-server", launched, {}, {})+ replay, _reason, _note = backend._prepare_cpu_fallback_launch(+ "llama-server", launched, {}, {}+ )stale = resolve_effective_memory_state(launched, {})fresh = resolve_effective_memory_state(replay, {})diff --git a/studio/backend/tests/test_metal_explicit_context_guard.py b/studio/backend/tests/test_metal_explicit_context_guard.pyindex c8fb8b6eb04..cbe88f5b1ed 100644--- a/studio/backend/tests/test_metal_explicit_context_guard.py+++ b/studio/backend/tests/test_metal_explicit_context_guard.py@@ -55,7 +55,11 @@ if "jwt" not in sys.modules:_jwt_stub.InvalidTokenError = type("InvalidTokenError", (Exception,), {})sys.modules["jwt"] = _jwt_stub-from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend # noqa: E402+from core.inference.llama_cpp import ( # noqa: E402+ _FIT_MIN_CTX,+ GgufLoadIntent,+ LlamaCppBackend,+)_message = LlamaCppBackend._metal_context_overcommit_message_ENV = LlamaCppBackend.METAL_CTX_OVERCOMMIT_ENV@@ -772,10 +776,17 @@ class TestWhenNothingFitsAtAll:assert _ctx_values(cmd)[-1] == "8192"def test_auto_is_untouched(self, tmp_path, monkeypatch):- """Auto has always launched at the 4096 floor on this host. Changing that is a- larger claim than this guard makes, and it is not what was reported."""+ """Auto launches at this arm's floor on this host, and the guard still does not+ move it.++ That floor was a hardcoded 4096 and is now _FIT_MIN_CTX, which is the larger+ claim this docstring used to decline to make -- made deliberately elsewhere, so+ that Metal stops publishing half the context a discrete GPU does for the same+ model. What this test owns is unchanged: the explicit-context guard leaves Auto+ alone. Spelled against the constant so the next floor move does not land here.+ """cmd = _launch(tmp_path, monkeypatch, n_ctx = 0, **self.NOTHING_FITS)["cmd"]- assert _ctx_values(cmd)[-1] == "4096"+ assert _ctx_values(cmd)[-1] == str(_FIT_MIN_CTX)def test_a_fixed_manual_layer_count_is_still_exempt(self, tmp_path, monkeypatch):cmd = _launch(diff --git a/studio/backend/tests/test_metal_never_starts_at_native_context.py b/studio/backend/tests/test_metal_never_starts_at_native_context.pyindex 45ea2c028a4..894df5b0b7b 100644--- a/studio/backend/tests/test_metal_never_starts_at_native_context.py+++ b/studio/backend/tests/test_metal_never_starts_at_native_context.py@@ -14,6 +14,8 @@ metadata (the cap is guarded on effective_ctx > 0), and the broadfrom __future__ import annotations+import inspect+import reimport structimport subprocessimport sys@@ -46,7 +48,12 @@ if "jwt" not in sys.modules:_jwt_stub.InvalidTokenError = type("InvalidTokenError", (Exception,), {})sys.modules["jwt"] = _jwt_stub-from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend # noqa: E402+from core.inference.llama_cpp import ( # noqa: E402+ _FIT_MIN_CTX,+ _LLAMA_FIT_MIN_CTX,+ GgufLoadIntent,+ LlamaCppBackend,+)_floor = LlamaCppBackend._metal_zero_ctx_floor_drops = LlamaCppBackend._metal_drops_zero_ctx_override@@ -179,26 +186,26 @@ def off_metal(monkeypatch):class TestOnMetal:def test_a_zero_context_is_floored(self, on_metal):"""The exception path: auto request restored to 0 after the cap ran."""- assert _floor(0, False, False, 262144) == 4096+ assert _floor(0, False, False, 262144) == _FIT_MIN_CTXdef test_a_model_shorter_than_the_floor_keeps_its_own_length(self, on_metal):assert _floor(0, False, False, 2048) == 2048def test_no_metadata_still_gets_a_floor(self, on_metal):"""The cap is guarded on ctx > 0, so this GGUF was never capped."""- assert _floor(0, False, False, None) == 4096+ assert _floor(0, False, False, None) == _FIT_MIN_CTXdef test_a_cap_below_the_floor_wins(self, on_metal):"""The exception path keeps max_available_ctx, whose KV answer can sit- under 4096. Floating back up would re-create the over-commit."""+ under the floor. Floating back up would re-create the over-commit."""assert _floor(0, False, False, 262144, 2048) == 2048def test_a_cap_above_the_floor_does_not_raise_it(self, on_metal):- assert _floor(0, False, False, 262144, 131072) == 4096+ assert _floor(0, False, False, 262144, 131072) == _FIT_MIN_CTXdef test_no_cap_yet_still_floors(self, on_metal):"""The no-metadata path never ran the cap, so there is no ceiling to respect."""- assert _floor(0, False, False, None, 0) == 4096+ assert _floor(0, False, False, None, 0) == _FIT_MIN_CTXdef test_a_positive_context_is_left_alone(self, on_metal):assert _floor(8192, False, False, 262144) == 0@@ -212,6 +219,73 @@ class TestOnMetal:assert _floor(0, False, True, 262144) == 0+def test_every_caller_of_the_floor_states_whether_the_fitter_runs():+ """``fitter_runs`` defaults to True, the permissive value, so a call that omits it+ gets the 8192 ceiling and the auto_fit exemption back.++ That default is deliberate: there is one production caller and 60-odd test call+ sites, and making it required would churn the latter to constrain the former. What+ it costs is that a SECOND production caller could reintroduce this bug by saying+ nothing, which is how the previous version of this arm went wrong -- a docstring+ claim about what callers pass, with nothing checking that they do. So the claim is+ checked here instead of asserted in prose.+ """+ source = Path(inspect.getfile(LlamaCppBackend)).read_text(encoding = "utf-8")+ calls = [m for m in re.finditer(r"self\._metal_zero_ctx_floor\(", source)]+ assert calls, "the floor is no longer called from the backend; this guard is stale"+ for match in calls:+ line = source[: match.start()].count("\n") + 1+ # Balance the parens rather than stopping at the first ")": the argument this+ # guard is looking for is itself a call, so a naive scan ends inside it.+ depth, end = 1, match.end()+ while end < len(source) and depth:+ depth += {"(": 1, ")": -1}.get(source[end], 0)+ end += 1+ args = source[match.end() : end - 1]+ assert "fitter_runs" in args, (+ f"llama_cpp.py:{line} calls _metal_zero_ctx_floor without fitter_runs, so it "+ "takes the default True and can hand a Mac 8192 tokens with the child fitter "+ "off, which nothing can then reduce. Pass fit_is_effectively_on(...) for this "+ "launch."+ )+++class TestWithNoFitterToReduceIt:+ """_FIT_MIN_CTX is a ceiling the child's --fit is expected to come down from.++ "Being BELOW llama.cpp's own floor is what made that safe to raise" -- so with+ the fitter off, this arm has to hand over what the fitter would have reduced+ to instead, or a Mac with room for 4096 and not 8192 has no way down.+ """++ def test_the_floor_drops_to_llama_cpps_own(self, on_metal):+ assert _floor(0, False, False, 262144, fitter_runs = False) == _LLAMA_FIT_MIN_CTX+ assert _LLAMA_FIT_MIN_CTX < _FIT_MIN_CTX++ def test_a_running_fitter_still_gets_the_raised_floor(self, on_metal):+ """The control: nothing about the ordinary Metal Auto path moved."""+ assert _floor(0, False, False, 262144, fitter_runs = True) == _FIT_MIN_CTX+ assert _floor(0, False, False, 262144) == _FIT_MIN_CTX++ def test_the_auto_layers_exemption_is_withdrawn_with_the_fitter(self, on_metal):+ """The docstring's claim, taken here rather than trusted to the caller:+ auto_fit means "--fit sizes it", which is false once --fit is off."""+ assert _floor(0, True, False, 262144, fitter_runs = False) == _LLAMA_FIT_MIN_CTX+ assert _floor(0, True, False, 262144, fitter_runs = True) == 0++ def test_a_measured_ceiling_below_it_still_wins(self, on_metal):+ assert _floor(0, False, False, 262144, 2048, fitter_runs = False) == 2048++ def test_a_model_shorter_than_it_keeps_its_own_length(self, on_metal):+ assert _floor(0, False, False, 2048, fitter_runs = False) == 2048++ def test_a_caller_owned_budget_is_still_exempt(self, on_metal):+ assert _floor(0, False, True, 262144, fitter_runs = False) == 0++ def test_it_stays_inert_off_apple_silicon(self, off_metal):+ assert _floor(0, False, False, 262144, fitter_runs = False) == 0++class TestEverywhereElse:@pytest.mark.parametrize("owns", [False, True])@pytest.mark.parametrize("ctx", [0, 4096])@@ -251,18 +325,18 @@ class TestTheEmittedCommand:def test_a_zero_override_does_not_outlive_the_floor(self, tmp_path, monkeypatch):cmd, _ = _launch(tmp_path, monkeypatch, extra_args = ["-c", "0", "--top-k", "5"])- assert _ctx_values(cmd) == ["4096"]+ assert _ctx_values(cmd) == [str(_FIT_MIN_CTX)]# Only the context is dropped; the rest of the user's extras survive.assert "--top-k" in cmd and "5" in cmddef test_the_long_spelling_is_dropped_too(self, tmp_path, monkeypatch):cmd, _ = _launch(tmp_path, monkeypatch, extra_args = ["--ctx-size=0"])- assert _ctx_values(cmd) == ["4096"]+ assert _ctx_values(cmd) == [str(_FIT_MIN_CTX)]def test_a_capped_context_also_drops_the_zero_override(self, tmp_path, monkeypatch):"""The Apple cap ran, so the floor stays inert -- the drop still has to fire."""cmd, _ = _launch(tmp_path, monkeypatch, ctx_metadata = 262144, extra_args = ["-c", "0"])- assert _ctx_values(cmd) == ["4096"]+ assert _ctx_values(cmd) == [str(_FIT_MIN_CTX)]def test_the_context_studio_computed_is_what_survives(self, tmp_path, monkeypatch):"""Not a constant: the cap's own answer stands, here the model's 2048.@@ -279,7 +353,7 @@ class TestTheEmittedCommand:def test_without_an_override_the_floor_stands(self, tmp_path, monkeypatch):cmd, _ = _launch(tmp_path, monkeypatch)- assert _ctx_values(cmd) == ["4096"]+ assert _ctx_values(cmd) == [str(_FIT_MIN_CTX)]def test_off_metal_nothing_is_touched(self, tmp_path, monkeypatch):"""Linux and Windows keep today's behaviour, zero override included."""@@ -338,13 +412,60 @@ class TestAutoLayersWithTheFitterTurnedOff:Extras land after Unsloth's own "--fit on" and win, so a pass-through"--fit off" leaves a command carrying no -c and no fitter, which isllama.cpp's native context and the over-commit this branch prevents.++ The floor that replaces it cannot be _FIT_MIN_CTX either. 8192 is defensible+ on a Mac only as a ceiling the child's own --fit can still reduce, down to+ llama.cpp's fit_params_min_ctx; with the fitter off there is no reduction+ path at all, so a Mac with room for 4096 and not 8192 fails at startup or at+ decode. The user typed --fit off, so the conservative context is what gives+ way, not their flag."""AUTO_LAYERS = {"gpu_memory_mode": "manual", "gpu_layers": -1}def test_the_floor_applies_once_fitting_is_off(self, tmp_path, monkeypatch):cmd, _ = _launch(tmp_path, monkeypatch, extra_args = ["--fit", "off"], **self.AUTO_LAYERS)- assert _ctx_values(cmd) == ["4096"]+ assert _ctx_values(cmd) == [str(_LLAMA_FIT_MIN_CTX)]++ def test_the_users_fit_off_is_not_taken_back_to_keep_the_higher_floor(+ self, tmp_path, monkeypatch+ ):+ """The other shape this could have taken. Overriding an explicit --fit off+ would let the floor stay at 8192, and would also re-arm a fitter the user+ may have turned off because it aborts on their host."""+ cmd, _ = _launch(tmp_path, monkeypatch, extra_args = ["--fit", "off"], **self.AUTO_LAYERS)+ assert cmd[-2:] == ["--fit", "off"]++ def test_the_no_kv_cap_lands_on_the_same_floor(self, tmp_path, monkeypatch):+ """The cap path, not the zero-context one, and in DEFAULT memory mode.++ Manual with Auto layers resolves an Auto request to 0, so it never reaches+ the cap; the default mode expands it to the model's native length, which+ does.++ A GGUF that DOES carry a context length takes the Apple cap, which assigns+ a positive context of its own. _metal_zero_ctx_floor never sees it: its+ first condition returns 0 for any positive effective_ctx, so the no-fitter+ reduction has to be made where the cap is chosen. Without that, this arm+ hands a Mac 8192 with nothing able to bring it down.+ """+ cmd, _ = _launch(+ tmp_path,+ monkeypatch,+ ctx_metadata = 262144,+ extra_args = ["--fit", "off"],+ )+ assert _ctx_values(cmd) == [str(_LLAMA_FIT_MIN_CTX)]++ def test_the_no_kv_cap_keeps_the_raised_floor_while_a_fitter_runs(self, tmp_path, monkeypatch):+ """The control: same path, fitter left on, so the exemption stands and the+ command carries no -c at all, leaving the child to size the context. What+ must NOT happen is this arm quietly adopting llama.cpp's lower floor for a+ launch that still has a fitter to come down from."""+ cmd, _ = _launch(tmp_path, monkeypatch, ctx_metadata = 262144)+ assert _ctx_values(cmd) == [+ str(_FIT_MIN_CTX)+ ], f"the raised ceiling was given up on a launch that still has a fitter: {cmd}"def test_a_zero_override_alongside_it_is_still_dropped(self, tmp_path, monkeypatch):cmd, _ = _launch(@@ -353,7 +474,14 @@ class TestAutoLayersWithTheFitterTurnedOff:extra_args = ["--fit", "off", "-c", "0"],**self.AUTO_LAYERS,)- assert _ctx_values(cmd) == ["4096"]+ assert _ctx_values(cmd) == [str(_LLAMA_FIT_MIN_CTX)]++ def test_an_inherited_fit_off_reaches_the_same_floor(self, tmp_path, monkeypatch):+ """llama.cpp applies LLAMA_ARG_FIT before argv, so the env twin turns the+ fitter off just as an extra does and withdraws the same exemption."""+ monkeypatch.setenv("LLAMA_ARG_FIT", "off")+ cmd, _ = _launch(tmp_path, monkeypatch, **self.AUTO_LAYERS)+ assert _ctx_values(cmd) == [str(_LLAMA_FIT_MIN_CTX)]def test_an_explicit_fit_on_keeps_the_exemption(self, tmp_path, monkeypatch):cmd, _ = _launch(tmp_path, monkeypatch, extra_args = ["--fit", "on"], **self.AUTO_LAYERS)@@ -403,7 +531,7 @@ class TestAnInheritedContextEnvironment:def test_an_emitted_context_leaves_the_environment_alone(self, tmp_path, monkeypatch):"""Automatic mode passes -c, and argv is parsed after the environment."""cmd, env_ctx = _launch_env(tmp_path, monkeypatch, env_ctx = "0")- assert _ctx_values(cmd) == ["4096"]+ assert _ctx_values(cmd) == [str(_FIT_MIN_CTX)]assert env_ctx == "0"def test_a_caller_owned_budget_is_left_alone(self, tmp_path, monkeypatch):@@ -437,17 +565,17 @@ class TestAVirtualisedMetalDevice:def test_an_auto_request_still_gets_the_floor(self, tmp_path, monkeypatch):cmd, _ = self._launch_pv(tmp_path, monkeypatch)- assert _ctx_values(cmd) == ["4096"]+ assert _ctx_values(cmd) == [str(_FIT_MIN_CTX)]def test_an_auto_request_still_drops_a_zero_override(self, tmp_path, monkeypatch):cmd, _ = self._launch_pv(tmp_path, monkeypatch, extra_args = ["-c", "0", "--top-k", "5"])- assert _ctx_values(cmd) == ["4096"]+ assert _ctx_values(cmd) == [str(_FIT_MIN_CTX)]assert "--top-k" in cmd and "5" in cmddef test_auto_layers_is_treated_the_same(self, tmp_path, monkeypatch):"""The pin took the layer freedom --fit needed, so the floor applies."""cmd, _ = self._launch_pv(tmp_path, monkeypatch, gpu_memory_mode = "manual", gpu_layers = -1)- assert _ctx_values(cmd) == ["4096"]+ assert _ctx_values(cmd) == [str(_FIT_MIN_CTX)]def test_a_fixed_manual_layer_count_is_still_the_callers(self, tmp_path, monkeypatch):cmd, _ = self._launch_pv(@@ -488,7 +616,7 @@ class TestTheAdvertisedCeilingMatchesWhatWeLaunch:def test_the_native_length_is_not_advertised_after_the_floor(self, on_metal):floor = _floor(0, False, False, self.NATIVE, self.NATIVE)- assert floor == 4096+ assert floor == _FIT_MIN_CTX# What load_model now publishes: the floor itself, not max(ceiling, floor).assert floor < self.NATIVE@@ -499,8 +627,8 @@ class TestTheAdvertisedCeilingMatchesWhatWeLaunch:def test_the_published_ceiling_is_never_above_what_we_launch(self, on_metal):for max_avail in (None, 3000, 4096, self.NATIVE):floor = _floor(0, False, False, self.NATIVE, max_avail)- assert floor <= (max_avail or 4096)- assert floor <= 4096+ assert floor <= (max_avail or _FIT_MIN_CTX)+ assert floor <= _FIT_MIN_CTXclass TestTheStripDoesNotRewriteWhatWasRequested:@@ -528,7 +656,7 @@ class TestTheStripDoesNotRewriteWhatWasRequested:monkeypatch.setattr(_llama_cpp, "_paravirtual_draft_ngl_flag", lambda caps: None)requested = ["-md", str(draft), "-c", "0", "--top-k", "5"]cmd, backend = _launch(tmp_path, monkeypatch, extra_args = list(requested), paravirtual = True)- assert _ctx_values(cmd) == ["4096"]+ assert _ctx_values(cmd) == [str(_FIT_MIN_CTX)]assert backend._requested_extra_args == requested@pytest.mark.parametrize("mode,layers", [("auto", -1), ("manual", -1)])diff --git a/studio/backend/tests/test_slot_reduction_context_refit.py b/studio/backend/tests/test_slot_reduction_context_refit.pyindex 5b0867e4f3b..42f0156c81c 100644--- a/studio/backend/tests/test_slot_reduction_context_refit.py+++ b/studio/backend/tests/test_slot_reduction_context_refit.py@@ -25,6 +25,19 @@ from test_llama_cpp_placement import _backend, _launch # noqa: E402MIB = 1024 * 1024NATIVE_CTX = 262144CARD_MIB = 12 * 1024 # usable 11,919 MiB at the 0.97 pin fraction++# The weights these cases are built on, named for the slot count the reduction+# leaves them at on CARD_MIB when four are asked for. The reduction only has+# something to do inside a band, and the band moves with _FIT_MIN_CTX, since the+# search prices every candidate slot count at the floor: raising it 4096 -> 8192+# moved the band down about 1,400 MiB and left the old weights either fitting+# whole at the floor under `--fit on` or collapsing to one slot for every ask.+# These were re-measured against the floor rather than nudged until green -- each+# keeps the role its test needs (a three-slot survivor, a two-slot survivor, and+# an ask that still discriminates), which is what the assertions below are about.+_KEEPS_THREE_MIB = 9_200+_KEEPS_TWO_MIB = 9_800+_ASK_STILL_MATTERS_MIB = 9_400MIXED_CARDS = (CARD_MIB, 1_280) # a primary plus a card too small to plan onto# Qwen3.8-27B-GGUF metadata.@@ -113,9 +126,9 @@ class TestTheLaunchedCountOwnsTheContext:@pytest.mark.parametrize("weights_mib,asked,slots,ctx",[- (9_600, 4, 3, 5_888), # main: 3 slots, 4096- (10_200, 4, 2, 7_680), # main: 2 slots, 4096- (10_200, 8, 2, 7_680), # main: 2 slots, 4096+ (_KEEPS_THREE_MIB, 4, 3, 12_288),+ (_KEEPS_TWO_MIB, 4, 2, 13_824),+ (_KEEPS_TWO_MIB, 8, 2, 13_824), # the same answer from a larger ask],)def test_auto_context_follows_the_reduction(self, tmp_path, weights_mib, asked, slots, ctx):@@ -123,7 +136,9 @@ class TestTheLaunchedCountOwnsTheContext:assert (got["slots"], got["fit"]) == (slots, "off")assert got["ctx"] == got["ceiling"] == ctx- @pytest.mark.parametrize("weights_mib,asked,final", [(9_600, 4, 3), (10_200, 4, 2)])+ @pytest.mark.parametrize(+ "weights_mib,asked,final", [(_KEEPS_THREE_MIB, 4, 3), (_KEEPS_TWO_MIB, 4, 2)]+ )def test_reducing_to_a_count_matches_starting_at_it(self, tmp_path, weights_mib, asked, final):"""A reduced plan matches one started at its final slot count."""reduced = _plan(tmp_path, weights_mib = weights_mib, n_parallel = asked, spec = "off")@@ -131,10 +146,17 @@ class TestTheLaunchedCountOwnsTheContext:assert reduced["slots"] == direct["slots"] == finalassert (reduced["ctx"], reduced["ceiling"]) == (direct["ctx"], direct["ceiling"])- def test_the_published_ceiling_is_not_the_4096_anchor(self, tmp_path):- """The published ceiling follows the final slot count."""- got = _plan(tmp_path, weights_mib = 10_200, n_parallel = 4, spec = "off")- assert got["ceiling"] == 7_680+ def test_the_published_ceiling_is_not_the_fit_floor_anchor(self, tmp_path):+ """The published ceiling follows the final slot count.++ Named for the floor rather than 4096 because the anchor it must not be is+ whatever _FIT_MIN_CTX currently is: the reduction prices its search there,+ so a ceiling that came back equal to the floor would mean the search result+ was published instead of the context the final slot count actually affords.+ """+ got = _plan(tmp_path, weights_mib = _KEEPS_TWO_MIB, n_parallel = 4, spec = "off")+ assert got["ceiling"] == 13_824+ assert got["ceiling"] != llama_cpp._FIT_MIN_CTXdef test_a_layer_split_across_two_cards_re_fits_the_same_way(self, tmp_path):"""The same invariant holds for a two-card layer split."""@@ -154,24 +176,30 @@ class TestTheRefitStaysOnTheCardsTheReductionChose:alone, and only the small card can hold a longer context."""def test_the_refit_does_not_pull_in_another_card(self, tmp_path):- got = _plan(tmp_path, weights_mib = 10_200, n_parallel = 4, spec = "off", vram_mib = MIXED_CARDS)+ got = _plan(+ tmp_path, weights_mib = _KEEPS_TWO_MIB, n_parallel = 4, spec = "off", vram_mib = MIXED_CARDS+ )assert (got["slots"], got["fit"], got["devices"]) == (2, "off", "0")- assert got["ctx"] == 7_680+ assert got["ctx"] == 13_824def test_it_matches_a_request_started_at_the_final_count(self, tmp_path):reduced = _plan(- tmp_path, weights_mib = 10_200, n_parallel = 4, spec = "off", vram_mib = MIXED_CARDS+ tmp_path, weights_mib = _KEEPS_TWO_MIB, n_parallel = 4, spec = "off", vram_mib = MIXED_CARDS+ )+ direct = _plan(+ tmp_path, weights_mib = _KEEPS_TWO_MIB, n_parallel = 2, spec = "off", vram_mib = MIXED_CARDS)- direct = _plan(tmp_path, weights_mib = 10_200, n_parallel = 2, spec = "off", vram_mib = MIXED_CARDS)assert reduced["devices"] == direct["devices"] == "0"assert (reduced["ctx"], reduced["ceiling"]) == (direct["ctx"], direct["ceiling"])def test_the_ceiling_still_counts_the_card_the_launch_left_out(self, tmp_path):"""The ceiling keeps measuring across both cards, not just the launched one."""- mixed = _plan(tmp_path, weights_mib = 10_200, n_parallel = 4, spec = "off", vram_mib = MIXED_CARDS)- alone = _plan(tmp_path, weights_mib = 10_200, n_parallel = 4, spec = "off")- assert mixed["ctx"] == alone["ctx"] == 7_680- assert (mixed["ceiling"], alone["ceiling"]) == (9_472, 7_680)+ mixed = _plan(+ tmp_path, weights_mib = _KEEPS_TWO_MIB, n_parallel = 4, spec = "off", vram_mib = MIXED_CARDS+ )+ alone = _plan(tmp_path, weights_mib = _KEEPS_TWO_MIB, n_parallel = 4, spec = "off")+ assert mixed["ctx"] == alone["ctx"] == 13_824+ assert (mixed["ceiling"], alone["ceiling"]) == (14_848, 13_824)class TestAutoSpeculationStillDecidesBeforeTheReduction:@@ -239,8 +267,8 @@ class TestWhatMustNotMove:@pytest.mark.parametrize("weights_mib,slots,ctx",[- (9_200, 3, 4_864), # main: 3 slots, 4096- (10_000, 1, 6_144), # main: 1 slot, 4096+ (8_200, 3, 8_704),+ (9_000, 1, 9_984),],)def test_a_dense_target_gains_only_its_compute_buffer(self, tmp_path, weights_mib, slots, ctx):@@ -267,23 +295,26 @@ class TestTheReductionIsPricedAtTheFitFloor:#9492 raised the constant 4096 -> 8192 and, through this one shared read, movedplacement. The arithmetic, on the 12 GiB card these tests use (budget- 12288 x 0.97 = 11,919.36 MiB) at 10,200 MiB of weights: the candidates are- 707 MiB apart (557.75 MiB of per-slot compute buffer plus 149.625 MiB of per-slot- Mamba state), while probing 256 tokens higher costs a uniform 64 KiB/token. The- 2-slot candidate is 11,685.0 MiB at 4096 and 11,947.0 MiB at 8192, so a display- constant moved it across the budget by 27.6 MiB.+ 12288 x 0.97 = 11,919.36 MiB) at the 10,200 MiB of weights this block was first+ written against: the candidates are 707 MiB apart (557.75 MiB of per-slot+ compute buffer plus 149.625 MiB of per-slot Mamba state), while probing 256+ tokens higher costs a uniform 64 KiB/token. The 2-slot candidate was 11,685.0+ MiB at a 4096 probe and 11,947.0 MiB at 8192, so a display constant moved it+ across the budget by 27.6 MiB. The weights above are lighter now only because+ _FIT_MIN_CTX itself moved to 8192 and carried the reducible band down with it;+ the margins being this thin is the reason the sweep below exists."""# A band that a reduction rescues from offload. Every one of these launched# `--fit off` before #9492 and `--fit on` after it, which is the ~3x decode# collapse (#6718) the reduction was written to avoid.RESCUED = [- (10_900, HYBRID),- (11_000, HYBRID),- (11_100, HYBRID),- (9_800, DENSE),- (10_000, DENSE),- (10_500, DENSE),+ (10_200, HYBRID),+ (10_400, HYBRID),+ (10_600, HYBRID),+ (9_000, DENSE),+ (9_200, DENSE),+ (9_400, DENSE),]@pytest.mark.parametrize("offload_ctx", _OFFLOAD_SWEEP)@@ -296,8 +327,8 @@ class TestTheReductionIsPricedAtTheFitFloor:satisfied by re-baselining the constant into the expectation."""monkeypatch.setattr(llama_cpp, "_AUTO_OFFLOAD_CTX", offload_ctx)- got = _plan(tmp_path, weights_mib = 10_200, n_parallel = 4, spec = "off")- assert (got["slots"], got["fit"], got["ctx"], got["devices"]) == (2, "off", 7_680, "0")+ got = _plan(tmp_path, weights_mib = _KEEPS_TWO_MIB, n_parallel = 4, spec = "off")+ assert (got["slots"], got["fit"], got["ctx"], got["devices"]) == (2, "off", 13_824, "0")@pytest.mark.parametrize("weights_mib,metadata", RESCUED)@pytest.mark.parametrize("offload_ctx", _OFFLOAD_SWEEP[:2])@@ -323,7 +354,7 @@ class TestTheReductionIsPricedAtTheFitFloor:def test_asking_for_more_slots_never_returns_fewer(self, tmp_path):"""Monotone in the ask. At head, asking for 2 got 2 and asking for 3 got 1."""finals = [- _plan(tmp_path, weights_mib = 10_200, n_parallel = n, spec = "off")["slots"]+ _plan(tmp_path, weights_mib = _ASK_STILL_MATTERS_MIB, n_parallel = n, spec = "off")["slots"]for n in (1, 2, 3, 4, 6, 8)]assert finals == sorted(finals), finals@@ -379,18 +410,23 @@ class TestTheLoggedReserveFollowsTheLaunch:monkeypatch.setattr("core.inference.llama_cpp.logger", _Recorder())assert planner_logger is not None # the real one is restored on teardown+ # Asks that converge on one plan at this floor. 2 is not among them any+ # more: at _FIT_MIN_CTX 8192 two slots fit on this card outright, so the+ # ask survives untouched and Auto settles on ngram-mod with no MTP reserve+ # to log. That is a different launch, not a differing reserve, so pinning+ # it here would test the fixture rather than the claim.seen = []- for asked in (2, 4, 8):+ for asked in (4, 6, 8):lines.clear()- got = _plan(tmp_path, weights_mib = 8_000, n_parallel = asked, spec = "auto", vram_mib = 9_728)+ got = _plan(tmp_path, weights_mib = 7_600, n_parallel = asked, spec = "auto", vram_mib = 9_728)reserves = set(re.findall(r"MTP reserve: ([\d.]+) GB", "\n".join(lines)))assert reserves, "the reserve was never logged"seen.append((got["slots"], got["ctx"], got["spec"], reserves))- assert seen[0][:3] == (1, 5_632, "draft-mtp")+ assert seen[0][:3] == (1, 11_520, "draft-mtp")assert len({row[:3] for row in seen}) == 1, "the three launches differ"assert len({frozenset(row[3]) for row in seen}) == 1, seen- assert seen[0][3] == {"0.31"}+ assert seen[0][3] == {"0.34"}# KV-estimable metadata without a native context length.diff --git a/studio/backend/tests/test_slot_refit_platform_matrix.py b/studio/backend/tests/test_slot_refit_platform_matrix.pyindex db4d42bfbac..fd8fb167127 100644--- a/studio/backend/tests/test_slot_refit_platform_matrix.py+++ b/studio/backend/tests/test_slot_refit_platform_matrix.py@@ -99,8 +99,12 @@ class _RefitSpy:# asked slot count but does fit at a reduced one, so the re-fit has something to do.# Named because whether it still sits in that band depends on _FIT_MIN_CTX, and# test_the_fixture_still_reaches_the_refit_at_this_fit_floor reports it by name when-# a floor change moves it out.-_FIXTURE_WEIGHTS_MIB = 10_200+# a floor change moves it out. This weight was picked by sweeping the band at+# _FIT_MIN_CTX 4096, 8192 and 16384 and taking a value reducible at all three, so+# the next floor change is less likely to move it out again: at 10_200 only 4096+# reduced, and the 4096 -> 8192 raise left the load fitting whole at the floor+# with --fit on, which is the planner's other answer and not this file's subject.+_FIXTURE_WEIGHTS_MIB = 8_800_FIXTURE_SLOTS = 4diff --git a/tests/test_dill_module_by_value_fix.py b/tests/test_dill_module_by_value_fix.pyindex b216799ed00..a1213ec520d 100644--- a/tests/test_dill_module_by_value_fix.py+++ b/tests/test_dill_module_by_value_fix.py@@ -628,9 +628,7 @@ def test_stripped_bytecode_answers_to_its_recorded_source(tmp_path):files = frozenset({recorded})module = types.ModuleType("pkg")- module.__spec__ = types.SimpleNamespace(- name = "pkg", origin = str(layer / "pkg" / "__init__.pyc")- )+ module.__spec__ = types.SimpleNamespace(name = "pkg", origin = str(layer / "pkg" / "__init__.pyc"))unrecorded = types.ModuleType("otherpkg")unrecorded.__spec__ = types.SimpleNamespace(name = "otherpkg", origin = str(layer / "otherpkg" / "__init__.pyc")@@ -642,9 +640,9 @@ def test_stripped_bytecode_answers_to_its_recorded_source(tmp_path):"the live .pyc is not matched to the .py its own metadata ""recorded, so a stripped layer keeps the crash")- assert not _dill_module_is_importable_by_name(unrecorded, files), (- "a .pyc whose source was never recorded is claimed anyway"- )+ assert not _dill_module_is_importable_by_name(+ unrecorded, files+ ), "a .pyc whose source was never recorded is claimed anyway"finally:del sys.modules["pkg"]del sys.modules["otherpkg"]