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: use --load-mode none when the model fits without paging (#9565)
Daniel Hane1ce1faf7279
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 146f9593083..88a425dee0e 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -71,9 +71,12 @@ from core.inference.llama_server_args import (apply_model_memory_policy,resolve_ctx_checkpoints,extra_args_disable_mmproj,+ extra_args_select_load_mode,fit_is_enabled_in,+ memory_env_selects_load_mode,memory_state_satisfies_settings,fit_is_effectively_on,+ fit_target_margin_in,resolve_effective_memory_state,scrub_denied_env,scrub_memory_env,@@ -83,6 +86,7 @@ from core.inference.llama_server_args import (parse_gpu_layers_override,parse_split_mode_override,resolve_requested_ctx,+ split_policy_starves_devices,strip_context_only,strip_shadowing_flags,strip_split_mode_only,@@ -3237,13 +3241,27 @@ def _kv_offload_from_args() -> bool:"""Resolve llama.cpp's environment and last-wins KV-offload flags (default on):LLAMA_ARG_KV_OFFLOAD parses before argv, and ``-kvo`` / ``--kv-offload`` is the- positive form, so a CLI re-enable beats a false env."""+ positive form, so a CLI re-enable beats a false env.++ Both env spellings, as with the projector pair above. ``-kvo`` is registered with+ a negative form (``{"-nkvo", "--no-kv-offload"}``, common/arg.cpp), so+ ``common_arg::get_value_from_env`` rewrites LLAMA_ARG_ to LLAMA_ARG_NO_, and if+ that variable EXISTS it forces the value to "0" and never reads the affirmative+ one (common/arg.cpp:127-141). Presence, empty value included, because llama.cpp+ tests it with getenv. Missing it is the optimistic direction here: the whole KV+ cache is then on the host (llama-kv-cache.cpp only upgrades a layer's buffer+ type inside ``if (offload)``) while the fit still lets free VRAM pay for it.+ """+ source_env = os.environ if env is None else envenabled = True- value = (os.environ if env is None else env).get("LLAMA_ARG_KV_OFFLOAD")- if value in _LLAMA_ARG_FALSE_VALUES:+ if source_env.get("LLAMA_ARG_NO_KV_OFFLOAD") is not None:enabled = False- elif value in _LLAMA_ARG_TRUE_VALUES:- enabled = True+ else:+ value = source_env.get("LLAMA_ARG_KV_OFFLOAD")+ if value in _LLAMA_ARG_FALSE_VALUES:+ enabled = False+ elif value in _LLAMA_ARG_TRUE_VALUES:+ enabled = Truefor raw in extra_args or ():flag = _flag_name(str(raw))if flag in {"-kvo", "--kv-offload"}:@@ -3296,6 +3314,29 @@ def _env_places_tensors_on_cpu(env: Optional[Mapping[str, str]] = None) -> bool:)+def _env_fixes_gpu_layers(env: Optional[Mapping[str, str]] = None) -> bool:+ """True when an inherited ``LLAMA_ARG_N_GPU_LAYERS`` owns the layer placement.++ The env twin of ``_GPU_LAYER_FLAGS``, and it bites harder than the tokens do:+ the fitting path emits ``--fit on`` and no ``-ngl`` at all, so an inherited+ count is the ONLY layer policy the child sees. llama.cpp's fitter then refuses+ to touch it -- ``common_params_fit_impl`` throws "n_gpu_layers already set by+ user" (common/fit.cpp:377) on any value but the default, and the caller+ downgrades that to a warning (common/fit.cpp:805) -- so the launch proceeds+ with the count as given, placing a prefix of the weights and running the rest+ out of host RAM the fit just credited to a card.++ ``auto`` / ``-1`` is that default (common/common.h:465,+ llama-model.cpp:2453), so it leaves the fitter free to choose and is not an+ override. Everything else is, ``all`` included: a count that stands is a count+ this fit did not price. Empty counts as unset -- llama.cpp's ``std::stoi``+ would throw on it and the child would never start.+ """+ raw = (os.environ if env is None else env).get("LLAMA_ARG_N_GPU_LAYERS")+ value = str(raw or "").strip().lower()+ return bool(value) and value not in _LLAMA_ARG_AUTO_VALUES++def _pipeline_parallel_disabled_by_args(extra_args: Optional[Iterable[str]],env: Optional[Mapping[str, str]] = None,@@ -4044,25 +4085,175 @@ def _extra_args_draft_cache_types(return k_type, v_type-def _extra_args_draft_offloaded_to_cpu(+_DRAFT_GPU_LAYER_FLAGS = frozenset(+ {"--spec-draft-ngl", "-ngld", "--gpu-layers-draft", "--n-gpu-layers-draft"}+)+++def _extra_args_draft_gpu_layers(extra_args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None-) -> bool:- """True if the SEPARATE draft model is on CPU (so the budget must not charge- its weights+KV): --spec-draft-ngl 0, or --spec-draft-device naming only- cpu/none, else the LLAMA_ARG_N_GPU_LAYERS_DRAFT env the child honors (the- device flag has no env). An embedded MTP head follows the main -ngl, so these- draft-only flags don't move it. Last-wins, so only each flag's final value counts."""- ngl_flags = {"--spec-draft-ngl", "-ngld", "--gpu-layers-draft", "--n-gpu-layers-draft"}+) -> Optional[str]:+ """The effective draft layer count for the SEPARATE drafter, as written.++ Last-wins over argv, falling back to the ``LLAMA_ARG_N_GPU_LAYERS_DRAFT`` twin+ the child reads before argv. None when neither is set."""args = [str(a) for a in extra_args] if extra_args else []last_ngl: Optional[str] = Nonefor i, raw in enumerate(args):flag = _flag_name(raw)_, eq, inline = raw.partition("=")value = inline if eq else (args[i + 1] if i + 1 < len(args) else "")- if flag in ngl_flags:+ if flag in _DRAFT_GPU_LAYER_FLAGS:last_ngl = valueif last_ngl is None:last_ngl = (os.environ if env is None else env).get("LLAMA_ARG_N_GPU_LAYERS_DRAFT")+ return last_ngl+++def _draft_is_split_across_host(+ extra_args: Optional[Iterable[str]],+ env: Optional[Mapping[str, str]] = None,+ *,+ n_draft_layers: Optional[int] = None,+) -> bool:+ """True when a fixed POSITIVE draft layer count splits the drafter between the+ GPU and host RAM.++ ``_extra_args_draft_offloaded_to_cpu`` is the whole-drafter question and only+ answers ``-ngld 0``. Anything between that and the drafter's own block count+ leaves the layers past the count on the host -- llama.cpp derives+ ``i_gpu_start`` from the count and hands every layer below it the CPU buffer+ list (llama-model.cpp), and each layer's KV follows its device+ (llama-kv-cache.cpp). llama.cpp's default is -1, "all", so only a non-negative+ count is a placement at all, and only a count ABOVE ``n_draft_layers`` places+ the drafter whole: ``i_gpu_start = max(n_layer_all + 1 - n_gpu_layers, 0)``+ (llama-model.cpp), so the count has to clear the block count by one to reach+ zero, and ``-ngld`` equal to the block count still leaves one block -- and its+ KV -- on the host. That is the same threshold the main model already uses+ (``requested <= n_layers`` in ``_partially_offloads_layers``, and+ ``0 <= gpu_layers <= n_layers`` in the pipelining check). An unreadable block+ count (None) says nothing either way, so a positive count stands as a split+ rather than being waved through.+ """+ raw = _extra_args_draft_gpu_layers(extra_args, env)+ if raw is None:+ return False+ try:+ count = int(str(raw).strip())+ except (TypeError, ValueError):+ # std::stoi would throw and the child never starts: nothing to misprice.+ return False+ if count <= 0:+ return False+ return not (n_draft_layers and count > n_draft_layers)+++_SIDECAR_ADAPTER_FLAGS = (+ "--lora",+ "--lora-scaled",+ "--control-vector",+ "--control-vector-scaled",+)+++def _sidecar_adapter_paths(extra_args: Optional[Iterable[str]]) -> list[str]:+ """Every adapter file the child loads and holds RESIDENT, in argv order.++ None of these have an env twin -- common/arg.cpp declares all four without+ ``set_env`` -- so the tokens are the whole surface. Each operand is a+ comma-separated row (``parse_csv_row``), and the ``-scaled`` spellings split+ every entry on ':' into exactly FNAME and SCALE and throw otherwise, so a+ malformed entry is a child that never starts and has no placement to misprice;+ it is skipped rather than priced. ACCUMULATED, not last-wins: every handler+ ``push_back``s onto ``lora_adapters`` / ``control_vectors``, so a second+ ``--lora`` adds to the first rather than replacing it.++ The ``-scaled`` pair also has a LEGACY spelling: builds up to the turn of the+ year declared it ``{"--lora-scaled"}, "FNAME", "SCALE"`` and took the scale as a+ SECOND token, and Studio runs whatever llama-server it is pointed at+ (``LLAMA_SERVER_PATH``, or one found on PATH), which is why the pass-through+ validator still admits that shape (``_OPTIONAL_SECOND_VALUE_FLAGS``). Read+ colon-first, since that is today's syntax; only when the colon parse priced+ NOTHING and the token after the operand is a bare number is this the two-token+ form, and then the operand is the whole filename -- which is also the one+ reading that survives a Windows drive letter. On a build that wants the colon+ the same tokens are upstream's own throw, so pricing the file there costs at+ most a fit that never launched.+ """+ args = [str(a) for a in extra_args] if extra_args else []+ paths: list[str] = []+ for i, raw in enumerate(args):+ flag = _flag_name(raw)+ if flag not in _SIDECAR_ADAPTER_FLAGS:+ continue+ _, eq, inline = raw.partition("=")+ operand = inline if eq else (args[i + 1] if i + 1 < len(args) else "")+ priced = 0+ for entry in (piece for piece in operand.split(",") if piece):+ if not flag.endswith("-scaled"):+ paths.append(entry)+ priced += 1+ continue+ # Upstream demands exactly 2 parts, so a bare or drive-lettered path throws.+ head, colon, tail = entry.partition(":")+ if not (colon and head) or ":" in tail:+ continue+ try:+ float(tail)+ except ValueError:+ continue+ paths.append(head)+ priced += 1+ if priced or not operand or eq or not flag.endswith("-scaled"):+ continue+ # Legacy "FNAME SCALE": the scale is the token AFTER the operand.+ scale = args[i + 2] if i + 2 < len(args) else ""+ try:+ float(scale.strip())+ except ValueError:+ continue+ paths.append(operand)+ return paths+++def _sidecar_adapter_bytes(extra_args: Optional[Iterable[str]]) -> Optional[int]:+ """Resident bytes the pass-through adapters add, or None when one cannot be sized.++ LoRA tensors are allocated on the BASE tensor's buffer type+ (``ggml_backend_buffer_get_type(model_tensor->buffer)``, llama-adapter.cpp) and+ a control vector on ``model.select_buft(il)``, so they follow the layer+ placement this fit just priced rather than living anywhere it can ignore.+ Neither path mmaps -- the file is read into a staging buffer and pushed with+ ``ggml_backend_tensor_set`` -- so these bytes are resident whatever+ ``--load-mode`` says, and they sit ON TOP of a placement llama.cpp's own fitter+ never accounted for (common/fit.cpp knows nothing about adapters).++ File size is the ceiling on the allocation (the loader skips ``_norm.weight``+ pairs and keeps every other tensor at its stored type), and overstating a term+ only ever costs a fit, so the stat is charged whole. An unreadable file is the+ "engaged but unsized" case the fit abstains on.+ """+ total = 0+ for path in _sidecar_adapter_paths(extra_args):+ try:+ total += max(0, os.stat(path).st_size)+ except OSError:+ return None+ return total+++def _extra_args_draft_offloaded_to_cpu(+ extra_args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None+) -> bool:+ """True if the SEPARATE draft model is on CPU (so the budget must not charge+ its weights+KV): --spec-draft-ngl 0, or --spec-draft-device naming only+ cpu/none, else the LLAMA_ARG_N_GPU_LAYERS_DRAFT env the child honors (the+ device flag has no env). An embedded MTP head follows the main -ngl, so these+ draft-only flags don't move it. Last-wins, so only each flag's final value counts.++ A count BETWEEN 0 and the drafter's block count is a split, not an offload; see+ ``_draft_is_split_across_host``."""+ last_ngl = _extra_args_draft_gpu_layers(extra_args, env)if last_ngl is not None:try:if int(last_ngl) == 0:@@ -4941,6 +5132,9 @@ class LlamaCppBackend:# False when a launch is fully offloaded to a discrete GPU, where# page-locking host RAM is skipped on purpose.self._memory_mlock_applicable: bool = True+ # The "--load-mode none" tokens the FIT emitted, so paths that replace the+ # placement can take them back out. Empty for a mode the user asked for.+ self._fit_load_mode_flags: list[str] = []# True between recording a launch's placement and the child being# spawned, so a save landing in that window still has a launch to# compare against.@@ -8706,6 +8900,303 @@ class LlamaCppBackend:"UNSLOTH_ALLOW_HOST_OFFLOAD=1 to load it anyway.")+ def _fits_without_paging(+ self,+ footprint_bytes: Optional[int],+ detected_gpus: Iterable[tuple],+ *,+ gpu_indices: Optional[Iterable[int]] = None,+ shared_gpu_ids: Iterable[int] = (),+ host_only_bytes: int = 0,+ vram_margin_mib: float = 0.0,+ avail_mib: Optional[int] = None,+ headroom_mib: int = _HOST_RAM_HEADROOM_MIB,+ ) -> Optional[bool]:+ """Whether the whole load fits in VRAM, or in VRAM plus host RAM (else False;+ None when it cannot be told). This is the ``--load-mode`` question: mmap earns+ its keep by demand-paging a footprint the machine cannot hold, so a load that+ fits never needs it.++ ``footprint_bytes`` is weights + KV + scratch, not weights alone. The refusal+ guards next door deliberately price weights only, because understating there+ can only fail to refuse a load that would have worked. Here the bias runs the+ other way: understating would claim a fit that isn't one and hand the load a+ loader that cannot page, so every term the launch knows about is charged.++ Shared iGPU memory is not added on top of host RAM (it IS host RAM), so those+ devices are dropped from the VRAM term and their weights are carried by the RAM+ term, the same split ``_launch_host_shortfall_message`` uses. ``gpu_indices``+ narrows the VRAM term to the devices this launch actually pins; unpinned cards+ hold nothing for it. Unreadable RAM answers None rather than guessing, which+ keeps the caller on llama.cpp's own default.++ ``host_only_bytes`` is the part of ``footprint_bytes`` that CANNOT be satisfied+ out of VRAM however much is free -- a drafter the launch pinned to the CPU is+ the case -- so it is subtracted from what VRAM may cover and added to the RAM+ requirement instead. Pooling it would let free VRAM pay for bytes that can only+ ever be allocated in host RAM.++ ``vram_margin_mib`` is the free VRAM llama.cpp's own fitter keeps PER DEVICE+ and will not allocate into (``--fit-target``, default 1024 MiB, "target margin+ per device for --fit"; common/arg.cpp, common/common.h). Under ``--fit on``+ the child spills weights to host RAM rather than dip into it, so those bytes+ are not credit this launch may spend. Zero on the proved path, which emits+ ``-ngl -1 --fit off`` and runs no fitter at all.+ """+ if not footprint_bytes or footprint_bytes <= 0:+ return None+ host_only = max(0, int(host_only_bytes or 0))+ shared = set(shared_gpu_ids or ())+ pinned = None if gpu_indices is None else {int(idx) for idx in gpu_indices}+ margin_mib = max(0.0, float(vram_margin_mib or 0.0))+ free_vram_mib = sum(+ max(0, row[1] - margin_mib)+ for row in (detected_gpus or ())+ if row[0] not in shared and (pinned is None or row[0] in pinned)+ )+ free_vram_bytes = int(free_vram_mib * 1024 * 1024)+ # VRAM covers the GPU-eligible part; its spill plus the host-only bytes hit RAM.+ spill = max(0, max(0, footprint_bytes - host_only) - free_vram_bytes) + host_only+ if spill <= 0:+ return True+ avail = self._available_system_memory_mib() if avail_mib is None else avail_mib+ if avail is None:+ return None+ # Same headroom the host-offload refusal keeps free: a RAM filled to the last+ # byte is the paging case this is trying to avoid.+ return spill <= max(0, avail - headroom_mib) * 1024 * 1024++ def _fit_derived_load_mode(+ self,+ *,+ model_size: Optional[int],+ mmproj_pinned_bytes: int = 0,+ kv_cache_bytes: int = 0,+ kv_sized: bool = True,+ mtp_bytes: int = 0,+ mtp_unsized: bool = False,+ host_only_bytes: int = 0,+ compute_buffer_flat: int = 0,+ compute_buffer_ctx: int = 0,+ pipeline_overhead_bytes: int = 0,+ soft_overhead: int = 0,+ gpus: Optional[Iterable[tuple]] = None,+ gpu_indices: Optional[Iterable[int]] = None,+ shared_gpu_ids: Iterable[int] = (),+ fit_margin_mib: float = 0.0,+ is_vulkan_backend: bool = False,+ avail_mib: Optional[int] = None,+ extra_args: Optional[Iterable[str]] = None,+ env: Optional[Mapping[str, str]] = None,+ ) -> Optional[str]:+ """``"none"`` when the fit proves the load needs no demand paging, else None.++ mmap exists to demand-page a footprint the machine cannot hold, and llama.cpp+ builds its async pinned-buffer upload path ONLY when mmap is off+ (llama-model-loader.cpp, ``upload_backend``), so a load that fits wants+ ``none``: same residency, faster load, no model-sized mapping left behind.+ Anything that does not fit, or that cannot be priced, keeps llama.cpp's own+ ``auto``, where the mapping is what stops an over-committed load from being+ killed outright.++ The footprint is charged WHOLE, weights and KV and scratch, because+ understating it would claim a fit that is not there and hand the load a loader+ that cannot page. Every term that cannot be read abstains for the same reason:+ unreadable weights, an unsized KV (the estimator returns 0 without the dims,+ and a 0 KV term on a long-context load is exactly the missing term) and a+ drafter engaged but unsized, which the placement itself covers with a flat+ cushion rather than a number.++ ``host_only_bytes`` is the slice of that footprint no amount of free VRAM can+ hold (a drafter pinned to the CPU with ``-ngld 0``): counted in the total, but+ charged to host RAM alone, because free VRAM cannot pay for an allocation the+ child only ever makes on the host. ``kv_cache_bytes`` joins it under an+ effective ``--no-kv-offload``, which puts the WHOLE cache on the host+ whatever the layer placement says (llama-kv-cache.cpp defaults each layer's+ buffer type to the CPU one and upgrades it only inside ``if (offload)``).++ Apple Silicon abstains outright. Metal is the one backend where+ ``buffer_from_host_ptr`` IS supported, so mmap wraps the weights in a Metal+ buffer in place, zero copy and file backed; ``none`` would allocate the same+ bytes anonymously, and an evictable 30 GB mapping on a 32 GB machine is the+ difference between working and being jetsammed. The host figure is the wrong+ ceiling there anyway (see ``_apple_metal_memory_budget_bytes``), so a fit read+ off ``MemAvailable`` would not be one worth acting on.++ ``extra_args`` is the pass-through block as the child will really get it (the+ caller strips what a ``gpu_ids`` pin owns first), and it voids the VRAM term.+ Those tokens are appended AFTER this launch's own placement flags and+ llama.cpp is last-wins (common/arg.cpp assigns ``n_gpu_layers`` / ``devices``+ on every occurrence), so a hand-typed ``-ngl``, a ``--device`` naming no GPU+ or a CPU tensor override runs weights out of host RAM that the planner just+ credited to a card. The placement this priced is then not the one that+ launches, and ``none`` on a footprint host RAM cannot hold is an OOM where+ ``auto`` would have demand-paged. Dropping the VRAM credit rather than+ abstaining keeps the answer for the case that is still provable: a load host+ RAM holds WHOLE is safe wherever those flags end up putting it. The same+ predicates the Model Memory host-residency gate uses, so the two cannot drift.++ ``env`` is the environment the child will really get (``os.environ`` when the+ caller passes none). Every one of those pass-through overrides has an env twin+ llama.cpp reads BEFORE argv, so classifying on the tokens alone would miss an+ inherited ``LLAMA_ARG_DEVICE=none``, which no automatic launch clears (only an+ explicit ``gpu_ids`` pin does). A ``--device`` naming FEWER devices than this+ fit credits voids the VRAM term for the same reason a CPU-valued one does: the+ cards it leaves out hold nothing for this launch. ``LLAMA_ARG_N_GPU_LAYERS``+ is the sharpest of them: the fitting path emits no ``-ngl`` for it to lose+ to, so an inherited count is the whole layer policy (see+ ``_env_fixes_gpu_layers``).++ ``fit_margin_mib`` is what llama.cpp's fitter keeps free per device when the+ fitter really runs, i.e. VRAM this load may not spend; see+ ``_fits_without_paging``. The caller answers that from the EFFECTIVE flags+ rather than from its own plan: the extras land after this launch's ``--fit``+ and llama.cpp is last-wins, ``-ngl -1`` is llama.cpp's own default so an+ enabled fitter is free to lower it (common/fit.cpp aborts only on a count the+ user really set), and a pass-through ``--fit-target`` raises the margin above+ anything ``_ctx_integrity_flags`` emitted.+ """+ from utils.hardware import is_apple_silicon++ if not model_size or not kv_sized or mtp_unsized or is_apple_silicon():+ return None+ # Pass-through adapters are resident weights model_size (the base GGUF alone)+ # never carried. A TERM, not a placement override, so an unreadable one abstains.+ sidecar_bytes = _sidecar_adapter_bytes(extra_args)+ if sidecar_bytes is None:+ return None+ rows = list(gpus or ())+ source_env = os.environ if env is None else env+ # A --device naming FEWER devices than this fit charges leaves the credit+ # paying for cards the child never opens. llama.cpp REPLACES the list on every+ # occurrence (parse_device_list) and reads LLAMA_ARG_DEVICE before argv, so the+ # last of the two wins. Counted, not name-matched: CUDA/ROCm ordinals are+ # assigned after a visibility mask this launch has not written yet.+ _dev_value = _extra_args_main_device(extra_args)+ if _dev_value is None:+ _dev_value = source_env.get("LLAMA_ARG_DEVICE")+ _dev_names = [d.strip() for d in str(_dev_value or "").split(",") if d.strip()]+ _credited = len(list(gpu_indices)) if gpu_indices is not None else len(rows)+ # DISTINCT names: llama.cpp appends every entry without deduplicating and+ # keeps the list verbatim, so "CUDA0,CUDA0" is ONE physical pool listed twice,+ # and counting it as two leaves the credit paying for a card that is not there.+ _device_narrows = bool(_dev_names) and len(set(_dev_names)) < _credited+ # Vulkan is the one backend where names ARE comparable (_vulkan_device_pin ->+ # "Vulkan<i>"), so hold a surviving --device to an exact match. That catches+ # what a count cannot: a same-sized list naming DIFFERENT cards, and a longer+ # one adding devices this footprint never charged for.+ _vulkan_pin_replaced = bool(+ is_vulkan_backend+ and gpu_indices is not None+ and _dev_names+ and {name.strip().lower() for name in _dev_names}+ != {f"vulkan{idx}" for idx in gpu_indices}+ )+ if (+ _extra_args_set_any_flag(extra_args, _GPU_LAYER_FLAGS)+ # And its env twin, the ONLY layer count the fitting path leaves: it+ # emits no -ngl, only Manual mode clears LLAMA_ARG_N_GPU_LAYERS, and the+ # fitter will not lower a count it did not set, so an inherited one stands+ # and loads a prefix out of host RAM.+ or _env_fixes_gpu_layers(source_env)+ # With the env twin: only an explicit gpu_ids pin clears LLAMA_ARG_DEVICE,+ # so an inherited "none" puts the whole load in host RAM.+ or _device_selection_is_cpu(extra_args, source_env)+ or _device_narrows+ or _vulkan_pin_replaced+ # Pass-through and last-wins: --split-mode none, or a --tensor-split that+ # zeroes a device, leaves the pooled credit paying for cards held empty.+ or split_policy_starves_devices(extra_args, _credited, source_env)+ or _args_place_tensors_on_cpu(extra_args)+ or _env_places_tensors_on_cpu(source_env)+ ):+ logger.info(+ "Load mode: pass-through arguments override the placement this fit "+ "priced; charging the whole load to host RAM."+ )+ rows, gpu_indices = [], None+ footprint = (+ model_size+ # Pass-through LoRA / control vectors, allocated alongside the base tensors.+ + max(0, sidecar_bytes)+ # A CPU-pinned projector left model_size but is still resident, and this+ # is a footprint rather than a VRAM budget.+ + max(0, mmproj_pinned_bytes)+ + max(0, kv_cache_bytes)+ # Carries the drafter's own weights and KV.+ + max(0, mtp_bytes)+ # Resident, but only ever in host RAM; charged to the RAM term alone below.+ + max(0, host_only_bytes)+ + max(0, compute_buffer_flat)+ + max(0, compute_buffer_ctx)+ # A layer split puts a fixed CUDA context and scratch on EVERY device, and+ # the lumps above cover one, so the rest is a term of its own (the same one+ # _subset_model_size reserves). 0 on a single GPU.+ + max(0, pipeline_overhead_bytes)+ + max(0, soft_overhead)+ )+ # Unified memory is ONE pool: an APU's free VRAM IS the host RAM the spill+ # comes out of, so adding both fits a model twice into memory that holds it+ # once. shared_gpu_ids already names Vulkan iGPUs; the ROCm APUs it cannot see+ # are added here. Both end up priced against host RAM alone.+ shared = set(shared_gpu_ids or ())+ pinned = list(gpu_indices) if gpu_indices is not None else [idx for idx, _free in rows]+ if rows and not is_vulkan_backend and self._amd_apu_wants_unified_memory(pinned):+ # Per device, not blanket: the gate above is the cheap "is ANY of them+ # unified" question, and a discrete card next to an APU still has a pool of+ # its own, so re-ask per row rather than forfeit a fit that is really there.+ shared |= {idx for idx, _free in rows if self._amd_apu_wants_unified_memory([idx])}+ # --no-kv-offload puts the WHOLE cache in host RAM whatever the layer placement+ # says (llama-kv-cache.cpp upgrades a layer's buffer type only inside+ # `if (offload)`), so free VRAM may not pay for it. Resolved off the same+ # effective views the placement overrides above use.+ _kv_on_host = not _kv_offload_from_args(extra_args, env = source_env)+ if self._fits_without_paging(+ footprint,+ rows,+ gpu_indices = gpu_indices,+ shared_gpu_ids = shared,+ # A CPU-pinned projector is host-resident: counted once in the footprint+ # above, and charged here to the term free VRAM may NOT pay for, so surplus+ # VRAM cannot cover it and answer True without consulting RAM.+ host_only_bytes = (+ max(0, host_only_bytes)+ + max(0, mmproj_pinned_bytes)+ # Same split as the pinned projector: counted once above, charged to RAM.+ + (max(0, kv_cache_bytes) if _kv_on_host else 0)+ ),+ vram_margin_mib = fit_margin_mib,+ avail_mib = avail_mib,+ ):+ logger.info(+ "Load mode: the whole load (%.1f GB) fits without paging, using --load-mode %s.",+ footprint / (1024**3),+ self._FIT_LOAD_MODE,+ )+ return self._FIT_LOAD_MODE+ return None++ # What a proven fit picks. One name, because the choice is a measurement.+ # Load-to-ready on a B200 over local NVMe, median of 3, full offload, b10360:+ #+ # Qwen3-4B Q4_K_M (2.5 GB) cold warm+ # mmap (no flag) 1.81 1.42+ # none 2.04 1.49+ # dio 2.05 1.69+ # Qwen3-30B-A3B UD-Q4_K_XL (17 GB) cold warm+ # mmap (no flag) 5.43 2.81+ # none 5.49 3.21+ # dio 2.26 2.30+ #+ # So "none" is NOT the fast one here: it drops mmap and unlocks llama.cpp's async+ # pinned-buffer uploader, but still pays the page-cache copy, which on this storage+ # costs more than the uploader wins. "dio" takes that uploader AND skips the cache,+ # and is 2.4x faster cold on the model big enough for loading to matter, which is+ # upstream's guidance too. Kept at "none" because that is what was asked for; this+ # constant is the whole switch. dio has no pre-enum spelling, so a build without+ # --load-mode would emit nothing rather than a legacy flag.+ _FIT_LOAD_MODE = "none"+METAL_CTX_OVERCOMMIT_ENV = "UNSLOTH_ALLOW_METAL_CTX_OVERCOMMIT"@staticmethod@@ -9799,6 +10290,62 @@ class LlamaCppBackend:)return int(nextn * (n_kv * k_len * bpe_k + v_width * bpe_v) * cells_per_stream * streams)+ def _cpu_resident_draft_bytes(+ self,+ n_ctx: int,+ *,+ drafter_path: Optional[str],+ draft_cache_type_k: Optional[str] = None,+ draft_cache_type_v: Optional[str] = None,+ n_parallel: int = 1,+ swa_full: bool = False,+ kv_unified: bool = True,+ n_ubatch: Optional[int] = None,+ flash_attn: bool = True,+ ) -> Optional[int]:+ """Host-RAM footprint of a SEPARATE drafter pinned to the CPU (``-ngld 0``).++ The VRAM budget drops such a drafter, and rightly: none of it is on the+ GPU. The load-mode fit asks the other question -- is the whole load+ resident without demand paging -- and there the bytes have not gone+ anywhere, they have moved to host RAM. llama.cpp carries the process-wide+ load mode into the draft model: ``common_base_params_to_speculative``+ starts from ``result = params`` and overrides only devices/model/+ n_gpu_layers, and ``--load-mode none`` clears ``use_mmap``+ (llama-model-loader.cpp), so the draft GGUF becomes a real anonymous+ allocation rather than an evictable file mapping. Charging it is the same+ reasoning that keeps a CPU-pinned projector in the footprint.++ 0 when no separate drafter is CPU-pinned. ``None`` when the drafter is+ there but cannot be priced, so the caller abstains instead of claiming a+ fit that is short a whole draft GGUF.+ """+ if not drafter_path:+ return 0+ try:+ weights = self._get_gguf_size_bytes(drafter_path)+ except Exception:+ weights = 0+ if weights <= 0:+ return None+ kv = self._mtp_draft_kv_bytes(+ n_ctx,+ drafter_path = drafter_path,+ draft_cache_type_k = draft_cache_type_k,+ draft_cache_type_v = draft_cache_type_v,+ n_parallel = n_parallel,+ swa_full = swa_full,+ kv_unified = kv_unified,+ n_ubatch = n_ubatch,+ flash_attn = flash_attn,+ )+ if kv is None:+ return None+ # The drafter has a llama_context of its own, so its decode graph is allocated+ # wherever it runs -- here, the host. _soft_overhead charges that constant only+ # while _mtp_reserves_gpu, which is False for exactly this placement.+ return int(weights) + max(0, int(kv)) + self._MTP_DRAFT_COMPUTE_BYTES+def _estimate_mtp_overhead_bytes(self,n_ctx: int,@@ -11307,6 +11854,7 @@ class LlamaCppBackend:self._memory_state = Noneself._memory_policy_active = Falseself._memory_mlock_applicable = True+ self._fit_load_mode_flags = []self._memory_launch_pending = Falseself._n_ubatch = self._DEFAULT_N_UBATCHself._requested_n_batch = None@@ -12407,6 +12955,21 @@ class LlamaCppBackend:logger.debug(f"Could not size mmproj {launch_mmproj_path}: {e}")return 0+ def _inherited_mmproj_soft_overhead(self, mmproj_bytes: int, *, on_host: bool) -> int:+ """Runtime buffer allowance for a projector that arrived only through the env.++ The resolved projector gets this term in the fit's ``soft_overhead``, but that+ one is gated on ``effective_is_vision``, itself gated on ``launch_mmproj_path``,+ so a ``LLAMA_ARG_MMPROJ`` projector is charged its file size and nothing for the+ ~1.3x the encoder really allocates. Understating the footprint is the direction+ that claims a fit which is not there.++ VRAM arm only: on the host arm the resolved projector is priced raw too.+ """+ if mmproj_bytes <= 0 or on_host:+ return 0+ return int(mmproj_bytes * (self._MMPROJ_VRAM_SAFETY - 1.0))+def _resolve_launch_mtp_path(self,*,@@ -14918,6 +15481,15 @@ class LlamaCppBackend:)if replay is None:return None+ # The replay runs on no GPU, so the VRAM half of the fit that chose "none" is+ # void and mmap is what keeps the host-RAM load survivable: hand the CPU attempt+ # llama.cpp's auto back. Only Unsloth's own tokens; a user's is theirs.+ if self._fit_load_mode_flags:+ replay = _without_subsequence(replay, self._fit_load_mode_flags)+ logger.info(+ "Load mode: dropping the fit's --load-mode none for the CPU "+ "fallback; it runs entirely from host RAM."+ )cpu_binary = self._cpu_isolated_binary(binary)if cpu_binary is None:return None@@ -16160,6 +16732,10 @@ class LlamaCppBackend:_placement_verdict_partial = Falsetotal_by_idx: dict[int, int] = {}model_size = None # set in the fit try; used by the APU RAM guard+ # "none" once the fit proves the load needs no demand paging, else None+ # for llama.cpp's own default. Bound before the try like the verdict+ # flags above: the except path falls through to the launch, which reads it.+ _fit_load_mode: Optional[str] = None# Layer-fallback min GPUs; raised below on a tensor downgrade. Bound# before the try so the --fit-on except path still has it (no UnboundLocal)._layer_min_gpus = 1@@ -16586,6 +17162,11 @@ class LlamaCppBackend:# drop it from the budget (an embedded head stays in the model).# Consult the env too: the child honors LLAMA_ARG_N_GPU_LAYERS_DRAFT._draft_on_cpu = _extra_args_draft_offloaded_to_cpu(extra_args, env = os.environ)+ # Kept for the load-mode fit, which the nulling below would leave+ # short a whole draft GGUF: dropping the drafter from the VRAM budget+ # moves those bytes to host RAM rather than deleting them. See+ # _cpu_resident_draft_bytes.+ _cpu_draft_path = _mtp_draft_for_budget if _draft_on_cpu else Noneif _draft_on_cpu:_mtp_draft_for_budget = None_mtp_draft_weights = 0@@ -16697,7 +17278,11 @@ class LlamaCppBackend:ctx, _np = slots, _n_ubatch = ubatch if ubatch else _effective_ubatch)- def _kv_bytes(ctx: int) -> int:+ def _kv_bytes(ctx: int, ctx_checkpoints: int = 0) -> int:+ # Checkpoints default OFF: the placement paths price the SWA+ # snapshots themselves, so charging them again here would shrink+ # the context they just chose. The load-mode fit, which has no+ # such term, passes the effective count in.return self._estimate_kv_cache_bytes(ctx,cache_type_kv,@@ -16705,6 +17290,7 @@ class LlamaCppBackend:swa_full = swa_full,kv_unified = planned_kv_unified,n_ubatch = _effective_ubatch,+ ctx_checkpoints = ctx_checkpoints,flash_attn = planned_flash_attn,)@@ -16750,6 +17336,20 @@ class LlamaCppBackend:self._TENSOR_PARALLEL_BUFFER_RESERVE_MIB * 1024 * 1024)+ # ...and the tensor-mode rate, reserved on EVERY selected device:+ # the f32 output buffer and the comm staging are replicated rather+ # than split, so the layer lump above is a fraction of what a tensor+ # split allocates. Same flat fallback when the dims are missing.+ _compute_buffer_tensor = self._estimate_compute_buffer_bytes(+ n_ubatch = _effective_ubatch,+ n_parallel = n_parallel,+ per_device_tensor = True,+ )+ if _compute_buffer_tensor <= 0:+ _compute_buffer_tensor = (+ self._TENSOR_PARALLEL_BUFFER_RESERVE_MIB * 1024 * 1024+ )+# Layer split adds a fixed per-device overhead on every GPU. The# folded buffer covers one device; reserve the extra devices'# share so a k-GPU split can't pin a context that OOMs a device@@ -16763,6 +17363,10 @@ class LlamaCppBackend:# Per-GPU weight proportions for tensor mode (None lets# llama.cpp split by free VRAM).tp_tensor_split: Optional[list[int]] = None+ # Whether the tensor-parallel branch below really planned this load.+ # Not readable from tp_tensor_split, which stays None on a tensor+ # split llama.cpp is left to size itself.+ _tp_planned = Falseexplicit_ctx = requested_ctx > 0# Nothing speculative on the GPU: the drafter that launches is the# separate CPU-offloaded one, and a sidecar wins over an embedded head@@ -17509,6 +18113,7 @@ class LlamaCppBackend:vram_fraction = _vram_frac,)use_fit = False+ _tp_planned = Trueelif gpus and self._can_estimate_kv() and effective_ctx > 0:# Compute the largest hardware-aware cap from the model's# native context across all usable GPU subsets (for UI@@ -18143,12 +18748,191 @@ class LlamaCppBackend:# is a partial-placement verdict. Set last, so any early# return or raise above leaves it False._placement_verdict_partial = bool(_detected_gpus) and bool(use_fit)++ # Load mode, from the same numbers the placement just used: mmap+ # exists to demand-page a footprint the machine cannot hold, so a+ # load that fits wants "none" and anything else keeps "auto". See+ # _fit_derived_load_mode. `gpus`, not `_detected_gpus`: the arch gate+ # empties that one on "--device none", and crediting VRAM the child+ # never reaches would claim a fit that has to come from RAM.+ _fit_devices = max(1, len(gpu_indices or ()) or len(gpus))+ # A CPU-pinned drafter is out of the VRAM budget above but still+ # resident in host RAM, so the footprint carries it. None means it+ # cannot be priced -> abstain, like the other unreadable terms.+ _cpu_draft_fit_bytes = self._cpu_resident_draft_bytes(+ effective_ctx,+ drafter_path = _cpu_draft_path,+ draft_cache_type_k = _mtp_draft_ck,+ draft_cache_type_v = _mtp_draft_cv,+ n_parallel = n_parallel,+ swa_full = swa_full,+ kv_unified = planned_kv_unified,+ n_ubatch = _effective_ubatch,+ flash_attn = planned_flash_attn,+ )+ # The extras and env as the child really gets them: a gpu_ids pin+ # drops the device flags AND their env twins, so classifying on+ # either would void the VRAM term for a "--device none" the launch+ # strips. Unpinned, the child inherits LLAMA_ARG_DEVICE verbatim.+ _fit_extras = (+ self._strip_device_extra_args(extra_args)+ if gpu_ids is not None+ else extra_args+ )+ _fit_env = dict(os.environ)+ if gpu_memory_mode == "manual":+ self._clear_manual_placement_env(_fit_env)+ if gpu_ids is not None:+ self._clear_device_placement_env(_fit_env)+ # What the placement branch below will emit, so the effective+ # (last-wins) fitter state is readable before the final argv exists.+ # Every reachable branch is fixed by use_fit.+ _fitter_runs = fit_is_effectively_on(+ ["--fit", "on" if use_fit else "off", *(_fit_extras or [])],+ _fit_env,+ )+ # _ctx_integrity_flags emits --fit-target only while use_fit, so a+ # fitter the EXTRAS turned back on keeps llama.cpp's own 1024 MiB+ # default; a pass-through --fit-target wins over either (below).+ # A drafter the extras SPLIT between card and host with a fixed+ # positive -ngld: _cpu_draft_path is None there (that predicate is+ # the whole-drafter question), so mtp_bytes carries the drafter WHOLE+ # while llama.cpp keeps the layers past the count, and their KV, in+ # host RAM. Nothing here says which slice stays on the card, so this+ # is the "engaged but unsized" case the fit abstains on.+ _draft_split_across_host = bool(+ _mtp_draft_for_budget+ and _draft_is_split_across_host(+ _fit_extras,+ _fit_env,+ n_draft_layers = getattr(+ self._draft_backend_for(_mtp_draft_for_budget),+ "_n_layers",+ None,+ ),+ )+ )+ _fit_margin_mib = (+ max(+ self._fit_target_margin_mib(+ auto_fit = (gpu_memory_mode == "manual" and gpu_layers < 0),+ fit_target_delta_mib = _fit_target_delta_mib if use_fit else 0.0,+ supports_fit_target = use_fit+ and bool(server_caps.get("supports_fit_target")),+ ),+ fit_target_margin_in(_fit_extras, _fit_env) or 0.0,+ )+ if _fitter_runs+ else 0.0+ )+ # A projector Studio never resolved but the child loads anyway:+ # LLAMA_ARG_MMPROJ / _URL are read before argv and only the vision+ # switch and the paravirtual pin clear them, while model_size carries+ # none of those bytes. A URL names a download that has not happened+ # (and outranks even the --mmproj this launch emits), and an+ # unreadable path cannot be sized, so both abstain.+ _fit_env_mmproj_scrubbed = bool(+ _pv_mmproj_unpinnable or _paravirtual_cpu_forced+ )+ _fit_env_mmproj = (+ ""+ if (+ launch_mmproj_path+ or _fit_env_mmproj_scrubbed+ or (+ disable_vision+ # The scrub's own audio-only reprieve: that projector+ # survives the switch, so it is loaded.+ and not _mmproj_env_is_audio_only(_fit_env.get("LLAMA_ARG_MMPROJ"))+ )+ )+ else (_fit_env.get("LLAMA_ARG_MMPROJ") or "").strip()+ )+ _fit_env_mmproj_url = (+ ""+ if (_fit_env_mmproj_scrubbed or disable_vision)+ else (_fit_env.get("LLAMA_ARG_MMPROJ_URL") or "").strip()+ )+ _fit_env_mmproj_bytes = self._mmproj_vram_bytes(_fit_env_mmproj or None)+ _fit_env_mmproj_unsized = bool(_fit_env_mmproj_url) or (+ bool(_fit_env_mmproj) and _fit_env_mmproj_bytes <= 0+ )+ # Host-resident when the resolved offload says CPU, the same split+ # the resolved projector gets.+ _fit_env_mmproj_on_host = (+ _resolved_mmproj_offload(_fit_extras, _fit_env) is False+ )+ _fit_model_size = model_size+ if _fit_env_mmproj_unsized:+ # Same abstain the other unreadable terms take.+ _fit_model_size = None+ elif _fit_model_size and not _fit_env_mmproj_on_host:+ _fit_model_size += _fit_env_mmproj_bytes+ _fit_soft_overhead = _soft_overhead + self._inherited_mmproj_soft_overhead(+ _fit_env_mmproj_bytes,+ on_host = _fit_env_mmproj_on_host,+ )+ _fit_load_mode = self._fit_derived_load_mode(+ model_size = _fit_model_size,+ mmproj_pinned_bytes = _mmproj_pinned_bytes+ + (_fit_env_mmproj_bytes if _fit_env_mmproj_on_host else 0),+ # Re-read WITH the SWA snapshots --ctx-checkpoints allocates;+ # the closure leaves them at 0 for the placement paths, which+ # price them by their own route.+ kv_cache_bytes = _kv_bytes(effective_ctx, _effective_ctx_checkpoints),+ kv_sized = self._can_estimate_kv(),+ mtp_bytes = _mtp_bytes(effective_ctx),+ # _flat_mtp_engages whole: its other arm, _mtp_kv_unsized,+ # prices weights but NO draft KV, and the placement covers that+ # gap with a flat cushion this footprint has no term for --+ # the "engaged but unsized" case the predicate abstains on.+ mtp_unsized = bool(+ _flat_mtp_engages+ or _cpu_draft_fit_bytes is None+ or _draft_split_across_host+ ),+ # Host-only, not pooled: -ngld 0 puts the drafter in RAM, which+ # free VRAM cannot pay for.+ host_only_bytes = _cpu_draft_fit_bytes or 0,+ # One lump on the layer path, where the graph buffer is+ # allocated once. A tensor split replicates it on every selected+ # device, so pricing one LAYER-mode buffer there understates a+ # multi-GPU load by GiBs. pipeline_overhead_bytes below is a flat+ # per-device constant and cannot cover it.+ compute_buffer_flat = (+ _fit_devices * _compute_buffer_tensor+ if _tp_planned+ else _compute_buffer_pipeline+ ),+ compute_buffer_ctx = _cc_bytes(effective_ctx, _fit_devices),+ # Ungated, like _subset_model_size: the per-device CUDA context+ # and scratch are there whether or not llama.cpp keeps the+ # pipeline (_cc_bytes is the term that gates on it).+ pipeline_overhead_bytes = (+ max(0, _fit_devices - 1) * _pipeline_overhead_bytes+ ),+ soft_overhead = _fit_soft_overhead,+ gpus = gpus,+ gpu_indices = gpu_indices,+ shared_gpu_ids = _shared_gpu_ids,+ # A running fitter keeps --fit-target free per device, so that+ # margin is not VRAM this fit may spend. Zero only when the+ # fitter is provably off; see _fitter_runs above.+ fit_margin_mib = _fit_margin_mib,+ is_vulkan_backend = is_vulkan_backend,+ # Never stripped, and appended last, so they beat this+ # launch's own -ngl.+ extra_args = _fit_extras,+ env = _fit_env,+ )except Exception as e:logger.warning(f"GPU selection failed ({e}), using --fit on")gpu_indices, use_fit = None, True# Not a verdict: this arm never priced anything. Explicit, so# the flag cannot survive from a previous load._placement_verdict_partial = False+ # Same reasoning: an unpriced load keeps llama.cpp's default.+ _fit_load_mode = Nonetp_tensor_split = Noneeffective_ctx = requested_ctx # fall back to original@@ -19104,11 +19888,57 @@ class LlamaCppBackend:# After Model Memory and on the extras it returned, because it# defers to those settings: while either one owns host placement# the per-model pick emits nothing at all.+ #+ # The fit's "none" only fills in for a model with no pick of its own,+ # and sits here rather than inside the policy so the whole precedence+ # chain stays in one place: the per-model mode wins over the fit, Model+ # Memory wins over both, and a hand-typed flag still wins by last-arg.+ #+ # An INHERITED loader mode is an explicit choice too: llama.cpp reads+ # LLAMA_ARG_LOAD_MODE (and the deprecated twins) before argv and both+ # assign the same params.load_mode, so the managed block below would+ # beat one silently. Only the FIT's mode stands aside, since a per-model+ # pick is a choice made for THIS model. Asked AFTER the same scrub the+ # child gets, so a var a Model Memory toggle drops vetoes nothing.+ _fit_load_mode_env_view = dict(_mem_env)+ scrub_memory_env(_fit_load_mode_env_view)+ if (+ _fit_load_mode+ and not load_mode+ and memory_env_selects_load_mode(_fit_load_mode_env_view)+ ):+ logger.info(+ "Load mode: the environment already selects a loader mode; "+ "leaving the fit's --load-mode %s off this launch.",+ _fit_load_mode,+ )+ _fit_load_mode = None+ # And a mode the EXTRAS pick. Their flag already wins by last-arg, but+ # the retry rungs below strip the pair by VALUE and take the FIRST match+ # (_without_subsequence), so a user who typed the same "--load-mode none"+ # leaves two identical pairs: one rung removes the fit's and records the+ # stripped argv, and the next, respawning from it, removes theirs.+ # Standing aside costs nothing and leaves every strip below the no-op+ # its docstring already claims to be.+ if _fit_load_mode and not load_mode and extra_args_select_load_mode(_mem_extras):+ logger.info(+ "Load mode: the extra arguments already select a loader mode; "+ "leaving the fit's --load-mode %s off this launch.",+ _fit_load_mode,+ )+ _fit_load_mode = None+ _resolved_load_mode = load_mode or _fit_load_mode_load_mode_managed, _mem_extras = apply_load_mode_policy(_mem_extras,supports_load_mode = bool(server_caps.get("supports_load_mode")),weights_in_host_memory = _mem_host_resident,- requested_load_mode = load_mode,+ requested_load_mode = _resolved_load_mode,+ )+ # Only when the FIT chose it: a user's own pick survives every fallback+ # below, but a conclusion about a placement has to go when that+ # placement does.+ self._fit_load_mode_flags = (+ list(_load_mode_managed) if (_fit_load_mode and not load_mode) else [])# Remembered so the reload hint and the duplicate-load comparator do# not demand an mlock this launch deliberately skipped.@@ -19235,8 +20065,14 @@ class LlamaCppBackend:# Record what the child will ACTUALLY run with (env defaults plus# last-wins argv), not just what Unsloth emitted, so the reload# hint also catches a user-supplied --mlock / --no-mmap.+ #+ # In argv order, including the load-mode pair: "none" holds a full+ # anonymous host copy (llama-model-loader.cpp sets use_mmap only for+ # mmap/mmap+mlock/auto), so leaving it out records the launch as+ # non-reserving and a later "Don't reserve system RAM" is judged already+ # satisfied, keeping the reservation instead of relaunching with mmap.self._memory_state = resolve_effective_memory_state(- list(_mem_managed) + list(_mem_extras), env+ list(_mem_managed) + list(_load_mode_managed) + list(_mem_extras), env)# Did the policy change this launch at all: emitted a flag,# suppressed a requested one, or scrubbed an inherited env var.@@ -19665,6 +20501,46 @@ class LlamaCppBackend:# fallback). A per-call flag left those successes unrecorded._did_rocm_retry = False+ def _drop_fit_load_mode_for_no_flash(fa_cmd: list) -> list:+ """The fit's ``--load-mode none`` off a --flash-attn off respawn.++ The FA-off rewrite changes the very footprint the fit priced. On an+ MLA model it takes the K cache down to f16 with V, because llama.cpp+ rejects a split K/V there before it rejects a quantized V without+ flash attention (llama-context.cpp checks type_k == type_v first),+ and the MLA branch of the KV estimator prices that latent cache at+ the K width alone. The non-flash attention path also materialises a+ full [n_kv, n_ubatch, n_head] F32 KQ tensor (llama-graph.cpp+ build_attn_mha) that the flash-attn-shaped compute-buffer estimate+ does not model. Under an active fitter the child answers a bigger+ requirement by offloading fewer layers and spilling more weights to+ host RAM, where "--load-mode none" makes them anonymous rather than+ file-backed: an OOM kill where the mapping would only have paged.++ Only Unsloth's own tokens; a user's --load-mode is theirs. The+ record is NOT cleared, for the same reason the --fit on retry keeps+ it: the CPU fallback below still respawns from an argv that carries+ these tokens and has to be able to name them. Stripping an+ already-stripped argv is a no-op.+ """+ if not self._fit_load_mode_flags:+ return fa_cmd+ stripped = _without_subsequence(fa_cmd, self._fit_load_mode_flags)+ if stripped != fa_cmd:+ # The record follows the argv: without "none" the child is back+ # on llama.cpp's auto, which maps, so a record still saying+ # "reserving" spends a full reload on the next "Don't reserve+ # system RAM". From the argv, not _mem_managed + _mem_extras:+ # this descends from _last_spawn_cmd, which carries any page-lock+ # the --fit on retry appended, and rebuilding would drop it.+ self._memory_state = resolve_effective_memory_state(stripped, env)+ logger.info(+ "Load mode: dropping the fit's --load-mode none for the "+ "--flash-attn off retry; the no-flash launch has a "+ "footprint the fit did not price."+ )+ return stripped+def _spawn_and_wait(run_cmd, *, label = ""):"""Start llama-server with run_cmd and wait for health.@@ -19813,6 +20689,23 @@ class LlamaCppBackend:_run = list(run_cmd)if "--fit" in _run:_run[_run.index("--fit") + 1] = "on"+ # Same reasoning as the page-lock below, one step+ # earlier: the fit picked "none" because it had proved+ # the load fits, and that proof is what just failed, so+ # give the retry llama.cpp's auto back. Only Unsloth's+ # own tokens; a user's --load-mode is untouched.+ if self._fit_load_mode_flags:+ _run = _without_subsequence(_run, self._fit_load_mode_flags)+ # The record is NOT cleared: it describes `cmd`, which+ # this retry never touched and the arch-crash and CPU+ # fallbacks respawn from, so clearing here would leave+ # them carrying a --load-mode none they can no longer+ # name. Stripping an already-stripped argv is a no-op.+ logger.info(+ "Load mode: dropping the fit's --load-mode none "+ "for the --fit on retry; the fit it was derived "+ "from did not hold."+ )# The full-offload prediction that suppressed the# page-lock was the very thing that just proved# wrong, so llama.cpp may now leave weights in host@@ -19965,6 +20858,13 @@ class LlamaCppBackend:self._vram_fraction_pending = Noneraise RuntimeError(detail)+ # The replay dropped the fit's --load-mode none, so a record taken+ # off the launch argv describes a reservation this child does not+ # 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:+ self._memory_state = resolve_effective_memory_state(_last_spawn_cmd, env)intent = self._apply_cpu_fallback_state(intent,is_vision = fallback_has_mmproj,@@ -20066,6 +20966,12 @@ class LlamaCppBackend:"`unsloth studio update` to repair the managed llama.cpp runtime.")cmd, _spawn_cwd = 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:+ self._memory_state = resolve_effective_memory_state(cmd, env)# 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).@@ -20249,6 +21155,22 @@ class LlamaCppBackend:"Arch-crash retry leaves one GPU; dropped tensor ""parallelism, which needs at least two.")+ # The fit chose "none" because the WHOLE footprint fit the+ # devices this launch PINNED, and the retry runs on a set that+ # proof never covered. The two guards above are weights-only+ # floors and cannot re-establish it, so KV and scratch can still+ # push the load past RAM while mmap stays off. Hand the respawn+ # llama.cpp's auto back, as the --fit on and CPU fallbacks do.+ # Only Unsloth's own tokens; a user's --load-mode is theirs.+ _fit_mode_left_cmd = bool(self._fit_load_mode_flags)+ if self._fit_load_mode_flags:+ cmd = _without_subsequence(cmd, self._fit_load_mode_flags)+ self._fit_load_mode_flags = []+ logger.info(+ "Load mode: dropping the fit's --load-mode none for "+ "the arch-crash retry; it runs on a different device "+ "set than the fit was proved against."+ )# This respawn starts from `cmd`, but the crashed launch may# have taken _spawn_and_wait's --fit retry, which appends a# page-lock to its OWN argv and records it. `cmd` never carried@@ -20262,6 +21184,14 @@ class LlamaCppBackend:self._memory_policy_active,self._memory_mlock_applicable,) = _mem_policy_for_cmd+ # ...except the load-mode pair just removed: the snapshot was+ # taken while `cmd` still carried it, so restoring it would+ # record a reservation this respawn no longer makes. From the+ # stripped argv, NOT rebuilt from _mem_managed + _mem_extras: by+ # here `cmd` may be a fallback argv those parts no longer add up+ # to, dropping whatever memory-relevant flags they added.+ if _fit_mode_left_cmd:+ self._memory_state = resolve_effective_memory_state(cmd, env)# Residency is a property of the DEVICES, which the retry just# changed: crash on the discrete card, land on the# unified-memory APU, and the weights are host-backed after@@ -20367,6 +21297,7 @@ class LlamaCppBackend:"Dropped inherited LLAMA_ARG_FLASH_ATTN for the ""--flash-attn off retry.")+ _fa_cmd = _drop_fit_load_mode_for_no_flash(_fa_cmd)_flash_attn_known_off = Truecmd = _fa_cmdhealthy = _spawn_and_wait(_fa_cmd, label = "-noflash")@@ -20439,6 +21370,7 @@ class LlamaCppBackend:"Dropped inherited LLAMA_ARG_FLASH_ATTN for the ""--flash-attn off retry.")+ _fa_cmd = _drop_fit_load_mode_for_no_flash(_fa_cmd)_flash_attn_known_off = Truecmd = _fa_cmdhealthy = (@@ -20588,6 +21520,31 @@ class LlamaCppBackend:)if _cpu_projector_cmd is not None:+ # The fit priced the projector as GPU-eligible, and this+ # retry moves those bytes into host RAM, so neither the+ # VRAM-only proof (which never asked what RAM holds) nor the+ # VRAM-plus-RAM one (answered with the projector on the card)+ # covers the launch this respawns. Only Unsloth's own tokens;+ # a user's --load-mode is theirs. The record is NOT cleared:+ # the fallbacks below respawn from an argv that carries these+ # tokens and has to be able to name them.+ if self._fit_load_mode_flags:+ _stripped_cpu_projector_cmd = _without_subsequence(+ _cpu_projector_cmd, self._fit_load_mode_flags+ )+ if _stripped_cpu_projector_cmd != _cpu_projector_cmd:+ # Same as the no-flash rung: the record follows the+ # argv, or a stale "reserving" spends a full reload+ # the running server already satisfies.+ self._memory_state = resolve_effective_memory_state(+ _stripped_cpu_projector_cmd, env+ )+ logger.info(+ "Load mode: dropping the fit's --load-mode none "+ "for the CPU-projector retry; it moves the "+ "projector into host RAM the fit credited to VRAM."+ )+ _cpu_projector_cmd = _stripped_cpu_projector_cmdlogger.warning("llama-server failed while loading this model's GPU ""vision projector (--mmproj); retrying with the "@@ -22979,6 +23936,26 @@ class LlamaCppBackend:logger.error(f"llama-server health check timed out after {timeout}s")return False+ @staticmethod+ def _fit_target_margin_mib(+ *,+ auto_fit: bool,+ fit_target_delta_mib: float = 0.0,+ supports_fit_target: bool = True,+ ) -> float:+ """Free VRAM per device llama.cpp's fitter keeps for itself under ``--fit on``.++ One reader for the flag and for the load-mode fit, so the margin the child is+ told to keep and the margin the fit refuses to spend cannot drift. A server+ too old for ``--fit-target`` still keeps llama.cpp's own 1024 MiB default+ (common/common.h, ``fit_params_target``), which is also what the legacy path+ deliberately stays silent about.+ """+ if not supports_fit_target:+ return _LLAMA_FIT_TARGET_DEFAULT_MIB+ base = _VRAM_FLOOR_RESERVE_MIB if auto_fit else _LLAMA_FIT_TARGET_DEFAULT_MIB+ return max(_VRAM_FLOOR_RESERVE_MIB, base + fit_target_delta_mib)+@staticmethoddef _ctx_integrity_flags(n_parallel: int,@@ -23023,8 +24000,10 @@ class LlamaCppBackend:# The budget moves that margin from where the path already sits, so the# default changes neither, and a raise stops at the same 512 floor every# other reserve here respects.- _base = _VRAM_FLOOR_RESERVE_MIB if auto_fit else _LLAMA_FIT_TARGET_DEFAULT_MIB- _target = max(_VRAM_FLOOR_RESERVE_MIB, _base + fit_target_delta_mib)+ _target = LlamaCppBackend._fit_target_margin_mib(+ auto_fit = auto_fit,+ fit_target_delta_mib = fit_target_delta_mib,+ )# The legacy path stays silent when it would only restate llama.cpp's# own default, so an untouched slider leaves the command unchanged.if auto_fit or _target != _LLAMA_FIT_TARGET_DEFAULT_MIB:diff --git a/studio/backend/core/inference/llama_server_args.py b/studio/backend/core/inference/llama_server_args.pyindex 1834df0ae34..42df991bb5e 100644--- a/studio/backend/core/inference/llama_server_args.py+++ b/studio/backend/core/inference/llama_server_args.py@@ -608,6 +608,9 @@ _SPEC_DRAFT_CACHE_V_FLAGS: frozenset[str] = frozenset()_SPEC_DRAFT_CACHE_FLAGS: frozenset[str] = _SPEC_DRAFT_CACHE_K_FLAGS | _SPEC_DRAFT_CACHE_V_FLAGS_FIT_FLAGS: frozenset[str] = frozenset({"-fit", "--fit"})+# The fitter's per-device margin. Never stripped (llama.cpp is last-wins), so a+# pass-through value is what the child really keeps free; see fit_target_margin_in.+_FIT_TARGET_FLAGS: frozenset[str] = frozenset({"-fitt", "--fit-target"})_LAYER_OFFLOAD_FLAGS: frozenset[str] = _GPU_LAYER_FLAGS | _FIT_FLAGS_MOE_OFFLOAD_FLAGS: frozenset[str] = frozenset({"-ncmoe", "--n-cpu-moe", "-cmoe", "--cpu-moe"})_OFFLOAD_SHADOWING_FLAGS: frozenset[str] = _LAYER_OFFLOAD_FLAGS | _MOE_OFFLOAD_FLAGS@@ -866,6 +869,93 @@ def fit_is_effectively_on(return str(raw_value).strip().lower() not in _ENV_FALSE_VALUES+def fit_target_margin_in(+ args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None+) -> Optional[float]:+ """The per-device margin an effective ``--fit-target`` asks the fitter to keep.++ ``-fitt/--fit-target`` takes a list of MiB values, one per device, and a+ single value is broadcast across all of them (common/arg.cpp; default 1024,+ ``fit_params_target`` in common/common.h). The fitter refuses+ to allocate into that margin and spills the rest to host RAM instead+ (``targets.push_back(dmds_full[id].free - margins[id])``, common/fit.cpp), so+ a load-mode fit that credits VRAM has to price it.++ Returns the LARGEST value in the list, because the fit charges one margin to+ every device it credits and understating would claim a fit that is not there.+ ``None`` when nothing readable is set, which leaves the caller on llama.cpp's+ own default rather than on a guess. Last-wins over argv, and the env twin only+ when argv sets nothing, the same precedence ``fit_is_effectively_on`` uses.+ """+ raw_value = _last_flag_value(args, _FIT_TARGET_FLAGS)+ if raw_value is None and env:+ raw_value = env.get("LLAMA_ARG_FIT_TARGET")+ if raw_value is None:+ return None+ values: list[float] = []+ # Upstream splits on both "," and "/" (common/arg.cpp), so "4096/4096" is a+ # well-formed two-device margin; reading it as one token would wrongly abstain.+ for part in str(raw_value).replace("/", ",").split(","):+ part = part.strip()+ if not part:+ continue+ try:+ values.append(float(part))+ except ValueError:+ # Upstream rejects the whole list, so abstain rather than price part of it.+ return None+ return max(values) if values else None+++def split_policy_starves_devices(+ args: Optional[Iterable[str]],+ n_credited: int,+ env: Optional[Mapping[str, str]] = None,+) -> bool:+ """True when the effective split leaves fewer devices holding weights than ``n_credited``.++ ``--split-mode`` and ``--tensor-split`` are pass-through under auto-select+ (``_SPLIT_SHADOWING_FLAGS`` is stripped only when the Tensor Parallelism toggle+ owns the split), so both reach the child appended after Studio's own placement+ flags. Either can quietly shrink the pool a pooled VRAM credit was priced for:++ * ``--split-mode none`` is ``LLAMA_SPLIT_MODE_NONE`` (common/arg.cpp), which+ puts the whole model on ``--main-gpu`` alone. ``row``/``layer``/``tensor``+ all keep every device, so only ``none`` starves.+ * ``--tensor-split`` is a per-device proportion list, and upstream zero-fills+ every device past the end of the list (common/arg.cpp), so a short list+ starves the tail just as an explicit ``0`` starves its own device.++ Value-aware on purpose: a restatement that keeps all devices is not an+ override, and voiding on it would abstain from a fit that is really there.+ """+ if n_credited <= 1:+ return False+ mode = _last_flag_value(args, _SPLIT_MODE_FLAGS)+ if mode is None and env:+ mode = env.get("LLAMA_ARG_SPLIT_MODE")+ if str(mode or "").strip().lower() == "none":+ return True+ raw_split = _last_flag_value(args, _TENSOR_SPLIT_FLAGS)+ if raw_split is None and env:+ raw_split = env.get("LLAMA_ARG_TENSOR_SPLIT")+ if raw_split is None:+ return False+ holding = 0+ # Upstream splits on both "," and "/" (common/arg.cpp).+ for part in str(raw_split).replace("/", ",").split(",")[:n_credited]:+ part = part.strip()+ if not part:+ continue+ try:+ if float(part) > 0.0:+ holding += 1+ except ValueError:+ # Upstream throws on this and the child never starts: nothing to misprice.+ return False+ return holding < n_credited++def parse_cache_override_per_axis(args: Optional[Iterable[str]],) -> tuple[Optional[str], Optional[str]]:@@ -1435,6 +1525,58 @@ def scrub_denied_env(env: dict) -> list[str]:return removed+def extra_args_select_load_mode(extra_args: Optional[Iterable[str]]) -> bool:+ """Whether the pass-through block already picks a loader mode itself.++ The argv twin of ``memory_env_selects_load_mode``, and it answers for both+ spellings: the ``--load-mode`` enum, and the flags it replaced+ (``--no-mmap`` / ``--mmap`` / the direct-IO pair), which are what this launch+ emits on a build predating the enum (``_LEGACY_LOAD_MODE_FLAGS``) and so are+ what a user's own flag would collide with there.++ Presence, not value: a fit-derived mode stands aside for any pick the user made+ rather than trying to rank the two. Their tokens are appended after the managed+ block and llama.cpp is last-wins, so theirs governs either way.+ """+ for raw in extra_args or ():+ if _flag_name(str(raw)) in _LOAD_MODE_FLAGS | _LOAD_MODE_ALIAS_FLAGS:+ return True+ return False+++def memory_env_selects_load_mode(env: Optional[Mapping[str, str]]) -> bool:+ """Whether the inherited environment already picks a loader mode.++ llama.cpp applies the ``LLAMA_ARG_*`` twins BEFORE argv (common/arg.cpp runs+ its environment loop and only then "handle command line arguments"), and both+ assign the same ``params.load_mode``, so a managed ``--load-mode`` emitted here+ beats an inherited choice without the user typing anything. A mode DERIVED from+ a fit has to stand aside for that choice, the same way it stands aside for the+ per-model pick; a hand-typed flag is argv and still wins by last-arg.++ Per variable, matching what upstream really does with each value: a no-value+ option (``--mlock``) runs its handler only for a truthy one (``opt.handler_void+ && is_truthy(value)``), a negative alias (``LLAMA_ARG_NO_MMAP`` /+ ``LLAMA_ARG_NO_DIO``) counts by PRESENCE whatever it says (``get_value_from_env``+ forces "0" when it exists), and the rest assign a mode for any value they parse.+ """+ if not env:+ return False+ for name in MEMORY_ENV_VARS:+ if name not in env:+ continue+ value = str(env.get(name) or "").strip()+ if name == "LLAMA_ARG_MLOCK":+ if value.lower() in _ENV_TRUE_VALUES:+ return True+ continue+ if name in {"LLAMA_ARG_NO_MMAP", "LLAMA_ARG_NO_DIO"}:+ return True+ if value:+ return True+ return False++def scrub_memory_env(env: dict) -> list[str]:"""Drop inherited memory placement the settings override.diff --git a/studio/backend/tests/test_llama_cpp_placement.py b/studio/backend/tests/test_llama_cpp_placement.pyindex fb4b28b2bec..472dff1567e 100644--- a/studio/backend/tests/test_llama_cpp_placement.py+++ b/studio/backend/tests/test_llama_cpp_placement.py@@ -2368,6 +2368,83 @@ def test_a_paravirtual_metal_launch_prices_the_whole_model(tmp_path, monkeypatchassert backend._launch_host_shortfall_message(argv, [], {}, child_has_no_gpu = True) is not None+def test_the_launched_load_mode_is_recorded_in_the_memory_state(tmp_path, monkeypatch):+ """A --load-mode the launch emitted has to reach _memory_state.++ "none" reads the weights into an anonymous host buffer (llama-model-loader+ sets use_mmap only for mmap / mmap+mlock / auto), so it IS a reservation. Left+ out of the record, a later "Don't reserve system RAM" is judged satisfied by+ the running child and Apply keeps the reservation instead of relaunching.+ """+ import utils.model_memory_settings as mm+ from core.inference.llama_server_args import memory_state_satisfies_settings++ monkeypatch.setattr(mm, "get_model_memory_settings", lambda: (False, False))+ monkeypatch.setattr(mm, "get_keep_resident", lambda: False)+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: False)+ monkeypatch.setattr(mm, "should_mlock", lambda: False)++ caps = dict(LlamaCppBackend.probe_server_capabilities.__func__(LlamaCppBackend, None))+ caps["supports_load_mode"] = True+ backend, gguf = _backend(tmp_path, vulkan = False, memory = [(0, 40000, 48000)])+ with patch.object(LlamaCppBackend, "probe_server_capabilities", lambda *a, **k: caps):+ captured = _launch(backend, gguf, load_mode = "none")++ assert captured["cmd"][captured["cmd"].index("--load-mode") + 1] == "none"+ # (mlock, reserves_ram)+ assert backend._memory_state == (False, True)++ # Both consumers now see the child contradicting the setting.+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: True)+ assert (+ memory_state_satisfies_settings(+ backend._memory_state,+ backend._memory_policy_active,+ backend._memory_mlock_applicable,+ )+ is False+ )+++def test_a_fit_derived_load_mode_is_recorded_too(tmp_path, monkeypatch):+ """Same record, for the mode the fit supplies rather than the user.++ The fit's "none" reserves exactly as much host RAM as a hand-picked one, so a+ launch that took it must not report itself as non-reserving to the settings+ route and the duplicate-load comparator.+ """+ import utils.model_memory_settings as mm+ from core.inference.llama_server_args import memory_state_satisfies_settings++ monkeypatch.setattr(mm, "get_model_memory_settings", lambda: (False, False))+ monkeypatch.setattr(mm, "get_keep_resident", lambda: False)+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: False)+ monkeypatch.setattr(mm, "should_mlock", lambda: False)++ caps = dict(LlamaCppBackend.probe_server_capabilities.__func__(LlamaCppBackend, None))+ caps["supports_load_mode"] = True+ backend, gguf = _backend(tmp_path, vulkan = False, memory = [(0, 40000, 48000)])+ with (+ patch.object(LlamaCppBackend, "probe_server_capabilities", lambda *a, **k: caps),+ patch.object(LlamaCppBackend, "_fit_derived_load_mode", return_value = "none"),+ ):+ captured = _launch(backend, gguf) # no per-model pick: the fit supplies it++ assert captured["cmd"][captured["cmd"].index("--load-mode") + 1] == "none"+ assert backend._fit_load_mode_flags == ["--load-mode", "none"]+ assert backend._memory_state == (False, True)++ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: True)+ assert (+ memory_state_satisfies_settings(+ backend._memory_state,+ backend._memory_policy_active,+ backend._memory_mlock_applicable,+ )+ is False+ )++# ── Tensor parallelism keeps the requested KV cache type ─────────────diff --git a/studio/backend/tests/test_llama_server_args.py b/studio/backend/tests/test_llama_server_args.pyindex 5261141a50d..1a7f7f23d41 100644--- a/studio/backend/tests/test_llama_server_args.py+++ b/studio/backend/tests/test_llama_server_args.py@@ -1187,3 +1187,33 @@ def test_the_projector_env_twins_survive_the_scrub():# the corrupt path it is undoing, and it does that itself.assert "LLAMA_ARG_MMPROJ" not in _lsa.DENIED_ENV_VARSassert "LLAMA_ARG_MMPROJ_URL" not in _lsa.DENIED_ENV_VARS+++# ------------------------------------- an inherited loader mode is a real choice+++ "env,expected",+ [+ ({}, False),+ (None, False),+ # The enum itself is handler_string, so any value assigns the mode.+ ({"LLAMA_ARG_LOAD_MODE": "mmap"}, True),+ ({"LLAMA_ARG_LOAD_MODE": "dio"}, True),+ # Set but empty selects nothing; upstream would reject it, not default.+ ({"LLAMA_ARG_LOAD_MODE": " "}, False),+ # --mlock is handler_void: only a truthy value assigns anything.+ ({"LLAMA_ARG_MLOCK": "1"}, True),+ ({"LLAMA_ARG_MLOCK": "0"}, False),+ # The deprecated boolean twins assign the whole mode either way.+ ({"LLAMA_ARG_MMAP": "on"}, True),+ ({"LLAMA_ARG_MMAP": "off"}, True),+ ({"LLAMA_ARG_DIO": "1"}, True),+ # Negative aliases count by PRESENCE: get_value_from_env forces "0".+ ({"LLAMA_ARG_NO_MMAP": "0"}, True),+ ({"LLAMA_ARG_NO_DIO": ""}, True),+ ({"LLAMA_ARG_FIT": "off", "LLAMA_ARG_DEVICE": "none"}, False),+ ],+)+def test_memory_env_selects_load_mode(env, expected):+ assert _lsa.memory_env_selects_load_mode(env) is expecteddiff --git a/studio/backend/tests/test_load_mode_fit.py b/studio/backend/tests/test_load_mode_fit.pynew file mode 100644index 00000000000..56c77aa0e47--- /dev/null+++ b/studio/backend/tests/test_load_mode_fit.py@@ -0,0 +1,98 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Unit tests for the fit-driven ``--load-mode`` pick.++Pins the predicate behind it: a load that fits in VRAM, or in VRAM plus host RAM,+takes ``none`` and llama.cpp's async pinned-buffer loader; anything larger, or+anything that cannot be priced, keeps ``auto`` and its mapping.+"""++from __future__ import annotations++import pytest++from core.inference.llama_cpp import LlamaCppBackend++GIB = 1024**3+++class _Stub:+ """Just enough backend for the unbound predicate: it reads host RAM and nothing else."""++ def __init__(self, avail_mib):+ self._avail_mib = avail_mib++ def _available_system_memory_mib(self):+ return self._avail_mib+++def _fits(+ footprint,+ gpus,+ *,+ avail_mib = 64 * 1024,+ **kwargs,+):+ return LlamaCppBackend._fits_without_paging(_Stub(avail_mib), footprint, gpus, **kwargs)+++def test_fits_in_vram_alone():+ # 8 GiB model, 24 GiB card: VRAM settles it, host RAM is never consulted.+ assert _fits(8 * GIB, [(0, 24 * 1024)], avail_mib = None) is True+++def test_fits_across_pooled_vram():+ assert _fits(20 * GIB, [(0, 11 * 1024), (1, 11 * 1024)]) is True+++def test_spill_fits_in_host_ram():+ # 20 GiB against an 8 GiB card: 12 GiB spills, and 64 GiB of RAM holds it.+ assert _fits(20 * GIB, [(0, 8 * 1024)]) is True+++def test_spill_exceeds_host_ram():+ # Same spill, 8 GiB of RAM, of which 2 GiB is headroom: it does not fit.+ assert _fits(20 * GIB, [(0, 8 * 1024)], avail_mib = 8 * 1024) is False+++def test_headroom_is_kept_free():+ # 10 GiB spill against exactly 10 GiB of RAM fails on the 2 GiB headroom alone.+ assert _fits(10 * GIB, [], avail_mib = 10 * 1024) is False+ assert _fits(10 * GIB, [], avail_mib = 12 * 1024) is True+++def test_unreadable_host_ram_abstains():+ # Nothing to price the spill against -> None, so the caller keeps llama.cpp's auto.+ assert _fits(20 * GIB, [(0, 8 * 1024)], avail_mib = None) is None++[email protected]("footprint", [0, None, -1])+def test_unsized_footprint_abstains(footprint):+ assert _fits(footprint, [(0, 24 * 1024)]) is None+++def test_shared_igpu_vram_is_not_added_to_host_ram():+ # The iGPU's 32 GiB IS host RAM, so it must not count on both sides: priced+ # once, 16 GiB of RAM (14 after headroom) cannot hold a 40 GiB load.+ assert (+ _fits(+ 40 * GIB,+ [(0, 32 * 1024)],+ shared_gpu_ids = [0],+ avail_mib = 16 * 1024,+ )+ is False+ )+++def test_unpinned_cards_hold_nothing():+ # Two 16 GiB cards, but the launch pins one: the 8 GiB spill needs host RAM.+ gpus = [(0, 16 * 1024), (1, 16 * 1024)]+ assert _fits(24 * GIB, gpus, gpu_indices = [0], avail_mib = 4 * 1024) is False+ assert _fits(24 * GIB, gpus, avail_mib = 4 * 1024) is True+++def test_negative_free_vram_is_floored():+ # A probe that reports a card as over-subscribed must not credit negative VRAM.+ assert _fits(4 * GIB, [(0, -8 * 1024)], avail_mib = 4 * 1024) is Falsediff --git a/studio/backend/tests/test_load_mode_fit_matrix.py b/studio/backend/tests/test_load_mode_fit_matrix.pynew file mode 100644index 00000000000..f2972ad60db--- /dev/null+++ b/studio/backend/tests/test_load_mode_fit_matrix.py@@ -0,0 +1,2297 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Platform matrix for the fit-driven ``--load-mode`` pick.++Walks [Linux, Windows, WSL, macOS] x [NVIDIA, AMD discrete, AMD APU, Vulkan iGPU,+CPU only] x [fits in VRAM, fits in VRAM plus RAM, does not fit], then the whole+policy chain the pick feeds into, then the fallback paths that have to take it back+out again. The point is the negative half: on every host where the fit abstains, the+argv has to be exactly what it was before this existed.+"""++from __future__ import annotations++import itertools+from types import SimpleNamespace++import pytest++import utils.hardware as hardware+from core.inference.llama_cpp import LlamaCppBackend+from core.inference.llama_server_args import (+ apply_load_mode_policy,+ apply_model_memory_policy,+ split_policy_starves_devices,+)++GIB = 1024**3+# What a proven fit picks; the constant is deliberately the only switch.+FIT_MODE = LlamaCppBackend._FIT_LOAD_MODE+MIB = 1024 * 1024++# (label, gpu rows, vulkan?, unified-memory APU?, shared ordinals)+HARDWARE = {+ "nvidia_discrete": ([(0, 24 * 1024)], False, False, set()),+ "nvidia_multi": ([(0, 12 * 1024), (1, 12 * 1024)], False, False, set()),+ "amd_discrete": ([(0, 24 * 1024)], False, False, set()),+ "amd_apu": ([(0, 24 * 1024)], False, True, set()),+ "vulkan_igpu": ([(0, 24 * 1024)], True, False, {0}),+ "cpu_only": ([], False, False, set()),+}++PLATFORMS = ["linux", "windows", "wsl", "macos"]++# The cartesian product the matrix walks, materialised once.+_OS_GPU = list(itertools.product(PLATFORMS, HARDWARE))+++class _Stub:+ """Only what the predicate touches: host RAM and the APU question."""++ def __init__(+ self,+ avail_mib,+ is_apu = False,+ ):+ self._avail_mib = avail_mib+ self._is_apu = is_apu++ def _available_system_memory_mib(self):+ return self._avail_mib++ def _amd_apu_wants_unified_memory(self, gpu_indices = None):+ return self._is_apu++ _fits_without_paging = LlamaCppBackend._fits_without_paging+ # Read off the backend, so flipping the constant moves the whole matrix.+ _FIT_LOAD_MODE = LlamaCppBackend._FIT_LOAD_MODE+++def _mode(platform, hw, footprint, avail_mib, monkeypatch, **kwargs):+ rows, vulkan, apu, shared = HARDWARE[hw]+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: platform == "macos")+ stub = _Stub(avail_mib, is_apu = apu)+ return LlamaCppBackend._fit_derived_load_mode(+ stub,+ model_size = footprint,+ gpus = rows,+ shared_gpu_ids = shared,+ is_vulkan_backend = vulkan,+ avail_mib = avail_mib,+ **kwargs,+ )+++# ---------------------------------------------------------------- the matrix++[email protected]("platform,hw", _OS_GPU)+def test_a_load_that_fits_in_vram_takes_none(platform, hw, monkeypatch):+ """8 GiB into a 24 GiB card, with host RAM deliberately too small to help."""+ rows, _vulkan, apu, _shared = HARDWARE[hw]+ got = _mode(platform, hw, 8 * GIB, 4 * 1024, monkeypatch)+ if platform == "macos":+ # Metal keeps mmap: buffer_from_host_ptr makes the mapping zero copy there.+ assert got is None+ elif not rows or apu or hw == "vulkan_igpu":+ # No usable dedicated VRAM to fit into, and 4 GiB of RAM cannot hold it.+ assert got is None+ else:+ assert got == FIT_MODE++[email protected]("platform,hw", _OS_GPU)+def test_a_load_that_fits_in_vram_plus_ram_takes_none(platform, hw, monkeypatch):+ """32 GiB against 24 GiB of VRAM and 64 GiB of RAM."""+ rows, _vulkan, apu, _shared = HARDWARE[hw]+ got = _mode(platform, hw, 32 * GIB, 64 * 1024, monkeypatch)+ if platform == "macos":+ assert got is None+ else:+ # Unified memory is priced against RAM alone, which still holds 32 GiB here.+ assert got == FIT_MODE, (platform, hw, apu, rows)++[email protected]("platform,hw", _OS_GPU)+def test_a_load_that_fits_nowhere_keeps_auto(platform, hw, monkeypatch):+ """400 GiB against 24 GiB of VRAM and 32 GiB of RAM: mmap is the only way."""+ assert _mode(platform, hw, 400 * GIB, 32 * 1024, monkeypatch) is None++[email protected]("platform", PLATFORMS)+def test_unified_memory_is_never_counted_twice(platform, monkeypatch):+ """40 GiB, an APU reporting 32 GiB of "VRAM", and 32 GiB of RAM.++ Counted on both sides that is 64 GiB and the model "fits". It is one 32 GiB+ pool, and it does not.+ """+ assert _mode(platform, "amd_apu", 40 * GIB, 32 * 1024, monkeypatch) is None+ assert _mode(platform, "vulkan_igpu", 40 * GIB, 32 * 1024, monkeypatch) is None++[email protected]("platform,hw", _OS_GPU)+def test_an_unsized_model_keeps_auto(platform, hw, monkeypatch):+ for unsized in (None, 0):+ assert _mode(platform, hw, unsized, 64 * 1024, monkeypatch) is None++[email protected]("platform,hw", _OS_GPU)+def test_an_unsized_kv_keeps_auto(platform, hw, monkeypatch):+ assert _mode(platform, hw, 8 * GIB, 64 * 1024, monkeypatch, kv_sized = False) is None++[email protected]("platform,hw", _OS_GPU)+def test_an_unsized_drafter_keeps_auto(platform, hw, monkeypatch):+ assert _mode(platform, hw, 8 * GIB, 64 * 1024, monkeypatch, mtp_unsized = True) is None++[email protected]("platform,hw", _OS_GPU)+def test_unreadable_host_ram_keeps_auto_when_vram_alone_will_not_do(platform, hw, monkeypatch):+ assert _mode(platform, hw, 32 * GIB, None, monkeypatch) is None+++def test_every_footprint_term_is_charged(monkeypatch):+ """Each term alone can push a load over the edge, so none may be dropped."""+ rows_free = 8 * GIB+ base = dict(+ platform = "linux",+ hw = "nvidia_discrete",+ avail_mib = 0,+ monkeypatch = monkeypatch,+ )+ # 8 GiB of weights into 24 GiB, with each extra term sized to blow past it.+ for term in (+ "mmproj_pinned_bytes",+ "kv_cache_bytes",+ "mtp_bytes",+ "compute_buffer_flat",+ "compute_buffer_ctx",+ "pipeline_overhead_bytes",+ "soft_overhead",+ ):+ assert _mode(footprint = rows_free, **base, **{term: 0}) == FIT_MODE+ assert _mode(footprint = rows_free, **base, **{term: 20 * GIB}) is None+++def test_the_extra_devices_pipeline_overhead_is_charged(monkeypatch):+ """A layer split allocates a fixed CUDA context and scratch on every card, and+ the placement reserves 1 GiB per EXTRA device for it (_subset_model_size). The+ load-mode footprint has to carry the same term: 23 GiB across two 12 GiB cards+ with no host RAM to spill into is a fit until the second card's share is+ priced, and claiming that fit would hand the load a loader that cannot page."""+ base = dict(platform = "linux", hw = "nvidia_multi", avail_mib = 0, monkeypatch = monkeypatch)+ assert _mode(footprint = 23 * GIB, **base) == FIT_MODE+ assert _mode(footprint = 23 * GIB, pipeline_overhead_bytes = 2 * GIB, **base) is None+ # Single GPU: the launch's max(0, n - 1) is 0 there, so the term never moves it.+ assert (+ _mode(+ platform = "linux",+ hw = "nvidia_discrete",+ footprint = 23 * GIB,+ avail_mib = 0,+ monkeypatch = monkeypatch,+ pipeline_overhead_bytes = 0,+ )+ == FIT_MODE+ )+++def test_the_launch_charges_the_pipeline_overhead_per_extra_device():+ """max(0, n - 1), so a single-GPU load adds nothing, and ungated by whether+ llama.cpp keeps the pipeline -- the per-device context is there either way,+ which is why the placement's own term is ungated too."""+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend as B++ compact = "".join(inspect.getsource(B.load_model).split())+ assert "pipeline_overhead_bytes=(max(0,_fit_devices-1)*_pipeline_overhead_bytes)" in compact+++# ------------------------------------------------- the CPU-pinned drafter+++class _DraftStub:+ """Only the two readers _cpu_resident_draft_bytes consults."""++ def __init__(self, weights, kv):+ self._weights = weights+ self._kv = kv++ def _get_gguf_size_bytes(self, path):+ if self._weights is None:+ raise OSError(path)+ return self._weights++ def _mtp_draft_kv_bytes(self, n_ctx, **kwargs):+ return self._kv++ _cpu_resident_draft_bytes = LlamaCppBackend._cpu_resident_draft_bytes+ _MTP_DRAFT_COMPUTE_BYTES = LlamaCppBackend._MTP_DRAFT_COMPUTE_BYTES+++def test_no_cpu_pinned_drafter_charges_nothing():+ stub = _DraftStub(3 * GIB, 512 * MIB)+ assert stub._cpu_resident_draft_bytes(8192, drafter_path = None) == 0+++def test_a_cpu_pinned_drafter_is_charged_weights_plus_kv_plus_its_graph():+ """``-ngld 0`` takes the drafter off the GPU. It does not delete it: those+ bytes are in host RAM, and ``none`` allocates them anonymously there.++ The decode graph goes with them. llama.cpp gives the drafter a context of its+ own and decodes through it (common/speculative.cpp), and _soft_overhead only+ charges _MTP_DRAFT_COMPUTE_BYTES while _mtp_reserves_gpu, which is False for+ exactly this placement -- so left out here it is nowhere in the footprint."""+ stub = _DraftStub(3 * GIB, 512 * MIB)+ assert stub._cpu_resident_draft_bytes(8192, drafter_path = "d.gguf") == (+ 3 * GIB + 512 * MIB + LlamaCppBackend._MTP_DRAFT_COMPUTE_BYTES+ )+++def test_the_cpu_drafters_decode_graph_is_charged_to_host_ram(monkeypatch):+ """And it is enough to move the answer on its own: 8 GiB of target against a+ 24 GiB card, with host RAM sized so the drafter's weights and KV clear the+ headroom by less than the graph. Charged to RAM alone, like the rest of a+ host-only term."""+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: False)+ stub = _DraftStub(2 * GIB, 0)+ draft = stub._cpu_resident_draft_bytes(8192, drafter_path = "d.gguf")+ # Room for the weights and the headroom, but not for the graph on top.+ avail_mib = (2 * GIB + LlamaCppBackend._MTP_DRAFT_COMPUTE_BYTES // 2) // MIB + 2 * 1024++ def _fit(host_only):+ return LlamaCppBackend._fit_derived_load_mode(+ _Stub(avail_mib),+ model_size = 8 * GIB,+ host_only_bytes = host_only,+ gpus = [(0, 24 * 1024)],+ avail_mib = avail_mib,+ )++ # Weights and KV alone still read as a fit; the graph is what tips it.+ assert _fit(2 * GIB) == FIT_MODE+ assert _fit(draft) is None++[email protected]("weights,kv", [(None, 512 * MIB), (0, 512 * MIB), (3 * GIB, None)])+def test_an_unpriceable_cpu_drafter_abstains(weights, kv):+ """A drafter that is there but cannot be sized is exactly the case that must+ not be silently charged as zero."""+ stub = _DraftStub(weights, kv)+ assert stub._cpu_resident_draft_bytes(8192, drafter_path = "d.gguf") is None+++def test_the_cpu_drafter_flips_a_fit_that_only_looked_like_one(monkeypatch):+ """20 GiB of target onto an 8 GiB card with 16 GiB of RAM: the 12 GiB spill+ clears the 2 GiB headroom and the fit reads as real. Add the 2.5 GiB drafter+ ``-ngld 0`` leaves resident in host RAM and it does not."""+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: False)+ stub = _Stub(16 * 1024)++ def _fit(mtp_bytes):+ return LlamaCppBackend._fit_derived_load_mode(+ stub,+ model_size = 20 * GIB,+ mtp_bytes = mtp_bytes,+ gpus = [(0, 8 * 1024)],+ avail_mib = 16 * 1024,+ )++ assert _fit(0) == FIT_MODE+ assert _fit(int(2.5 * GIB)) is None+++def test_the_launch_charges_the_cpu_pinned_drafter_to_the_fit():+ """The budget nulls the drafter path before its weights are sized, so the+ fit has to keep its own copy. Checked at the source, like the other launch+ ordering invariants here: the call site sits inside load_model's fit try."""+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend as B++ compact = "".join(inspect.getsource(B.load_model).split())+ # Captured BEFORE the VRAM budget drops it.+ assert "_cpu_draft_path=_mtp_draft_for_budgetif_draft_on_cpuelseNone" in compact+ assert compact.index("_cpu_draft_path=_mtp_draft_for_budget") < compact.index(+ "if_draft_on_cpu:_mtp_draft_for_budget=None"+ )+ # ... and charged to the footprint as a HOST-ONLY term (free VRAM cannot pay for+ # an allocation the child only ever makes in RAM), abstaining when unpriceable.+ assert "host_only_bytes=_cpu_draft_fit_bytesor0" in compact+ assert "or_cpu_draft_fit_bytesisNone" in compact+++def test_a_weights_only_drafter_reserve_counts_as_unsized():+ """_flat_mtp_engages is "callback missing OR _mtp_kv_unsized", and the second+ arm is the one this call site has to keep: _estimate_mtp_overhead_bytes returns+ weights (plus any MLA/Mamba target copy) rather than None when the draft KV+ cannot be sized, so the callback exists and prices no draft KV at all. Charging+ that as a sized drafter understates a ctx-linear term the placement only covers+ with a flat cushion the footprint has no room for. Re-narrowing to+ "mtp_overhead_fn is None" absorbs the arm away, which is what it used to do."""+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend as B++ compact = "".join(inspect.getsource(B.load_model).split())+ assert (+ "mtp_unsized=bool(_flat_mtp_engagesor_cpu_draft_fit_bytesisNone"+ "or_draft_split_across_host)"+ ) in compact+ assert "_flat_mtp_engagesandmtp_overhead_fnisNone" not in compact+++def test_a_cpu_pinned_drafter_is_not_paid_for_out_of_vram(monkeypatch):+ """8 GiB target and a 3 GiB CPU-pinned drafter against a 24 GiB card with 4 GiB+ of RAM. Pooled, the card covers all 11 GiB and the fit reads as real; but+ ``-ngld 0`` means those 3 GiB can only be allocated in host RAM, where 4 GiB+ minus the 2 GiB headroom does not hold them, and ``none`` would make them+ anonymous instead of a mapping the OS can page."""+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: False)+ stub = _Stub(4 * 1024)++ def _fit(**kwargs):+ return LlamaCppBackend._fit_derived_load_mode(+ stub,+ model_size = 8 * GIB,+ gpus = [(0, 24 * 1024)],+ avail_mib = 4 * 1024,+ **kwargs,+ )++ assert _fit() == FIT_MODE+ assert _fit(host_only_bytes = 3 * GIB) is None+ # Same bytes on the GPU side of the ledger DO fit the card, which is the+ # difference this term draws.+ assert _fit(mtp_bytes = 3 * GIB) == FIT_MODE+ # And with RAM that can hold them, the host-only term is satisfied too.+ stub._avail_mib = 16 * 1024+ assert (+ LlamaCppBackend._fit_derived_load_mode(+ stub,+ model_size = 8 * GIB,+ gpus = [(0, 24 * 1024)],+ avail_mib = 16 * 1024,+ host_only_bytes = 3 * GIB,+ )+ == FIT_MODE+ )+++# ------------------------------------------- the fitter's own VRAM margin+++def test_the_fitters_margin_is_not_credited_to_the_fit(monkeypatch):+ """23 GiB free on a 24 GiB card and a 22.5 GiB footprint, with 2 GiB of RAM.++ Raw free VRAM covers it, but a launch that leaves ``--fit on`` runs llama.cpp's+ fitter, which keeps ``--fit-target`` (default 1024 MiB, "target margin per device+ for --fit") free on every device and spills the rest to host RAM instead. Those+ weights would then be anonymous under ``none``, on RAM nobody priced.+ """+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: False)+ stub = _Stub(2 * 1024)+ rows = [(0, 23 * 1024)]+ footprint = int(22.5 * GIB)++ def _fit(margin):+ return LlamaCppBackend._fit_derived_load_mode(+ stub,+ model_size = footprint,+ gpus = rows,+ fit_margin_mib = margin,+ avail_mib = 2 * 1024,+ )++ # --fit off (Studio proved the placement): no fitter, no margin, the card pays.+ assert _fit(0.0) == FIT_MODE+ # --fit on: the last 1 GiB is the fitter's, so 0.5 GiB of weights spill, and+ # 2 GiB of RAM is exactly the headroom, so nothing is left to hold them.+ assert _fit(1024.0) is None+++def test_the_margin_is_charged_per_device():+ """--fit-target is per device, so two cards keep two margins."""+ stub = _Stub(None) # host RAM unreadable: the VRAM term has to settle it+ rows = [(0, 12 * 1024), (1, 12 * 1024)]+ # 23 GiB fits 24 GiB of raw free, but not 24 - 2 x 1 GiB.+ assert stub._fits_without_paging(23 * GIB, rows, avail_mib = None) is True+ assert stub._fits_without_paging(23 * GIB, rows, vram_margin_mib = 1024.0, avail_mib = None) is None+ assert stub._fits_without_paging(21 * GIB, rows, vram_margin_mib = 1024.0, avail_mib = None) is True+++ "auto_fit,delta,supports,expected",+ [+ # Legacy auto path, untouched slider: llama.cpp's own default.+ (False, 0.0, True, 1024.0),+ # Manual + Auto starts from the tighter floor.+ (True, 0.0, True, 512.0),+ # A lowered VRAM budget raises the margin Studio asks the fitter to keep.+ (False, 2048.0, True, 3072.0),+ # ...and never below the 512 MiB floor.+ (True, -4096.0, True, 512.0),+ # Too old for the flag: the child still keeps its own 1024 MiB.+ (True, 0.0, False, 1024.0),+ ],+)+def test_the_fit_and_the_flag_read_the_same_margin(auto_fit, delta, supports, expected):+ got = LlamaCppBackend._fit_target_margin_mib(+ auto_fit = auto_fit,+ fit_target_delta_mib = delta,+ supports_fit_target = supports,+ )+ assert got == expected+ # And the emitted flag is that same number, so the margin the child is told to+ # keep and the margin the fit refuses to spend cannot drift.+ flags = LlamaCppBackend._ctx_integrity_flags(+ 1,+ True,+ auto_fit,+ 0,+ 0,+ {"supports_fit_target": supports},+ )+ if "--fit-target" in flags:+ assert flags[flags.index("--fit-target") + 1] == str(int(expected))+++def test_the_launch_charges_the_fitters_margin_only_when_fit_stays_on():+ """Checked at the source: reaching this call needs a real GPU probe."""+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend as B++ compact = "".join(inspect.getsource(B.load_model).split())+ call = compact[compact.index("_fit_margin_mib=(") :]+ call = call[: call.index("exceptExceptionase:")]+ assert "max(self._fit_target_margin_mib(" in call+ # Not `use_fit`: the extras land after this launch's own --fit and llama.cpp is+ # last-wins, so only the effective state may zero the whole margin.+ assert "or0.0,)if_fitter_runselse0.0" in call+ # A fitter the extras turned back on gets llama.cpp's own default, not this+ # launch's budget, which _ctx_integrity_flags never emitted for it.+ assert "fit_target_delta_mib=_fit_target_delta_mibifuse_fitelse0.0" in call+ assert "supports_fit_target=use_fitand" in call+ # And a pass-through --fit-target raises the margin above either.+ assert "fit_target_margin_in(_fit_extras,_fit_env)or0.0" in call+ assert "fit_margin_mib=_fit_margin_mib" in call+++def test_the_effective_fitter_state_reads_the_launchs_own_fit_flag():+ """`--fit on` in the extras beats the proved path's `--fit off` by last-arg.++ llama.cpp assigns `params.fit_params` on every occurrence (common/arg.cpp) and+ `-ngl -1` is its own default, which the fitter is free to lower (common/fit.cpp+ aborts only on a count the user really set). So the margin has to be charged.+ """+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend as B+ from core.inference.llama_server_args import fit_is_effectively_on++ compact = "".join(inspect.getsource(B.load_model).split())+ assert '_fitter_runs=fit_is_effectively_on(["--fit","on"ifuse_fitelse"off",' in compact++ # The synthetic prefix the call site builds, exercised directly.+ def _runs(+ use_fit,+ extras,+ env = None,+ ):+ return fit_is_effectively_on(["--fit", "on" if use_fit else "off", *extras], env)++ assert _runs(False, []) is False # proved path: no fitter+ assert _runs(True, []) is True+ assert _runs(False, ["--fit", "on"]) is True # the bug this closes+ assert _runs(True, ["--fit", "off"]) is False+ # The env twin cannot revive a fitter argv turned off: llama.cpp reads the+ # env BEFORE argv, and this launch always emits a --fit.+ assert _runs(False, [], {"LLAMA_ARG_FIT": "1"}) is False+++ "extras,env,expected",+ [+ ([], None, None),+ (["--fit-target", "4096"], None, 4096.0),+ (["-fitt", "8192"], None, 8192.0),+ # A comma list is one margin per device; the fit credits every device it+ # counts, so the largest is the only safe price.+ (["--fit-target", "512,4096,1024"], None, 4096.0),+ # Upstream splits on both "," and "/" (common/arg.cpp), so a slash list is+ # a well-formed per-device margin, not an unreadable token.+ (["--fit-target", "4096/4096"], None, 4096.0),+ (["-fitt", "512/4096/1024"], None, 4096.0),+ (["--fit-target", "512,4096/1024"], None, 4096.0),+ ([], {"LLAMA_ARG_FIT_TARGET": "1024/8192"}, 8192.0),+ # Still unreadable when a slash-separated entry is: upstream's stoull+ # throws on the whole list.+ (["--fit-target", "512/lots"], None, None),+ # Last-wins over argv, like every other llama.cpp flag.+ (["--fit-target", "4096", "--fit-target", "512"], None, 512.0),+ # Env twin only when argv sets nothing.+ ([], {"LLAMA_ARG_FIT_TARGET": "2048"}, 2048.0),+ (["--fit-target", "512"], {"LLAMA_ARG_FIT_TARGET": "8192"}, 512.0),+ # Unreadable abstains: upstream would reject the whole list.+ (["--fit-target", "lots"], None, None),+ (["--fit-target", "512,lots"], None, None),+ ],+)+def test_a_pass_through_fit_target_is_the_margin_the_child_really_keeps(extras, env, expected):+ from core.inference.llama_server_args import fit_target_margin_in+ assert fit_target_margin_in(extras, env) == expected+++# ------------------------------------------------------- the policy chain+++def toggles(monkeypatch):+ """Drive the Model Memory settings the two policies read lazily."""++ def _set(keep_resident, no_ram_reserve):+ import utils.model_memory_settings as mm++ monkeypatch.setattr(+ mm, "get_model_memory_settings", lambda: (keep_resident, no_ram_reserve)+ )+ monkeypatch.setattr(mm, "get_keep_resident", lambda: keep_resident)+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: no_ram_reserve)+ monkeypatch.setattr(mm, "should_mlock", lambda: keep_resident)++ return _set+++def _chain(extras, *, user_mode, fit_mode, supports, host_resident):+ """What load_model does, in the same order."""+ managed, rest = apply_model_memory_policy(+ extras,+ supports_load_mode = supports,+ weights_in_host_memory = host_resident,+ )+ lm_managed, rest = apply_load_mode_policy(+ rest,+ supports_load_mode = supports,+ weights_in_host_memory = host_resident,+ requested_load_mode = user_mode or fit_mode,+ )+ return list(managed) + list(lm_managed) + list(rest)+++_CHAIN_AXES = list(+ itertools.product(+ [(False, False), (True, False), (False, True), (True, True)], # toggles+ [None, "none", "mmap", "mlock", "dio", "auto"], # user pick+ [None, "none"], # fit pick+ [True, False], # supports --load-mode+ [True, False], # weights in host memory+ )+)++[email protected]("axes", _CHAIN_AXES)+def test_the_chain_never_emits_an_unknown_or_duplicate_mode(axes, toggles):+ (keep, no_reserve), user, fit, supports, host = axes+ toggles(keep, no_reserve)+ argv = _chain([], user_mode = user, fit_mode = fit, supports = supports, host_resident = host)+ # At most one managed mode selector reaches the child.+ assert argv.count("--load-mode") <= 1+ if "--load-mode" in argv:+ value = argv[argv.index("--load-mode") + 1]+ assert value in {"none", "mmap", "mlock", "mmap+mlock", "dio"}+ # A build without the flag must never be handed it.+ assert supports+ if not supports:+ assert "-lm" not in argv++[email protected]("axes", _CHAIN_AXES)+def test_the_fit_changes_nothing_a_user_pick_did_not_already_decide(axes, toggles):+ """With a user pick present, the fit is invisible: same argv either way."""+ (keep, no_reserve), user, _fit, supports, host = axes+ if user is None:+ pytest.skip("no user pick to defer to")+ toggles(keep, no_reserve)+ with_fit = _chain([], user_mode = user, fit_mode = "none", supports = supports, host_resident = host)+ without = _chain([], user_mode = user, fit_mode = None, supports = supports, host_resident = host)+ assert with_fit == without+++def _chain_before_this_change(extras, *, user_mode, supports, host_resident):+ """The chain exactly as it was: the per-model pick, and nothing else.++ Kept as its own literal copy rather than calling ``_chain`` with no fit, so a+ future edit to the live chain cannot quietly redefine what "before" means.+ """+ managed, rest = apply_model_memory_policy(+ extras,+ supports_load_mode = supports,+ weights_in_host_memory = host_resident,+ )+ lm_managed, rest = apply_load_mode_policy(+ rest,+ supports_load_mode = supports,+ weights_in_host_memory = host_resident,+ requested_load_mode = user_mode,+ )+ return list(managed) + list(lm_managed) + list(rest)++[email protected]("axes", _CHAIN_AXES)[email protected]("extras", [[], ["--mlock"], ["--no-mmap"], ["-ngl", "10"]])+def test_an_abstaining_fit_reproduces_the_old_argv_exactly(axes, extras, toggles):+ """The upgrade-safety property, against a literal copy of the old chain.++ Every host where the fit cannot prove a fit -- unreadable RAM, an unsized+ model, Apple Silicon, a load too big for the machine -- has to come out of+ this byte-identical to a Studio that never had the feature.+ """+ (keep, no_reserve), user, _fit, supports, host = axes+ toggles(keep, no_reserve)+ assert _chain(+ list(extras), user_mode = user, fit_mode = None, supports = supports, host_resident = host+ ) == _chain_before_this_change(+ list(extras), user_mode = user, supports = supports, host_resident = host+ )++[email protected]("toggle_pair", [(True, False), (False, True), (True, True)])+def test_the_model_memory_settings_still_win_over_the_fit(toggle_pair, toggles):+ keep, no_reserve = toggle_pair+ toggles(keep, no_reserve)+ argv = _chain([], user_mode = None, fit_mode = "none", supports = True, host_resident = True)+ if no_reserve:+ # "Don't reserve system RAM" vetoes none outright.+ assert "none" not in argv+ if keep and not no_reserve:+ # "Keep model in GPU memory" owns the mode.+ assert argv[:2] == ["--load-mode", "mmap+mlock"]+ assert "none" not in argv+++def test_the_fit_applies_when_both_toggles_are_off(toggles):+ toggles(False, False)+ assert _chain([], user_mode = None, fit_mode = "none", supports = True, host_resident = True) == [+ "--load-mode",+ "none",+ ]+++def test_an_old_binary_gets_the_pre_enum_spelling(toggles):+ toggles(False, False)+ assert _chain([], user_mode = None, fit_mode = "none", supports = False, host_resident = True) == [+ "--no-mmap"+ ]+++def test_a_hand_typed_flag_still_wins_by_last_arg(toggles):+ toggles(False, False)+ argv = _chain(+ ["--load-mode", "mmap"],+ user_mode = None,+ fit_mode = "none",+ supports = True,+ host_resident = True,+ )+ # Managed block first, the user's copy after it, so llama.cpp's last-wins+ # parsing lands on the user's.+ assert argv == ["--load-mode", "none", "--load-mode", "mmap"]+ assert argv[-1] == "mmap"+++# ------------------------------------------- the paths that must take it back+++def test_the_cpu_fallback_drops_the_fits_load_mode(monkeypatch):+ """A CPU replay runs on no GPU, so the VRAM half of the fit is void and the+ whole model has to come out of host RAM. mmap is what makes that survivable."""+ from unittest import mock++ from core.inference import llama_cpp as lc++ backend = LlamaCppBackend.__new__(LlamaCppBackend)+ backend._fit_load_mode_flags = ["--load-mode", "none"]+ replay = [+ "llama-server",+ "-m",+ "model.gguf",+ "--load-mode",+ "none",+ "--gpu-layers",+ "0",+ "--device",+ "none",+ ]+ with (+ mock.patch.object(lc.LlamaCppBackend, "_is_vulkan_backend", return_value = True),+ mock.patch.object(lc.LlamaCppBackend, "_cpu_isolated_replay", return_value = list(replay)),+ mock.patch.object(lc.LlamaCppBackend, "_cpu_isolated_binary", return_value = "cpu-server"),+ mock.patch.object(+ lc.LlamaCppBackend,+ "_llama_server_env_for_binary",+ return_value = {lc._loader_path_var(): "/staged"},+ ),+ ):+ out, _reason = backend._prepare_cpu_fallback_launch("llama-server", replay, {}, {})+ assert "--load-mode" not in out+ assert "none" not in out[: out.index("--gpu-layers")]+ # The placement flags the replay itself adds are untouched.+ assert out[-2:] == ["--device", "none"]+++def test_the_cpu_fallback_keeps_a_load_mode_the_user_asked_for(monkeypatch):+ """Only Unsloth's own tokens are recorded, so a user's pick survives."""+ from unittest import mock++ from core.inference import llama_cpp as lc++ backend = LlamaCppBackend.__new__(LlamaCppBackend)+ backend._fit_load_mode_flags = [] # user pick: nothing recorded+ replay = ["llama-server", "-m", "model.gguf", "--load-mode", "none"]+ with (+ mock.patch.object(lc.LlamaCppBackend, "_is_vulkan_backend", return_value = True),+ mock.patch.object(lc.LlamaCppBackend, "_cpu_isolated_replay", return_value = list(replay)),+ mock.patch.object(lc.LlamaCppBackend, "_cpu_isolated_binary", return_value = "cpu-server"),+ mock.patch.object(+ lc.LlamaCppBackend,+ "_llama_server_env_for_binary",+ return_value = {lc._loader_path_var(): "/staged"},+ ),+ ):+ out, _reason = backend._prepare_cpu_fallback_launch("llama-server", replay, {}, {})+ assert out[-2:] == ["--load-mode", "none"]+++def test_only_the_recorded_subsequence_is_removed():+ """A user's own --load-mode after ours must survive the strip."""+ from core.inference.llama_cpp import _without_subsequence++ argv = ["-m", "m.gguf", "--load-mode", "none", "--load-mode", "mmap"]+ assert _without_subsequence(argv, ["--load-mode", "none"]) == [+ "-m",+ "m.gguf",+ "--load-mode",+ "mmap",+ ]+++def test_the_fit_on_retry_drops_the_fits_load_mode():+ """The retry exists because the fit did NOT hold, so the conclusion it drew+ from that fit cannot ride along. Checked at the source, like the other+ ordering invariants in this launch path, because the retry only runs behind a+ real startup crash."""+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend as B++ src = inspect.getsource(B.load_model)+ retry = src[src.index("retrying once with --fit on so it can offload") :]+ retry = retry[: retry.index("_did_fit_retry = True")]+ assert "_fit_load_mode_flags" in retry+ assert "_without_subsequence" in retry+ # ...but the RECORD stays: this retry rewrites its own argv, not `cmd`, so the+ # arch-crash respawn below still has to be able to name the tokens `cmd` is+ # carrying. Clearing here would leave it stripping nothing.+ assert "self._fit_load_mode_flags = []" not in retry+++def test_the_arch_crash_retry_voids_the_fit_the_weights_only_floor_still_allows():+ """The premise behind the strip below, priced on real numbers.++ A 40 GB card and a 4 GB one, 20 GB of RAM. The fit was proved against the card+ the launch PINNED; the arch-crash retry moves to the survivor, and there the+ same footprint no longer fits. The retry's own guard is a weights-only floor by+ design, so it passes and cannot re-establish the proof.+ """+ rows = [(0, 40_000), (1, 4_000)]+ footprint = 30 * GIB # weights + KV + scratch+ weights = 20 * GIB+ stub = _Stub(20_000)++ # The retry really does move off the fitted card.+ assert LlamaCppBackend._arch_crash_retry_gpu_ids([0], [0, 1]) == [1]++ assert stub._fits_without_paging(footprint, rows, gpu_indices = [0]) is True+ assert stub._fits_without_paging(footprint, rows, gpu_indices = [1]) is False+ # ...while the weights-only refusal the retry runs stays silent, so nothing on+ # that path would take the fit's "none" back out on its own.+ assert LlamaCppBackend._host_offload_shortfall_message(weights - 4_000 * MIB, 20_000) is None+++def test_the_arch_crash_retry_drops_the_fits_load_mode():+ """The retry respawns from `cmd` on a device set the fit was never proved+ against (cards the crashed launch never touched, or the discrete survivors of a+ narrowing), so the mode that fit concluded cannot ride along. Checked at the+ source, like the --fit on retry above, because this arm only runs behind a real+ kernel-image crash."""+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend as B++ src = inspect.getsource(B.load_model)+ retry = src[src.index("the llama.cpp build has no kernels") :]+ # Bounded at the respawn, so the strip is proved to happen BEFORE it.+ retry = retry[: retry.index('label = "-archfallback"')]+ assert "_without_subsequence(cmd, self._fit_load_mode_flags)" in retry+ assert "self._fit_load_mode_flags = []" in retry+ # The record is dropped ONLY where `cmd` itself was rewritten. Anywhere else it+ # would disarm this strip for a respawn that still carries the tokens.+ assert src.count("self._fit_load_mode_flags = []") == 1+++def test_the_no_flash_retry_drops_the_fits_load_mode():+ """Both --flash-attn off respawns, which rewrite the footprint the fit priced.++ The mode is NOT gated on full offload: a partially offloaded "--fit on" launch+ that fits VRAM plus RAM carries it too, and on that launch the --fit on retry+ (gated on fully_gpu_offloaded) is not a second net. Checked at the source, like+ the retries above, because this arm only runs behind a real signal crash.+ """+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend as B++ src = inspect.getsource(B.load_model)+ # Both sites, each bounded at its own respawn so the strip is proved to happen+ # BEFORE it: the startup crash and the MTP first-decode crash.+ for label in ('label = "-noflash"', 'label = "-noflash-mtp"'):+ arm = src[: src.index(label)]+ arm = arm[arm.rindex("self._with_flash_attn_off(") :]+ assert "_drop_fit_load_mode_for_no_flash(_fa_cmd)" in arm+ # One helper, so the two arms cannot drift, and it strips without clearing:+ # the CPU fallback below still respawns from an argv carrying the tokens.+ assert src.count("_drop_fit_load_mode_for_no_flash(_fa_cmd)") == 2+ helper = src[src.index("def _drop_fit_load_mode_for_no_flash(") :]+ helper = helper[: helper.index("def _spawn_and_wait(")]+ assert "_without_subsequence(fa_cmd, self._fit_load_mode_flags)" in helper+ assert "self._fit_load_mode_flags = []" not in helper+++def test_the_no_flash_rewrite_really_grows_the_footprint_the_fit_priced():+ """The premise behind the strip above, on the two terms the estimator misses.++ The FA-off rewrite takes a quantized V to f16, and on an MLA model K goes with+ it, because llama.cpp rejects a split K/V there before it rejects a quantized V+ without flash attention. The MLA branch of the KV estimate prices that latent+ cache at the K width alone, so the upcast is unbudgeted.+ """+ from core.inference.llama_cpp import LlamaCppBackend as B++ cmd = ["llama-server", "--flash-attn", "on", "--cache-type-k", "q8_0", "--cache-type-v", "q8_0"]+ out = B._with_flash_attn_off(cmd, mla = True)+ assert out is not None+ # Flash attention really is off...+ assert "on" not in out[out.index("--flash-attn") : out.index("--flash-attn") + 2]+ # ...and BOTH axes were upcast, which is more KV than the fit charged.+ assert out[out.index("--cache-type-v") + 1] == "f16"+ assert out[out.index("--cache-type-k") + 1] == "f16"+++# ------------------------------------ pass-through args that move the weights+++# Every spelling llama.cpp accepts for "run this somewhere the planner did not put+# it", each appended AFTER Unsloth's own placement flags and so winning by last-arg.+PLACEMENT_OVERRIDES = [+ ["-ngl", "0"],+ ["--gpu-layers", "0"],+ ["--n-gpu-layers", "0"],+ ["--gpu-layers=0"],+ # A partial count is the same problem: the planner priced full offload.+ ["-ngl", "12"],+ ["--device", "none"],+ ["-dev", "cpu"],+ ["--n-cpu-moe", "24"],+ ["-ot", r".ffn_.*_exps.=CPU"],+]++[email protected]("extras", PLACEMENT_OVERRIDES)+def test_a_pass_through_placement_override_voids_the_vram_credit(extras, monkeypatch):+ """8 GiB into a 24 GiB card, 4 GiB of host RAM: the fit that says "none" is+ the VRAM one, and these flags run the weights out of RAM instead. Charging+ that fit's VRAM anyway would disable mmap on a load RAM cannot hold, which is+ an OOM kill where llama.cpp's own default would have demand-paged."""+ assert _mode("linux", "nvidia_discrete", 8 * GIB, 4 * 1024, monkeypatch) == FIT_MODE+ assert (+ _mode("linux", "nvidia_discrete", 8 * GIB, 4 * 1024, monkeypatch, extra_args = extras) is None+ )++[email protected]("extras", PLACEMENT_OVERRIDES)+def test_an_override_still_takes_none_when_host_ram_holds_the_whole_load(extras, monkeypatch):+ """The credit is dropped, not the answer: 8 GiB against 64 GiB of RAM is+ resident wherever these flags put it, so the pick stands."""+ assert (+ _mode("linux", "nvidia_discrete", 8 * GIB, 64 * 1024, monkeypatch, extra_args = extras)+ == FIT_MODE+ )+++ "extras",+ [+ [],+ None,+ ["-c", "8192"],+ ["--flash-attn", "on"],+ # -ncmoe 0 and -otd place nothing on this model's CPU side.+ ["--n-cpu-moe", "0"],+ ["-otd", r".*=CPU"],+ ["--device", "CUDA0"],+ ],+)+def test_extras_that_leave_placement_alone_keep_the_fit(extras, monkeypatch):+ assert (+ _mode("linux", "nvidia_discrete", 8 * GIB, 4 * 1024, monkeypatch, extra_args = extras)+ == FIT_MODE+ )+++ "var,value",+ [+ ("LLAMA_ARG_OVERRIDE_TENSOR", r".ffn_.*_exps.=CPU"),+ ("LLAMA_ARG_CPU_MOE", "1"),+ ("LLAMA_ARG_N_CPU_MOE", "24"),+ ],+)+def test_inherited_cpu_placement_env_voids_the_vram_credit(var, value, monkeypatch):+ """The child inherits these, so they outlive any token stripping."""+ monkeypatch.setenv(var, value)+ assert _mode("linux", "nvidia_discrete", 8 * GIB, 4 * 1024, monkeypatch) is None++[email protected]("value", ["0", "12", " 12 ", "all", "garbage"])+def test_an_inherited_gpu_layer_count_voids_the_vram_credit(value, monkeypatch):+ """The env twin of -ngl, and the sharper of the two: the fitting path emits+ "--fit on" and no layer flag at all, so an inherited count is the ONLY layer+ policy the child sees, and llama.cpp's fitter refuses to lower a count it did+ not set (common/fit.cpp: "n_gpu_layers already set by user, abort", downgraded+ to a warning). Nothing clears it on an automatic load -- only Manual mode owns+ it -- so the weights the fit credited to a card load into host RAM instead."""+ monkeypatch.setenv("LLAMA_ARG_N_GPU_LAYERS", value)+ assert _mode("linux", "nvidia_discrete", 8 * GIB, 4 * 1024, monkeypatch) is None+ # Dropped credit, not a dropped answer: RAM that holds the whole load is a fit+ # wherever the count puts it.+ assert _mode("linux", "nvidia_discrete", 8 * GIB, 64 * 1024, monkeypatch) == FIT_MODE++[email protected]("value", ["-1", "auto", "AUTO", "", " "])+def test_an_inherited_default_gpu_layer_count_keeps_the_fit(value, monkeypatch):+ """-1 / "auto" IS llama.cpp's default (common/common.h, llama-model.cpp), so+ the fitter still runs and still owns the placement this fit priced. An empty+ value never reaches placement at all: std::stoi throws and the child dies."""+ monkeypatch.setenv("LLAMA_ARG_N_GPU_LAYERS", value)+ assert _mode("linux", "nvidia_discrete", 8 * GIB, 4 * 1024, monkeypatch) == FIT_MODE+++def test_the_launch_hands_the_fit_the_extras_the_child_will_get():+ """The predicate is only worth anything if the call site feeds it. Checked at+ the source, like the fallback ordering tests above, because reaching this call+ needs a real GPU probe."""+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend as B++ src = inspect.getsource(B.load_model)+ call = src[src.index("_fit_extras = (") :]+ call = call[: call.index("except Exception as e:")]+ assert "extra_args = _fit_extras" in call+ # A gpu_ids pin drops the device flags from the emitted extras, so the fit has+ # to classify on the stripped copy rather than the request.+ assert "_strip_device_extra_args(extra_args)" in call+ # Every one of those overrides has an env twin read BEFORE argv, so the tokens+ # alone are half an answer, and the pin drops the twins with the flags.+ assert "env = _fit_env" in call+ assert "_fit_env = dict(os.environ)" in call+ assert "self._clear_device_placement_env(_fit_env)" in call+ assert "self._clear_manual_placement_env(_fit_env)" in call+++def test_an_inherited_device_selection_voids_the_vram_credit(monkeypatch):+ """Nothing clears LLAMA_ARG_DEVICE on an automatic load, so the child gets it.++ Only an explicit gpu_ids pin calls _clear_device_placement_env; unpinned, an+ inherited "none" runs the whole load out of host RAM while the argv says+ nothing at all. llama.cpp applies the env before argv (common/arg.cpp).+ """+ monkeypatch.setenv("LLAMA_ARG_DEVICE", "none")+ # 8 GiB against a 24 GiB card would fit VRAM outright, but 4 GiB of RAM+ # (minus the 2 GiB headroom) cannot hold it once the credit is void.+ assert _mode("linux", "nvidia_discrete", 8 * GIB, 4 * 1024, monkeypatch) is None+ # ... and the argv still wins over the env, so a GPU pick in the extras is+ # not condemned by a stale variable it overrides.+ assert (+ _mode(+ "linux",+ "nvidia_discrete",+ 8 * GIB,+ 4 * 1024,+ monkeypatch,+ extra_args = ["--device", "CUDA0"],+ )+ == FIT_MODE+ )+++ "hw,extras,gpu_indices,expected",+ [+ # One card, one name: a restatement, not a narrowing.+ ("nvidia_discrete", ["--device", "CUDA0"], None, FIT_MODE),+ # Two cards, one name: the child opens one of them, so crediting both+ # pays for VRAM it never reaches.+ ("nvidia_multi", ["--device", "CUDA0"], None, None),+ ("nvidia_multi", ["-dev", "CUDA1"], None, None),+ # Both named: nothing is left out.+ ("nvidia_multi", ["--device", "CUDA0,CUDA1"], None, FIT_MODE),+ # Two entries, ONE card: parse_device_list never deduplicates, so both+ # resolve to the same device and one VRAM pool. A raw count would call it a+ # restatement and credit a card that is not there; distinct names do not.+ ("nvidia_multi", ["--device", "CUDA0,CUDA0"], None, None),+ ("nvidia_multi", ["-dev", "CUDA1,CUDA1,CUDA1"], None, None),+ # ...and on a one-card host the same list still names every credited+ # device, so it stays a restatement.+ ("nvidia_discrete", ["--device", "CUDA0,CUDA0"], None, FIT_MODE),+ # Last-wins, like every other llama.cpp flag.+ ("nvidia_multi", ["--device", "CUDA0", "--device", "CUDA0,CUDA1"], None, FIT_MODE),+ ("nvidia_multi", ["--device", "CUDA0,CUDA1", "--device", "CUDA0"], None, None),+ # No selection at all: unchanged, the credit stands.+ ("nvidia_multi", [], None, FIT_MODE),+ ],+)+def test_a_narrowing_device_pass_through_voids_the_vram_credit(+ hw, extras, gpu_indices, expected, monkeypatch+):+ """`--device` is opt-in under auto-select (stripped only when gpu_ids is set).++ llama.cpp REPLACES the device list on every occurrence and offloads to nothing+ else (common/arg.cpp parse_device_list), so a name list shorter than what this+ fit charges leaves the credit paying for cards the child never opens.+ """+ # Fits the pair (2 x 12 GiB) but not one card, and host RAM cannot hold it.+ assert (+ _mode(+ "linux",+ hw,+ 20 * GIB,+ 2 * 1024,+ monkeypatch,+ extra_args = extras,+ gpu_indices = gpu_indices,+ )+ == expected+ )+++def test_the_device_narrowing_is_counted_against_what_the_fit_credits(monkeypatch):+ """Not against what was DETECTED: a launch already pinned to one card is not+ narrowed by an extras `--device` naming one, and voiding there would abstain on+ a fit that still holds."""+ # 10 GiB on one 12 GiB card of a two-card host, and host RAM cannot hold it,+ # so the answer turns entirely on whether the credit was voided.+ for extras, expected in ((["--device", "CUDA0"], FIT_MODE), ([], FIT_MODE)):+ assert (+ _mode(+ "linux",+ "nvidia_multi",+ 10 * GIB,+ 2 * 1024,+ monkeypatch,+ extra_args = extras,+ gpu_indices = [0],+ )+ == expected+ )+++# ------------------------------------------------- split policy overrides+++def _multi(footprint, avail_mib, monkeypatch, **kwargs):+ """Two 12 GiB cards, both credited, so a starved split is observable."""+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: False)+ return LlamaCppBackend._fit_derived_load_mode(+ _Stub(avail_mib),+ model_size = footprint,+ gpus = [(0, 12 * 1024), (1, 12 * 1024)],+ shared_gpu_ids = set(),+ is_vulkan_backend = False,+ avail_mib = avail_mib,+ **kwargs,+ )+++ "extras",+ [+ # One GPU holds everything, so the second card's credit is imaginary.+ ["--split-mode", "none"],+ ["-sm", "none"],+ # An explicit zero starves its device.+ ["--tensor-split", "1,0"],+ ["-ts", "1,0"],+ # A short list zero-fills the tail upstream, starving it just the same.+ ["--tensor-split", "1"],+ # Last-wins: the starving value is the one that reaches the child.+ ["--split-mode", "layer", "--split-mode", "none"],+ ],+)+def test_a_starving_split_voids_the_pooled_vram_credit(extras, monkeypatch):+ """18 GiB across 2x12 GiB fits the pool but not one card, and RAM is far too+ small to hold the spill. Crediting both cards anyway would emit the no-mmap+ flag for weights that then have nowhere pageable to live."""+ assert _multi(18 * GIB, 4 * 1024, monkeypatch, extra_args = extras) is None+++ "env_value",+ [{"LLAMA_ARG_SPLIT_MODE": "none"}, {"LLAMA_ARG_TENSOR_SPLIT": "1,0"}],+)+def test_an_inherited_starving_split_voids_it_too(env_value, monkeypatch):+ """The child inherits these exactly as it inherits LLAMA_ARG_DEVICE."""+ assert _multi(18 * GIB, 4 * 1024, monkeypatch, env = env_value) is None+++ "extras",+ [+ # Every mode but "none" keeps all devices holding weights.+ ["--split-mode", "layer"],+ ["--split-mode", "row"],+ ["--split-mode", "tensor"],+ # A ratio that starves nobody is a restatement, not an override.+ ["--tensor-split", "1,1"],+ ["--tensor-split", "3,1"],+ # Upstream throws and the child never starts: nothing to misprice.+ ["--tensor-split", "nonsense"],+ ],+)+def test_a_split_that_starves_nobody_keeps_the_fit(extras, monkeypatch):+ assert _multi(18 * GIB, 4 * 1024, monkeypatch, extra_args = extras) == FIT_MODE+++def test_a_starving_split_is_a_no_op_on_a_single_gpu(monkeypatch):+ """--split-mode none confines the model to one card, which is where a+ single-GPU load already put it."""+ assert (+ _mode(+ "linux",+ "nvidia_discrete",+ 8 * GIB,+ 4 * 1024,+ monkeypatch,+ extra_args = ["--split-mode", "none"],+ )+ == FIT_MODE+ )+++def test_a_starving_split_still_takes_none_when_ram_holds_the_load(monkeypatch):+ """The credit is dropped, not the answer, exactly as for the other overrides."""+ assert _multi(18 * GIB, 64 * 1024, monkeypatch, extra_args = ["-sm", "none"]) == FIT_MODE+++ "raw,n_credited,expected",+ [+ ("none", 2, True),+ ("NONE", 2, True),+ ("none", 1, False),+ ("layer", 2, False),+ ("row", 2, False),+ ("tensor", 2, False),+ (None, 2, False),+ ],+)+def test_split_mode_starvation_is_value_aware(raw, n_credited, expected):+ args = None if raw is None else ["--split-mode", raw]+ assert split_policy_starves_devices(args, n_credited) is expected+++ "raw,n_credited,expected",+ [+ ("1,0", 2, True),+ ("0,1", 2, True),+ ("1", 2, True), # zero-filled tail+ ("1/0", 2, True), # upstream splits on "/" too+ ("1,1", 2, False),+ ("3,1", 2, False),+ ("1,1,1", 2, False), # only the credited prefix matters+ ("1,0", 1, False), # single GPU: nothing to starve+ ],+)+def test_tensor_split_starvation_matches_upstream_parsing(raw, n_credited, expected):+ assert split_policy_starves_devices(["-ts", raw], n_credited) is expected+++# ----------------------------------------------- vulkan device replacement+++def _vulkan(footprint, avail_mib, monkeypatch, **kwargs):+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: False)+ return LlamaCppBackend._fit_derived_load_mode(+ _Stub(avail_mib),+ model_size = footprint,+ gpus = [(0, 12 * 1024), (1, 12 * 1024), (2, 12 * 1024)],+ shared_gpu_ids = set(),+ is_vulkan_backend = True,+ avail_mib = avail_mib,+ gpu_indices = [0, 1],+ **kwargs,+ )+++ "extras",+ [+ # Same COUNT, different cards: a count cannot see this, a name can.+ ["--device", "Vulkan1,Vulkan2"],+ ["-dev", "Vulkan0,Vulkan2"],+ # Longer: adds a device this footprint charged no compute or overhead for.+ ["--device", "Vulkan0,Vulkan1,Vulkan2"],+ ],+)+def test_a_replaced_vulkan_pin_voids_the_credit(extras, monkeypatch):+ """Studio pins Vulkan0,Vulkan1 from the credited ordinals; a pass-through+ --device lands after it and last-wins."""+ assert _vulkan(18 * GIB, 4 * 1024, monkeypatch, extra_args = extras) is None+++ "extras",+ [+ ["--device", "Vulkan0,Vulkan1"],+ ["--device", "vulkan0,vulkan1"], # ggml name-matching is not case sensitive here+ ["--device", "Vulkan1,Vulkan0"], # order is not a placement change+ ],+)+def test_a_restated_vulkan_pin_keeps_the_fit(extras, monkeypatch):+ assert _vulkan(18 * GIB, 4 * 1024, monkeypatch, extra_args = extras) == FIT_MODE+++def test_a_replaced_cuda_pin_is_still_judged_by_count(monkeypatch):+ """Only Vulkan gets the exact match: CUDA/ROCm ordinals are assigned after a+ visibility mask this launch has not written, so there is no name to compare."""+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: False)+ assert (+ LlamaCppBackend._fit_derived_load_mode(+ _Stub(4 * 1024),+ model_size = 18 * GIB,+ gpus = [(0, 12 * 1024), (1, 12 * 1024), (2, 12 * 1024)],+ shared_gpu_ids = set(),+ is_vulkan_backend = False,+ avail_mib = 4 * 1024,+ gpu_indices = [0, 1],+ extra_args = ["--device", "CUDA1,CUDA2"],+ )+ == FIT_MODE+ )+++# ------------------------------------------- CPU-pinned projector bytes+++def test_a_cpu_pinned_projector_is_charged_to_host_ram(monkeypatch):+ """8 GiB of weights and a 10 GiB projector pinned to the CPU by+ --no-mmproj-offload. The card has 24 GiB, so surplus VRAM would happily+ cover all 18 GiB and answer yes without ever asking RAM -- but the projector+ can only live in the 4 GiB of RAM this host has."""+ assert (+ _mode(+ "linux",+ "nvidia_discrete",+ 8 * GIB,+ 4 * 1024,+ monkeypatch,+ mmproj_pinned_bytes = 10 * GIB,+ )+ is None+ )+++def test_a_cpu_pinned_projector_fits_when_ram_really_holds_it(monkeypatch):+ """The same load with RAM that can take the projector still picks the mode."""+ assert (+ _mode(+ "linux",+ "nvidia_discrete",+ 8 * GIB,+ 64 * 1024,+ monkeypatch,+ mmproj_pinned_bytes = 10 * GIB,+ )+ == FIT_MODE+ )+++# ------------------------------------- mixed ROCm host: APU plus discrete card+++class _MixedRocmStub(_Stub):+ """A ROCm host where only SOME of the visible devices are unified-memory APUs.++ The plain _Stub answers the APU question blanket, which is exactly the shape+ that cannot tell a mixed host from a pure one.+ """++ def __init__(self, avail_mib, unified):+ super().__init__(avail_mib)+ self._unified = set(unified)++ def _amd_apu_wants_unified_memory(self, gpu_indices = None):+ if gpu_indices is None:+ return bool(self._unified)+ return any(idx in self._unified for idx in gpu_indices)+++def _mixed_rocm(footprint, avail_mib, unified, rows, monkeypatch, **kwargs):+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: False)+ return LlamaCppBackend._fit_derived_load_mode(+ _MixedRocmStub(avail_mib, unified),+ model_size = footprint,+ gpus = rows,+ shared_gpu_ids = set(),+ is_vulkan_backend = False,+ avail_mib = avail_mib,+ gpu_indices = [idx for idx, _free in rows],+ **kwargs,+ )+++def test_a_discrete_rocm_card_keeps_its_vram_next_to_an_apu(monkeypatch):+ """An 8 GiB APU beside a 24 GiB discrete Radeon, 20 GiB to place.++ The APU's "VRAM" IS the host RAM the spill would come from, so it is dropped+ from the credit -- but the discrete card's 24 GiB is its own pool and holds+ the whole load. Marking every row shared because one of them is an APU would+ forfeit a fit that is really there: 4 GiB of RAM (2 after headroom) is+ nowhere near enough.+ """+ rows = [(0, 8 * 1024), (1, 24 * 1024)]+ assert _mixed_rocm(20 * GIB, 4 * 1024, {0}, rows, monkeypatch) == FIT_MODE+++def test_an_apu_only_rocm_host_still_loses_the_whole_credit(monkeypatch):+ """The case the union exists for: counting the shared pool as VRAM AND as the+ RAM the spill comes from would fit the model twice into memory holding it once.+ """+ rows = [(0, 24 * 1024)]+ assert _mixed_rocm(20 * GIB, 4 * 1024, {0}, rows, monkeypatch) is None+++def test_every_apu_on_a_mixed_host_loses_its_credit(monkeypatch):+ """Per device, not "the first one": two APUs beside one discrete card leaves+ only the discrete card's 12 GiB, which cannot hold 20 GiB."""+ rows = [(0, 24 * 1024), (1, 24 * 1024), (2, 12 * 1024)]+ assert _mixed_rocm(20 * GIB, 4 * 1024, {0, 1}, rows, monkeypatch) is None+++# ---------------------------------------- a KV cache the launch pins to the host+++ "extras,env",+ [+ (["--no-kv-offload"], None),+ (["-nkvo"], None),+ ([], {"LLAMA_ARG_KV_OFFLOAD": "0"}),+ # Last-wins, and the positive form is a real flag: -nkvo then -kvo is back on.+ (["-kvo", "-nkvo"], None),+ # The env twin parses BEFORE argv, so a false env survives an absent flag.+ ([], {"LLAMA_ARG_KV_OFFLOAD": "false"}),+ # And the NEGATIVE spelling, which get_value_from_env checks first and+ # forces falsey on PRESENCE, whatever it says (common/arg.cpp).+ ([], {"LLAMA_ARG_NO_KV_OFFLOAD": "1"}),+ ([], {"LLAMA_ARG_NO_KV_OFFLOAD": "0"}),+ ([], {"LLAMA_ARG_NO_KV_OFFLOAD": ""}),+ # It is read before the affirmative one and returns, so it wins outright.+ ([], {"LLAMA_ARG_NO_KV_OFFLOAD": "0", "LLAMA_ARG_KV_OFFLOAD": "1"}),+ ],+)+def test_a_cpu_only_kv_cache_is_charged_to_host_ram_alone(extras, env, monkeypatch):+ """8 GiB of weights and a 12 GiB cache on a 24 GiB card with 4 GiB of RAM.++ Pooled, the card's surplus covers the cache and the fit answers yes without+ ever asking RAM. But --no-kv-offload allocates every layer's K and V on the+ CPU buffer whatever the layer placement says (llama-kv-cache.cpp upgrades the+ buffer type only inside `if (offload)`), so those 12 GiB can only come out of+ the 4 GiB this host has.+ """+ assert (+ _mode(+ "linux",+ "nvidia_discrete",+ 8 * GIB,+ 4 * 1024,+ monkeypatch,+ kv_cache_bytes = 12 * GIB,+ extra_args = extras,+ env = env or {},+ )+ is None+ )+++ "extras,env",+ [+ ([], None),+ (["--kv-offload"], None),+ # A CLI re-enable beats a false env: llama.cpp reads the env first.+ (["-kvo"], {"LLAMA_ARG_KV_OFFLOAD": "0"}),+ (["-nkvo", "-kvo"], None),+ # Same for the negative spelling: env parses first, argv still wins.+ (["-kvo"], {"LLAMA_ARG_NO_KV_OFFLOAD": "1"}),+ ],+)+def test_an_offloaded_kv_cache_is_still_pooled(extras, env, monkeypatch):+ """The same load with the cache where llama.cpp puts it by default. Charging+ it to host RAM anyway would abstain on a fit that is really there."""+ assert (+ _mode(+ "linux",+ "nvidia_discrete",+ 8 * GIB,+ 4 * 1024,+ monkeypatch,+ kv_cache_bytes = 12 * GIB,+ extra_args = extras,+ env = env or {},+ )+ == FIT_MODE+ )+++def test_a_cpu_only_kv_cache_is_not_charged_twice(monkeypatch):+ """Host-only, like the pinned projector: counted ONCE in the footprint and+ charged to RAM, not added on top of it. 8 + 12 GiB into 32 GiB of RAM (30+ after headroom) fits; double-counting the cache would make it 32 and fail."""+ assert (+ _mode(+ "linux",+ "cpu_only",+ 8 * GIB,+ 32 * 1024,+ monkeypatch,+ kv_cache_bytes = 12 * GIB,+ extra_args = ["-nkvo"],+ )+ == FIT_MODE+ )+++# ---------------------------- the tensor-parallel compute buffer, replicated+++def test_a_tensor_split_charges_the_replicated_compute_buffer():+ """Checked at the source: reaching this call needs a real multi-GPU probe.++ _plan_tensor_parallel admits devices against, and reserves per device,+ _estimate_compute_buffer_bytes(per_device_tensor = True). The fit has to charge+ the same thing: the layer-mode lump is ONE device's buffer at the smaller rate,+ and understating it on a pooled multi-GPU credit is the direction that claims a+ fit that is not there.+ """+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend as B++ compact = "".join(inspect.getsource(B.load_model).split())+ # The tensor-mode rate is measured alongside the layer one...+ assert "_compute_buffer_tensor=self._estimate_compute_buffer_bytes(" in compact+ assert "per_device_tensor=True,)" in compact+ # ...and the same flat fallback covers missing dims.+ assert "if_compute_buffer_tensor<=0:" in compact+ # ...and it is what the fit charges per selected device, but only when the+ # tensor-parallel branch really planned this load (tp_tensor_split cannot say:+ # it stays None on a split llama.cpp is left to size itself).+ assert "_tp_planned=False" in compact+ assert "use_fit=False_tp_planned=True" in compact+ assert (+ "compute_buffer_flat=(_fit_devices*_compute_buffer_tensor"+ "if_tp_plannedelse_compute_buffer_pipeline)"+ ) in compact+++def test_the_tensor_rate_really_exceeds_the_layer_one():+ """The under-charge the fix closes is not a rounding difference: at one slot+ the layer figure drops the vocab-width output buffer entirely."""++ class _Dims:+ # is_embedding_gguf is a read-only property on the real backend.+ _vocab_size = 151936+ _embedding_length = 5120+ is_embedding_gguf = False+ _DEFAULT_N_UBATCH = LlamaCppBackend._DEFAULT_N_UBATCH+ _COMPUTE_BUFFER_SAFETY = LlamaCppBackend._COMPUTE_BUFFER_SAFETY++ layer = LlamaCppBackend._estimate_compute_buffer_bytes(+ _Dims(), n_ubatch = 512, n_parallel = 1, per_device_tensor = False+ )+ tensor = LlamaCppBackend._estimate_compute_buffer_bytes(+ _Dims(), n_ubatch = 512, n_parallel = 1, per_device_tensor = True+ )+ assert tensor > layer+ # 4-GPU tensor split: what the fit used to charge vs what it now does.+ assert 4 * tensor - layer > GIB+++def test_the_replicated_buffer_can_decide_the_fit(monkeypatch):+ """23 GiB across two 12 GiB cards with no host RAM is a fit until the second+ device's copy of the compute buffer is priced."""+ base = dict(platform = "linux", hw = "nvidia_multi", avail_mib = 0, monkeypatch = monkeypatch)+ assert _mode(footprint = 22 * GIB, compute_buffer_flat = GIB, **base) == FIT_MODE+ assert _mode(footprint = 22 * GIB, compute_buffer_flat = 3 * GIB, **base) is None+++# ------------------------------- a drafter split between the GPU and the host+++ "extras,env,n_draft_layers,expected",+ [+ # Nothing set: llama.cpp's own -1 default places the drafter whole.+ ([], None, 28, False),+ (["-ngld", "-1"], None, 28, False),+ # The whole-drafter case _extra_args_draft_offloaded_to_cpu already owns.+ (["-ngld", "0"], None, 28, False),+ # A real split: the layers past the count stay in host RAM.+ (["-ngld", "1"], None, 28, True),+ (["--gpu-layers-draft", "14"], None, 28, True),+ (["--spec-draft-ngl=4"], None, 28, True),+ (["-ngld", "1"], None, None, True), # unreadable block count says nothing+ # Equal to the block count is still a split: i_gpu_start is 1 there, so+ # the first block and its KV stay on the host.+ (["-ngld", "28"], None, 28, True),+ # Only a count ABOVE the block count places the drafter whole.+ (["-ngld", "29"], None, 28, False),+ (["-ngld", "999"], None, 28, False),+ # The env twin the child reads before argv...+ ([], {"LLAMA_ARG_N_GPU_LAYERS_DRAFT": "1"}, 28, True),+ # ...which argv last-wins over.+ (["-ngld", "-1"], {"LLAMA_ARG_N_GPU_LAYERS_DRAFT": "1"}, 28, False),+ # Last-wins within argv too.+ (["-ngld", "1", "-ngld", "-1"], None, 28, False),+ (["-ngld", "-1", "-ngld", "1"], None, 28, True),+ # Upstream's std::stoi throws and the child never starts.+ (["-ngld", "lots"], None, 28, False),+ ],+)+def test_a_partial_draft_offload_is_recognised(extras, env, n_draft_layers, expected):+ from core.inference.llama_cpp import _draft_is_split_across_host+ assert _draft_is_split_across_host(extras, env or {}, n_draft_layers = n_draft_layers) is expected+++def test_the_draft_whole_offload_threshold_matches_the_main_model():+ """``-ngld <block count>`` is a split, on llama.cpp's own off-by-one.++ ``i_gpu_start = max(n_layer_all + 1 - n_gpu_layers, 0)`` (llama-model.cpp), and+ ``n_layer_all`` is the GGUF block count read straight off the key, so a count+ EQUAL to the block count leaves ``i_gpu_start == 1`` and hands block 0 the CPU+ buffer list. The main model already draws the line there+ (``_partially_offloads_layers``); the drafter has to agree, or the fit credits+ VRAM for a block that never reaches the card.+ """+ from core.inference.llama_cpp import LlamaCppBackend as B+ from core.inference.llama_cpp import _draft_is_split_across_host++ # The boundary itself, from both spellings and the env twin.+ assert _draft_is_split_across_host(["-ngld", "28"], {}, n_draft_layers = 28) is True+ assert _draft_is_split_across_host(["--spec-draft-ngl=12"], {}, n_draft_layers = 12) is True+ assert (+ _draft_is_split_across_host([], {"LLAMA_ARG_N_GPU_LAYERS_DRAFT": "28"}, n_draft_layers = 28)+ is True+ )+ # One above it clears the whole drafter onto the card, so a real fit survives.+ assert _draft_is_split_across_host(["-ngld", "29"], {}, n_draft_layers = 28) is False+ # The same threshold the main model uses, asked of its own predicate over a+ # stub: a count equal to the block count is partial there too. A premise test,+ # here to pin the two thresholds together.+ stub = SimpleNamespace(n_layers = 28)+ assert B._partially_offloads_layers(stub, ["-ngl", "28"], {}) is True+ assert B._partially_offloads_layers(stub, ["-ngl", "29"], {}) is False+++def test_a_partial_draft_offload_leaves_the_drafter_unsized():+ """Checked at the source: reaching this call needs a real drafter GGUF.++ -ngld 1 is not _extra_args_draft_offloaded_to_cpu (that is the -ngld 0 case), so+ _cpu_draft_path is None and mtp_bytes carries the drafter WHOLE in the+ GPU-eligible term while llama.cpp pins the layers past the count, and their KV,+ in host RAM. Nothing at the call site can say which slice stays on the card, so+ it has to abstain rather than credit VRAM for bytes that never reach it.+ """+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend as B++ compact = "".join(inspect.getsource(B.load_model).split())+ assert (+ "_draft_split_across_host=bool(_mtp_draft_for_budgetand_draft_is_split_across_host("+ in compact+ )+ # The same effective views the other overrides are classified on.+ assert "_draft_is_split_across_host(_fit_extras,_fit_env," in compact+ # Scoped by the drafter's own block count, off the backend the KV sizing above+ # already cached, so -ngld at or above it is not treated as a split.+ assert (+ 'n_draft_layers=getattr(self._draft_backend_for(_mtp_draft_for_budget),"_n_layers",None,)'+ in compact+ )+ # And it lands on the abstain, not on a term.+ assert "or_draft_split_across_host" in compact+++# ------------------------------------- round 7: terms and paths the fit missed+++def test_the_cpu_projector_retry_voids_the_fit_it_was_proved_against():+ """The premise behind the strip below, priced on real numbers.++ A 24 GiB card and 2 GiB of free host RAM. As launched the projector is on the+ card and the whole load fits VRAM alone, so ``_fits_without_paging`` answers+ True without ever consulting RAM. The CPU-projector retry moves exactly those+ bytes into host RAM (--no-mmproj-offload clears mmproj_use_gpu, and clip.cpp+ gates its whole GPU backend on it), and there the same footprint does not fit.+ """+ stub = _Stub(2 * 1024)+ rows = [(0, 24 * 1024)]+ weights, projector = 16 * GIB, 4 * GIB++ assert stub._fits_without_paging(weights + projector, rows) is True+ assert stub._fits_without_paging(weights + projector, rows, host_only_bytes = projector) is False+++def test_the_cpu_projector_retry_drops_the_fits_load_mode():+ """The projector respawn changes placement, so the fit's conclusion goes with+ it, like the --fit on, arch-crash and no-flash retries. Checked at the source,+ like those, because this arm only runs behind a real projector startup crash."""+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend as B++ src = inspect.getsource(B.load_model)+ # Bounded at the respawn, so the strip is proved to happen BEFORE it.+ arm = src[: src.index('label = "-mmproj-cpu"')]+ arm = arm[arm.rindex("_cpu_projector_cmd = self._with_mmproj_offload_disabled(") :]+ assert "self._fit_load_mode_flags" in arm+ assert "_without_subsequence(" in arm+ # The record stays: the fallbacks below respawn from an argv carrying these+ # tokens and have to be able to name them.+ assert "self._fit_load_mode_flags = []" not in arm+ assert src.count("self._fit_load_mode_flags = []") == 1+++def _checkpoint_swa_backend():+ """A Gemma-shaped SWA model, the one architecture --ctx-checkpoints charges."""+ b = LlamaCppBackend()+ for name, value in {+ "_n_layers": 62,+ "_n_kv_heads": 16,+ "_n_heads": 32,+ "_embedding_length": 5376,+ "_kv_key_length": 128,+ "_kv_value_length": 128,+ "_sliding_window": 1024,+ }.items():+ setattr(b, name, value)+ return b+++def test_context_checkpoint_snapshots_move_the_fit_verdict(monkeypatch):+ """The premise: the snapshots are GiBs, not a rounding error.++ 62 SWA layers at 8192 context: 1.5 GiB of KV becomes 4.4 GiB with 8 snapshots+ per slot. A card sized for the first answers "none" for a load that really+ needs the second, and with the host holding nothing that is an OOM where the+ mapping would only have paged.+ """+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: False)+ backend = _checkpoint_swa_backend()+ ctx = 8192+ base = backend._estimate_kv_cache_bytes(ctx, "f16")+ snapshotted = backend._estimate_kv_cache_bytes(ctx, "f16", ctx_checkpoints = 8)+ assert snapshotted - base > 2 * GIB++ model = 16 * GIB+ stub = _Stub(1024) # 1 GiB of RAM: nothing spills anywhere+ rows = [(0, (model + base) // MIB)] # exactly holds the unsnapshotted load++ def _verdict(kv_bytes):+ return LlamaCppBackend._fit_derived_load_mode(+ stub,+ model_size = model,+ kv_cache_bytes = kv_bytes,+ gpus = rows,+ avail_mib = 1024,+ )++ assert _verdict(base) == FIT_MODE+ assert _verdict(snapshotted) is None+++def test_the_fit_prices_the_effective_checkpoint_count():+ """...and the call site really passes it, while the closure default leaves the+ placement paths -- which price the snapshots by their own route -- unmoved."""+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend as B++ compact = "".join(inspect.getsource(B.load_model).split())+ assert "kv_cache_bytes=_kv_bytes(effective_ctx,_effective_ctx_checkpoints)," in compact+ assert "def_kv_bytes(ctx:int,ctx_checkpoints:int=0)->int:" in compact+++def test_an_inherited_loader_mode_wins_over_the_fits_pick():+ """llama.cpp applies LLAMA_ARG_LOAD_MODE before argv, so the managed flag would+ beat an operator's inherited choice silently. The fit's mode stands aside for+ it, the way it stands aside for the per-model pick; a per-model pick still+ wins, and so does a hand-typed flag, by last-arg."""+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend as B++ compact = "".join(inspect.getsource(B.load_model).split())+ arm = compact[+ compact.index("_fit_load_mode_env_view=dict(_mem_env)") : compact.index(+ "_resolved_load_mode=load_modeor_fit_load_mode"+ )+ ]+ # Asked of the child's environment AFTER the same scrub it gets, so a var a+ # Model Memory toggle drops vetoes nothing.+ assert "scrub_memory_env(_fit_load_mode_env_view)" in arm+ # Assert the CONDITIONS, not one rendering: the formatter is free to wrap this,+ # which breaks a single-string pin. Each clause is asserted on its own.+ assert "_fit_load_mode" in arm and "notload_mode" in arm+ assert "memory_env_selects_load_mode(_fit_load_mode_env_view)" in arm+ assert "_fit_load_mode=None" in arm+++def test_an_unpriced_projector_is_the_difference_between_a_fit_and_an_oom(monkeypatch):+ """The premise behind pricing an inherited projector: 18 GiB of weights fit a+ 20 GiB card, and the same load with a 3 GiB projector the child loads from+ LLAMA_ARG_MMPROJ does not."""+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: False)+ stub = _Stub(1024)+ rows = [(0, 20 * 1024)]+ weights, projector = 18 * GIB, 3 * GIB++ def _verdict(model_size):+ return LlamaCppBackend._fit_derived_load_mode(+ stub, model_size = model_size, gpus = rows, avail_mib = 1024+ )++ assert _verdict(weights) == FIT_MODE+ assert _verdict(weights + projector) is None+++def test_the_fit_prices_a_projector_inherited_through_the_environment():+ """model_size is gated on launch_mmproj_path, so a projector that arrives only+ through LLAMA_ARG_MMPROJ is resident but uncharged. Sized when it can be, and+ abstaining when it cannot: a URL names a download that has not happened, and an+ unreadable path cannot be sized."""+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend as B++ compact = "".join(inspect.getsource(B.load_model).split())+ assert 'else(_fit_env.get("LLAMA_ARG_MMPROJ")or"").strip()' in compact+ assert 'else(_fit_env.get("LLAMA_ARG_MMPROJ_URL")or"").strip()' in compact+ # Unsized -> abstain, the same answer the other unreadable terms give.+ assert "_fit_env_mmproj_unsized=bool(_fit_env_mmproj_url)or(" in compact+ assert "if_fit_env_mmproj_unsized:" in compact+ assert "_fit_model_size=None" in compact+ assert "model_size=_fit_model_size," in compact+ # Host-resident when the resolved offload says CPU, pooled otherwise.+ assert (+ "mmproj_pinned_bytes=_mmproj_pinned_bytes+(_fit_env_mmproj_bytesif_fit_env_mmproj_on_hostelse0),"+ in compact+ )+ # Not charged where the child never sees it: the vision switch and the+ # paravirtual pin both scrub those vars out of the child environment.+ assert (+ "_fit_env_mmproj_scrubbed=bool(_pv_mmproj_unpinnableor_paravirtual_cpu_forced)" in compact+ )+++def _allowance(mmproj_bytes, *, on_host):+ """The projector allowance, resolved at call time.++ Bound here rather than in a class body so a missing method fails the tests that+ rely on it instead of erroring out the whole module at import.+ """+ stub = SimpleNamespace(_MMPROJ_VRAM_SAFETY = LlamaCppBackend._MMPROJ_VRAM_SAFETY)+ return LlamaCppBackend._inherited_mmproj_soft_overhead(stub, mmproj_bytes, on_host = on_host)+++def test_an_inherited_projector_carries_the_same_safety_allowance_as_a_resolved_one():+ """The resolved projector's allowance rides in _soft_overhead, which is gated on+ effective_is_vision -> launch_mmproj_path, so an env-only projector was charged its+ file size and nothing for the buffers the encoder really allocates.++ Same formula as the three resolved call sites, read off the constant so moving it+ moves both together.+ """+ projector = 8 * GIB+ expected = int(projector * (LlamaCppBackend._MMPROJ_VRAM_SAFETY - 1.0))++ assert _allowance(projector, on_host = False) == expected+ assert expected > 0+ # Host arm: the resolved projector is priced raw there too, so no allowance.+ assert _allowance(projector, on_host = True) == 0+ # Nothing inherited, nothing to charge.+ assert _allowance(0, on_host = False) == 0+++def test_the_projector_allowance_flips_a_fit_that_only_looked_like_one(monkeypatch):+ """22 GiB of weights-plus-projector into a 24 GiB card looks like a fit while the+ 8 GiB projector is charged raw. With the allowance the real footprint is 25.2 GiB,+ which does not fit, and understating it is the direction that hands the load a+ loader that cannot page. Host RAM is deliberately too small to cover the gap.+ """+ projector = 8 * GIB+ footprint = 22 * GIB+ allowance = _allowance(projector, on_host = False)++ assert _mode("linux", "nvidia_discrete", footprint, 512, monkeypatch) == FIT_MODE+ assert (+ _mode(+ "linux",+ "nvidia_discrete",+ footprint,+ 512,+ monkeypatch,+ soft_overhead = allowance,+ )+ is None+ )+++def test_the_launch_wires_the_projector_allowance_into_the_fit():+ """Reachability only: driving load_model this far needs a real GPU probe."""+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend as B++ compact = "".join(inspect.getsource(B.load_model).split())+ assert "_inherited_mmproj_soft_overhead" in compact+ assert "soft_overhead=_fit_soft_overhead" in compact+++# ------------------------- round 8: adapter sidecars the extras pass through+++def test_pass_through_adapter_paths_follow_llama_cpp_parsing():+ from core.inference.llama_cpp import _sidecar_adapter_paths++ # parse_csv_row: one operand, many adapters.+ assert _sidecar_adapter_paths(["--lora", "/a.gguf,/b.gguf"]) == ["/a.gguf", "/b.gguf"]+ # The inline spelling, and the FNAME:SCALE tail the -scaled flags carry.+ assert _sidecar_adapter_paths(["--lora-scaled=/a.gguf:0.5"]) == ["/a.gguf"]+ assert _sidecar_adapter_paths(["--control-vector", "/cv.gguf"]) == ["/cv.gguf"]+ assert _sidecar_adapter_paths(["--control-vector-scaled", "/cv.gguf:2"]) == ["/cv.gguf"]+ # ACCUMULATED, not last-wins: every handler push_back()s, so a second --lora+ # adds to the first. Pricing only the last would understate the load.+ assert _sidecar_adapter_paths(["--lora", "/a.gguf", "--lora", "/b.gguf"]) == [+ "/a.gguf",+ "/b.gguf",+ ]+ # string_split(item, ':') demands exactly two parts, so these are upstream's own+ # throw: the child never starts and there is no placement to misprice.+ assert _sidecar_adapter_paths(["--lora-scaled", "/a.gguf"]) == []+ assert _sidecar_adapter_paths(["--lora-scaled", "C:/a.gguf:0.5"]) == []+ assert _sidecar_adapter_paths(["--lora-scaled", "/a.gguf:half"]) == []+ # Nothing else on the command line is an adapter.+ assert _sidecar_adapter_paths(["--lora-init-without-apply", "-ngl", "-1"]) == []+ assert _sidecar_adapter_paths([]) == []+ assert _sidecar_adapter_paths(None) == []+++def test_the_fit_prices_pass_through_adapter_weights(tmp_path, monkeypatch):+ """A 3 GiB LoRA is the difference between an 18 GiB load fitting a 20 GiB card+ and not. llama.cpp allocates the adapter on the base tensor's own buffer type+ (llama-adapter.cpp) and never mmaps it, so those bytes are resident on top of a+ placement neither this fit nor common/fit.cpp ever charged for.+ """+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: False)+ adapter = tmp_path / "adapter.gguf"+ adapter.write_bytes(b"")+ import os as _os++ with open(adapter, "wb") as fh: # sparse, so the test costs no disk+ fh.truncate(3 * GIB)+ assert _os.stat(adapter).st_size == 3 * GIB++ stub = _Stub(1024)+ rows = [(0, 20 * 1024)]++ def _verdict(extras):+ return LlamaCppBackend._fit_derived_load_mode(+ stub,+ model_size = 18 * GIB,+ gpus = rows,+ avail_mib = 1024,+ extra_args = extras,+ env = {},+ )++ # The same load, with and without the adapter the extras pass through.+ assert _verdict([]) == FIT_MODE+ assert _verdict(["--lora", str(adapter)]) is None+ assert _verdict([f"--lora-scaled={adapter}:0.5"]) is None+ # Charged once per occurrence: two references to the same file is two loads.+ assert _verdict(["--lora", f"{adapter},{adapter}"]) is None+ # A small adapter still fits, so the fit is not simply refused on the flag.+ small = tmp_path / "small.gguf"+ small.write_bytes(b"x" * 4096)+ assert _verdict(["--lora", str(small)]) == FIT_MODE+++def test_the_fit_prices_the_legacy_two_token_scaled_adapter(tmp_path, monkeypatch):+ """``--lora-scaled FNAME SCALE`` is the spelling older llama-servers declared,+ and Studio runs whatever binary it is pointed at. Reading only FNAME as the+ operand and dropping it for want of a colon prices the adapter at zero, which is+ the optimistic direction: a load that needs 21 GiB on a 20 GiB card would be+ handed a loader that cannot page.+ """+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: False)+ adapter = tmp_path / "adapter.gguf"+ with open(adapter, "wb") as fh: # sparse, so the test costs no disk+ fh.truncate(3 * GIB)++ stub = _Stub(1024)++ def _verdict(extras):+ return LlamaCppBackend._fit_derived_load_mode(+ stub,+ model_size = 18 * GIB,+ gpus = [(0, 20 * 1024)],+ avail_mib = 1024,+ extra_args = extras,+ env = {},+ )++ assert _verdict([]) == FIT_MODE+ assert _verdict(["--lora-scaled", str(adapter), "0.5"]) is None+ assert _verdict(["--control-vector-scaled", str(adapter), "1"]) is None+ # A drive letter is a filename, not a scale, once the scale is its own token.+ from core.inference.llama_cpp import _sidecar_adapter_paths++ assert _sidecar_adapter_paths(["--lora-scaled", "C:/a.gguf", "0.5"]) == ["C:/a.gguf"]+ # Today's syntax is unchanged, and a lone FNAME with no scale after it is still+ # upstream's own throw rather than a load to price.+ assert _sidecar_adapter_paths(["--lora-scaled", "/a.gguf:0.5"]) == ["/a.gguf"]+ assert _sidecar_adapter_paths(["--lora-scaled", "/a.gguf"]) == []+ assert _sidecar_adapter_paths(["--lora-scaled", "/a.gguf", "--lora", "/b.gguf"]) == [+ "/b.gguf",+ ]+++def test_an_unreadable_adapter_abstains(tmp_path, monkeypatch):+ """Engaged but unsized, the same answer every other unreadable term gives."""+ monkeypatch.setattr(hardware, "is_apple_silicon", lambda: False)+ stub = _Stub(1024)+ got = LlamaCppBackend._fit_derived_load_mode(+ stub,+ model_size = 8 * GIB,+ gpus = [(0, 24 * 1024)],+ avail_mib = 1024,+ extra_args = ["--lora", str(tmp_path / "missing.gguf")],+ env = {},+ )+ assert got is None+++def test_adapter_flags_really_reach_the_child():+ """Premise test (holds either way): the fit only has to price these because the+ pass-through layer lets them through. It is a denylist, and none of the four+ adapter flags is on it."""+ from core.inference.llama_server_args import validate_extra_args+ for flag in ("--lora", "--lora-scaled", "--control-vector", "--control-vector-scaled"):+ assert validate_extra_args([flag, "/a.gguf:0.5"]) == [flag, "/a.gguf:0.5"]+++# ----------------- round 8: a user's own load mode across a retry CHAIN+++def test_the_extras_own_load_mode_stands_the_fit_down():+ from core.inference.llama_server_args import extra_args_select_load_mode++ # The enum, both spellings, value and inline forms.+ assert extra_args_select_load_mode(["--load-mode", "none"]) is True+ assert extra_args_select_load_mode(["-lm", "mmap"]) is True+ assert extra_args_select_load_mode(["--load-mode=mlock"]) is True+ # The legacy flags the enum replaced, which is what this launch emits on a+ # pre-enum binary, so a user's own copy collides there the same way.+ assert extra_args_select_load_mode(["--no-mmap"]) is True+ assert extra_args_select_load_mode(["--mmap"]) is True+ # Nothing else on the command line picks a loader mode.+ assert extra_args_select_load_mode(["-ngl", "-1", "--temp", "0.7"]) is False+ assert extra_args_select_load_mode([]) is False+ assert extra_args_select_load_mode(None) is False+++def test_a_chained_retry_cannot_eat_the_users_own_load_mode():+ """_without_subsequence removes the FIRST value match, so two identical pairs+ in one argv are two removals across two retry rungs -- the second taking the+ user's. The fit standing aside when the extras pick a mode is what keeps the+ strips the no-ops their docstrings claim to be.+ """+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend as B+ from core.inference.llama_cpp import _without_subsequence+ from core.inference.llama_server_args import (+ apply_load_mode_policy,+ extra_args_select_load_mode,+ )++ user = ["--load-mode", "none"]+ assert extra_args_select_load_mode(user)++ def two_rungs(requested):+ """The real policy call and the real strip, twice, as the retry does."""+ managed, extras = apply_load_mode_policy(+ list(user),+ supports_load_mode = True,+ weights_in_host_memory = True,+ requested_load_mode = requested,+ )+ # What load_model records as the fit's own flags: only when the fit chose.+ fit_flags = list(managed) if requested else []+ argv = [*managed, "--temp", "0.7", *extras]+ return _without_subsequence(_without_subsequence(argv, fit_flags), fit_flags)++ # Emitting the fit's pair alongside an identical user pair is what loses it:+ # two rungs, two first-match removals, and the typed flag is the second.+ assert two_rungs("none") == ["--temp", "0.7"]+ # Standing aside leaves one pair, so both rungs are the no-op the docstrings+ # claim, and the flag the user typed is still there on the second respawn.+ assert two_rungs(None) == ["--temp", "0.7", "--load-mode", "none"]++ # Reachability of the guard in load_model. A single call expression, so a+ # reformat that wraps the `if` cannot break it once whitespace is stripped.+ compact = "".join(inspect.getsource(B.load_model).split())+ # Assert each clause on its own -- the formatter is free to wrap the `if`.+ assert "extra_args_select_load_mode(_mem_extras)" in compact+ assert "_fit_load_mode" in compact and "notload_mode" in compact+ assert "_fit_load_mode=None" in compact+ # The view is pinned by the call above (_mem_extras, as Model Memory left them)+ # and deliberately NOT by a second pin on the apply_load_mode_policy call: that+ # is a multi-token run a reformat can wrap, the shape that broke CI last round.+++def test_the_fit_still_emits_when_the_extras_pick_nothing():+ """The guard is scoped to a real pick, not to the presence of any extras."""+ from core.inference.llama_server_args import apply_load_mode_policy, extra_args_select_load_mode++ extras = ["-ngl", "-1", "--temp", "0.7"]+ assert extra_args_select_load_mode(extras) is False+ managed, passed = apply_load_mode_policy(+ extras, supports_load_mode = True, requested_load_mode = FIT_MODE+ )+ assert managed == ["--load-mode", FIT_MODE]+ assert passed == extras+++# ------------------ round 11: the record has to follow the argv on every rung+++def test_a_stripped_load_mode_changes_what_the_reload_predicate_answers(monkeypatch):+ """The premise behind the two recomputes below, on the real predicates.++ Both rungs take the fit's ``--load-mode none`` back out, which returns the+ child to llama.cpp's auto, and auto maps (llama-model-loader.cpp derives+ use_mmap from mmap/mmap+mlock/auto). A record still describing the pre-retry+ argv therefore says "reserves RAM" about a child that maps, and under "Don't+ reserve system RAM" that is a full model reload the running server already+ satisfies.+ """+ import utils.model_memory_settings as mm+ from core.inference.llama_cpp import _without_subsequence+ from core.inference.llama_server_args import (+ memory_state_satisfies_settings,+ resolve_effective_memory_state,+ )++ launched = ["llama-server", "-m", "m.gguf", "--load-mode", FIT_MODE, "--flash-attn", "off"]+ stripped = _without_subsequence(launched, ["--load-mode", FIT_MODE])++ stale = resolve_effective_memory_state(launched, {})+ fresh = resolve_effective_memory_state(stripped, {})+ assert stale == (False, True)+ assert fresh == (False, False)++ monkeypatch.setattr(mm, "get_keep_resident", lambda: False)+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: True)+ # The stale record is the pessimistic direction: a reload that buys nothing,+ # never a reservation left standing.+ assert memory_state_satisfies_settings(stale, True) is False+ assert memory_state_satisfies_settings(fresh, True) is True+++def test_the_recompute_reads_the_argv_not_the_managed_block():+ """Why both rungs recompute from the argv they are about to spawn.++ They descend from _last_spawn_cmd, which carries any page-lock+ _spawn_and_wait's --fit on retry appended to its own argv. Rebuilding from+ the Model Memory block instead would drop that lock and record an unlocked+ child that is in fact locked, which is the optimistic direction: no-reserve+ would read as satisfied while the reservation stands.+ """+ from core.inference.llama_cpp import _without_subsequence+ from core.inference.llama_server_args import resolve_effective_memory_state++ retried = ["llama-server", "-m", "m.gguf", "--load-mode", FIT_MODE, "--load-mode", "mmap+mlock"]+ stripped = _without_subsequence(retried, ["--load-mode", FIT_MODE])+ assert resolve_effective_memory_state(stripped, {}) == (True, False)+ # The managed block alone knows nothing about that appended lock.+ assert resolve_effective_memory_state([], {}) == (False, False)+++def test_the_no_flash_rung_recomputes_the_memory_record():+ """Reachability at the source, like the strip it sits next to: the arm only+ runs behind a real signal crash. Whitespace stripped, so a reformat that+ wraps the call cannot break the pin."""+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend as B++ src = inspect.getsource(B.load_model)+ helper = src[src.index("_drop_fit_load_mode_for_no_flash") :]+ # Bounded at the next definition, so this proves the recompute is in the+ # helper and not merely somewhere later in load_model.+ helper = helper[: helper.index("_spawn_and_wait")]+ assert "self._memory_state" in helper+ compact = "".join(helper.split())+ assert "resolve_effective_memory_state(stripped" in compact+++def test_the_cpu_projector_rung_recomputes_the_memory_record():+ """Same, for the projector respawn."""+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend as B++ src = inspect.getsource(B.load_model)+ arm = src[: src.index('"-mmproj-cpu"')]+ arm = arm[arm.rindex("_with_mmproj_offload_disabled") :]+ assert "self._memory_state" in arm+ compact = "".join(arm.split())+ assert "resolve_effective_memory_state(_stripped_cpu_projector_cmd" in compact+++def test_the_arch_crash_rung_records_from_the_argv_not_the_parts():+ """The record has to be recomputed from the stripped argv on this rung too.++ By the time the arch-crash retry strips the fit's pair, `cmd` may have been+ rebuilt as the CPU, device-gated, no-tensor-split or arch-retry argv, so+ _mem_managed + _mem_extras no longer add up to it. Rebuilding from the parts+ drops whatever those paths added, and dropping a page-lock records an+ unlocked child that is in fact locked -- the optimistic direction.+ """+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend as B+ from core.inference.llama_server_args import resolve_effective_memory_state++ # The two inputs genuinely disagree, so which one is used is observable.+ parts = ["--mlock", "--temp", "0.7"]+ argv_after_retry = ["--mlock", "--temp", "0.7", "--no-mmap"]+ assert resolve_effective_memory_state(parts, {}) != resolve_effective_memory_state(+ argv_after_retry, {}+ )++ # Reachability: single call expression, whitespace stripped, so a reformat+ # that wraps the call cannot break it.+ compact = "".join(inspect.getsource(B.load_model).split())+ assert "resolve_effective_memory_state(cmd,env)" in compact+++# ------------------ round 12: the CPU fallback is a rung that strips the loader+++def test_the_cpu_replay_and_the_launch_record_disagree(monkeypatch):+ """The premise, on the real functions rather than a hand-written argv.++ _prepare_cpu_fallback_launch takes the fit's pair out, so a record taken off+ the launch argv describes a reservation the replay does not make. Under+ "Don't reserve system RAM" that stale record is a full model reload the CPU+ server already satisfies.+ """+ from unittest import mock++ import utils.model_memory_settings as mm+ from core.inference import llama_cpp as lc+ from core.inference.llama_server_args import (+ memory_state_satisfies_settings,+ resolve_effective_memory_state,+ )++ backend = LlamaCppBackend.__new__(LlamaCppBackend)+ backend._fit_load_mode_flags = ["--load-mode", FIT_MODE]+ launched = ["llama-server", "-m", "model.gguf", "--load-mode", FIT_MODE]+ with (+ mock.patch.object(lc.LlamaCppBackend, "_is_vulkan_backend", return_value = True),+ mock.patch.object(lc.LlamaCppBackend, "_cpu_isolated_replay", return_value = list(launched)),+ mock.patch.object(lc.LlamaCppBackend, "_cpu_isolated_binary", return_value = "cpu-server"),+ mock.patch.object(+ lc.LlamaCppBackend,+ "_llama_server_env_for_binary",+ return_value = {lc._loader_path_var(): "/staged"},+ ),+ ):+ replay, _reason = backend._prepare_cpu_fallback_launch("llama-server", launched, {}, {})++ stale = resolve_effective_memory_state(launched, {})+ fresh = resolve_effective_memory_state(replay, {})+ assert stale == (False, True)+ assert fresh == (False, False)++ monkeypatch.setattr(mm, "get_keep_resident", lambda: False)+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: True)+ assert memory_state_satisfies_settings(stale, True) is False+ assert memory_state_satisfies_settings(fresh, True) is True+++def test_the_crash_path_cpu_fallback_recomputes_the_memory_record():+ """Reachability at the source, like the rungs beside it: the arm runs only+ behind a real signal crash on an auto-selected Vulkan backend.++ From _last_spawn_cmd, not from the replay handed to the spawn: that is the+ argv that really started, so a page-lock _spawn_and_wait's own --fit retry+ appended is kept rather than recorded away.+ """+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend as B++ # Whitespace stripped before slicing, so a reformat that rewraps any of it+ # cannot break the pin.+ src = "".join(inspect.getsource(B.load_model).split())+ arm = src[src.index("_try_auto_vulkan_cpu_fallback") :]+ # Bounded at the normalisation that closes the recovery, so this proves the+ # recompute is in the arm and not merely somewhere later in load_model.+ arm = arm[: arm.index("_apply_cpu_fallback_state")]+ assert "resolve_effective_memory_state(_last_spawn_cmd,env)" in arm+++def test_the_replayed_cpu_fallback_recomputes_the_memory_record():+ """Same, for a request that carries cpu_fallback and rebuilds the replay+ before anything spawns."""+ import inspect++ from core.inference.llama_cpp import LlamaCppBackend as B++ src = "".join(inspect.getsource(B.load_model).split())+ # allow_manual_cpu is what distinguishes this eligibility check from the+ # crash path's, which reads the same helper without it.+ arm = src[src.index("allow_manual_cpu=True") :]+ arm = arm[: arm.index("_apply_cpu_fallback_state")]+ assert "resolve_effective_memory_state(cmd,env)" in armdiff --git a/studio/frontend/src/features/model-picker/components/model-config-page.tsx b/studio/frontend/src/features/model-picker/components/model-config-page.tsxindex 4860345cb47..98cdb5b7cf1 100644--- a/studio/frontend/src/features/model-picker/components/model-config-page.tsx+++ b/studio/frontend/src/features/model-picker/components/model-config-page.tsx@@ -1003,12 +1003,15 @@ function LoadModeRow({<div className="flex min-w-0 items-center gap-1.5"><span className={LABEL_CLASS}>Mmap/Mlock</span><InfoHint>- How the weights are read off disk (--load-mode). Auto memory-maps- unless a device cannot, which is the default. mmap forces the- mapping, mlock keeps the model in RAM rather than letting it swap or- compress, mmap+mlock does both, DirectIO streams the file where the- platform supports it, and None asks for no special mode. Model- Memory, in Settings, owns this when either of its toggles is on.+ How the weights are read off disk (--load-mode). Auto is the+ default: Unsloth picks None when it can prove the model fits without+ paging, since a mapped read is slower, and otherwise leaves the+ choice to llama.cpp, which memory-maps unless a device cannot. mmap+ forces the mapping, mlock keeps the model in RAM rather than letting+ it swap or compress, mmap+mlock does both, DirectIO streams the file+ where the platform supports it, and None asks for no special mode.+ Model Memory, in Settings, owns this when either of its toggles is+ on.</InfoHint></div><Selectdiff --git a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts b/studio/frontend/src/features/model-picker/model-config/per-model-config.tsindex 02c261e9e3c..06ee7cda1ea 100644--- a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts+++ b/studio/frontend/src/features/model-picker/model-config/per-model-config.ts@@ -29,8 +29,8 @@ export interface PerModelConfig {nParallel: number | null;nBatch: number | null;nUbatch: number | null;- /** --load-mode; null follows llama.cpp's own `auto`, so a build that redefines- * auto is followed rather than pinned. */+ /** --load-mode; null lets the fit decide: `none` when the load fits in VRAM+ * (or VRAM plus host RAM), else no flag. Any value set here wins. */loadMode?: string | null;/** --ctx-checkpoints; null follows the llama.cpp default (32). */ctxCheckpoints?: number | null;@@ -174,9 +174,9 @@ export const KV_CACHE_DTYPES = [export const MLX_KV_BITS: readonly number[] = [8, 6, 5, 4, 3, 2];const VALID_KV_CACHE_DTYPES = new Set<string>(KV_CACHE_DTYPES);-// llama-server's --load-mode enum, in --help order. "auto" is both a real value-// and the default, so the UI shows it while storage keeps null: emitting nothing-// follows whatever auto means in the build that runs.+// llama-server's --load-mode enum, in --help order. "auto" is the default: the UI+// shows it, storage keeps null and the backend emits no flag, so the fit may pick+// "none". Never sent verbatim; builds like b10360 reject "auto" as a value.export const LOAD_MODES = ["auto","none",