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: spill weights with -ot instead of layers, so the KV cache stays on the GPU (#9675)
Daniel Hanba34b8f70bb3
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 88a425dee0e..aed62b460da 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -61,9 +61,12 @@ from core.inference.context_window import ()from core.inference.stream_errors import stream_error_from_chunkfrom core.inference.llama_server_args import (+ _DEVICE_FLAGS,_GPU_LAYER_FLAGS,_LAYER_OFFLOAD_FLAGS,_MOE_OFFLOAD_FLAGS,+ _SPLIT_MODE_FLAGS,+ _TENSOR_SPLIT_FLAGS,_effective_tensor_parallel,_flag_name,_tensor_parallel_matches_loaded,@@ -4387,6 +4390,37 @@ def _emitted_n_batch(n_batch: Optional[int], n_parallel: int) -> Optional[int]:return max(int(n_batch), max(2, int(n_parallel or 1)))+def _extra_args_n_parallel(+ extra_args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None+) -> Optional[int]:+ """Serving slots a pass-through overrides to, or None when nothing does.++ Same precedence as the launched command line: extras are appended last+ (llama_cpp.py emits Studio's --parallel first), and llama.cpp is last-wins,+ so an extras value beats both the emitted flag and the env. 0 is rejected at+ parse time on the server path, so it is not a value anyone gets.+ """+ source_env = os.environ if env is None else env+ found: Optional[int] = None+ raw = source_env.get("LLAMA_ARG_N_PARALLEL")+ if raw:+ try:+ found = int(str(raw).strip())+ except (TypeError, ValueError):+ pass+ args = [str(a) for a in extra_args] if extra_args else []+ for i, arg in enumerate(args):+ name, _, inline = arg.partition("=")+ if name not in ("-np", "--parallel"):+ continue+ value = inline if inline else (args[i + 1] if i + 1 < len(args) else "")+ try:+ found = int(value.strip())+ except (TypeError, ValueError):+ continue+ return found++def _extra_args_n_ubatch(extra_args: Optional[Iterable[str]],env: Optional[Mapping[str, str]] = None,@@ -5006,6 +5040,9 @@ class LlamaCppBackend:# Relative model share per GPU (--tensor-split), in GPU order; None =# default (llama.cpp splits by free VRAM).self._tensor_split: Optional[List[float]] = None+ # Tokens the tensor-spill plan added to this argv, so a retry that re-places+ # the model can strip them with _without_subsequence. Empty when it abstained.+ self._spill_plan_flags: List[str] = []# Ratio the arch gate dropped from this argv, so the duplicate-load check# knows the live server already IS this request normalized (#7624).self._arch_gate_dropped_tensor_split: Optional[tuple[float, ...]] = None@@ -11883,6 +11920,7 @@ class LlamaCppBackend:self._diffusion_requested_ngl = _diffusion_manual_ngl(gpu_memory_mode, gpu_layers)self._n_cpu_moe = 0self._tensor_split = None+ self._spill_plan_flags = []# Diffusion is never tensor-parallel; clear any state left by a prior TP# chat load (load_model phase 1 only kills the process, it doesn't run# the unload reset) so /status doesn't misreport TP and an identical@@ -16730,6 +16768,12 @@ class LlamaCppBackend:# from the default unless the verdict is recorded on its own.# Bound before the try for the same reason as _detected_gpus._placement_verdict_partial = False+ # Sized inputs for the tensor-spill planner, None when the fit never+ # priced them. Bound before the try like _placement_verdict_partial:+ # the except arm restores use_fit=True without rebinding+ # kv_cache_bytes, so reading it from the spill arm would be an+ # UnboundLocalError on the path that reaches it most often.+ _spill_inputs: Optional[dict] = Nonetotal_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@@ -18731,6 +18775,61 @@ class LlamaCppBackend:)kv_cache_bytes = _kv_bytes(effective_ctx)+ # Everything the spill planner needs, snapshotted as plain ints+ # where it is already evaluated.+ _spill_inputs = {+ "model_size": model_size,+ "kv_cache_bytes": kv_cache_bytes,+ "gpus": list(gpus or ()),+ # The budget the fit above tested, per device: _gpu_usable+ # applies the VRAM-budget fraction and the reserve floor.+ # Raw free_mib is 3.5 GiB per card larger at 0.80 on a+ # 24 GiB card, so planning on it under-spills and then pins+ # the result with --fit off.+ "gpu_usable_mib": {+ _idx: max(0.0, _gpu_usable((_idx, _free)))+ for _idx, _free in (gpus or ())+ },+ "gpu_indices": gpu_indices,+ "soft_overhead": _soft_overhead,+ # GPU-resident bytes in model_size_fit the planner cannot+ # see: it rebuilds from the target GGUF's tensor table, so+ # the projector and MTP reserve are absent from its deficit.+ "extra_gpu_bytes": (mmproj_size + _shared_pool_mmproj + _mtp_reserve_bytes),+ # The compute buffer, charged on the same terms as the fit+ # that produced the use_fit verdict: model_size_fit carries+ # the flat _compute_buffer_pipeline IN ADDITION to+ # _soft_overhead, and the fit adds _cc_bytes(ctx) per device+ # on top, so there is no double charge. Omitting them is not+ # conservative -- _cc_bytes is context-linear (tens of GiB+ # on deepseek4 at 1M, ~2.4 GiB on a quantised cache at 128K)+ # and the plan is pinned with --fit off, so the shortfall is+ # a graph_reserve OOM with nothing left to catch it.+ "compute_buffer_flat": int(_compute_buffer_pipeline),+ "ctx_compute_per_device": (+ _cc_bytes(effective_ctx, max(1, len(gpus or ())))+ // max(1, len(gpus or ()))+ ),+ # An engaging draft turns the trailing nextn/MTP blocks from+ # skipped bytes into resident ones in the TARGET's load, so+ # charge them back. Any engaged draft counts: load_mtp comes+ # from the spec type (common/common.cpp:1713), and a+ # separate drafter that is itself an MTP head selects that+ # same type (common/speculative.cpp:2257-2261).+ # Over-charging only spills more.+ "mtp_will_engage": bool(_mtp_will_engage),+ # The planner reads the real tensor table, not a bucket+ # total, so it can spill the MINIMUM set of blocks.+ "model_path": model_path,+ "n_ctx": effective_ctx,+ # The slot count the KV and recurrent state were PRICED at.+ # A pass-through --parallel is appended after Studio's own+ # and wins, and both caches scale with it.+ "n_parallel": int(n_parallel or 1),+ # An iGPU or APU reports host RAM as VRAM: crediting it and+ # then "spilling" into that pool counts one memory twice.+ "shared_gpu_ids": set(_shared_gpu_ids or ()),+ }mmproj_note = (f"mmproj: {mmproj_size / (1024**3):.1f} GB, " if mmproj_size else "")@@ -19258,7 +19357,32 @@ class LlamaCppBackend:# don't report it as active via /status and /load.self._tensor_split = Noneelif use_fit:- cmd.extend(["--fit", "on"])+ # Studio could not prove a fit, so llama.cpp's fitter takes the+ # placement. Its dense path fills "back to front with dense+ # layers" (common/fit.cpp:402), i.e. WHOLE layers, and a layer+ # takes its KV cache with it because the cache buffer comes+ # from model.dev_layer(il) (llama-kv-cache.cpp:215). Spilling+ # weight TENSORS instead leaves the cache resident: measured on+ # a 27B at 128K, 13.63 t/s resident against 1.03 t/s evicted.+ _spill = self._planned_tensor_spill(+ _spill_inputs,+ extra_args = extra_args,+ env = os.environ,+ )+ # NOT `if _spill:` -- Plan is a dataclass, so every instance is+ # truthy, including ones saying it could not place this at all.+ _spill_flags = self._spill_plan_flags_for(_spill)+ if _spill_flags:+ self._spill_plan_flags = _spill_flags+ cmd.extend(self._spill_plan_flags)+ logger.info(+ "Tensor spill: %s (resident %.1f GB, host %.1f GB)",+ " ".join(_spill.ot_patterns),+ _spill.vram_bytes / (1024**3),+ _spill.host_bytes / (1024**3),+ )+ else:+ cmd.extend(["--fit", "on"])elif gpu_indices is not None:# Fits on selected GPU(s) -- force all layers on GPU. --fit off is# required: without it llama.cpp's default --fit on second-guesses@@ -20553,6 +20677,13 @@ class LlamaCppBackend:# page-lock and writes it back, which without this makes the# read below an UnboundLocalError instead.nonlocal _last_spawn_cmd, _mem_host_resident, _did_rocm_retry+ # One revocation point for the tensor-spill plan instead of a+ # strip per retry site. `label` is empty ONLY on the first+ # spawn, so a retry added later is covered automatically. The+ # plan's arithmetic assumed this launch's devices, cache dtype+ # and projector placement, and each retry changes one of them.+ if label:+ run_cmd = self._drop_tensor_spill(run_cmd, label.lstrip("-") or "retry")_fit_retry_allowed = self._fit_off_retry_eligible(run_cmd, use_fit)_did_fit_retry = Falsefor _spawn_attempt in (0, 1, 2):@@ -20661,6 +20792,37 @@ class LlamaCppBackend:env["LD_LIBRARY_PATH"] = _retry_ld_did_rocm_retry = Truecontinue+ if (+ not _did_fit_retry+ and _startup_crashed+ and not _tensor_capability_crash+ and not _hip_rocr_mismatch+ ):+ # A spill-planned launch that crashed on startup. The+ # two recoveries below cannot reach it: the spill arm+ # leaves fully_gpu_offloaded False and runs under+ # use_fit=True with an explicit --fit, so+ # _fit_off_retry_eligible is False on both counts and+ # the load would skip to the terminal/CPU fallbacks+ # even though the --fit on placement it replaced would+ # have worked. A crash means the prediction was wrong,+ # so hand placement back to llama.cpp. Self-gating:+ # _drop_tensor_spill returns run_cmd unchanged when no+ # plan is present.+ _reverted = self._drop_tensor_spill(run_cmd, "startup failure")+ if _reverted != run_cmd:+ logger.warning(+ "llama-server crashed during startup (exit code %s) "+ "with a tensor-spill plan; the plan was optimistic, "+ "retrying once with --fit on so llama.cpp can place "+ "the model itself. Crash log: %s",+ self._process.returncode,+ self._llama_log_path,+ )+ run_cmd = _reverted+ self._memory_state = resolve_effective_memory_state(run_cmd, env)+ _did_fit_retry = True+ continueif (not _did_fit_retryand fully_gpu_offloaded@@ -23387,6 +23549,314 @@ class LlamaCppBackend:finally:logging.raiseExceptions = raise_exceptions+ def _planned_tensor_spill(+ self,+ inputs: Optional[dict],+ *,+ extra_args: Optional[Iterable[str]] = None,+ env: Optional[Mapping[str, str]] = None,+ ) -> "Optional[SpillPlan]":+ """A ``-ot`` spill plan for a load Studio could not fit, or None to abstain.++ Abstaining reproduces today's ``--fit on`` byte for byte, so every+ uncertain input abstains rather than guessing. That is the whole safety+ argument: the only behaviour that changes is the case where a plan was+ produced, and a plan is only produced when the numbers are known.++ The planner must NOT run when anything else owns placement. Pricing a+ placement the child will not actually get is the single bug class behind+ most of the review traffic on the load-mode work, and the cheap way to+ avoid it is to decline rather than to model the override.+ """+ from core.inference.offload_cost_model import HostProfile+ from core.inference.offload_planner import (+ PlanOptions,+ plan_placement,+ smart_offload_enabled,+ )++ source_env = os.environ if env is None else env+ if not smart_offload_enabled(source_env) or not inputs:+ return None++ # Unified memory: spilling moves bytes inside one pool, so the trade does+ # not exist. Metal also keeps mmap zero copy via buffer_from_host_ptr.+ from utils.hardware import is_apple_silicon++ if is_apple_silicon():+ return None++ # Someone else owns the placement -- decline. Each of these re-places the+ # model out from under a plan made here: -ot / --cpu-moe (or its env twin)+ # already moves tensors, a layer count overrides -ngl -1, a device list+ # changes which cards the resident half was sized against.+ if (+ _args_place_tensors_on_cpu(extra_args)+ or _env_places_tensors_on_cpu(source_env)+ or _extra_args_set_any_flag(extra_args, _GPU_LAYER_FLAGS)+ or str(source_env.get("LLAMA_ARG_N_GPU_LAYERS", "")).strip()+ or _extra_args_set_any_flag(extra_args, _DEVICE_FLAGS)+ or str(source_env.get("LLAMA_ARG_DEVICE", "")).strip()+ # A pinned DRAFT device is placement too and is not in _DEVICE_FLAGS.+ # Its reserve rides in extra_resident_bytes, which+ # _per_device_shortfall books onto device 0, while llama.cpp puts the+ # drafter on the pinned card -- approving a footprint for the wrong+ # device, then pinning it with --fit off. cpu/none are not a pin.+ or _extra_args_draft_device_pin(extra_args)+ # Split mode and tensor split are placement too and are NOT in+ # _DEVICE_FLAGS. Both pass through to the child and extras are appended+ # last, so they win. -sm none truncates model->devices to the single+ # main GPU (llama.cpp:288-299) while this planner credits the SUM of+ # every selected card, sizing a plan against a pool the child never+ # gets. -ts replaces the free-memory proportional split+ # (llama-model.cpp:1417-1447), so one device can overflow while the+ # pool total still fits.+ or _extra_args_set_any_flag(extra_args, _SPLIT_MODE_FLAGS)+ or _extra_args_set_any_flag(extra_args, _TENSOR_SPLIT_FLAGS)+ or str(source_env.get("LLAMA_ARG_SPLIT_MODE", "")).strip()+ or str(source_env.get("LLAMA_ARG_TENSOR_SPLIT", "")).strip()+ # ANY explicit --fit, not just an enabling one. A retry revokes the+ # plan by appending "--fit on", and extras are appended BEFORE that,+ # so planning over a user's "--fit off" would let the revocation+ # silently overturn it. Same test _fit_off_retry_eligible uses.+ or any(+ str(a) in ("-fit", "--fit") or str(a).startswith(("-fit=", "--fit="))+ for a in (extra_args or ())+ )+ or str(source_env.get("LLAMA_ARG_FIT", "")).strip()+ # KV placement is placement too. -nkvo (or a false LLAMA_ARG_KV_OFFLOAD)+ # sends the WHOLE cache to host RAM whatever -ngl says: offload is one+ # scalar and the buft falls back to ggml_backend_cpu_buffer_type() for+ # every layer (llama-kv-cache.cpp:210-219), same branch in the recurrent+ # and DSV4 caches. This planner charges the cache against VRAM+ # (kv_bytes_floor below), so it would spill FFN blocks for a deficit the+ # child never has. --fit on measures buffer types instead of modelling+ # them and books a host-resident cache into the host bucket+ # (common/fit.cpp:74-79), which the per-device loop then ignores+ # (common/fit.cpp:326-347).+ or not _kv_offload_from_args(extra_args, env = source_env)+ ):+ logger.debug("Tensor spill: declined, pass-through arguments own the placement")+ return None++ # Slots are SIZING, not placement, and these numbers were priced at Studio's+ # own --parallel. A pass-through is appended after it and llama.cpp is+ # last-wins, so a larger one grows the attention cache and the recurrent+ # state under a deficit computed for the smaller count. Only larger matters:+ # a smaller value leaves the plan over-reserved, the safe direction.+ priced_parallel = int(inputs.get("n_parallel") or 1)+ override_parallel = _extra_args_n_parallel(extra_args, source_env)+ if override_parallel is not None and override_parallel > priced_parallel:+ logger.debug(+ "Tensor spill: declined, --parallel %d overrides the %d slots this was priced at",+ override_parallel,+ priced_parallel,+ )+ return None++ model_size = int(inputs.get("model_size") or 0)+ kv_cache_bytes = int(inputs.get("kv_cache_bytes") or 0)+ rows = list(inputs.get("gpus") or ())+ if not model_size or not kv_cache_bytes or not rows:+ return None+ if not self._can_estimate_kv():+ return None++ layout = self._tensor_spill_layout(inputs.get("model_path"))+ if layout is None or not layout.complete:+ return None++ # Per-device VRAM the planner may credit. SHARED rows are dropped, not+ # summed: an APU or iGPU reports host RAM as VRAM, so crediting it and then+ # spilling into the same RAM counts one pool twice.+ pinned = inputs.get("gpu_indices")+ shared = set(inputs.get("shared_gpu_ids") or ())+ pinned_set = None if pinned is None else set(pinned)+ # Dropping a shared device from the BUDGET only helps if the child stops+ # using it, and nothing here can promise that: the auto-Vulkan arm pins+ # every DETECTED gpu, iGPU included, and runs after this snapshot (so+ # gpu_indices reads None here); with no --device the child sees every card+ # anyway. llama.cpp splits rows by free memory and an iGPU's "free" is the+ # whole host pool, so it draws the MAJORITY of the layers and their caches+ # -- the opposite of this planner's premise. Decline instead.+ if shared and (pinned_set is None or (shared & pinned_set)):+ logger.debug(+ "Tensor spill: declined, a shared-memory GPU stays in the child's device list"+ )+ return None+ # The USABLE budget Studio's fit tested, not raw free: it carries the+ # VRAM-budget fraction and the per-card reserve floor. Falling back to free+ # keeps a caller that supplies no map working.+ usable_mib = inputs.get("gpu_usable_mib") or {}+ kept = [+ (idx, free_mib)+ for idx, free_mib in rows+ if idx not in shared and (pinned_set is None or idx in pinned_set)+ ]+ vram_per_device = [+ int(usable_mib.get(idx, free_mib) * 1024 * 1024) for idx, free_mib in kept+ ]+ # llama.cpp sizes its row ranges from RAW free VRAM (llama-model.cpp:1433),+ # so the split must be modelled on the raw numbers. The budget subtracts a+ # reserve that depends on each card's TOTAL, preserving the ratios only when+ # every card has the same free/total. Same filter and order as above, so+ # index i means the same device in both lists.+ split_weights = [int(free_mib * 1024 * 1024) for _idx, free_mib in kept]+ if not vram_per_device:+ return None+ avail_mib = self._available_system_memory_mib()+ if avail_mib is None:+ return None++ # The trailing nextn/MTP blocks the layout dropped, charged back when a+ # draft will engage. Studio's budget already assumed they were paid for (an+ # embedded head contributes 0 to _mtp_draft_weights because its weights sit+ # inside model_size), but the planner rebuilds from the tensor table, where+ # they are gone -- leaving the deficit short by the whole MTP head.+ extra_gpu_bytes = int(inputs.get("extra_gpu_bytes") or 0)+ if inputs.get("mtp_will_engage") and layout.excluded_block_bytes:+ extra_gpu_bytes += layout.excluded_block_bytes++ # The compute buffer, on the same terms as the fit that sent us here:+ # ctx_compute is per device, compute_buffer_flat is one lump charged once+ # against the pool and booked onto device 0, where it lives.+ extra_gpu_bytes += int(inputs.get("compute_buffer_flat") or 0)++ return plan_placement(+ layout,+ vram_per_device,+ avail_mib * 1024 * 1024,+ int(inputs.get("n_ctx") or 0),+ split_weights_per_device = split_weights,+ opts = PlanOptions(+ overhead_bytes_per_device = (+ int(inputs.get("soft_overhead") or 0)+ + self._PIPELINE_PER_DEVICE_OVERHEAD_MIB * 1024 * 1024+ + int(inputs.get("ctx_compute_per_device") or 0)+ ),+ host_ram_headroom_bytes = self._HOST_RAM_HEADROOM_MIB * 1024 * 1024,+ # GPU-resident allocations the layout cannot see, since it is built+ # from the target GGUF alone: the vision projector and the MTP draft+ # reserve. Both are in the footprint that produced the use_fit+ # verdict, so omitting them makes the deficit too small.+ extra_resident_bytes = extra_gpu_bytes,+ # Spilled decode runs on the CPU backend (ggml migrates an op to the+ # GPU only at batch >= 32, and decode is batch 1), so the penalty+ # tracks core count. Read the real one, not a default.+ host = HostProfile(+ threads = os.cpu_count() or 1,+ # Wired, not defaulted. On a unified-memory APU the credited+ # "VRAM" IS system RAM, so an -ot spill frees no device memory+ # and only buys the CPU backend's slower read path. The planner+ # abstains on those, but only if told: left at False it would+ # plan a spill on every Strix Halo (gfx1151), Strix Point+ # (gfx1150), Krackan (gfx1152) and Phoenix iGPU. Studio already+ # classifies these from the driver's integrated flag, then+ # gcnArchName, then the device-name substrings.+ unified_memory = self._amd_apu_wants_unified_memory(inputs.get("gpu_indices")),+ ),+ ),+ # The cache Studio already priced for THIS launch, byte-accurately:+ # cache dtype, SWA windows, MLA latents, unified vs per-slot streams,+ # cell padding and flash-attention V padding. layout.kv_bytes() is a+ # bare f16 GQA product with none of those, so on an MLA or f32-cache+ # load it lands well UNDER the real cache. A floor, not a replacement,+ # so the layout still wins where it is the more conservative.+ kv_bytes_floor = kv_cache_bytes,+ )++ @staticmethod+ def _spill_plan_flags_for(plan: "Optional[SpillPlan]") -> "list[str]":+ """The argv tokens for ``plan``, or ``[]`` when it must not be emitted.++ The emptiness test is the point. ``Plan`` is a dataclass with no+ ``__bool__``/``__len__``, so EVERY instance is truthy -- including the+ ones ``plan_placement`` returns to report that it could not place the+ load (``insufficient``), that it abstained (incomplete layout, unified+ memory, no creditable VRAM), or that the load already fits. Emitting for+ those would append ``-ngl -1 --fit off`` with no tensor moved to the+ host, i.e. pin every layer to the GPU and switch the fitter off on+ exactly the loads the planner just said do not fit. Only a plan that+ actually spills something earns the flags; everything else falls through+ to ``--fit on``, which is what this arm did before the planner existed.++ One flag per pattern: llama-server ACCUMULATES repeated ``-ot``+ (common/arg.cpp:2657 push_backs into the shared override vector). Do not+ join with ";" -- that is llama-bench's separator; llama-server splits an+ ``-ot`` value on ",".++ ``--fit off`` is REQUIRED, not tidiness. The fitter aborts only on an+ n_gpu_layers the USER set (common/fit.cpp:377) and -1 is llama.cpp's own+ default (llama-model.cpp:2453), so ``-ngl -1`` does not hold it off: left+ on, it would re-place layers over this plan and put the cache back on the+ host. ``-ngl -1`` keeps every layer assigned to a GPU so the cache stays+ there (llama-kv-cache.cpp:215); the ``-ot`` patterns move only the named+ weights.+ """+ if plan is None or not plan.spills_anything:+ return []+ tokens = [tok for pat in plan.ot_patterns for tok in ("-ot", f"{pat}=CPU")]+ if not tokens:+ return []+ return ["-ngl", "-1", "--fit", "off", *tokens]++ def _drop_tensor_spill(self, run_cmd: "list[str]", why: str) -> "list[str]":+ """Take the spill plan back out of an argv and restore ``--fit on``.++ Every retry that re-places the model or resizes the cache invalidates the+ arithmetic the plan was built on: a no-flash retry changes the KV dtype, an+ arch fallback changes the device set, a projector move changes the resident+ floor. Rather than re-plan on a path that is already recovering from a+ crash, hand the placement back to llama.cpp, which is what this arm did+ before the planner existed.++ The record is deliberately NOT cleared: the CPU fallback respawns later+ from an argv that may still carry these tokens.+ """+ if not self._spill_plan_flags:+ return run_cmd+ stripped = _without_subsequence(run_cmd, self._spill_plan_flags)+ if stripped == run_cmd:+ return run_cmd+ logger.info("Tensor spill: dropping the plan for the %s retry; %s", why, "using --fit on")+ return [*stripped, "--fit", "on"]++ def _tensor_spill_layout(self, model_path: "Optional[str]") -> "Optional[ModelLayout]":+ """The GGUF's placement buckets, read once per path and cached.++ Per BLOCK, not per bucket total, so the planner can spill the minimum set+ that closes the deficit rather than the whole FFN. That matters: the spill+ penalty is linear in bytes (measured 5.544 ms/GiB across 16/32/48/65+ blocks, intercept -0.10 ms), so every byte spilled beyond the deficit is+ paid on every token for nothing.++ Any read failure returns None and the whole feature abstains, leaving the+ argv byte-identical to today. A guess here would be priced as a fit.+ """+ from core.inference.offload_layout import layout_from_gguf++ if not model_path:+ return None+ # Keyed on file IDENTITY, not name: the backend outlives a load, so+ # re-downloading or re-quantising to the same path would otherwise plan+ # against the OLD tensor table and understate the deficit. Same+ # (size, mtime_ns) stat identity _slot_launch_fingerprint uses.+ try:+ st = os.stat(model_path)+ key = (model_path, st.st_size, st.st_mtime_ns)+ except OSError:+ key = (model_path, None, None)+ cached = getattr(self, "_spill_layout_cache", None)+ if cached is not None and cached[0] == key:+ return cached[1]+ try:+ layout = layout_from_gguf(model_path)+ except Exception as e: # unreadable, truncated, or an arch we cannot bucket+ logger.debug("Tensor spill: cannot read layout from %s (%s)", model_path, e)+ layout = None+ self._spill_layout_cache = (key, layout)+ return layout+@staticmethoddef _fit_off_retry_eligible(cmd: "list[str]", use_fit: bool) -> bool:"""Whether a llama-server startup crash may be retried with --fit off.diff --git a/studio/backend/core/inference/offload_cost_model.py b/studio/backend/core/inference/offload_cost_model.pynew file mode 100644index 00000000000..9183ce3bc97--- /dev/null+++ b/studio/backend/core/inference/offload_cost_model.py@@ -0,0 +1,273 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Relative throughput of a candidate offload placement.++The planner needs to RANK placements, not predict absolute t/s. So this models+the marginal cost of moving a tensor group off the GPU, in milliseconds per+token, and leaves the resident baseline as a free parameter the caller supplies+or ignores.++Two regimes, measured separately because they have different mechanisms:++``generation``+ One token at a time. Host-resident weights are computed by the CPU backend,+ NOT streamed to the GPU. Measured directly: with the dense FFN spilled,+ generation scales with thread count (2.42 / 5.83 / 11.82 t/s at 4 / 16 / 64+ threads) while a fully resident run does not move at all (87.30 vs 87.31 at+ 4 vs 64). So the cost scales with the HOST's compute and memory bandwidth,+ not with the PCIe generation.++``prefill``+ A whole ubatch at once. ggml's scheduler sends the large GEMM to the GPU and+ copies the weights in, so this regime IS link-bound, and it reads the FULL+ tensor rather than only the activated slice.++The distinction matters most for MoE: generation touches ``n_used / n_expert``+of the expert weights per token, but a 512-token prefill ubatch touches+essentially all of them. MoE therefore tolerates spilling far better than a+dense model during generation and slightly WORSE during prefill.++Calibration is in ``_RATE_RATIOS`` and comes from the measurements in+``plans/impl_planner_cost.md``. Rates are expressed as multiples of the+contiguous-weight rate, because ratios transfer across machines much better than+absolute milliseconds do.+"""++from __future__ import annotations++from dataclasses import dataclass, field+from enum import Enum++GIB = float(1024**3)++# Reference host (192 cores, one B200), dense FFN spilled in 16/32/48/65-block+# steps: least-squares fit gives 5.544 ms per GiB, intercept -0.10 ms. The+# near-zero intercept means partial spilling is LINEAR, so spill the minimum.+REFERENCE_CONTIGUOUS_MS_PER_GIB = 5.544++# Reference host thread count the rate above was measured at.+REFERENCE_HOST_THREADS = 192++# Generation penalty vs threads, ms per GiB = a / threads + b. Least squares over+# 39.81 / 15.86 / 7.248 / 5.498 ms per GiB at 4 / 16 / 64 / 192 threads (full+# dense FFN spilled) gives a = 138.4, b = 5.57, every point within 14%. Amdahl,+# not a power law: ``a`` is the CPU backend's parallel quantised matmul, ``b`` the+# floor (host bandwidth, graph-split sync, non-overlapping GPU work), so 4x the+# cores buys much less than 4x the speed.+_THREAD_PARALLEL_MS_PER_GIB = 138.4+_THREAD_SERIAL_MS_PER_GIB = 5.57++# The fit above varies threads on ONE machine; across DIFFERENT machines the+# slope is steeper (12 cloud vCPUs are ~6 physical cores on one memory+# controller). Least squares over dense Q4 on 12 and 48 vCPU hosts (24.21 and+# 6.82 ms per GiB) gives a = 278.2, b = 1.03. Neither fit dominates -- at 192+# threads cross-machine predicts 2.48 vs 5.498 measured, at 12 one-machine+# predicts 17.1 vs 24.21 -- so take whichever is MORE expensive: optimism quotes+# a spill that runs several times slower than promised.+_CROSS_HOST_PARALLEL_MS_PER_GIB = 278.2+_CROSS_HOST_SERIAL_MS_PER_GIB = 1.03++# Residual model/measured over 70 runs on T4, L4, A100 and RTX PRO 6000 (2, 8,+# 12, 48 vCPU), Qwen3.8-27B and Qwen3.6-35B-A3B at Q2_K_XL / Q4_K_XL / Q8_K_XL:+# medians 1.09 (48 cpu), 0.59 (12), 0.24 (8), 0.24 (2).+#+# One case stays materially under-priced: DENSE Q2_K on a very small host. Cost+# per spilled GiB tracks dequant complexity, not byte count -- at 12 vCPU Q2_K+# 84.17, Q4_K 24.21, Q8 19.96 ms per GiB (Q8 cheapest despite being largest),+# compressing to 8.70 / 6.82 / 6.29 at 48 vCPU. A quant multiplier would itself+# move with core count (3.5x at 12 vCPU, 1.3x at 48), so fitting it from two core+# counts would be overfitting. Left unmodelled deliberately.+++class Access(str, Enum):+ """How a tensor group is read, which sets its cost per byte."""++ #: Dense FFN: large contiguous matmuls, best case for the CPU backend.+ CONTIGUOUS = "contiguous"+ #: lm_head: one tall matvec, usually higher-bit. Parallelises worse than 64+ #: independent FFN blocks and dequantises more bytes per output element.+ SINGLE_MATVEC = "single_matvec"+ #: MoE experts: 8-of-256 scattered small matmuls per layer per token.+ SCATTERED = "scattered"+ #: The attention cache. By far the worst thing to move off the device.+ KV_CACHE = "kv_cache"+++# Cost per activated byte, relative to CONTIGUOUS. Derived in the plan doc:+# lm_head 10.51 / 5.955 = 1.77; MoE expert 14.80 / 5.955 = 2.49+# KV cache 119.7 / 5.955 = 20.1 (20.4 from 121.2 on a structurally different+# model -- agreeing to 1.3%, the strongest single calibration point here)+_RATE_RATIOS: dict[Access, float] = {+ Access.CONTIGUOUS: 1.00,+ Access.SINGLE_MATVEC: 1.77,+ Access.SCATTERED: 2.49,+ Access.KV_CACHE: 20.1,+}++# Prefill streaming bandwidth, GiB/s. Bracketed by the two measurements (dense+# 49.4, MoE 66.9); that spread is why this is a coarse constant, not a curve.+PREFILL_STREAM_GIB_S = 55.0++# Spilling several groups costs MORE than the sum of each alone -- contention,+# not amortisation. Measured 6% for the dense FFN + lm_head pair. The "costs are+# sub-additive" reading compares throughput percentages instead of times.+MULTI_GROUP_CONTENTION = 0.06+++@dataclass(frozen = True)+class TensorGroup:+ """A set of weights the planner can place as a unit."""++ name: str+ bytes_total: int+ access: Access+ #: Fraction of ``bytes_total`` read per token during GENERATION. 1.0 for+ #: dense weights; ``n_expert_used / n_expert`` for MoE experts.+ activation_fraction: float = 1.0++ @property+ def activated_bytes(self) -> int:+ return int(self.bytes_total * self.activation_fraction)+++@dataclass(frozen = True)+class HostProfile:+ """What the host can bring to bear on CPU-resident weights.++ ``threads`` is the honest knob. Generation cost scales with it (measured+ 2.42 / 5.83 / 11.82 t/s at 4 / 16 / 64), with diminishing returns as the+ memory subsystem saturates, which ``thread_scaling_exponent`` captures.+ """++ threads: int = REFERENCE_HOST_THREADS+ #: Set for unified-memory hosts (Apple Silicon, AMD APU, Vulkan iGPU) where+ #: "spilling" moves nothing, because the two pools are one pool.+ unified_memory: bool = False++ @property+ def generation_slowdown(self) -> float:+ """How much slower than the reference host this one is per host byte."""+ if self.threads <= 0:+ return 1.0++ def rate(threads: float) -> float:+ """ms per GiB, taking whichever fit is more expensive at this size.++ The two fits cross: the one-machine sweep wins at large thread+ counts, the cross-machine one at small. Taking the max keeps the+ reference host's own validated numbers while refusing to quote a+ small host the throughput of a server.+ """+ return max(+ _THREAD_PARALLEL_MS_PER_GIB / threads + _THREAD_SERIAL_MS_PER_GIB,+ _CROSS_HOST_PARALLEL_MS_PER_GIB / threads + _CROSS_HOST_SERIAL_MS_PER_GIB,+ )++ return rate(float(self.threads)) / rate(float(REFERENCE_HOST_THREADS))+++@dataclass+class Placement:+ """A candidate: which groups sit in host memory, and where the cache is."""++ host_groups: list[TensorGroup] = field(default_factory = list)+ #: Bytes of attention cache forced to host RAM. Only ``--no-kv-offload``+ #: puts anything here; ``-ot`` leaves it resident, ``-ngl`` drags it off.+ kv_host_bytes: int = 0+++def generation_penalty_ms(placement: Placement, host: HostProfile | None = None) -> float:+ """Extra milliseconds per generated token, versus everything resident.++ Additive in TIME across groups, plus a contention term when more than one+ group is spilled. Returns 0.0 for a fully resident placement, and for any+ placement on a unified-memory host, where moving a tensor between "VRAM"+ and "RAM" does not change which chips hold it.+ """+ host = host or HostProfile()+ if host.unified_memory:+ return 0.0++ groups = list(placement.host_groups)+ per_group = [+ (g.activated_bytes / GIB) * REFERENCE_CONTIGUOUS_MS_PER_GIB * _RATE_RATIOS[g.access]+ for g in groups+ ]+ if placement.kv_host_bytes > 0:+ per_group.append(+ (placement.kv_host_bytes / GIB)+ * REFERENCE_CONTIGUOUS_MS_PER_GIB+ * _RATE_RATIOS[Access.KV_CACHE]+ )++ total = sum(per_group)+ if len([c for c in per_group if c > 0.0]) > 1:+ total *= 1.0 + MULTI_GROUP_CONTENTION+ return total * host.generation_slowdown+++def prefill_penalty_ms_per_token(+ placement: Placement,+ n_ubatch: int = 512,+ host: HostProfile | None = None,+) -> float:+ """Extra milliseconds per PROMPT token during prefill.++ Uses FULL bytes, not activated bytes: a 512-token ubatch selects+ essentially every expert at least once, so sparsity buys nothing here. This+ is the term that makes MoE's prefill penalty WORSE than a dense model's even+ though its generation penalty is much better.++ The weights are copied once per ubatch and reused across every token in it,+ so the per-token cost falls as ``n_ubatch`` rises -- the amortisation that+ makes prefill so much cheaper than generation per byte moved.++ ``host`` is accepted and used only for ``unified_memory``: this regime runs+ on the GPU with the weights copied in, so it is bound by the link and NOT by+ host cores. That asymmetry against generation is the point, so callers pass+ the same profile to both and let each use what applies.+ """+ host = host or HostProfile()+ if host.unified_memory:+ return 0.0+ # kv_host_bytes counts here too: leaving it out made a cache-offloaded+ # placement prefill FOR FREE while generation_penalty_ms charged it.+ # UNCALIBRATED lower bound -- counts the cache as streamed once per ubatch+ # like the weights, though attention re-reads it and the read grows with+ # depth. No production path builds kv_host_bytes > 0; this only stops rank()+ # calling a cache spill free.+ host_bytes = sum(g.bytes_total for g in placement.host_groups) + placement.kv_host_bytes+ if host_bytes <= 0 or n_ubatch <= 0:+ return 0.0+ per_ubatch_ms = (host_bytes / GIB) / PREFILL_STREAM_GIB_S * 1000.0+ return per_ubatch_ms / float(n_ubatch)+++def rank(+ candidates: list[Placement],+ host: HostProfile | None = None,+ n_generated: int = 1,+ n_prompt: int = 0,+ n_ubatch: int = 512,+) -> list[tuple[Placement, float]]:+ """Sort placements cheapest first for a workload of a given shape.++ Both terms are milliseconds for the WHOLE request, so they are commensurate:+ ``n_prompt`` tokens of prefill plus ``n_generated`` tokens of decode. A long+ prompt with a short reply and a short prompt with a long reply are genuinely+ different questions and can rank placements differently, so the caller+ states the shape rather than accepting a baked-in answer.++ Defaults to pure single-token generation, which is where placements differ+ most.+ """+ scored = [+ (+ c,+ n_generated * generation_penalty_ms(c, host)+ + n_prompt * prefill_penalty_ms_per_token(c, n_ubatch, host),+ )+ for c in candidates+ ]+ return sorted(scored, key = lambda pair: pair[1])diff --git a/studio/backend/core/inference/offload_layout.py b/studio/backend/core/inference/offload_layout.pynew file mode 100644index 00000000000..0c5c5b22505--- /dev/null+++ b/studio/backend/core/inference/offload_layout.py@@ -0,0 +1,320 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""GGUF tensor layout, bucketed by where each tensor is allowed to live.++Split out from ``offload_planner`` on purpose: this half does file IO and knows+about GGUF key names, the other half is pure arithmetic. The planner can then be+tested exhaustively from hand-built layouts with no fixtures on disk.+"""++from __future__ import annotations++import logging+import re+from dataclasses import dataclass, field+from typing import Optional++logger = logging.getLogger(__name__)++# blk.<N>.<tail>+_BLOCK_RE = re.compile(r"^blk\.(\d+)\.(.+)$")++# Sparse MoE experts: only expert_used_count of expert_count read per token, so+# host traffic is a small fraction of their size. The cheap thing to spill.+_MOE_EXPERT_RE = re.compile(r"^ffn_(up|gate|down)_exps\.weight$")+# Dense FFN. Fully activated: every byte crosses the bus every token.+_DENSE_FFN_RE = re.compile(r"^ffn_(up|gate|down)\.weight$")+++@dataclass(frozen = True)+class BlockLayout:+ """One transformer block, split into what may and may not be spilled."""++ index: int+ # ffn_*_exps (MoE) or plain ffn_* (dense). Safe to push to host RAM.+ spillable_bytes: int+ # attention, norms, routers, shared experts, ssm: on the critical path every+ # token, or the KV cache hangs off them.+ resident_bytes: int+++@dataclass(frozen = True)+class ModelLayout:+ """Everything the planner needs, and nothing about files."""++ arch: str = ""+ n_layers: int = 0+ n_attention_layers: int = 0+ blocks: tuple[BlockLayout, ...] = field(default_factory = tuple)+ # Rides the layer list at index n_layer_all, so it is GPU-resident for any+ # -ngl >= 1 and can only be moved with an explicit override.+ lm_head_bytes: int = 0+ # llama-model.cpp pins dev_input to the CPU unconditionally, so this is+ # never charged to VRAM. Tracked because it IS charged to host RAM.+ token_embd_bytes: int = 0+ # output_norm and friends: GPU-resident, too small to be worth spilling.+ other_resident_bytes: int = 0+ # Attention cache for ONE token at f16, across the attention layers only.+ kv_bytes_per_token_f16: int = 0+ # Mamba conv/SSM state. Context independent; follows the layer, which -ot never moves.+ recurrent_bytes: int = 0+ n_ctx_train: int = 0+ is_moe: bool = False+ # Sparse-MoE routing: experts read per token is expert_used/expert_count.+ # Offloaded experts move only that fraction per token, a dense FFN all of it.+ n_expert: int = 0+ n_expert_used: int = 0+ # ``blocks`` drops the trailing nextn/MTP blk.<N> tensors: block_count counts+ # them (llama-model.cpp reads it into n_layer_all) but the target does not use+ # them. They are real blk.<N>.ffn_* weights (models/qwen35moe.cpp,+ # load_block_mtp), so an unbounded ^blk\.\d+\. spill pattern WOULD match them+ # once a draft is loaded. The planner uses this to stay bounded.+ has_excluded_blocks: bool = False+ # Total bytes of those dropped blocks, so a caller that knows a draft WILL+ # engage can charge them back. Dropping them suits the ordinary load: every+ # trailing block gets TENSOR_SKIP unless load_mtp is set+ # (models/glm4-moe.cpp:42-44, the same gate in every embedded-MTP arch) and+ # TENSOR_SKIP returns before the tensor exists+ # (llama-model-loader.cpp:1123-1131). But ``--spec-type draft-mtp`` sets+ # load_mtp on the TARGET's own params (common/common.cpp:1713), so the block is+ # materialised at its layer's buffer type, and i_gpu_start counting back from+ # n_layer_all (llama-model.cpp:1449) puts those blocks on a GPU FIRST.+ # llama.cpp's own fitter widens its offloadable-layer count the same way+ # (common/fit.cpp:139-142). Zero when nothing was dropped.+ excluded_block_bytes: int = 0+ # Sliding-window attention: some layers keep a window-sized cache, some the+ # full context (llama-kv-cache-iswa.cpp:69-104 builds two caches and filters+ # each by hparams.is_swa(il)), interleaved per layer. Every layer is still an+ # attention layer, so n_attention_layers does NOT reveal this. A multi-device+ # split has to know WHERE the big caches land, so the planner abstains.+ has_swa: bool = False+ # False when a needed quantity could not be read. The planner abstains.+ complete: bool = False++ @property+ def spillable_bytes(self) -> int:+ return sum(b.spillable_bytes for b in self.blocks)++ @property+ def block_resident_bytes(self) -> int:+ return sum(b.resident_bytes for b in self.blocks)++ def kv_bytes(+ self,+ n_ctx: int,+ bytes_per_elem: int = 2,+ ) -> int:+ """Attention cache at ``n_ctx``. bytes_per_elem 2 = f16, 1 = q8_0-ish."""+ if self.kv_bytes_per_token_f16 <= 0 or n_ctx <= 0:+ return 0+ return self.kv_bytes_per_token_f16 * n_ctx * bytes_per_elem // 2+++def _field(+ reader,+ key: str,+ default = None,+):+ f = reader.fields.get(key)+ if f is None:+ return default+ try:+ return f.contents()+ except Exception: # a malformed field must not take the whole load down+ return default+++def layout_from_gguf(path: str) -> ModelLayout:+ """Read ``path`` into a :class:`ModelLayout`.++ Returns an incomplete layout (``complete = False``) rather than raising when+ anything required is missing, so a surprising GGUF makes the planner abstain+ instead of failing a load that llama.cpp would have handled.+ """+ try:+ from gguf import GGUFReader+ reader = GGUFReader(path)+ except Exception as exc:+ logger.debug("offload layout: cannot read %s (%s)", path, exc)+ return ModelLayout()++ try:+ return _layout_from_reader(reader)+ except Exception as exc:+ logger.debug("offload layout: cannot interpret %s (%s)", path, exc)+ return ModelLayout()+++def _layout_from_reader(reader) -> ModelLayout:+ # Split GGUF: llama.cpp loads every sibling shard+ # (llama-model-loader.cpp:590-618), but GGUFReader memmaps only the ONE path+ # it was given. Shard 1 still carries the metadata, so the layout would look+ # complete while undercounting resident and spillable by most of the model --+ # an overstated fit, too few -ot patterns, and a startup OOM with --fit off.+ # Abstain instead; the seam then reproduces --fit on exactly.+ if int(_field(reader, "split.count") or 0) > 1:+ return ModelLayout()++ arch = str(_field(reader, "general.architecture") or "")+ if not arch:+ return ModelLayout()++ blocks_total = _field(reader, f"{arch}.block_count")+ if not blocks_total:+ return ModelLayout()+ blocks_total = int(blocks_total)++ # llama.cpp keeps embedded MTP blocks out of the target context and prices+ # their cache separately, so the attention count must not include them.+ nextn = int(_field(reader, f"{arch}.nextn_predict_layers") or 0)+ n_layers = max(0, blocks_total - nextn)++ # Hybrid: only 1 in full_attention_interval layers carries a KV cache, the+ # rest are recurrent. Absent (or 0) means every layer is attention.+ fai = int(_field(reader, f"{arch}.full_attention_interval") or 0)+ n_attention = -(-n_layers // fai) if fai > 0 else n_layers+ n_recurrent = max(0, n_layers - n_attention)++ n_kv_head = _field(reader, f"{arch}.attention.head_count_kv")+ n_head = _field(reader, f"{arch}.attention.head_count")+ n_embd = _field(reader, f"{arch}.embedding_length")+ key_len = _field(reader, f"{arch}.attention.key_length")+ val_len = _field(reader, f"{arch}.attention.value_length")+ if key_len is None and n_embd and n_head:+ key_len = int(n_embd) // int(n_head)+ if val_len is None:+ val_len = key_len+ if not n_kv_head or not key_len or not val_len:+ return ModelLayout()++ kv_per_token = int(n_attention) * int(n_kv_head) * (int(key_len) + int(val_len)) * 2++ # Charging every layer the full context above is the safe direction for the+ # TOTAL; what it cannot say is which layers hold the big caches.+ has_swa = bool(_field(reader, f"{arch}.attention.sliding_window") or 0)++ # Mamba conv + SSM state, one f32 copy per sequence. Mirrors llama.cpp's+ # own sizing; zero when the model has no recurrent layers.+ d_inner = int(_field(reader, f"{arch}.ssm.inner_size") or 0)+ d_state = int(_field(reader, f"{arch}.ssm.state_size") or 0)+ n_group = int(_field(reader, f"{arch}.ssm.group_count") or 0)+ d_conv = int(_field(reader, f"{arch}.ssm.conv_kernel") or 0)+ recurrent = 0+ if n_recurrent and d_inner and d_state and d_conv:+ n_embd_r = max(0, d_conv - 1) * (d_inner + 2 * n_group * d_state)+ n_embd_s = d_state * d_inner+ recurrent = n_recurrent * (n_embd_r + n_embd_s) * 4++ n_expert = int(_field(reader, f"{arch}.expert_count") or 0)+ n_expert_used = int(_field(reader, f"{arch}.expert_used_count") or 0)+ is_moe = bool(n_expert)++ spill: dict[int, int] = {}+ resident: dict[int, int] = {}+ lm_head = 0+ token_embd = 0+ other_resident = 0++ for tensor in reader.tensors:+ name = str(tensor.name)+ nbytes = int(tensor.n_bytes)+ match = _BLOCK_RE.match(name)+ if match:+ index = int(match.group(1))+ tail = match.group(2)+ # Shared experts (ffn_*_shexp) and routers (ffn_gate_inp*) run on every+ # token: dense-FFN bandwidth for a rounding error of size. Not spillable.+ spillable = _MOE_EXPERT_RE.match(tail) or (not is_moe and _DENSE_FFN_RE.match(tail))+ if spillable:+ spill[index] = spill.get(index, 0) + nbytes+ else:+ resident[index] = resident.get(index, 0) + nbytes+ continue+ if "token_embd" in name:+ token_embd += nbytes+ elif name == "output.weight":+ lm_head += nbytes+ else:+ other_resident += nbytes++ if not spill and not resident:+ return ModelLayout()++ # Tied embeddings duplicate the vocabulary matrix, they do not SAVE it. With no+ # output.weight llama.cpp re-creates the output tensor from token_embd as+ # TENSOR_DUPLICATED (models/llama.cpp:41-45, models/qwen3.cpp:22-25,+ # models/gemma3.cpp:43-47, and ~60 more) and routes a duplicated TOKEN_EMBD+ # through the OUTPUT buffer list (llama-model-loader.cpp:1113-1114). dev_input+ # is CPU-pinned while dev_output follows the layer split (llama-model.cpp:1465,+ # 1474), so the buffer-type contexts differ, the same-context reuse check misses+ # (llama-model-loader.cpp:1309-1314), and ggml_dup_tensor allocates a second+ # full matrix (llama-model-loader.cpp:1318) that load_all_data fills by name+ # with a real host to device copy (:1542, :1583). Counting the one stored tensor+ # as host-only understates VRAM by a whole vocabulary matrix -- the optimistic+ # direction. Resident, not lm_head: the duplicate keeps the name+ # token_embd.weight, so LM_HEAD_PATTERN cannot match and the lm_head rung would+ # credit a spill that moves nothing.+ if not lm_head and token_embd:+ other_resident += token_embd++ # Trailing nextn/MTP blocks are NOT part of the target model and are not loaded+ # unless a draft is engaged, so an -ot naming them moves nothing: measured,+ # spilling only blk.<nextn> leaves the host buffer at exactly token_embd and the+ # device buffer unchanged. Counting them spillable would credit bytes that can+ # never be freed. Studio prices the drafter separately anyway.+ all_block_indices = set(spill) | set(resident)+ block_indices = sorted(i for i in all_block_indices if i < n_layers)+ has_excluded = any(i >= n_layers for i in all_block_indices)+ excluded_bytes = sum(+ spill.get(i, 0) + resident.get(i, 0) for i in all_block_indices if i >= n_layers+ )+ blocks = tuple(+ BlockLayout(+ index = i,+ spillable_bytes = spill.get(i, 0),+ resident_bytes = resident.get(i, 0),+ )+ for i in block_indices+ )++ return ModelLayout(+ arch = arch,+ n_layers = n_layers,+ n_attention_layers = int(n_attention),+ has_swa = has_swa,+ blocks = blocks,+ lm_head_bytes = lm_head,+ token_embd_bytes = token_embd,+ other_resident_bytes = other_resident,+ kv_bytes_per_token_f16 = kv_per_token,+ recurrent_bytes = recurrent,+ n_ctx_train = int(_field(reader, f"{arch}.context_length") or 0),+ is_moe = is_moe,+ n_expert = n_expert,+ n_expert_used = n_expert_used,+ has_excluded_blocks = has_excluded,+ excluded_block_bytes = excluded_bytes,+ complete = True,+ )+++def spill_pattern_for(layout: ModelLayout, indices: Optional[list[int]] = None) -> str:+ """The anchored ``-ot`` pattern matching the spillable FFN of ``indices``.++ Anchored because llama.cpp matches with ``std::regex_search``: an unanchored+ ``output\\.weight`` also matches every ``blk.N.attn_output.weight``, which+ silently moves 16 attention projections nobody asked to move. The trailing+ ``\\.weight$`` likewise keeps ``ffn_(up|gate|down)\\.`` from matching+ ``ffn_gate_inp.weight``.+ """+ body = "ffn_(up|gate|down)_exps" if layout.is_moe else "ffn_(up|gate|down)"+ if indices is None:+ block = r"\d+"+ else:+ block = "|".join(str(i) for i in sorted(indices))+ block = f"({block})"+ return rf"^blk\.{block}\.{body}\.weight$"+++LM_HEAD_PATTERN = r"^output\.weight$"diff --git a/studio/backend/core/inference/offload_planner.py b/studio/backend/core/inference/offload_planner.pynew file mode 100644index 00000000000..215dfbd61f8--- /dev/null+++ b/studio/backend/core/inference/offload_planner.py@@ -0,0 +1,796 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Placement planner: spill weights with ``-ot``, never the KV cache.++llama.cpp's ``--fit on`` spills whole layers through ``n_gpu_layers``, and a+layer's KV cache is allocated on ``model.dev_layer(il)`` (llama-kv-cache.cpp),+so spilling a layer drags its cache to host RAM with it. Measured at 128K on one+B200, that is the expensive direction by a wide margin:++ weights spilled, cache resident 71.63 t/s+ cache spilled, weights resident 3.24 t/s++``-ot`` overrides tensor buffer types WITHOUT touching layer assignment, so the+cache stays put: measured ``offloaded 66/66 layers to GPU`` with the whole cache+on CUDA0 even when every block tensor was forced to the host.++This module is pure arithmetic over a :class:`ModelLayout`. It performs no IO and+reads no globals, so the whole decision table is testable directly.+"""++from __future__ import annotations++import os+from dataclasses import dataclass, field+from enum import Enum+from typing import Iterable, Mapping, Optional, Sequence++from core.inference.offload_cost_model import (+ Access,+ HostProfile,+ Placement,+ TensorGroup,+ generation_penalty_ms,+)+from core.inference.offload_layout import (+ LM_HEAD_PATTERN,+ BlockLayout,+ ModelLayout,+ spill_pattern_for,+)++GIB = 1024**3+MIB = 1024**2+++class ContextPolicy(Enum):+ """Whether the planner may shrink a context the user asked for.++ llama.cpp's fitter shrinks context before spilling anything, and on+ throughput grounds that is right: a resident smaller context beats a spilled+ larger one. But context is a user-visible feature, not a free variable, so+ quietly trading it away is not a safe default.+ """++ NEVER_REDUCE = "never"+ # Shrink if that avoids spilling entirely.+ PREFER_RESIDENT = "prefer_resident"+ # Shrink only when no rung of the ladder fits.+ FIT_ONLY = "fit_only"+++class SpillOrder(Enum):+ """Which blocks to spill when only some are needed.++ UNMEASURED: every -ot measurement so far spilled all blocks or none, so the+ ordering is justified by byte-minimality alone, not by benchmark. Contiguous+ runs may schedule better (adjacent host blocks can merge into one graph+ split), which would favour FRONT/BACK over LARGEST. Hence configurable.+ """++ # Best-fit-decreasing: fewest blocks AND least overshoot. Overshoot is real+ # bandwidth -- a 209 MiB block for a 50 MiB deficit wastes 159 MiB per token.+ LARGEST_FIRST = "largest_first"+ FRONT_FIRST = "front_first"+ BACK_FIRST = "back_first"+++@dataclass(frozen = True)+class PlanOptions:+ # Compute buffer + CUDA context + scratch, charged on every device.+ #+ # 1 GiB was too thin and failed CONSISTENTLY: the planner fills to+ # ``budget - overhead_bytes_per_device``, leaving exactly this much free+ # whatever the budget is, so the dense 27B at depth 32768 died identically at+ # 6, 7, 8 and 10 GiB with+ #+ # ggml_backend_cuda_buffer_type_alloc_buffer: allocating 594.16 MiB+ # on device 0: cudaMalloc failed: out of memory+ #+ # The child needs the PREFILL compute buffer (594 MiB measured) plus its own+ # CUDA primary context, which took the rest of the old 1 GiB. Not benchmark+ # fragmentation: 16, 64 and 1024 MiB hog blocks all reproduced the identical+ # 594.16 MiB failure. 1.5 GiB covers the measured 1.07 GiB with margin -- a+ # measured floor, not a fitted curve, since the steady-state compute buffer is+ # flat in context (493 to 509 MiB from depth 4096 to 32768) but the prefill+ # graph's reservation is not. Erring high costs some spill (linear at+ # 5.544 ms/GiB), erring low costs the whole load.+ overhead_bytes_per_device: int = (3 * GIB) // 2+ # GPU-resident bytes NOT in the layout (a vision projector, an MTP draft+ # reserve), charged once against the pooled budget: the layout only knows the+ # target GGUF's tensor table. Subtracting from the budget also reaches+ # max_context_for. 0 keeps the pure-layout behaviour.+ extra_resident_bytes: int = 0+ # Host RAM this planner refuses to spend, so a spill does not push the box+ # into swap.+ host_ram_headroom_bytes: int = 2 * GIB+ context_policy: ContextPolicy = ContextPolicy.NEVER_REDUCE+ min_ctx: int = 4096+ spill_order: SpillOrder = SpillOrder.LARGEST_FIRST+ allow_lm_head_spill: bool = True+ # What the host brings to bear on spilled weights. Spilled generation runs on+ # the CPU backend -- ggml only moves an op to the GPU at batch >= 32+ # (ggml-cuda.cu, op_offload_min_batch_size) and decode is batch 1 -- so the+ # penalty scales with core count: 2.42 / 5.83 / 11.82 / 14.94 t/s at+ # 4 / 16 / 64 / 192 threads.+ host: HostProfile = field(default_factory = HostProfile)+ # q8_0 measured 35% slower generation, and without GGML_CUDA_FA_ALL_QUANTS+ # only four MATCHED K/V combinations are compiled (a mismatched pair falls+ # to CPU and stalls). Off by default; matched pairs only when enabled.+ allow_kv_quant: bool = False+ kv_quant_type: str = "q8_0"+++@dataclass(frozen = True)+class Plan:+ """What to launch with, and why."""++ # False means "emit nothing new": either the planner abstained or the load+ # needs no help. Always safe, since llama.cpp's own defaults then apply.+ changed: bool = False+ n_ctx: int = 0+ ot_patterns: tuple[str, ...] = field(default_factory = tuple)+ load_mode_none: bool = False+ cache_type_k: Optional[str] = None+ cache_type_v: Optional[str] = None+ spilled_blocks: tuple[int, ...] = field(default_factory = tuple)+ spilled_lm_head: bool = False+ # No rung fits. mmap has to stay, because it is the only thing that makes an+ # over-commit pageable rather than OOM-killed.+ insufficient: bool = False+ vram_bytes: int = 0+ host_bytes: int = 0+ # Predicted extra ms per generated token versus fully resident, on the host+ # this was planned for. 0.0 when nothing is spilled. Reported so callers can+ # surface the real cost instead of implying a spill is free.+ predicted_gen_penalty_ms: float = 0.0+ reason: str = ""++ @property+ def spills_anything(self) -> bool:+ return bool(self.spilled_blocks) or self.spilled_lm_head+++def _usable_vram(vram_bytes_per_device: Sequence[int], opts: PlanOptions) -> int:+ """Total creditable VRAM: every device pays the fixed per-device overhead,+ then the pool pays once for whatever sits on a card outside the layout."""+ pooled = sum(max(0, v - opts.overhead_bytes_per_device) for v in vram_bytes_per_device)+ return pooled - max(0, opts.extra_resident_bytes)+++def _select_blocks(+ blocks: Iterable[BlockLayout], deficit: int, order: SpillOrder+) -> tuple[list[BlockLayout], int]:+ """Blocks to spill to free at least ``deficit``, and what they actually free."""+ remaining = [b for b in blocks if b.spillable_bytes > 0]+ if order is SpillOrder.FRONT_FIRST:+ remaining.sort(key = lambda b: b.index)+ elif order is SpillOrder.BACK_FIRST:+ remaining.sort(key = lambda b: -b.index)+ else:+ remaining.sort(key = lambda b: -b.spillable_bytes)++ chosen: list[BlockLayout] = []+ freed = 0+ while freed < deficit and remaining:+ if order is SpillOrder.LARGEST_FIRST:+ residual = deficit - freed+ # Prefer the SMALLEST block that closes the gap: the last pick must+ # not overshoot by a whole large block.+ covering = [b for b in remaining if b.spillable_bytes >= residual]+ pick = min(covering, key = lambda b: b.spillable_bytes) if covering else remaining[0]+ else:+ pick = remaining[0]+ remaining.remove(pick)+ chosen.append(pick)+ freed += pick.spillable_bytes+ return chosen, freed+++def _spill_penalty_ms(+ layout: ModelLayout, chosen: Sequence[BlockLayout], spill_lm_head: bool, host: HostProfile+) -> float:+ """Predicted extra ms per generated token for this spill, on this host.++ Spilled weights are read by the CPU backend, not streamed to the GPU: ggml+ only migrates an op at batch >= 32 and decode is batch 1, so the cost tracks+ host cores. MoE experts are charged their ROUTED fraction, since only+ ``n_expert_used`` of ``n_expert`` are touched per token, which is why MoE+ tolerates spilling far better than a fully activated dense FFN.+ """+ groups: list[TensorGroup] = []+ spilled = sum(b.spillable_bytes for b in chosen)+ if spilled:+ if layout.is_moe and layout.n_expert and layout.n_expert_used:+ groups.append(+ TensorGroup(+ "experts",+ spilled,+ Access.SCATTERED,+ activation_fraction = layout.n_expert_used / layout.n_expert,+ )+ )+ else:+ groups.append(TensorGroup("ffn", spilled, Access.CONTIGUOUS))+ if spill_lm_head and layout.lm_head_bytes:+ groups.append(TensorGroup("lm_head", layout.lm_head_bytes, Access.SINGLE_MATVEC))+ if not groups:+ return 0.0+ return generation_penalty_ms(Placement(host_groups = groups), host)+++def _kv_elem_bytes(quantised: bool) -> int:+ return 1 if quantised else 2+++def cache_bytes(+ layout: ModelLayout,+ n_ctx: int,+ *,+ kv_quantised: bool = False,+ kv_bytes_floor: int = 0,+) -> int:+ """Attention cache to reserve, never below a caller-supplied measurement.++ ``layout.kv_bytes`` is a plain f16 GQA product: heads times key+value width+ times context. It has no cache-dtype, SWA, MLA, unified-stream, slot-padding+ or flash-attention-padding term, so against a caller that has priced the real+ cache it can land either side. Over is harmless -- the plan just reserves+ more. UNDER is the dangerous direction: the deficit comes out too small, too+ few blocks are spilled, and the launch path follows that with ``--fit off``,+ so the server OOMs on a cache the caller had already sized correctly. MLA is+ the worst case (a compressed K-only latent that this product models as a full+ K+V pair), and it is exactly the huge-MoE shape this planner exists for.++ Taking the maximum keeps the planner conservative in both directions without+ a tolerance to tune. The floor is a measurement at the REQUESTED context, so+ where a shrink rung re-prices at a smaller context it over-reserves; that is+ the safe direction and at worst gives up a rung.+ """+ return max(layout.kv_bytes(n_ctx, _kv_elem_bytes(kv_quantised)), max(0, kv_bytes_floor))+++def resident_floor_bytes(+ layout: ModelLayout,+ n_ctx: int,+ *,+ kv_quantised: bool = False,+ kv_bytes_floor: int = 0,+) -> int:+ """VRAM needed with EVERY spillable tensor already on the host.++ Attention weights, norms, routers, shared experts, the recurrent state, the+ cache and lm_head. Below this, ``-ot`` has nothing left to give and only a+ smaller quant or less context can help.+ """+ return (+ layout.block_resident_bytes+ + layout.lm_head_bytes+ + layout.other_resident_bytes+ + layout.recurrent_bytes+ + cache_bytes(layout, n_ctx, kv_quantised = kv_quantised, kv_bytes_floor = kv_bytes_floor)+ )+++def all_resident_bytes(+ layout: ModelLayout,+ n_ctx: int,+ *,+ kv_quantised: bool = False,+ kv_bytes_floor: int = 0,+) -> int:+ """VRAM needed with nothing spilled. token_embd is excluded: it is never+ GPU-resident (llama-model.cpp pins dev_input to the CPU unconditionally)."""+ return (+ resident_floor_bytes(+ layout, n_ctx, kv_quantised = kv_quantised, kv_bytes_floor = kv_bytes_floor+ )+ + layout.spillable_bytes+ )+++def max_context_for(+ layout: ModelLayout,+ vram_bytes_per_device: Sequence[int],+ *,+ spill_all_ffn: bool = False,+ spill_lm_head: bool = False,+ kv_quantised: bool = False,+ opts: Optional[PlanOptions] = None,+) -> int:+ """Largest context whose cache fits, rounded down to 256 as CUDA wants."""+ opts = opts or PlanOptions()+ if not layout.complete or layout.kv_bytes_per_token_f16 <= 0:+ return 0+ fixed = (+ layout.block_resident_bytes+ + layout.other_resident_bytes+ + layout.recurrent_bytes+ + (0 if spill_lm_head else layout.lm_head_bytes)+ + (0 if spill_all_ffn else layout.spillable_bytes)+ )+ free = _usable_vram(vram_bytes_per_device, opts) - fixed+ if free <= 0:+ return 0+ per_token = layout.kv_bytes_per_token_f16 * _kv_elem_bytes(kv_quantised) // 2+ if per_token <= 0:+ return 0+ ctx = (free // per_token) // 256 * 256+ if layout.n_ctx_train:+ ctx = min(ctx, layout.n_ctx_train)+ return max(0, ctx)+++def plan_placement(+ layout: ModelLayout,+ vram_bytes_per_device: Sequence[int],+ host_ram_bytes: Optional[int],+ requested_ctx: int,+ *,+ opts: Optional[PlanOptions] = None,+ kv_bytes_floor: int = 0,+ split_weights_per_device: Sequence[int] = (),+) -> Plan:+ """Decide the placement for one launch.++ ``split_weights_per_device`` is the RAW free VRAM llama.cpp will size its row+ ranges from, in the same device order as ``vram_bytes_per_device``. It is a+ different quantity from the budget by construction -- the budget subtracts a+ per-card reserve -- so the two must not be conflated when modelling the+ split. Empty falls back to the budget, which is right whenever the caller has+ applied no per-card adjustment at all.++ ``kv_bytes_floor`` is an attention-cache size the caller has already computed+ byte-accurately for this launch. The planner never reserves less than it; see+ :func:`cache_bytes` for why the layout's own f16 product is not enough on its+ own. 0 (the default) keeps the pure-layout arithmetic.++ Ladder, cheapest first, measured on a dense 27B at 128K:+ rung 0 nothing spilled 75.37 t/s+ rung 1 FFN to host 13.63 t/s+ rung 2 FFN + lm_head 11.39 t/s+ never -ngl or --no-kv-offload ~1.03 t/s++ The order is confirmed by the cost model rather than assumed, and is stated+ in TIME. Ranking on percentage loss is wrong: lm_head reads "43% alone, 16%+ on top of FFN", which looks sub-additive, while the same 0.97 GiB costs+ 10.206 ms/token alone and 14.428 on top -- 41% MORE, not less. Percentages+ of different baselines are not commensurable; milliseconds are.+ """+ opts = opts or PlanOptions()++ if not layout.complete or not vram_bytes_per_device:+ return Plan(reason = "layout or device inventory incomplete, leaving llama.cpp defaults")+ if opts.host.unified_memory:+ # One pool: "spilling" renames bytes on the same chips and frees nothing.+ # Metal also keeps mmap zero copy (buffer_from_host_ptr), so the no-mmap+ # rule inverts there too.+ return Plan(reason = "unified memory host, spilling frees no device memory")+ budget = _usable_vram(vram_bytes_per_device, opts)+ if budget <= 0:+ return Plan(reason = "no creditable VRAM after per-device overhead and reserved allocations")++ n_ctx = requested_ctx if requested_ctx > 0 else layout.n_ctx_train+ if layout.n_ctx_train:+ n_ctx = min(n_ctx, layout.n_ctx_train)+ if n_ctx <= 0:+ return Plan(reason = "no usable context length")++ # PREFER_RESIDENT gets its say before the ladder: a smaller fully resident+ # context outruns a larger spilled one, when the caller allows it to move.+ if (+ opts.context_policy is ContextPolicy.PREFER_RESIDENT+ and all_resident_bytes(layout, n_ctx, kv_bytes_floor = kv_bytes_floor) > budget+ ):+ shrunk = max_context_for(layout, vram_bytes_per_device, opts = opts)+ if shrunk >= opts.min_ctx:+ return _finish(+ layout,+ opts,+ min(shrunk, n_ctx),+ [],+ False,+ host_ram_bytes,+ reason = (+ f"shrank context {n_ctx} -> {min(shrunk, n_ctx)} to keep every tensor "+ "resident, which outruns a larger spilled context"+ ),+ )++ for quantised in _kv_modes(opts):+ plan = _plan_at(+ layout,+ opts,+ n_ctx,+ budget,+ host_ram_bytes,+ quantised,+ kv_bytes_floor,+ vram_bytes_per_device,+ split_weights_per_device or vram_bytes_per_device,+ )+ if plan is not None:+ return plan++ # Nothing fit at the requested context. Only now may FIT_ONLY shrink it.+ if opts.context_policy in (ContextPolicy.FIT_ONLY, ContextPolicy.PREFER_RESIDENT):+ for quantised in _kv_modes(opts):+ shrunk = max_context_for(+ layout,+ vram_bytes_per_device,+ spill_all_ffn = True,+ spill_lm_head = opts.allow_lm_head_spill,+ kv_quantised = quantised,+ opts = opts,+ )+ shrunk = min(shrunk, n_ctx)+ if shrunk >= opts.min_ctx:+ plan = _plan_at(+ layout,+ opts,+ shrunk,+ budget,+ host_ram_bytes,+ quantised,+ kv_bytes_floor,+ vram_bytes_per_device,+ split_weights_per_device or vram_bytes_per_device,+ )+ if plan is not None:+ return plan++ floor = resident_floor_bytes(layout, n_ctx, kv_bytes_floor = kv_bytes_floor)+ return Plan(+ changed = False,+ n_ctx = n_ctx,+ insufficient = True,+ vram_bytes = floor,+ reason = (+ f"even with every spillable tensor on the host the load needs "+ f"{floor / GIB:.2f} GiB of VRAM against {budget / GIB:.2f} GiB usable; "+ "keeping mmap so llama.cpp can page rather than be OOM-killed. "+ "A smaller quant or a shorter context is the fix, not more offload"+ ),+ )+++def _kv_modes(opts: PlanOptions) -> tuple[bool, ...]:+ """f16 first, then q8_0 only if the caller opted in."""+ return (False, True) if opts.allow_kv_quant else (False,)+++def _device_slots(n_slots: int, split_weights: Sequence[int]) -> list[list[int]]:+ """Which of the ``n_slots`` layer rows land on which device.++ Mirrors llama.cpp's default tensor split exactly: free VRAM per device+ (llama-model.cpp:1420-1433), prefix-summed and normalised (:1439-1447), then+ ``upper_bound`` on the normalised row index (:1457). Row ``n_layer_all`` is+ the output row (:1467). With every layer offloaded ``i_gpu_start`` is 0 and+ ``act_gpu_layers`` is ``n_layer_all + 1``, which is ``n_slots`` here.+ """+ weights = [max(0, v) for v in split_weights]+ total = sum(weights)+ if total <= 0:+ return [list(range(n_slots))] + [[] for _ in weights[1:]]+ cumulative: list[float] = []+ running = 0.0+ for w in weights:+ running += w+ cumulative.append(running / total)+ slots: list[list[int]] = [[] for _ in weights]+ for row in range(n_slots):+ fraction = row / n_slots+ # std::upper_bound: first cumulative strictly greater than fraction.+ device = next((i for i, c in enumerate(cumulative) if c > fraction), len(weights) - 1)+ slots[device].append(row)+ return slots+++def _per_device_shortfall(+ layout: ModelLayout,+ opts: PlanOptions,+ n_ctx: int,+ spilled_indices: set[int],+ spill_lm_head: bool,+ vram_bytes_per_device: Sequence[int],+ *,+ quantised: bool,+ kv_bytes_floor: int,+ split_weights_per_device: Sequence[int] = (),+) -> Optional[str]:+ """``None`` when every device provably fits, else why it cannot be shown to.++ A pooled budget is not a per-device fit test, and it does not become one just+ because every spillable block was taken. llama.cpp hands out CONTIGUOUS ROW+ RANGES sized by free memory, so a device's share of the ROWS is proportional+ to its free VRAM while its share of the BYTES is not: what stays resident+ differs row by row (a block with a shared expert keeps more than a plain+ dense one), and the budget subtracts a FIXED per-device overhead, which+ already breaks proportionality on mixed cards -- 24 GiB and 8 GiB split the+ rows 75/25 but the budgets 77.6/22.4, so the small card is over on a load the+ pool says fits. A per-device shortfall is a hard throw (llama-model.cpp:1731)+ and ``--fit off`` means common/fit.cpp never runs to catch it.+ """+ if len(vram_bytes_per_device) <= 1:+ return None+ # These three make the per-row byte split unknowable from the layout, so+ # there is nothing to validate against and the honest answer is to abstain.+ if layout.recurrent_bytes > 0:+ return "the recurrent state's per-layer split is not visible in the layout"+ if layout.n_attention_layers != layout.n_layers:+ return (+ f"only {layout.n_attention_layers} of {layout.n_layers} layers hold a cache "+ "and the layout does not say which"+ )+ if layout.has_swa:+ # The check above passes (every layer IS attention), but a window layer's+ # cache is a fraction of a full-context one (Gemma3 interleaves 5:1) and+ # the layout does not say which rows are which. An even spread under-books+ # whichever card drew the full-context rows.+ return "the cache is per-layer uneven (sliding-window attention) and the layout does not say which layers are full-context"+ if layout.has_excluded_blocks:+ return "the GGUF carries trailing blocks that shift llama.cpp's row count"++ n_slots = layout.n_layers + 1+ if n_slots <= 1:+ return None+ cache = cache_bytes(layout, n_ctx, kv_quantised = quantised, kv_bytes_floor = kv_bytes_floor)+ kv_per_layer = cache // layout.n_layers if layout.n_layers else 0+ by_index = {b.index: b for b in layout.blocks}+ output_row_bytes = layout.other_resident_bytes + (0 if spill_lm_head else layout.lm_head_bytes)++ slots = _device_slots(n_slots, split_weights_per_device or vram_bytes_per_device)+ for device, rows in enumerate(slots):+ used = 0+ for row in rows:+ if row == n_slots - 1:+ used += output_row_bytes+ continue+ block = by_index.get(row)+ if block is None:+ continue+ used += block.resident_bytes + kv_per_layer+ if row not in spilled_indices:+ used += block.spillable_bytes+ # Everything outside the layout sits on the main device, which is+ # devices[0] once -sm none has already pruned the list.+ if device == 0:+ used += max(0, opts.extra_resident_bytes)+ headroom = max(0, vram_bytes_per_device[device] - opts.overhead_bytes_per_device)+ if used > headroom:+ return (+ f"device {device} would still hold {used / GIB:.2f} GiB of its "+ f"{len(rows)}-row share against {headroom / GIB:.2f} GiB usable"+ )+ return None+++def _plan_at(+ layout: ModelLayout,+ opts: PlanOptions,+ n_ctx: int,+ budget: int,+ host_ram_bytes: Optional[int],+ quantised: bool,+ kv_bytes_floor: int = 0,+ vram_bytes_per_device: Sequence[int] = (),+ split_weights_per_device: Sequence[int] = (),+) -> Optional[Plan]:+ """One pass of the ladder at a fixed context and cache dtype."""+ needed = all_resident_bytes(+ layout, n_ctx, kv_quantised = quantised, kv_bytes_floor = kv_bytes_floor+ )+ if needed <= budget:+ return _finish(+ layout,+ opts,+ n_ctx,+ [],+ False,+ host_ram_bytes,+ quantised = quantised,+ kv_bytes_floor = kv_bytes_floor,+ reason = (+ f"the whole load fits in VRAM ({needed / GIB:.2f} of "+ f"{budget / GIB:.2f} GiB usable), so nothing is spilled"+ ),+ )++ n_devices = len(vram_bytes_per_device)+ deficit = needed - budget+ chosen, freed = _select_blocks(layout.blocks, deficit, opts.spill_order)+ if freed >= deficit:+ spillable = [b for b in layout.blocks if b.spillable_bytes > 0]+ if n_devices > 1 and len(chosen) < len(spillable):+ # A pooled budget is not a per-device fit test for a PARTIAL spill.+ # llama.cpp fixes the split before any override exists -- free memory+ # per device at llama-model.cpp:1425-1433, prefix-summed at :1439-1447,+ # then upper_bound on the normalised LAYER INDEX at :1457, so each+ # device owns a contiguous index range -- and -ot only swaps a tensor's+ # buffer type in llama_model_loader::create_tensor+ # (llama-model-loader.cpp:1177-1203), leaving dev_layer(il) untouched+ # (llama-model.cpp:1467-1474). Nothing rebalances afterwards and with+ # --fit off common/fit.cpp never runs, so a subset of indices sitting+ # in one device's range relieves only that device: the aggregate+ # deficit is covered while a single card is still over, and a+ # per-device shortfall is a hard throw (llama-model.cpp:1731-1733).+ # Which rows the chosen indices land on is exactly what makes it+ # uneven, so no arithmetic rescues it. Abstain: --fit on is per-device+ # aware (common/fit.cpp:646-651, :687, :705). A FULL spill IS+ # checkable, and is checked below rather than assumed.+ return Plan(+ n_ctx = n_ctx,+ reason = (+ f"a partial spill ({len(chosen)} of {len(spillable)} blocks) across "+ f"{n_devices} devices cannot be checked against a pooled budget, "+ "because llama.cpp assigns contiguous layer ranges per device and "+ "-ot does not move a layer; leaving llama.cpp's own fitter to place it"+ ),+ )+ uneven = _per_device_shortfall(+ layout,+ opts,+ n_ctx,+ {b.index for b in chosen},+ False,+ vram_bytes_per_device,+ quantised = quantised,+ kv_bytes_floor = kv_bytes_floor,+ split_weights_per_device = split_weights_per_device,+ )+ if uneven is not None:+ return Plan(+ n_ctx = n_ctx,+ reason = (+ f"spilling every block still does not fit device by device: {uneven}; "+ "leaving llama.cpp's own fitter to place it"+ ),+ )+ return _finish(+ layout,+ opts,+ n_ctx,+ chosen,+ False,+ host_ram_bytes,+ quantised = quantised,+ kv_bytes_floor = kv_bytes_floor,+ reason = (+ f"spilled the FFN of {len(chosen)} of {len(layout.blocks)} blocks "+ f"({freed / GIB:.2f} GiB) to cover a {deficit / GIB:.2f} GiB deficit, "+ "keeping the KV cache resident"+ ),+ )++ # Every block spilled and still short: lm_head is the last rung. It costs+ # 16% here against 43% if taken first, because FFN offload has already made+ # generation host-bandwidth-bound.+ if opts.allow_lm_head_spill and layout.lm_head_bytes:+ if freed + layout.lm_head_bytes >= deficit:+ uneven = _per_device_shortfall(+ layout,+ opts,+ n_ctx,+ {b.index for b in chosen},+ True,+ vram_bytes_per_device,+ quantised = quantised,+ kv_bytes_floor = kv_bytes_floor,+ split_weights_per_device = split_weights_per_device,+ )+ if uneven is not None:+ return Plan(+ n_ctx = n_ctx,+ reason = (+ "spilling every block and lm_head still does not fit device by "+ f"device: {uneven}; leaving llama.cpp's own fitter to place it"+ ),+ )+ return _finish(+ layout,+ opts,+ n_ctx,+ chosen,+ True,+ host_ram_bytes,+ quantised = quantised,+ kv_bytes_floor = kv_bytes_floor,+ reason = (+ f"spilled every block's FFN ({freed / GIB:.2f} GiB) plus lm_head "+ f"({layout.lm_head_bytes / GIB:.2f} GiB) to cover a "+ f"{deficit / GIB:.2f} GiB deficit"+ ),+ )+ return None+++def _finish(+ layout: ModelLayout,+ opts: PlanOptions,+ n_ctx: int,+ chosen: list[BlockLayout],+ spill_lm_head: bool,+ host_ram_bytes: Optional[int],+ *,+ quantised: bool = False,+ kv_bytes_floor: int = 0,+ reason: str = "",+) -> Plan:+ """Assemble patterns, decide the load mode, and account for both sides."""+ patterns: list[str] = []+ indices = sorted(b.index for b in chosen)+ if indices:+ # One global pattern when every spillable block is going -- shorter, and+ # the form the benchmarks used. NOT when the GGUF carries blocks the layout+ # dropped: the unbounded \d+ would also match the trailing nextn/MTP+ # blocks, whose ffn_*_exps load the moment a draft is engaged. That moves+ # bytes neither host_bytes nor the deficit counted (so the mmap decision is+ # made on an undercount) and drags the draft FFN onto the CPU backend.+ spillable = [b.index for b in layout.blocks if b.spillable_bytes > 0]+ all_of_them = set(indices) == set(spillable) and not layout.has_excluded_blocks+ patterns.append(spill_pattern_for(layout, None if all_of_them else indices))+ if spill_lm_head:+ patterns.append(LM_HEAD_PATTERN)++ spilled_bytes = sum(b.spillable_bytes for b in chosen) + (+ layout.lm_head_bytes if spill_lm_head else 0+ )+ # token_embd is host-resident on every launch, so it is host RAM this plan+ # has to be able to pay for even when nothing is spilled.+ host_bytes = layout.token_embd_bytes + spilled_bytes+ vram_bytes = (+ all_resident_bytes(layout, n_ctx, kv_quantised = quantised, kv_bytes_floor = kv_bytes_floor)+ - spilled_bytes+ )++ # mmap costs 2 to 4.6x on host-resident weight reads, so turn it off -- but only+ # when host RAM holds the host side; otherwise mmap keeps an over-commit pageable.+ if host_ram_bytes is None:+ load_mode_none = False+ else:+ load_mode_none = host_bytes <= max(0, host_ram_bytes - opts.host_ram_headroom_bytes)++ cache_type = opts.kv_quant_type if quantised else None+ changed = bool(patterns) or load_mode_none or cache_type is not None+ return Plan(+ changed = changed,+ n_ctx = n_ctx,+ ot_patterns = tuple(patterns),+ load_mode_none = load_mode_none,+ # Matched pairs only: an unmatched K/V combination is not compiled+ # without GGML_CUDA_FA_ALL_QUANTS and silently falls back to CPU.+ cache_type_k = cache_type,+ cache_type_v = cache_type,+ spilled_blocks = tuple(indices),+ spilled_lm_head = spill_lm_head,+ vram_bytes = vram_bytes,+ host_bytes = host_bytes,+ predicted_gen_penalty_ms = _spill_penalty_ms(layout, chosen, spill_lm_head, opts.host),+ reason = reason,+ )+++def plan_to_args(plan: Plan) -> list[str]:+ """The launch flags for ``plan``. Empty when it changes nothing."""+ args: list[str] = []+ for pattern in plan.ot_patterns:+ args.extend(["-ot", f"{pattern}=CPU"])+ if plan.load_mode_none:+ args.extend(["--load-mode", "none"])+ if plan.cache_type_k and plan.cache_type_v:+ args.extend(["--cache-type-k", plan.cache_type_k])+ args.extend(["--cache-type-v", plan.cache_type_v])+ return args+++def smart_offload_enabled(env: Optional[Mapping[str, str]] = None) -> bool:+ """Whether the launch path may emit a spill plan.++ Off by default. The planner changes how a model is placed, and the failure+ mode of getting it wrong is a load that OOMs where llama.cpp's own default+ would have paged, so it opts in rather than out until it has run on more+ than one machine.+ """+ raw = (os.environ if env is None else env).get("UNSLOTH_SMART_OFFLOAD", "")+ return str(raw).strip().lower() in ("1", "true", "yes", "on", "enabled")diff --git a/studio/backend/tests/test_offload_cost_model.py b/studio/backend/tests/test_offload_cost_model.pynew file mode 100644index 00000000000..2bc6d732228--- /dev/null+++ b/studio/backend/tests/test_offload_cost_model.py@@ -0,0 +1,339 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The cost model against every measurement that produced it.++Anchors are real llama-bench runs on one B200 with a 192-core host, llama.cpp+b10360-era build, at 128K context unless stated. Each ``MEASURED_*`` figure is a+throughput in t/s converted to milliseconds per token, because time is the+quantity that composes and throughput is not.+"""++from __future__ import annotations++import pytest++from core.inference.offload_cost_model import (+ REFERENCE_CONTIGUOUS_MS_PER_GIB,+ Access,+ HostProfile,+ Placement,+ TensorGroup,+ generation_penalty_ms,+ prefill_penalty_ms_per_token,+ rank,+)++GIB = float(1024**3)+++def ms(t_per_s: float) -> float:+ return 1000.0 / t_per_s+++# ---------------------------------------------------------------- the anchors++# Qwen3.8-27B UD-Q4_K_XL, dense, 128K.+DENSE_BASE = ms(75.37)+DENSE_LM_HEAD = ms(42.60)+DENSE_FFN = ms(13.63)+DENSE_BOTH = ms(11.39)+DENSE_KV_HOST = ms(1.03)++# Qwen3.6-35B-A3B UD-Q4_K_XL, MoE, 128K.+MOE_BASE = ms(182.0)+MOE_EXPERTS = ms(71.63)+MOE_KV_HOST = ms(3.24)++DENSE_FFN_G = TensorGroup("ffn", int(10.092 * GIB), Access.CONTIGUOUS)+DENSE_LM_G = TensorGroup("lm_head", int(0.9713 * GIB), Access.SINGLE_MATVEC)+# 16 attention layers x 4 kv heads x (256+256) x 2 bytes x 131072 tokens.+DENSE_KV_BYTES = 16 * 4 * 512 * 2 * 131072++# 256 experts, 8 used per token: the sparsity that makes MoE cheap to spill.+MOE_EXPERT_G = TensorGroup(+ "experts", int(18.320 * GIB), Access.SCATTERED, activation_fraction = 8 / 256+)+# 10 attention layers x 2 kv heads x (256+256) x 2 bytes x 131072 tokens.+MOE_KV_BYTES = 10 * 2 * 512 * 2 * 131072+++def rel_err(predicted: float, measured: float) -> float:+ return abs(predicted - measured) / measured+++# One free constant plus three per-access ratios. It under-predicts every 128K+# anchor by a near-identical ~7%: the base rate is calibrated on the cleaner+# depth-0 partial-spill sweep while these anchors sit at 128K where attention+# contends. A uniform offset cannot change an ordering, which is all the planner+# asks of it.+ANCHOR_TOL = 0.10+++ "label,placement,measured_delta",+ [+ ("lm_head only", Placement([DENSE_LM_G]), DENSE_LM_HEAD - DENSE_BASE),+ ("ffn only", Placement([DENSE_FFN_G]), DENSE_FFN - DENSE_BASE),+ ("ffn + lm_head", Placement([DENSE_FFN_G, DENSE_LM_G]), DENSE_BOTH - DENSE_BASE),+ (+ "kv to host",+ Placement([], kv_host_bytes = DENSE_KV_BYTES),+ DENSE_KV_HOST - DENSE_BASE,+ ),+ ("moe experts", Placement([MOE_EXPERT_G]), MOE_EXPERTS - MOE_BASE),+ (+ "moe kv to host",+ Placement([], kv_host_bytes = MOE_KV_BYTES),+ MOE_KV_HOST - MOE_BASE,+ ),+ ],+)+def test_the_model_reproduces_every_measured_anchor(label, placement, measured_delta):+ assert rel_err(generation_penalty_ms(placement), measured_delta) < ANCHOR_TOL, label+++def test_the_kv_ratio_transfers_across_two_unrelated_models():+ """The strongest calibration point, and the only genuinely predictive one.++ The KV rate was derived from the dense model alone. Applied unchanged to a+ MoE model with a different layer count, head count and cache size, it lands+ within the same tolerance. Two structurally unrelated models agreeing on one+ constant is what makes "never move the cache" a rule rather than a datum.+ """+ dense_rate = (DENSE_KV_HOST - DENSE_BASE) / (DENSE_KV_BYTES / GIB)+ moe_rate = (MOE_KV_HOST - MOE_BASE) / (MOE_KV_BYTES / GIB)+ assert rel_err(moe_rate, dense_rate) < 0.03+++# ------------------------------------------------- the orderings that matter+++def test_the_cache_is_the_worst_byte_to_move_by_an_order_of_magnitude():+ """20x per byte against contiguous weights. This is the whole reason the+ planner uses -ot (which leaves the cache resident) instead of -ngl."""+ one_gib_weights = Placement([TensorGroup("w", int(GIB), Access.CONTIGUOUS)])+ one_gib_cache = Placement([], kv_host_bytes = int(GIB))+ assert generation_penalty_ms(one_gib_cache) > 15 * generation_penalty_ms(one_gib_weights)+++def test_ffn_is_cheaper_per_byte_than_lm_head():+ """Which is why FFN is spilled first, even though lm_head is the smaller+ tensor and looks like the tidier thing to move."""+ per_gib = {+ access: generation_penalty_ms(Placement([TensorGroup("x", int(GIB), access)]))+ for access in (Access.CONTIGUOUS, Access.SINGLE_MATVEC, Access.SCATTERED)+ }+ assert per_gib[Access.CONTIGUOUS] < per_gib[Access.SINGLE_MATVEC]+ assert per_gib[Access.SINGLE_MATVEC] < per_gib[Access.SCATTERED]+++def test_spilling_two_groups_costs_MORE_than_the_sum_not_less():+ """The correction that matters most.++ Read as throughput percentages, lm_head "costs 43% alone but only 16% on top+ of FFN", which reads as a discount. In time it is the opposite: the same+ 0.97 GiB adds 10.2 ms alone and 14.4 ms once FFN is already spilled. Ranking+ on percentages would pick the wrong placement.+ """+ alone = generation_penalty_ms(Placement([DENSE_LM_G]))+ ffn_only = generation_penalty_ms(Placement([DENSE_FFN_G]))+ both = generation_penalty_ms(Placement([DENSE_FFN_G, DENSE_LM_G]))+ assert both > ffn_only + alone+ marginal = both - ffn_only+ assert marginal > alone+++def test_the_measured_marginal_cost_of_lm_head_really_does_rise():+ """Same claim, against the raw numbers rather than the model."""+ alone = DENSE_LM_HEAD - DENSE_BASE+ marginal_on_top_of_ffn = DENSE_BOTH - DENSE_FFN+ assert marginal_on_top_of_ffn > alone+ assert 1.3 < marginal_on_top_of_ffn / alone < 1.5+++# ---------------------------------------------------------- partial spilling+++ "gib,measured_delta",+ [+ # depth 0, so these are compared among themselves, not to the 128K set.+ (2.184, ms(43.67) - ms(87.30)),+ (4.610, ms(26.62) - ms(87.30)),+ (7.053, ms(19.71) - ms(87.30)),+ (10.092, ms(14.94) - ms(87.30)),+ ],+)+def test_partial_spilling_is_linear(gib, measured_delta):+ """A least-squares fit over these four points gives 5.544 ms/GiB with a+ -0.10 ms intercept, so there is no per-split fixed cost worth modelling and+ the planner may spill exactly the minimum that fits."""+ predicted = generation_penalty_ms(+ Placement([TensorGroup("part", int(gib * GIB), Access.CONTIGUOUS)])+ )+ assert rel_err(predicted, measured_delta) < 0.10+++def test_spilling_less_always_costs_less():+ """Monotonicity. Without it the planner could prefer a larger spill."""+ costs = [+ generation_penalty_ms(Placement([TensorGroup("p", int(gib * GIB), Access.CONTIGUOUS)]))+ for gib in (1.0, 3.0, 5.0, 10.0)+ ]+ assert costs == sorted(costs)+++# ------------------------------------------------------ prefill vs generation+++def test_moe_wins_at_generation_and_loses_at_prefill():+ """The crossover the two regimes produce, and the reason they are modelled+ apart. Generation reads 8/256 of the experts; a 512-token prefill ubatch+ reads all of them, so the sparsity that makes MoE cheap to spill during+ generation buys nothing during prefill."""+ moe = Placement([MOE_EXPERT_G])+ dense = Placement([DENSE_FFN_G])+ assert generation_penalty_ms(moe) < generation_penalty_ms(dense)+ assert prefill_penalty_ms_per_token(moe) > prefill_penalty_ms_per_token(dense)+++def test_the_measured_penalties_show_that_same_crossover():+ """Against the raw anchors: MoE is hurt less on generation, more on prefill."""+ moe_gen = MOE_EXPERTS / MOE_BASE+ dense_gen = DENSE_FFN / DENSE_BASE+ assert moe_gen < dense_gen # 2.54x vs 5.39x+ moe_pp, dense_pp = 5522.0 / 1397.0, 2095.0 / 1141.0+ assert moe_pp > dense_pp # 3.95x vs 1.84x+++# ----------------------------------------------------------------- the hosts+++def test_a_smaller_host_makes_every_spill_worse():+ """Generation cost tracks host threads, measured 2.42 / 5.83 / 11.82 t/s at+ 4 / 16 / 64 with the FFN spilled, against a flat 87.30 resident. A desktop+ is not a small version of this box; it is a different recommendation.++ This used to under-warn by about 22% at 16 threads, predicting 2.26x against+ a measured 2.885x. That gap was the one-machine fit being applied across+ machines. The cross-host floor closes it: the prediction is now 2.93x, a+ little OVER the measured ratio rather than well under it.++ Over is the side to be on. Under-warning quotes a spill that then runs+ several times slower than promised, which is the same direction as every+ real defect this planner has had; over-warning costs some throughput a user+ could have had. Held to within 10% so "conservative" cannot drift into+ "useless".+ """+ big = generation_penalty_ms(Placement([DENSE_FFN_G]), HostProfile(threads = 192))+ small = generation_penalty_ms(Placement([DENSE_FFN_G]), HostProfile(threads = 16))+ assert small > 2 * big+ measured_ratio = (ms(5.83) - ms(87.30)) / (ms(14.94) - ms(87.30))+ assert small / big >= measured_ratio # no longer under-warns+ assert small / big < measured_ratio * 1.1+++def test_thread_scaling_matches_the_measured_sweep():+ """Predicted ratio between 16 and 64 threads against the measured 11.82/5.83."""+ at16 = generation_penalty_ms(Placement([DENSE_FFN_G]), HostProfile(threads = 16))+ at64 = generation_penalty_ms(Placement([DENSE_FFN_G]), HostProfile(threads = 64))+ measured_ratio = 11.82 / 5.83+ assert rel_err(at16 / at64, measured_ratio) < 0.20+++def test_prefill_ignores_host_threads_while_generation_does_not():+ """The asymmetry between the two regimes, asserted as a contrast rather than+ by comparing a call to itself.++ Prefill clears ggml's op-offload batch threshold (32, ggml-cuda.cu:5465) so+ the op moves to the GPU and the weights are copied in: link-bound, cores+ irrelevant. Generation at batch 1 stays below it and runs on the CPU+ backend: core-bound.+ """+ p = Placement([DENSE_FFN_G])+ big, small = HostProfile(threads = 192), HostProfile(threads = 8)+ assert prefill_penalty_ms_per_token(p, host = small) == prefill_penalty_ms_per_token(p, host = big)+ assert generation_penalty_ms(p, small) > 2 * generation_penalty_ms(p, big)+++def test_prefill_amortises_over_the_ubatch():+ """Weights are copied once per ubatch and reused by every token in it, which+ is why prefill is so much cheaper per byte moved than generation."""+ p = Placement([DENSE_FFN_G])+ assert prefill_penalty_ms_per_token(p, n_ubatch = 512) == pytest.approx(+ prefill_penalty_ms_per_token(p, n_ubatch = 256) / 2.0+ )+ # And the measured per-token prefill penalty is far below the generation one.+ assert prefill_penalty_ms_per_token(p) < generation_penalty_ms(p) / 100.0+++def test_unified_memory_hosts_gain_nothing_from_spilling():+ """Apple Silicon, AMD APUs and Vulkan iGPUs report host RAM as VRAM. Moving+ a tensor between the two does not change which chips hold it, so the planner+ must not pay a penalty for it -- nor claim it freed anything."""+ unified = HostProfile(unified_memory = True)+ assert generation_penalty_ms(Placement([DENSE_FFN_G, DENSE_LM_G]), unified) == 0.0+ assert generation_penalty_ms(Placement([], kv_host_bytes = DENSE_KV_BYTES), unified) == 0.0+++# ------------------------------------------------------------------ ranking+++def test_ranking_puts_the_measured_best_placement_first():+ """The ladder, rediscovered rather than hard-coded: resident, then FFN, then+ FFN plus lm_head, and the cache last by a wide margin."""+ resident = Placement([])+ ffn = Placement([DENSE_FFN_G])+ ffn_lm = Placement([DENSE_FFN_G, DENSE_LM_G])+ kv = Placement([], kv_host_bytes = DENSE_KV_BYTES)+ order = [p for p, _ in rank([kv, ffn_lm, ffn, resident])]+ assert order == [resident, ffn, ffn_lm, kv]+++def test_a_prefill_heavy_mix_can_reorder_dense_against_moe():+ """A caller that weights prefill is answering a different question, and the+ model must let it, rather than baking in the generation answer."""+ moe, dense = Placement([MOE_EXPERT_G]), Placement([DENSE_FFN_G])+ gen_first = [p for p, _ in rank([dense, moe], n_generated = 1, n_prompt = 0)]+ pp_first = [p for p, _ in rank([dense, moe], n_generated = 0, n_prompt = 4096)]+ assert gen_first[0] is moe+ assert pp_first[0] is dense+++def test_the_cross_host_floor_matches_the_measured_cloud_hosts():+ """The floor is fitted to real cloud VMs, so hold it to them.++ Measured dense Q4_K_XL, ms per GiB of spilled weights, over 70 runs on+ T4 / L4 / A100 / RTX PRO 6000: 24.21 at 12 vCPU, 6.82 at 48, and 5.498 at+ the 192-thread reference. Before the floor the 12 vCPU case was predicted at+ 17.1, i.e. 0.59 of the truth.+ """+ rate = lambda t: ( # noqa: E731 - one expression, reads better inline+ HostProfile(threads = t).generation_slowdown * REFERENCE_CONTIGUOUS_MS_PER_GIB+ )+ for threads, measured in ((12, 24.21), (48, 6.82), (192, 5.498)):+ ratio = rate(threads) / measured+ assert 0.85 <= ratio <= 1.15, (threads, rate(threads), measured, ratio)+ # Monotone in cores, and a tiny host is charged much more than a big one.+ assert rate(2) > rate(8) > rate(12) > rate(48) > rate(192)+ assert rate(2) > 10 * rate(192)+++def test_a_host_cache_is_not_free_during_prefill():+ """generation_penalty_ms charges kv_host_bytes and prefill did not, so a+ cache-offloaded placement prefilled for free and TIED with a fully resident+ one at n_generated = 0. The asymmetry was the bug: the cache crosses the same+ link as the weights."""+ resident = Placement()+ kv_host = Placement(kv_host_bytes = int(4 * GIB))++ assert prefill_penalty_ms_per_token(resident) == 0.0+ assert prefill_penalty_ms_per_token(kv_host) > 0.0++ ordered = rank([kv_host, resident], n_generated = 0, n_prompt = 4096)+ assert ordered[0][0] is resident, "resident must win a pure-prefill ranking"+ assert ordered[0][1] < ordered[1][1], "and it must not be a tie"++ # Still zero where moving bytes between two names for one pool is free.+ assert prefill_penalty_ms_per_token(kv_host, host = HostProfile(unified_memory = True)) == 0.0diff --git a/studio/backend/tests/test_offload_planner.py b/studio/backend/tests/test_offload_planner.pynew file mode 100644index 00000000000..6bff0309ca5--- /dev/null+++ b/studio/backend/tests/test_offload_planner.py@@ -0,0 +1,1088 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The -ot spill planner: the ladder, the patterns, and everything it must never do.++The negative half matters most. The planner exists because llama.cpp's own+fitter spills whole layers and drags the KV cache to host RAM with them, so a+plan that emits -ngl or --no-kv-offload, or that charges token_embd to VRAM, is+worse than no plan at all.+"""++from __future__ import annotations++import os+import re+from dataclasses import replace++import pytest++from core.inference.offload_layout import (+ LM_HEAD_PATTERN,+ BlockLayout,+ ModelLayout,+ _layout_from_reader,+ layout_from_gguf,+ spill_pattern_for,+)+from core.inference.offload_cost_model import HostProfile+from core.inference.offload_planner import (+ _device_slots,+ _per_device_shortfall,+ ContextPolicy,+ Plan,+ PlanOptions,+ SpillOrder,+ all_resident_bytes,+ max_context_for,+ plan_placement,+ plan_to_args,+ resident_floor_bytes,+)++GIB = 1024**3+MIB = 1024**2++_MODELS = "/mnt/disks/unslothai/daniel3/workspace_11/temp/loadmode_sim"+Q2_PATH = f"{_MODELS}/qwen38/Qwen3.8-27B-UD-Q2_K_XL.gguf"+Q4_PATH = f"{_MODELS}/qwen38/Qwen3.8-27B-UD-Q4_K_XL.gguf"+MOE_PATH = f"{_MODELS}/qwen36moe/Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf"++needs_gguf = pytest.mark.skipif(+ not os.path.exists(Q4_PATH), reason = "local GGUF fixtures not present"+)+++# ----------------------------------------------------------------- synthetic layouts+# Byte totals are the measured ones for Qwen3.8-27B, so the ladder tests run the+# real arithmetic without needing 27 GB of fixtures on disk.+++def _uniform_layout(+ *,+ n_blocks: int = 65,+ spillable_total: int,+ resident_total: int,+ lm_head: int,+ token_embd: int,+ kv_per_token: int = 65536,+ recurrent: int = 156_893_184,+ is_moe: bool = False,+ n_ctx_train: int = 262144,+) -> ModelLayout:+ per_spill, per_res = spillable_total // n_blocks, resident_total // n_blocks+ blocks = tuple(+ BlockLayout(index = i, spillable_bytes = per_spill, resident_bytes = per_res)+ for i in range(n_blocks)+ )+ return ModelLayout(+ arch = "qwen35moe" if is_moe else "qwen35",+ n_layers = 64,+ n_attention_layers = 16,+ blocks = blocks,+ lm_head_bytes = lm_head,+ token_embd_bytes = token_embd,+ kv_bytes_per_token_f16 = kv_per_token,+ recurrent_bytes = recurrent,+ n_ctx_train = n_ctx_train,+ is_moe = is_moe,+ complete = True,+ )+++def q4_layout() -> ModelLayout:+ return _uniform_layout(+ spillable_total = 10_836_131_840,+ resident_total = 4_953_923_584,+ lm_head = 1_042_915_328,+ token_embd = 715_128_832,+ )+++def q2_layout() -> ModelLayout:+ return _uniform_layout(+ spillable_total = 5_900_615_680,+ resident_total = 2_785_009_664,+ lm_head = 715_128_832,+ token_embd = 417_202_176,+ )+++def uneven_layout() -> ModelLayout:+ """Four blocks with deliberately lopsided FFN, for selection policy."""+ sizes = [100 * MIB, 400 * MIB, 200 * MIB, 50 * MIB]+ blocks = tuple(+ BlockLayout(index = i, spillable_bytes = s, resident_bytes = 10 * MIB)+ for i, s in enumerate(sizes)+ )+ return ModelLayout(+ arch = "qwen35",+ n_layers = 4,+ n_attention_layers = 4,+ blocks = blocks,+ lm_head_bytes = 100 * MIB,+ token_embd_bytes = 50 * MIB,+ kv_bytes_per_token_f16 = 1024,+ recurrent_bytes = 0,+ n_ctx_train = 65536,+ complete = True,+ )+++# ------------------------------------------------------------------- the ladder+++def test_a_load_that_fits_spills_nothing():+ plan = plan_placement(q2_layout(), [24 * GIB], 64 * GIB, 8192)+ assert plan.spilled_blocks == ()+ assert plan.spilled_lm_head is False+ assert plan.ot_patterns == ()+ assert plan.load_mode_none is True+ assert "fits in VRAM" in plan.reason+++def test_a_load_that_does_not_fit_spills_ffn_and_keeps_the_cache():+ """The whole point: weights move, the cache does not."""+ plan = plan_placement(q4_layout(), [12 * GIB], 64 * GIB, 32768)+ assert plan.spilled_blocks, "should have spilled something"+ assert plan.spilled_lm_head is False, "lm_head is the LAST rung, not the first"+ args = plan_to_args(plan)+ assert "-ngl" not in args and "--n-gpu-layers" not in args+ assert "--no-kv-offload" not in args and "-nkvo" not in args+++def test_lm_head_is_only_spilled_after_every_block():+ """43% of generation alone, 16% after FFN. Never take it first."""+ layout = q4_layout()+ # Tight enough that the whole FFN is not enough on its own.+ plan = plan_placement(layout, [7 * GIB], 64 * GIB, 8192)+ assert plan.spilled_lm_head is True+ assert len(plan.spilled_blocks) == len(layout.blocks), "all blocks go first"+++def test_partial_spill_takes_only_what_is_needed():+ layout = q4_layout()+ plan = plan_placement(layout, [16 * GIB], 64 * GIB, 8192)+ assert 0 < len(plan.spilled_blocks) < len(layout.blocks)+++def test_a_load_that_cannot_fit_keeps_mmap_and_says_so():+ """Below the resident floor, -ot has nothing left to give. mmap must stay:+ it is the only thing that makes an over-commit pageable instead of killed."""+ plan = plan_placement(q4_layout(), [4 * GIB], 64 * GIB, 131072)+ assert plan.insufficient is True+ assert plan.changed is False+ assert plan.load_mode_none is False+ assert plan_to_args(plan) == []+ assert "smaller quant" in plan.reason+++# ------------------------------------------------------------ what must never happen++[email protected]("vram", [4 * GIB, 8 * GIB, 12 * GIB, 16 * GIB, 24 * GIB])[email protected]("ctx", [4096, 32768, 131072])+def test_no_plan_ever_moves_the_kv_cache(vram, ctx):+ """-ngl and --no-kv-offload both cost 22x to 73x. Neither may ever appear."""+ for layout in (q2_layout(), q4_layout()):+ args = plan_to_args(plan_placement(layout, [vram], 64 * GIB, ctx))+ for banned in ("-ngl", "--gpu-layers", "--n-gpu-layers", "-nkvo", "--no-kv-offload"):+ assert banned not in args+++def test_token_embd_is_never_charged_to_vram():+ """llama-model.cpp pins dev_input to the CPU unconditionally, so the+ embedding is host RAM the plan must pay for, never VRAM it may spend.++ Proved by varying ONLY token_embd: a 4 GiB embedding must not change the+ VRAM figure or the spill decision by a single byte, and must show up in the+ host figure in full.+ """+ small = q4_layout()+ big = ModelLayout(**{**small.__dict__, "token_embd_bytes": 4 * GIB})++ tight = [12 * GIB]+ a = plan_placement(small, tight, 64 * GIB, 8192)+ b = plan_placement(big, tight, 64 * GIB, 8192)++ assert a.vram_bytes == b.vram_bytes+ assert a.spilled_blocks == b.spilled_blocks+ assert b.host_bytes - a.host_bytes == 4 * GIB - small.token_embd_bytes+++def test_load_mode_none_is_withheld_when_host_ram_cannot_hold_the_spill():+ """Turning mmap off on a host that cannot hold the spill turns a pageable+ load into an OOM kill."""+ layout = q4_layout()+ roomy = plan_placement(layout, [12 * GIB], 64 * GIB, 8192)+ cramped = plan_placement(layout, [12 * GIB], 3 * GIB, 8192)+ assert roomy.load_mode_none is True+ assert cramped.load_mode_none is False+++def test_unreadable_host_ram_keeps_mmap():+ plan = plan_placement(q4_layout(), [12 * GIB], None, 8192)+ assert plan.load_mode_none is False+++# ------------------------------------------------------------------- patterns+++def test_every_emitted_pattern_is_anchored():+ """Unanchored is a live trap: 'output\\.weight' also matches every+ blk.N.attn_output.weight, which silently moved 16 attention projections."""+ for layout in (q2_layout(), q4_layout()):+ for vram in (6 * GIB, 12 * GIB, 16 * GIB):+ plan = plan_placement(layout, [vram], 64 * GIB, 8192)+ for pattern in plan.ot_patterns:+ assert pattern.startswith("^") and pattern.endswith("$"), pattern+++def test_the_lm_head_pattern_does_not_catch_attention_output():+ assert re.search(LM_HEAD_PATTERN, "output.weight")+ assert not re.search(LM_HEAD_PATTERN, "blk.3.attn_output.weight")+ # The unanchored form is what went wrong; pin the difference.+ assert re.search(r"output\.weight", "blk.3.attn_output.weight")+++def test_the_dense_pattern_does_not_catch_the_router():+ pattern = spill_pattern_for(q4_layout())+ assert re.search(pattern, "blk.7.ffn_up.weight")+ assert re.search(pattern, "blk.7.ffn_gate.weight")+ assert not re.search(pattern, "blk.7.ffn_gate_inp.weight")+ assert not re.search(pattern, "blk.7.ffn_norm.weight")+ assert not re.search(pattern, "blk.7.attn_q.weight")+++def test_the_moe_pattern_spills_experts_but_not_shared_experts():+ """Shared experts run on EVERY token, like a dense FFN, for 0.6% of the+ model. Spilling them buys nothing and costs dense-like bandwidth."""+ moe = _uniform_layout(+ n_blocks = 40,+ spillable_total = 19_671_285_760,+ resident_total = 1_597_483_520,+ lm_head = 540_000_000,+ token_embd = 540_000_000,+ kv_per_token = 20480,+ is_moe = True,+ )+ pattern = spill_pattern_for(moe)+ assert re.search(pattern, "blk.5.ffn_up_exps.weight")+ assert re.search(pattern, "blk.5.ffn_down_exps.weight")+ assert not re.search(pattern, "blk.5.ffn_up_shexp.weight")+ assert not re.search(pattern, "blk.5.ffn_gate_inp.weight")+++def test_partial_spill_names_only_the_chosen_blocks():+ pattern = spill_pattern_for(q4_layout(), [3, 7, 11])+ assert re.search(pattern, "blk.3.ffn_up.weight")+ assert re.search(pattern, "blk.11.ffn_down.weight")+ assert not re.search(pattern, "blk.4.ffn_up.weight")+ # blk.1 must not sneak in through blk.11's alternation.+ assert not re.search(pattern, "blk.1.ffn_up.weight")+++def test_a_full_spill_uses_the_compact_global_pattern():+ layout = q4_layout()+ plan = plan_placement(layout, [7 * GIB], 64 * GIB, 8192)+ assert plan.ot_patterns[0] == spill_pattern_for(layout, None)+ assert r"\d+" in plan.ot_patterns[0]+++def test_plan_to_args_shape():+ layout = q4_layout()+ args = plan_to_args(plan_placement(layout, [12 * GIB], 64 * GIB, 8192))+ assert args.count("-ot") == 1+ assert args[args.index("-ot") + 1].endswith("=CPU")+ assert "--load-mode" in args and args[args.index("--load-mode") + 1] == "none"+++# ---------------------------------------------------------------- spill selection+++def test_largest_first_minimises_overshoot():+ """Best-fit-decreasing: cover a small residual with a small block, not by+ dragging a 400 MiB block across the bus on every token."""+ layout = uneven_layout()+ # Need ~50 MiB freed: the 50 MiB block alone should do it.+ floor = resident_floor_bytes(layout, 4096)+ budget = floor + layout.spillable_bytes - 40 * MIB + 1 * GIB # +overhead+ plan = plan_placement(+ layout,+ [budget],+ 64 * GIB,+ 4096,+ opts = PlanOptions(+ overhead_bytes_per_device = GIB,+ ),+ )+ spilled = sum(b.spillable_bytes for b in layout.blocks if b.index in plan.spilled_blocks)+ assert spilled == 50 * MIB, "should take the 50 MiB block, not a bigger one"+++def test_front_and_back_orders_pick_opposite_ends():+ layout = uneven_layout()+ floor = resident_floor_bytes(layout, 4096)+ budget = floor + layout.spillable_bytes - 40 * MIB + 1 * GIB+ front = plan_placement(+ layout,+ [budget],+ 64 * GIB,+ 4096,+ opts = PlanOptions(overhead_bytes_per_device = GIB, spill_order = SpillOrder.FRONT_FIRST),+ )+ back = plan_placement(+ layout,+ [budget],+ 64 * GIB,+ 4096,+ opts = PlanOptions(overhead_bytes_per_device = GIB, spill_order = SpillOrder.BACK_FIRST),+ )+ assert front.spilled_blocks == (0,)+ assert back.spilled_blocks == (3,)+++# ------------------------------------------------------------------ abstention+++def test_an_incomplete_layout_abstains():+ plan = plan_placement(ModelLayout(), [24 * GIB], 64 * GIB, 8192)+ assert plan.changed is False+ assert plan_to_args(plan) == []+++def test_no_devices_abstains():+ assert plan_placement(q4_layout(), [], 64 * GIB, 8192).changed is False+++def test_a_device_smaller_than_its_own_overhead_abstains():+ assert plan_placement(q4_layout(), [512 * MIB], 64 * GIB, 8192).changed is False+++# -------------------------------------------------------------------- multi GPU+++def test_every_device_pays_the_fixed_overhead():+ """A layer split puts a CUDA context and scratch on each card, so two 8 GiB+ cards are not one 16 GiB card. Read through max_context_for, which is the+ budget arithmetic without the ladder: the same 16 GiB split in two credits+ one overhead less, so it holds strictly less cache."""+ layout = q4_layout()+ one_big = max_context_for(layout, [16 * GIB], spill_all_ffn = True)+ two_small = max_context_for(layout, [8 * GIB, 8 * GIB], spill_all_ffn = True)+ assert one_big > 0 and two_small > 0+ assert two_small < one_big+++def test_a_partial_spill_across_two_gpus_abstains():+ """A pooled budget is not a per-device fit test for a partial spill.++ llama.cpp fixes the layer split from free memory BEFORE any override exists+ (llama-model.cpp:1416-1447) and hands each device a contiguous layer-index+ range (:1457), while -ot only swaps one tensor's buffer type inside+ create_tensor (llama-model-loader.cpp:1177-1203) and never touches+ dev_layer(il) (:1467-1474). So a subset of block indices can relieve one+ card while another keeps its whole share: the aggregate deficit reads+ covered, one device is still over, and --fit off means nothing rebalances+ (a per-device shortfall throws, llama-model.cpp:1731-1733). The same layout+ on ONE card of the same pooled size still plans, which is what makes this+ about device COUNT and not about the budget.+ """+ layout = q4_layout()+ one_card = plan_placement(layout, [16 * GIB], 64 * GIB, 8192)+ assert one_card.spilled_blocks+ assert len(one_card.spilled_blocks) < len(layout.blocks), "partial, not everything"++ two_cards = plan_placement(layout, [8 * GIB, 8 * GIB], 64 * GIB, 8192)+ assert two_cards.spilled_blocks == ()+ assert two_cards.ot_patterns == ()+ assert two_cards.changed is False+++def test_a_full_spill_is_checked_per_device_not_assumed():+ """A full spill used to be waved through on the theory that "every device+ keeps its layer share". It does keep its ROW share -- llama.cpp splits rows+ in proportion to free VRAM (llama-model.cpp:1439-1457) -- but rows are+ integers and bytes are not: 65 rows over two equal cards is 33/32, so at a+ budget sized to the pooled total device 0 is over by half a row's worth. The+ pooled arithmetic says it fits, the per-device check says it does not, and+ abstaining hands the load to --fit on, which is per-device aware.++ The identical pooled budget on ONE card has no split to be uneven about and+ still plans, which is what makes this about the SPLIT and not the budget.+ """+ layout = _layout_from_reader(_StubReader(_shard_fields(), _shard_tensors(range(64))))+ half = _ALL_SPILL_VRAM // 2+ plan = plan_placement(layout, [half, half], 256 * GIB, 4096, opts = _NO_OVERHEAD)+ assert plan.changed is False+ assert plan.spilled_blocks == ()+ assert "device 0" in plan.reason++ one = plan_placement(layout, [_ALL_SPILL_VRAM], 256 * GIB, 4096, opts = _NO_OVERHEAD)+ assert len(one.spilled_blocks) == len(layout.blocks)+++def test_a_full_spill_abstains_when_the_cache_layout_is_unknown():+ """A hybrid keeps a recurrent state on some layers only, and the layout does+ not record WHICH -- so there is no per-row byte model to validate against.+ Abstain rather than guess uniform. Again scoped to the multi-device split:+ the same layout on one card is unaffected."""+ layout = _layout_from_reader(_StubReader(_shard_fields(), _shard_tensors(range(64))))+ hybrid = replace(layout, recurrent_bytes = 8 * MIB)+ half = _ALL_SPILL_VRAM // 2+ plan = plan_placement(hybrid, [half, half], 256 * GIB, 4096, opts = _NO_OVERHEAD)+ assert plan.changed is False+ assert "recurrent state" in plan.reason++ one = plan_placement(hybrid, [_ALL_SPILL_VRAM], 256 * GIB, 4096, opts = _NO_OVERHEAD)+ assert len(one.spilled_blocks) == len(layout.blocks)+++def test_the_row_split_matches_llama_cpp():+ """_device_slots is a transcription of llama-model.cpp:1439-1457, so pin the+ two properties that matter: contiguous ranges, and sizes in proportion to+ free VRAM with the remainder landing on the EARLIER device."""+ assert [len(r) for r in _device_slots(65, [8 * GIB, 8 * GIB])] == [33, 32]+ assert [len(r) for r in _device_slots(65, [24 * GIB, 8 * GIB])] == [49, 16]+ assert [len(r) for r in _device_slots(65, [8 * GIB, 8 * GIB, 8 * GIB])] == [22, 22, 21]+ # Contiguous, in device order, covering every row exactly once.+ rows = _device_slots(65, [24 * GIB, 8 * GIB])+ assert rows[0] == list(range(0, 49)) and rows[1] == list(range(49, 65))+ # One device takes everything, and a zero-sized pool does not divide by zero.+ assert _device_slots(65, [8 * GIB]) == [list(range(65))]+ assert _device_slots(4, [0, 0]) == [[0, 1, 2, 3], []]+++def test_the_per_device_check_passes_when_the_shares_really_fit():+ """The check must not be a disguised "never plan on two GPUs". Cards sized so+ that each one's row share fits with room to spare return None -- no abstain+ reason -- for the same full spill the tight case rejects."""+ layout = _layout_from_reader(_StubReader(_shard_fields(), _shard_tensors(range(64))))+ spilled = {b.index for b in layout.blocks}+ tight = _ALL_SPILL_VRAM // 2+ assert (+ _per_device_shortfall(+ layout,+ _NO_OVERHEAD,+ 4096,+ spilled,+ False,+ [tight, tight],+ quantised = False,+ kv_bytes_floor = 0,+ )+ is not None+ )+ roomy = _ALL_SPILL_VRAM+ assert (+ _per_device_shortfall(+ layout,+ _NO_OVERHEAD,+ 4096,+ spilled,+ False,+ [roomy, roomy],+ quantised = False,+ kv_bytes_floor = 0,+ )+ is None+ )+++def test_multi_gpu_credit_sums():+ layout = q2_layout()+ assert (+ plan_placement(+ layout, [6 * GIB, 6 * GIB], 64 * GIB, 8192, opts = FIXED_OVERHEAD_OPTS+ ).spilled_blocks+ == ()+ )+++# --------------------------------------------------------------- context policy+++def test_never_reduce_keeps_the_requested_context():+ layout = q4_layout()+ plan = plan_placement(layout, [12 * GIB], 64 * GIB, 65536)+ assert plan.n_ctx == 65536+ assert plan.spilled_blocks, "it pays with spill, not with the user's context"+++def test_prefer_resident_shrinks_instead_of_spilling():+ layout = q4_layout()+ plan = plan_placement(+ layout,+ [18 * GIB],+ 64 * GIB,+ 65536,+ opts = PlanOptions(context_policy = ContextPolicy.PREFER_RESIDENT),+ )+ assert plan.spilled_blocks == ()+ assert plan.n_ctx < 65536+ assert "shrank context" in plan.reason+++def test_prefer_resident_still_spills_when_even_min_ctx_will_not_fit():+ layout = q4_layout()+ plan = plan_placement(+ layout,+ [10 * GIB],+ 64 * GIB,+ 65536,+ opts = PlanOptions(context_policy = ContextPolicy.PREFER_RESIDENT),+ )+ assert plan.spilled_blocks, "shrinking cannot save this one, so spill"+++def test_context_is_clamped_to_what_the_model_was_trained_on():+ layout = q4_layout()+ plan = plan_placement(layout, [24 * GIB], 128 * GIB, 999_999)+ assert plan.n_ctx == layout.n_ctx_train+++# ------------------------------------------------------------------- KV quant+++def test_kv_quantisation_is_off_by_default():+ """35% slower generation, and only matched pairs are compiled."""+ plan = plan_placement(q4_layout(), [12 * GIB], 64 * GIB, 65536)+ assert plan.cache_type_k is None and plan.cache_type_v is None+++def test_kv_quantisation_rescues_a_load_f16_cannot_fit():+ """9 GiB with 64K of context: the f16 cache alone puts the resident floor+ at 9.73 GiB against 8 GiB usable, so no rung of the ladder fits. Halving the+ cache brings the floor to 7.73 and it does."""+ layout = q4_layout()+ without = plan_placement(layout, [9 * GIB], 64 * GIB, 65536)+ assert without.insufficient is True++ with_quant = plan_placement(+ layout,+ [9 * GIB],+ 64 * GIB,+ 65536,+ opts = PlanOptions(allow_kv_quant = True),+ )+ assert with_quant.insufficient is False+ assert with_quant.cache_type_k == "q8_0"+ # Matched pair, always: an unmatched K/V combination is not compiled without+ # GGML_CUDA_FA_ALL_QUANTS and silently falls back to CPU.+ assert with_quant.cache_type_k == with_quant.cache_type_v+++def test_f16_is_preferred_when_it_fits_even_with_quant_allowed():+ """q8_0 costs 35% of generation, so it is a rescue, not a default."""+ plan = plan_placement(+ q2_layout(),+ [24 * GIB],+ 64 * GIB,+ 8192,+ opts = PlanOptions(allow_kv_quant = True),+ )+ assert plan.cache_type_k is None+++# ------------------------------------------------- the budget ladder, end to end+++ "budget_gib,expected_k",+ # From the independently computed placement table: max context with the FFN+ # spilled, f16 cache, 1 GiB overhead.+ [(8, 20), (10, 52), (12, 84), (16, 148), (20, 212)],+)+def test_q4_ffn_spilled_context_ladder(budget_gib, expected_k):+ got = max_context_for(+ q4_layout(), [budget_gib * GIB], spill_all_ffn = True, opts = FIXED_OVERHEAD_OPTS+ )+ assert expected_k * 1024 <= got < (expected_k + 1) * 1024, got+++# Budgets and expected contexts here are ARITHMETIC against a stated overhead+# reserve, not measurements, so moving the constant (1 GiB -> 1.5 GiB, to cover+# the prefill compute buffer that was OOMing at depth) does not silently+# invalidate them. The constant itself is pinned by+# test_the_overhead_reserve_covers_the_measured_prefill_buffer.+FIXED_OVERHEAD_OPTS = PlanOptions(overhead_bytes_per_device = GIB)++[email protected]("budget_gib,expected_k", [(6, 25), (8, 57), (12, 121), (20, 249)])+def test_q2_ffn_spilled_context_ladder(budget_gib, expected_k):+ got = max_context_for(+ q2_layout(), [budget_gib * GIB], spill_all_ffn = True, opts = FIXED_OVERHEAD_OPTS+ )+ assert expected_k * 1024 <= got < (expected_k + 1) * 1024, got++[email protected]("budget_gib,expected_k", [(12, 33), (16, 97), (24, 225)])+def test_q2_fully_resident_context_ladder(budget_gib, expected_k):+ got = max_context_for(q2_layout(), [budget_gib * GIB], opts = FIXED_OVERHEAD_OPTS)+ assert expected_k * 1024 <= got < (expected_k + 1) * 1024, got++[email protected]("budget_gib", [4, 6, 8, 10])+def test_q4_cannot_be_fully_resident_below_18_gib(budget_gib):+ assert max_context_for(q4_layout(), [budget_gib * GIB]) == 0+++def test_the_ladder_never_regresses_as_vram_grows():+ """More VRAM must never mean more spill."""+ layout = q4_layout()+ counts = [+ len(+ plan_placement(+ layout, [g * GIB], 64 * GIB, 32768, opts = FIXED_OVERHEAD_OPTS+ ).spilled_blocks+ )+ for g in (8, 10, 12, 14, 16, 18, 20, 22, 24)+ ]+ assert counts == sorted(counts, reverse = True), counts+++# ------------------------------------------------------ against the real GGUFs+++@needs_gguf+ "path,spillable_gib,resident_gib,lm_head_gib,embd_gib,moe",+ [+ (Q2_PATH, 5.291, 2.471, 0.666, 0.389, False),+ (Q4_PATH, 9.888, 4.491, 0.971, 0.666, False),+ (MOE_PATH, 18.320, 1.488, 0.503, 0.503, True),+ ],+)+def test_layout_matches_the_measured_buckets(+ path, spillable_gib, resident_gib, lm_head_gib, embd_gib, moe+):+ layout = layout_from_gguf(path)+ assert layout.complete+ assert layout.is_moe is moe+ assert layout.spillable_bytes / GIB == pytest.approx(spillable_gib, abs = 0.01)+ assert layout.block_resident_bytes / GIB == pytest.approx(resident_gib, abs = 0.01)+ assert layout.lm_head_bytes / GIB == pytest.approx(lm_head_gib, abs = 0.01)+ assert layout.token_embd_bytes / GIB == pytest.approx(embd_gib, abs = 0.01)+++@needs_gguf+def test_the_hybrid_cache_is_priced_on_attention_layers_only():+ """qwen35 is 1-in-4 attention, so a naive all-layers cache would be 4x too+ big and would refuse fits that are really there."""+ layout = layout_from_gguf(Q4_PATH)+ assert layout.n_layers == 64+ assert layout.n_attention_layers == 16+ assert layout.kv_bytes_per_token_f16 == 16 * 4 * (256 + 256) * 2+ assert layout.recurrent_bytes / MIB == pytest.approx(149.6, abs = 1.0)+++@needs_gguf+def test_a_bad_path_abstains_rather_than_raising():+ assert layout_from_gguf("/nonexistent/model.gguf").complete is False+++class _StubField:+ def __init__(self, value):+ self._value = value++ def contents(self):+ return self._value+++class _StubTensor:+ def __init__(self, name, n_bytes):+ self.name = name+ self.n_bytes = n_bytes+++class _StubReader:+ """The handful of attributes ``_layout_from_reader`` touches."""++ def __init__(self, fields, tensors):+ self.fields = {k: _StubField(v) for k, v in fields.items()}+ self.tensors = tensors+++def _shard_fields(**extra):+ base = {+ "general.architecture": "llama",+ "llama.block_count": 64,+ "llama.attention.head_count_kv": 8,+ "llama.attention.head_count": 64,+ "llama.embedding_length": 8192,+ "llama.attention.key_length": 128,+ "llama.attention.value_length": 128,+ "llama.context_length": 262144,+ }+ base.update(extra)+ return base+++def _shard_tensors(indices):+ out = []+ for i in indices:+ out.append(_StubTensor(f"blk.{i}.ffn_up.weight", GIB // 8))+ out.append(_StubTensor(f"blk.{i}.attn_q.weight", MIB * 32))+ return out+++def test_a_single_file_gguf_is_still_read():+ """The guard below must not catch an ordinary one-file model."""+ layout = _layout_from_reader(_StubReader(_shard_fields(), _shard_tensors(range(64))))+ assert layout.complete+ assert len(layout.blocks) == 64+++def test_a_split_gguf_abstains_instead_of_planning_on_one_shard():+ """GGUFReader memmaps the ONE path it is given, but llama.cpp reads+ split.count off the first shard and loads every sibling+ (llama-model-loader.cpp:590-618). Shard 1 carries the model metadata, so+ without the guard the layout looks complete while holding a fraction of the+ tensors. Undercounting the model is the OPTIMISTIC direction: the plan claims+ a fit that is not there, emits too few -ot patterns, and the launch path+ follows it with --fit off."""+ partial = _StubReader(_shard_fields(**{"split.count": 4}), _shard_tensors(range(16)))+ assert _layout_from_reader(partial).complete is False++ # The undercount it guards against is real: the same shard read as the whole+ # model reports a quarter of the blocks and a quarter of the spillable bytes.+ whole = _layout_from_reader(_StubReader(_shard_fields(), _shard_tensors(range(64))))+ as_if_whole = _layout_from_reader(_StubReader(_shard_fields(), _shard_tensors(range(16))))+ assert as_if_whole.spillable_bytes * 4 == whole.spillable_bytes+++# ------------------------------------------------- host profile and cost integration+++def _dense_q4() -> ModelLayout:+ """Measured Qwen3.8-27B UD-Q4_K_XL buckets."""+ return _uniform_layout(+ spillable_total = int(10.092 * GIB),+ resident_total = int(4.614 * GIB),+ lm_head = int(0.971 * GIB),+ token_embd = int(0.666 * GIB),+ )+++def test_a_unified_memory_host_never_spills():+ """Apple Silicon, an AMD APU and a Vulkan iGPU all report host RAM as VRAM,+ so moving a tensor to "host" frees nothing on the device. The planner must+ abstain rather than emit -ot flags that buy no memory and cost real speed."""+ plan = plan_placement(+ _dense_q4(),+ [8 * GIB],+ 64 * GIB,+ 32768,+ opts = PlanOptions(host = HostProfile(unified_memory = True)),+ )+ assert plan.changed is False+ assert plan.ot_patterns == ()+ assert "unified memory" in plan.reason+++def test_a_spilling_plan_reports_what_it_will_cost():+ """A plan that spills is not free, and the number has to travel with it."""+ tight = plan_placement(_dense_q4(), [8 * GIB], 64 * GIB, 32768, opts = FIXED_OVERHEAD_OPTS)+ roomy = plan_placement(_dense_q4(), [48 * GIB], 64 * GIB, 32768, opts = FIXED_OVERHEAD_OPTS)+ assert tight.spills_anything and tight.predicted_gen_penalty_ms > 0.0+ assert not roomy.spills_anything and roomy.predicted_gen_penalty_ms == 0.0+++def test_a_small_host_is_predicted_to_suffer_more_for_the_same_spill():+ """Spilled decode runs on the CPU backend (ggml migrates an op only at+ batch >= 32, and decode is batch 1), so the penalty tracks core count. A+ desktop must not be told a server's story."""+ layout, vram, ram, ctx = _dense_q4(), [8 * GIB], 64 * GIB, 32768+ big = plan_placement(+ layout,+ vram,+ ram,+ ctx,+ opts = PlanOptions(overhead_bytes_per_device = GIB, host = HostProfile(threads = 192)),+ )+ small = plan_placement(+ layout,+ vram,+ ram,+ ctx,+ opts = PlanOptions(overhead_bytes_per_device = GIB, host = HostProfile(threads = 8)),+ )+ assert big.spilled_blocks == small.spilled_blocks, "same placement, different host"+ assert small.predicted_gen_penalty_ms > big.predicted_gen_penalty_ms * 2+++def test_routed_experts_are_charged_less_than_a_dense_ffn_of_equal_size():+ """Only n_expert_used of n_expert are read per token, so an offloaded MoE+ moves a fraction of its bytes while a dense FFN moves all of them. This is+ the real reason MoE tolerates spilling (2.5x) and dense does not (5.5x) --+ NOT the mmap penalty ratio, which points the other way."""+ dense = _dense_q4()+ moe = _uniform_layout(+ spillable_total = int(10.092 * GIB),+ resident_total = int(4.614 * GIB),+ lm_head = int(0.971 * GIB),+ token_embd = int(0.666 * GIB),+ is_moe = True,+ )+ moe = ModelLayout(**{**moe.__dict__, "n_expert": 256, "n_expert_used": 8})+ opts = PlanOptions(overhead_bytes_per_device = GIB, host = HostProfile(threads = 192))+ d = plan_placement(dense, [8 * GIB], 64 * GIB, 32768, opts = opts)+ m = plan_placement(moe, [8 * GIB], 64 * GIB, 32768, opts = opts)+ assert d.spilled_blocks == m.spilled_blocks, "same bytes spilled either way"+ assert m.predicted_gen_penalty_ms < d.predicted_gen_penalty_ms+++@needs_gguf+def test_the_mtp_block_is_not_counted_as_spillable():+ """blk.<nextn> is not part of the target model and llama.cpp does not load it+ unless a draft is engaged, so an -ot pattern naming it moves nothing.++ Measured against the real binary: spilling ONLY that block leaves the host+ buffer at exactly token_embd (682.03 MiB) and the device buffer unchanged at+ 15718.48 MiB. Counting it would credit the plan 209 MiB it can never free,+ which is the optimistic direction that claims a fit that is not there.+ """+ layout = layout_from_gguf(Q4_PATH)+ assert layout.n_layers == 64+ assert [b.index for b in layout.blocks] == list(range(64)), "no nextn block"+ assert all(b.index < layout.n_layers for b in layout.blocks)+++def test_the_overhead_reserve_covers_the_measured_prefill_buffer():+ """The reserve is what the planner leaves free on every device, and it has+ to cover the child's prefill compute buffer plus its CUDA primary context.++ 1 GiB did not, and failed CONSISTENTLY rather than randomly, which is what+ made it easy to miss: the planner fills to budget minus this reserve, so+ whatever the budget it leaves exactly this much, and the dense 27B at depth+ 32768 died with the identical shortfall at 6, 7, 8 and 10 GiB budgets:++ allocating 594.16 MiB on device 0: cudaMalloc failed: out of memory+ llama_init_from_model: failed to allocate compute pp buffers++ Not fragmentation from the benchmark's VRAM pinning: the same case at 16, 64+ and 1024 MiB hog blocks reproduced the identical 594.16 MiB failure.+ """+ reserve = PlanOptions().overhead_bytes_per_device+ measured_prefill_buffer = int(594.16 * 1024 * 1024)+ # The context consumed the remainder of the old 1 GiB, since 594 MiB could+ # not be allocated inside it.+ inferred_cuda_context = GIB - measured_prefill_buffer+ assert reserve >= measured_prefill_buffer + inferred_cuda_context+ assert reserve > GIB, "1 GiB is the value that OOMed"+ # Bounded: erring high costs spill at 5.544 ms/GiB, so it is not free.+ assert reserve <= 2 * GIB+++# ------------------------------------------- excluded blocks and the pool budget+++# Just too little VRAM for the 64-block stub at 4096 ctx, so every block spills+# and the planner reaches the all-of-them branch that emits the compact pattern.+_NO_OVERHEAD = PlanOptions(overhead_bytes_per_device = 0)+_ALL_SPILL_VRAM = 3 * GIB + 64 * MIB+++def _nextn_reader(nextn: int, total_blocks: int = 66):+ """A GGUF whose block_count includes trailing nextn/MTP blocks.++ llama.cpp reads block_count straight into n_layer_all+ (llama-model.cpp:1206) and n_layer() subtracts n_layer_nextn+ (llama-hparams.cpp:301-303), so the last `nextn` blk.<N> are the MTP head.+ They carry real ffn_* weights, loaded when a draft is engaged+ (models/qwen35moe.cpp, load_block_mtp).+ """+ fields = _shard_fields(+ **{"llama.block_count": total_blocks, "llama.nextn_predict_layers": nextn}+ )+ return _StubReader(fields, _shard_tensors(range(total_blocks)))+++def _tied_reader(*, with_output: bool):+ """The 64-block stub plus a vocabulary matrix, tied or untied."""+ tensors = list(_shard_tensors(range(64)))+ tensors.append(_StubTensor("token_embd.weight", GIB))+ if with_output:+ tensors.append(_StubTensor("output.weight", GIB))+ return _StubReader(_shard_fields(), tensors)+++def test_a_tied_embedding_gguf_still_charges_a_vocabulary_matrix_to_vram():+ """Omitting output.weight does not save the matrix, it duplicates it.++ Every tying architecture re-creates the output tensor from token_embd with+ TENSOR_DUPLICATED (models/llama.cpp:41-45, models/qwen3.cpp:22-25,+ models/gemma3.cpp:43-47), and the loader routes a duplicated TOKEN_EMBD+ through the OUTPUT buffer list (llama-model-loader.cpp:1113-1114). dev_input+ is pinned to the CPU while dev_output follows the layer split+ (llama-model.cpp:1465, 1474), so the same-context reuse check misses+ (llama-model-loader.cpp:1309-1314), ggml_dup_tensor allocates a second full+ matrix (:1318) and load_all_data fills it by name over PCIe (:1542, :1583).+ Charging it to host RAM only understated VRAM by a whole vocabulary, which+ is the optimistic direction: too few blocks spill, and --fit off pins that.+ """+ tied = _layout_from_reader(_tied_reader(with_output = False))+ untied = _layout_from_reader(_tied_reader(with_output = True))+ assert tied.complete and untied.complete+ assert tied.lm_head_bytes == 0, "there is no output.weight to spill"++ # The VRAM floor is the same either way: a vocabulary matrix is resident in+ # both, it just arrives as a duplicate in the tied case.+ assert resident_floor_bytes(tied, 4096) == resident_floor_bytes(untied, 4096)+ assert all_resident_bytes(tied, 4096) == all_resident_bytes(untied, 4096)++ # And it reaches the decision: the same card spills the same blocks.+ opts = PlanOptions(overhead_bytes_per_device = 0)+ tied_plan = plan_placement(tied, [10 * GIB], 256 * GIB, 4096, opts = opts)+ untied_plan = plan_placement(untied, [10 * GIB], 256 * GIB, 4096, opts = opts)+ assert tied_plan.spilled_blocks, "a partial spill, so lm_head is not in play"+ assert len(tied_plan.spilled_blocks) == len(untied_plan.spilled_blocks)++ # Never as lm_head: the duplicate keeps the name token_embd.weight, so+ # LM_HEAD_PATTERN cannot match it and spilling it would move nothing.+ assert tied_plan.spilled_lm_head is False+ assert LM_HEAD_PATTERN not in tied_plan.ot_patterns++ # token_embd itself is still host RAM the plan pays for, counted once.+ assert tied_plan.host_bytes - untied_plan.host_bytes == 0+++def test_excluded_mtp_block_bytes_are_kept_so_a_draft_can_be_charged():+ """Dropping the trailing blocks is right for an ordinary load -- llama.cpp+ gives them TENSOR_SKIP unless load_mtp is set (models/glm4-moe.cpp:42-44)+ and TENSOR_SKIP returns before a tensor exists+ (llama-model-loader.cpp:1123-1131). But --spec-type draft-mtp sets load_mtp+ on the TARGET's model params (common/common.cpp:1713), so the whole trailing+ block becomes resident, and i_gpu_start counting backwards from n_layer_all+ (llama-model.cpp:1449) puts it on a GPU first. The seam charges it through+ extra_resident_bytes, so the total has to survive the drop."""+ layout = _layout_from_reader(_nextn_reader(2))+ assert layout.has_excluded_blocks is True++ per_block = layout.blocks[0].spillable_bytes + layout.blocks[0].resident_bytes+ assert layout.excluded_block_bytes == 2 * per_block++ plain = _layout_from_reader(_StubReader(_shard_fields(), _shard_tensors(range(64))))+ assert plain.excluded_block_bytes == 0++ # Charging it shrinks the budget, so more blocks spill.+ base = PlanOptions(overhead_bytes_per_device = 0)+ charged = PlanOptions(+ overhead_bytes_per_device = 0, extra_resident_bytes = layout.excluded_block_bytes+ )+ without = plan_placement(layout, [10 * GIB], 256 * GIB, 4096, opts = base)+ with_mtp = plan_placement(layout, [10 * GIB], 256 * GIB, 4096, opts = charged)+ assert len(with_mtp.spilled_blocks) > len(without.spilled_blocks)+++def test_a_nextn_gguf_is_marked_as_having_excluded_blocks():+ with_mtp = _layout_from_reader(_nextn_reader(2))+ assert with_mtp.complete+ assert with_mtp.has_excluded_blocks is True+ assert [b.index for b in with_mtp.blocks] == list(range(64))++ plain = _layout_from_reader(_StubReader(_shard_fields(), _shard_tensors(range(64))))+ assert plain.has_excluded_blocks is False+++def test_the_spill_pattern_never_reaches_an_excluded_mtp_block():+ """Spilling every block used to emit the unbounded ^blk\\.\\d+\\. form, which+ llama.cpp applies with std::regex_search (llama-model-loader.cpp:1182) --+ so it also matched the trailing nextn blocks the layout deliberately+ dropped. Those are real weights once a draft is loaded, and moving them+ spills bytes that neither host_bytes nor the deficit ever counted, then+ runs the draft FFN on the CPU backend.+ """+ layout = _layout_from_reader(_nextn_reader(2))+ plan = plan_placement(layout, [_ALL_SPILL_VRAM], 256 * GIB, 4096, opts = _NO_OVERHEAD)+ assert len(plan.spilled_blocks) == len(layout.blocks), "every block goes"+ assert len(plan.ot_patterns) >= 1++ pattern = re.compile(plan.ot_patterns[0])+ assert pattern.search("blk.0.ffn_up.weight"), "a target block still spills"+ assert pattern.search("blk.63.ffn_up.weight")+ for excluded in ("blk.64.ffn_up.weight", "blk.65.ffn_down.weight"):+ assert pattern.search(excluded) is None, excluded+++def test_a_gguf_without_excluded_blocks_keeps_the_compact_pattern():+ """The bound is only paid where it buys something: with nothing excluded the+ global form is still used, which is the shape the benchmarks measured."""+ layout = _layout_from_reader(_StubReader(_shard_fields(), _shard_tensors(range(64))))+ plan = plan_placement(layout, [_ALL_SPILL_VRAM], 256 * GIB, 4096, opts = _NO_OVERHEAD)+ assert len(plan.spilled_blocks) == len(layout.blocks)+ assert re.compile(plan.ot_patterns[0]).search("blk.999.ffn_up.weight")+++def test_extra_resident_bytes_are_charged_against_the_pooled_budget():+ """GPU-resident bytes outside the layout -- a vision projector, an MTP draft+ reserve -- have to shrink the budget, or the deficit comes out too small on+ a load the caller already judged not to fit."""+ layout = q4_layout()+ base = PlanOptions(overhead_bytes_per_device = GIB)+ charged = PlanOptions(overhead_bytes_per_device = GIB, extra_resident_bytes = 3 * GIB)++ without = plan_placement(layout, [16 * GIB], 128 * GIB, 8192, opts = base)+ with_extra = plan_placement(layout, [16 * GIB], 128 * GIB, 8192, opts = charged)++ assert without.spills_anything and with_extra.spills_anything+ assert len(with_extra.spilled_blocks) > len(without.spilled_blocks)+ # And it reaches the context ladder too, not just the deficit.+ assert max_context_for(layout, [16 * GIB], spill_all_ffn = True, opts = charged) < max_context_for(+ layout, [16 * GIB], spill_all_ffn = True, opts = base+ )+++def test_row_ownership_is_modelled_on_raw_free_not_on_the_budget():+ """llama.cpp reads free VRAM straight from the driver for its split+ (llama-model.cpp:1433); the budget is that minus a reserve sized on each+ card's TOTAL, so the two agree only when every card has the same free/total.+ Feeding the budget in as the split weight silently moves the boundary."""+ layout = _layout_from_reader(_StubReader(_shard_fields(), _shard_tensors(range(64))))+ spilled = {b.index for b in layout.blocks}+ budgets = [2 * GIB, 2 * GIB]++ # Same budgets, different RAW free: the rows move, so the verdict may too.+ even = _per_device_shortfall(+ layout,+ _NO_OVERHEAD,+ 4096,+ spilled,+ False,+ budgets,+ quantised = False,+ kv_bytes_floor = 0,+ split_weights_per_device = [8 * GIB, 8 * GIB],+ )+ lopsided = _per_device_shortfall(+ layout,+ _NO_OVERHEAD,+ 4096,+ spilled,+ False,+ budgets,+ quantised = False,+ kv_bytes_floor = 0,+ split_weights_per_device = [1 * GIB, 15 * GIB],+ )+ assert even != lopsided, "the split weights have to reach _device_slots"+ assert "device 1" in (lopsided or ""), "the card drawing 60 of 65 rows is the one over"+++def test_a_sliding_window_model_abstains_on_a_multi_gpu_split():+ """Gemma3 and friends interleave window and full-context layers, and EVERY+ layer is an attention layer, so the n_attention_layers guard passes. Spreading+ the cache evenly then under-books whichever card drew the full-context rows,+ which is the optimistic direction."""+ layout = _layout_from_reader(_StubReader(_shard_fields(), _shard_tensors(range(64))))+ swa = replace(layout, has_swa = True)+ assert swa.n_attention_layers == swa.n_layers, "the earlier guard does NOT cover this"++ half = _ALL_SPILL_VRAM // 2+ plan = plan_placement(swa, [half, half], 256 * GIB, 4096, opts = _NO_OVERHEAD)+ assert plan.changed is False+ assert "sliding-window" in plan.reason++ # One card has no split to mislocate the caches across.+ one = plan_placement(swa, [_ALL_SPILL_VRAM], 256 * GIB, 4096, opts = _NO_OVERHEAD)+ assert len(one.spilled_blocks) == len(layout.blocks)diff --git a/studio/backend/tests/test_offload_planner_seam.py b/studio/backend/tests/test_offload_planner_seam.pynew file mode 100644index 00000000000..8415045723b--- /dev/null+++ b/studio/backend/tests/test_offload_planner_seam.py@@ -0,0 +1,800 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The launch-path seam for the tensor-spill planner.++Two halves, and the negative half is the important one: on every path where the+planner does not produce a plan, the argv has to be exactly what it was before+this existed. The positive half pins the flags a plan emits, above all that it+carries ``--fit off`` (a running fitter would re-place layers on top of the plan+and put the KV cache back on the host) and ``-ngl -1`` (which keeps every layer+assigned to a GPU so the cache stays with it).+"""++from __future__ import annotations++import pytest++from core.inference.llama_cpp import LlamaCppBackend+from core.inference.offload_layout import LM_HEAD_PATTERN, BlockLayout, ModelLayout+from core.inference.offload_planner import Plan, plan_placement, smart_offload_enabled++# The planner's decision table is covered in test_offload_planner.py. HERE is the+# seam: whether the launch path declines when it should, emits the tokens+# llama-server actually parses, and takes the plan back out on every retry.+FFN_SPILL_PATTERN = r"blk\.\d+\.ffn_"+LM_HEAD_SPILL_PATTERN = LM_HEAD_PATTERN++GIB = 1024**3+MIB = 1024 * 1024+++class _Stub:+ """Only what the seam touches."""++ _PIPELINE_PER_DEVICE_OVERHEAD_MIB = 1024+ _HOST_RAM_HEADROOM_MIB = 2048+ # Discrete by default, so every existing case here is a discrete host. The+ # unified answer is the APU's, and it is exercised deliberately below.+ _unified = False+ # Bytes of trailing nextn/MTP blocks the layout dropped. 0 = an ordinary+ # model, which is every existing case here.+ _excluded_bytes = 0++ def _amd_apu_wants_unified_memory(self, gpu_indices = None):+ return self._unified++ def __init__(+ self,+ avail_mib = 64 * 1024,+ ffn = 10 * GIB,+ lm_head = 1 * GIB,+ moe = 0,+ ):+ self._avail_mib = avail_mib+ self._ffn_weight_bytes = ffn+ self._lm_head_bytes = lm_head+ self.n_moe_layers = moe+ self._spill_plan_flags: list[str] = []++ def _available_system_memory_mib(self):+ return self._avail_mib++ def _can_estimate_kv(self):+ return True++ _planned_tensor_spill = LlamaCppBackend._planned_tensor_spill+ _drop_tensor_spill = LlamaCppBackend._drop_tensor_spill++ def _tensor_spill_layout(self, model_path):+ """Stand in for the GGUF read: the seam's job is to decline or to hand+ the planner well-formed inputs, not to parse a file. ``ffn = None``+ stands for an unreadable model, which must abstain."""+ if self._ffn_weight_bytes is None or not model_path:+ return None+ n = 64+ return ModelLayout(+ arch = "qwen35moe" if self.n_moe_layers else "qwen35",+ n_layers = n,+ n_attention_layers = 16,+ blocks = tuple(+ BlockLayout(+ index = i,+ spillable_bytes = self._ffn_weight_bytes // n,+ resident_bytes = (2 * GIB) // n,+ )+ for i in range(n)+ ),+ lm_head_bytes = self._lm_head_bytes or 0,+ token_embd_bytes = 512 * MIB,+ kv_bytes_per_token_f16 = 65536,+ n_ctx_train = 262144,+ is_moe = bool(self.n_moe_layers),+ n_expert = 256 if self.n_moe_layers else 0,+ n_expert_used = 8 if self.n_moe_layers else 0,+ has_excluded_blocks = bool(self._excluded_bytes),+ excluded_block_bytes = self._excluded_bytes,+ complete = True,+ )+++def _inputs(+ model_size = 30 * GIB,+ kv = 2 * GIB,+ free_mib = 24 * 1024,+ indices = None,+ usable_mib = None,+ extra_gpu = 0,+ mtp = None,+ shared = None,+ gpus = None,+ n_parallel = 1,+ compute_flat = 0,+ ctx_compute = 0,+):+ return {+ "model_size": model_size,+ "kv_cache_bytes": kv,+ "gpus": list(gpus) if gpus is not None else [(0, free_mib)],+ "gpu_usable_mib": {} if usable_mib is None else {0: usable_mib},+ "compute_buffer_flat": compute_flat,+ "ctx_compute_per_device": ctx_compute,+ "extra_gpu_bytes": extra_gpu,+ "gpu_indices": indices,+ "soft_overhead": 0,+ "model_path": "/models/stub.gguf",+ "n_ctx": 32768,+ "n_parallel": n_parallel,+ "shared_gpu_ids": set() if shared is None else set(shared),+ **({} if mtp is None else {"mtp_will_engage": mtp}),+ }+++def _plan(+ stub,+ env = None,+ extra_args = None,+ **kw,+):+ return stub._planned_tensor_spill(+ _inputs(**kw),+ extra_args = extra_args,+ env = {"UNSLOTH_SMART_OFFLOAD": "1", **(env or {})},+ )+++# ------------------------------------------------------------------ the gate+++def test_the_planner_is_off_by_default():+ """No env, no plan. An old install cannot change behaviour by upgrading."""+ assert smart_offload_enabled({}) is False+ assert _Stub()._planned_tensor_spill(_inputs(), env = {}) is None++[email protected]("value", ["1", "on", "true", "yes", "enabled", "ON", " 1 "])+def test_the_gate_accepts_the_usual_spellings(value):+ assert smart_offload_enabled({"UNSLOTH_SMART_OFFLOAD": value}) is True++[email protected]("value", ["0", "off", "", "no", "nope"])+def test_the_gate_rejects_everything_else(value):+ assert smart_offload_enabled({"UNSLOTH_SMART_OFFLOAD": value}) is False+++# ------------------------------------------------- abstain = today's behaviour+++def test_an_unpriced_placement_abstains():+ """The except arm restores use_fit without pricing anything, so the seam+ reads None here rather than an UnboundLocal kv_cache_bytes."""+ assert _Stub()._planned_tensor_spill(None, env = {"UNSLOTH_SMART_OFFLOAD": "1"}) is None+++ "extra_args",+ [+ ["-ot", ".ffn_.*=CPU"], # user already moves tensors+ ["--override-tensor", "x=CPU"],+ ["--cpu-moe"],+ ["--n-cpu-moe", "24"],+ ["-ngl", "12"], # user owns the layer count+ ["--gpu-layers", "0"],+ ["--device", "CUDA0"], # user owns the device set+ ["-dev", "none"],+ ["--fit", "on"], # user asked for the fitter+ # --fit OFF too: a retry revokes the plan by appending "--fit on", and+ # extras land before that, so planning here would overturn the user.+ ["--fit", "off"],+ ["--fit=off"],+ ["-fit", "off"],+ ],+)+def test_a_pass_through_placement_override_declines(extra_args):+ """Pricing a placement the child will not get is the bug class behind most of+ the load-mode review traffic. Decline instead of modelling the override."""+ assert _plan(_Stub(), extra_args = extra_args) is None+++ "env",+ [+ {"LLAMA_ARG_N_GPU_LAYERS": "12"},+ {"LLAMA_ARG_DEVICE": "none"},+ {"LLAMA_ARG_OVERRIDE_TENSOR": ".ffn_.*=CPU"},+ {"LLAMA_ARG_CPU_MOE": "1"},+ ],+)+def test_an_inherited_placement_env_declines(env):+ """The child inherits these, so they outlive any flag stripping."""+ assert _plan(_Stub(), env = env) is None+++def test_an_unsized_model_abstains():+ assert _plan(_Stub(), model_size = 0) is None+++def test_an_unsized_cache_abstains():+ assert _plan(_Stub(), kv = 0) is None+++def test_no_gpus_abstains():+ stub = _Stub()+ assert (+ stub._planned_tensor_spill({**_inputs(), "gpus": []}, env = {"UNSLOTH_SMART_OFFLOAD": "1"})+ is None+ )+++def test_an_absent_layout_abstains():+ """_ffn_weight_bytes is the planner-core half and does not exist yet, so the+ feature is inert until it lands even with the gate on."""+ assert _plan(_Stub(ffn = None)) is None+++def test_unreadable_host_ram_abstains():+ assert _plan(_Stub(avail_mib = None)) is None+++# ------------------------------------------------------------ the plan itself+++def test_a_load_that_needs_ffn_spilled_gets_the_ffn_pattern():+ got = _plan(_Stub(), model_size = 30 * GIB, kv = 2 * GIB, free_mib = 12 * 1024)+ assert got is not None+ assert got.ot_patterns and all("ffn" in p for p in got.ot_patterns)+++def test_a_moe_load_spills_expert_tensors_not_dense_ffn():+ got = _plan(_Stub(moe = 40), model_size = 30 * GIB, kv = 2 * GIB, free_mib = 12 * 1024)+ assert got is not None+ assert got.ot_patterns and all("ffn" in p for p in got.ot_patterns)+++def test_lm_head_is_only_spilled_after_ffn():+ """43% of generation on its own, 16% on top of an already host-bound step, so+ it is never the first rung."""+ tight = _plan(_Stub(), model_size = 60 * GIB, kv = 2 * GIB, free_mib = 5632)+ assert tight is not None+ assert tight.spilled_lm_head is True+ assert tight.spilled_blocks, "lm_head is never the first rung"+ assert tight.ot_patterns[-1] == LM_HEAD_SPILL_PATTERN+++def test_the_lm_head_pattern_is_anchored():+ """An unanchored "output\\.weight" also matches every blk.N.attn_output.weight+ under std::regex_search, which silently moves the attention output projections+ too (measured: an extra 357 MiB on a 27B)."""+ assert LM_HEAD_SPILL_PATTERN.startswith("^output")+ assert LM_HEAD_SPILL_PATTERN.endswith("$"), "must not match blk.N.attn_output.weight"+++def test_a_spill_host_ram_cannot_hold_abstains():+ """--fit on at least demand-pages; a plan here would be an OOM kill."""+ got = _plan(_Stub(avail_mib = 3 * 1024), model_size = 30 * GIB, kv = 2 * GIB, free_mib = 12 * 1024)+ assert got is None or got.load_mode_none is False+++def test_a_floor_that_does_not_fit_emits_no_flags():+ """If attention plus the cache alone will not fit, no weight spill helps and+ only -ngl (which evicts the cache) or a smaller context would.++ Asserted on the FLAGS, not on the plan object. plan_placement reports that+ case as Plan(changed=False, insufficient=True, ot_patterns=()), and a+ dataclass instance is truthy, so a seam that tested the plan for truthiness+ emitted -ngl -1 --fit off with nothing moved to the host: every layer pinned+ to the GPU and the fitter switched off, on precisely the load the planner had+ just said does not fit. Checking `insufficient` on the returned plan passes+ either way and proves nothing.+ """+ got = _plan(_Stub(), model_size = 30 * GIB, kv = 2 * GIB, free_mib = 4 * 1024)+ assert got is not None+ assert got.insufficient+ assert LlamaCppBackend._spill_plan_flags_for(got) == []+++def test_an_abstaining_plan_emits_no_flags():+ """Every plan_placement abstention returns a Plan, not None: incomplete+ layout, unified-memory host, no creditable VRAM, no usable context. None of+ them may reach the argv."""+ for plan in (+ plan_placement(ModelLayout(), [8 * GIB], 32 * GIB, 4096),+ plan_placement(+ ModelLayout(complete = True, n_ctx_train = 4096),+ [0],+ 32 * GIB,+ 4096,+ ),+ ):+ assert plan.spills_anything is False+ assert LlamaCppBackend._spill_plan_flags_for(plan) == []+++def test_a_plan_that_already_fits_emits_no_flags():+ """The planner disagreeing with Studio ("it fits after all") is not licence+ to pin every layer and turn the fitter off."""+ got = _plan(_Stub(), free_mib = 200 * 1024)+ assert got is not None and not got.spills_anything+ assert LlamaCppBackend._spill_plan_flags_for(got) == []+++def test_the_measured_cache_floors_the_planners_own_estimate():+ """layout.kv_bytes is a bare f16 GQA product with no cache-dtype, SWA, MLA,+ stream or padding term, so on an MLA or f32-cache load it lands under the+ cache Studio already sized. Under is the dangerous direction: the deficit+ comes out small, too few blocks spill, and --fit off follows the plan."""+ stub = _Stub()+ layout = stub._tensor_spill_layout("/models/stub.gguf")+ unfloored = plan_placement(layout, [20 * GIB], 64 * GIB, 32768)+ floored = plan_placement(layout, [20 * GIB], 64 * GIB, 32768, kv_bytes_floor = 8 * GIB)+ assert len(floored.spilled_blocks) > len(unfloored.spilled_blocks)+++def test_the_seam_hands_the_planner_studios_cache_size():+ """The byte-accurate number is computed at the call site and was previously+ only tested for nonzero. A bigger measured cache has to buy more spill."""+ small = _plan(_Stub(), kv = 2 * GIB, free_mib = 14 * 1024)+ large = _plan(_Stub(), kv = 10 * GIB, free_mib = 14 * 1024)+ assert small is not None and large is not None+ assert len(large.spilled_blocks) > len(small.spilled_blocks)+++# --------------------------------------------------------------- the revocation+++def test_a_retry_takes_the_plan_back_out_and_restores_the_fitter():+ stub = _Stub()+ stub._spill_plan_flags = ["-ngl", "-1", "--fit", "off", "-ot", FFN_SPILL_PATTERN]+ cmd = ["llama-server", "-m", "x.gguf", *stub._spill_plan_flags, "--port", "8080"]+ got = stub._drop_tensor_spill(cmd, "noflash")+ assert "-ot" not in got+ assert got[-2:] == ["--fit", "on"]+ assert got[:4] == ["llama-server", "-m", "x.gguf", "--port"]+++def test_the_revocation_keeps_the_record_for_a_later_respawn():+ """The CPU fallback respawns from an argv that may still carry the tokens."""+ stub = _Stub()+ stub._spill_plan_flags = ["-ngl", "-1", "--fit", "off", "-ot", FFN_SPILL_PATTERN]+ stub._drop_tensor_spill(["a", *stub._spill_plan_flags], "retry")+ assert stub._spill_plan_flags+++def test_the_revocation_is_a_no_op_without_a_plan():+ stub = _Stub()+ cmd = ["llama-server", "--fit", "on"]+ assert stub._drop_tensor_spill(cmd, "retry") == cmd+++def test_the_revocation_is_a_no_op_when_the_argv_never_carried_it():+ """The -cpu replay builds its own argv; stripping must not append --fit on+ to a command that never had the plan."""+ stub = _Stub()+ stub._spill_plan_flags = ["-ngl", "-1", "--fit", "off", "-ot", FFN_SPILL_PATTERN]+ replay = ["llama-server", "--gpu-layers", "0", "--fit", "off", "--device", "none"]+ assert stub._drop_tensor_spill(replay, "cpu") == replay+++# ------------------------------------------------------------------- emission+++def test_repeated_ot_flags_rather_than_a_joined_value():+ """llama-server accumulates repeated -ot and splits an -ot VALUE on ",".+ Joining with ";" is llama-bench's syntax and would be parsed as one pattern.+ """+ plan = Plan(ot_patterns = (FFN_SPILL_PATTERN, LM_HEAD_SPILL_PATTERN))+ tokens = [tok for pat in plan.ot_patterns for tok in ("-ot", f"{pat}=CPU")]+ assert tokens.count("-ot") == 2+ assert ";" not in " ".join(tokens)+++# ---------------------------------------------------- the argv, structurally+++def _load_model_source() -> str:+ import inspect+ return inspect.getsource(LlamaCppBackend.load_model)+++def test_the_abstain_branch_still_emits_exactly_fit_on():+ """The negative half of the compatibility argument: when the planner+ declines, the arm emits what it emitted before this existed.++ This used to assert the SOURCE TEXT of the else branch, which is why it+ passed while the abstain path was in fact emitting "-ngl -1 --fit off" --+ Plan is a dataclass with no __bool__, so the truthiness check upstream fired+ on abstained plans too. A source pin cannot see that. Driven through the+ real flag builder instead, so the emptiness that routes control to the else+ branch is what is actually asserted.+ """+ from core.inference.offload_planner import Plan++ for reason in (+ "layout or device inventory incomplete, leaving llama.cpp defaults",+ "unified memory host, spilling frees no device memory",+ "no creditable VRAM after per-device overhead",+ "no usable context length",+ ):+ plan = Plan(reason = reason)+ assert plan, "Plan is truthy, which is the trap this test exists for"+ assert LlamaCppBackend._spill_plan_flags_for(plan) == [], reason++ # Same for a plan that cannot place the load, and for one that needs nothing.+ assert (+ LlamaCppBackend._spill_plan_flags_for(Plan(reason = "does not fit", insufficient = True)) == []+ )+ assert LlamaCppBackend._spill_plan_flags_for(None) == []+++def test_the_plan_disables_the_fitter_and_pins_every_layer_to_a_gpu():+ """Both halves are load-bearing.++ --fit off: the fitter aborts only on an n_gpu_layers the USER set+ (common/fit.cpp:377) and -1 IS llama.cpp's default (llama-model.cpp:2453), so+ -ngl -1 does NOT hold it off. Left on it would re-place layers over the plan+ and put the cache back on the host, which is the thing being fixed.++ -ngl -1: keeps every layer assigned to a GPU, so dev_layer(il) is a GPU and+ the cache is allocated there (llama-kv-cache.cpp:215).++ Driven through the real emitter rather than matched against the source text:+ a formatter that rewraps the literal must not be able to fail this.+ """+ got = _plan(_Stub(), free_mib = 12 * 1024)+ assert got is not None and got.spills_anything+ flags = LlamaCppBackend._spill_plan_flags_for(got)+ assert flags[:4] == ["-ngl", "-1", "--fit", "off"]+ assert flags.count("-ot") == len(got.ot_patterns) >= 1+ assert all(tok.endswith("=CPU") for tok in flags[5::2])+++def test_a_spill_plan_startup_failure_can_revoke_the_plan():+ """The spill arm leaves fully_gpu_offloaded False and runs under use_fit with+ an explicit --fit on the argv, so BOTH existing crash recoveries are+ unreachable from it. Without a third arm a slightly optimistic plan skips+ straight to the terminal fallbacks instead of retrying the --fit on placement+ it replaced. Reachability only: the revocation must be reachable from the+ crash path, not just from the `label` guard at the top of the spawn."""+ import inspect++ body = inspect.getsource(LlamaCppBackend.load_model)+ body = body[body.index("def _spawn_and_wait") :]+ assert body.count("_drop_tensor_spill") >= 2+++def test_the_revocation_runs_only_on_retries():+ """Gated on `label`, which is empty only on the first spawn. A retry added+ later is covered without anyone remembering to strip -- the failure mode that+ produced most of the review traffic on the load-mode work."""+ import inspect++ src = inspect.getsource(LlamaCppBackend.load_model)+ idx = src.index("def _spawn_and_wait")+ head = src[idx : idx + 1600]+ assert "if label:" in head+ assert "_drop_tensor_spill" in head+++# ------------------------------------------------- unified memory APUs (ROCm)+++def test_a_unified_memory_apu_is_declared_to_the_planner():+ """The seam has to TELL the planner the host is unified; it cannot guess.++ On a unified-memory APU the credited "VRAM" is system RAM, so an -ot spill+ moves bytes between two names for one pool: it frees no device memory and+ only buys the CPU backend's slower read path. plan_placement abstains on+ those, but solely on HostProfile.unified_memory, which defaults False.++ The neighbouring `shared_gpu_ids` guard does not cover this. It is populated+ only when `is_vulkan_backend` is true (Vulkan reports total VRAM 0 for an+ iGPU), so a Strix Halo on ROCm -- what scripts/install_rocm_wsl_strixhalo.sh+ installs -- arrives with an EMPTY shared set, its APU "VRAM" credited AND+ host RAM credited, which counts one pool twice.+ """+ discrete = _Stub()+ apu = _Stub()+ apu._unified = True++ # Same numbers either way, so the difference is attributable to the flag.+ got_discrete = _plan(discrete, free_mib = 12 * 1024)+ got_apu = _plan(apu, free_mib = 12 * 1024)++ assert got_apu is not None+ assert not got_apu.spills_anything+ assert "unified memory" in got_apu.reason+ assert LlamaCppBackend._spill_plan_flags_for(got_apu) == []++ assert got_discrete is not None+ assert got_discrete.spills_anything, "the discrete host is free to plan"++ # And the seam passes the real predicate rather than leaving the default.+ import inspect++ compact = "".join(inspect.getsource(LlamaCppBackend._planned_tensor_spill).split())+ assert "unified_memory=self._amd_apu_wants_unified_memory(" in compact+++# ------------------------------------------- the budget the fit actually tested+++ "extra_args",+ [+ ["--split-mode", "none"],+ ["-sm", "none"],+ ["--split-mode", "row"],+ ["--tensor-split", "3,1"],+ ["-ts", "3,1"],+ ],+)+def test_a_split_placement_argument_declines(extra_args):+ """Split mode and tensor split are placement, and they are not in+ _DEVICE_FLAGS, so the old guard let them through.++ They reach the child: the layer path's own note in this module says "-sm+ none/row keep the layer path and pass through", and extras are appended+ last, so they win. Under -sm none llama.cpp truncates model->devices to the+ single main GPU (llama.cpp:288-299), while this planner credits the SUM of+ every selected card -- so it would size the plan against a pool the child+ never gets and then pin that with --fit off. -ts replaces the free-memory+ proportional split (llama-model.cpp:1417-1447), so one device can overflow+ while the pool total still fits.+ """+ assert _plan(_Stub(), extra_args = extra_args) is None+ # Not vacuous: the same load DOES plan without the argument.+ assert _plan(_Stub()) is not None+++ "env",+ [{"LLAMA_ARG_SPLIT_MODE": "none"}, {"LLAMA_ARG_TENSOR_SPLIT": "3,1"}],+)+def test_an_inherited_split_placement_env_declines(env):+ assert _plan(_Stub(), env = env) is None+++def test_the_planner_gets_the_budget_the_fit_tested_not_raw_free():+ """_gpu_usable applies the user's VRAM-budget fraction and the per-card+ reserve floor; raw free_mib is neither.++ The budget is settable down to 0.80 (vram_budget_settings), so on a 24 GiB+ card the fit tests ~4.8 GiB less than free, and even at the 0.97 default a+ big card holds back 3% rather than the planner's flat per-device reserve.+ Planning on free credits VRAM the fit had already ruled out, emits too few+ -ot overrides, and then appends --fit off over the result.+ """+ stub = _Stub()+ on_free = _plan(stub, free_mib = 15 * 1024)+ on_budget = _plan(stub, free_mib = 15 * 1024, usable_mib = 13 * 1024)++ assert on_free is not None and on_budget is not None+ assert on_free.spills_anything and on_budget.spills_anything+ assert len(on_budget.spilled_blocks) > len(on_free.spilled_blocks)+++def test_the_projector_and_mtp_reserve_reach_the_planner():+ """The layout is rebuilt from the target GGUF's tensor table, so a vision+ projector and the MTP draft reserve are invisible to it -- yet both are in+ the model_size_fit that produced the use_fit verdict this arm answers.+ Leaving them out makes the deficit too small on exactly the loads Studio+ already judged not to fit, and the launch then follows that with --fit off.+ """+ stub = _Stub()+ without = _plan(stub, free_mib = 15 * 1024)+ with_extra = _plan(stub, free_mib = 15 * 1024, extra_gpu = 2 * GIB)++ assert without is not None and with_extra is not None+ assert without.spills_anything and with_extra.spills_anything+ assert len(with_extra.spilled_blocks) > len(without.spilled_blocks)+++def test_the_layout_cache_notices_a_gguf_replaced_in_place(tmp_path, monkeypatch):+ """The backend instance outlives a load, so re-downloading or re-quantising+ a model to the SAME path inside one session must not be planned against the+ old tensor table: a larger replacement understates the deficit, emits too+ few -ot overrides, and still appends --fit off.+ """+ from core.inference import offload_layout++ class _CacheStub:+ _tensor_spill_layout = LlamaCppBackend._tensor_spill_layout++ reads: list[int] = []++ def _fake(path):+ reads.append(len(reads))+ return ModelLayout(arch = "llama", n_layers = len(reads), complete = True)++ monkeypatch.setattr(offload_layout, "layout_from_gguf", _fake)++ gguf = tmp_path / "model.gguf"+ gguf.write_bytes(b"a")+ backend = _CacheStub()++ first = backend._tensor_spill_layout(str(gguf))+ assert backend._tensor_spill_layout(str(gguf)) is first, "unchanged file is cached"+ assert len(reads) == 1++ gguf.write_bytes(b"bb")+ second = backend._tensor_spill_layout(str(gguf))+ assert len(reads) == 2, "a replaced file is re-read"+ assert second.n_layers != first.n_layers+++# ------------------------------------------------- KV placement is placement too+++ "extra_args",+ [["-nkvo"], ["--no-kv-offload"]],+)+def test_a_forced_cpu_kv_cache_declines(extra_args):+ """-nkvo sends the WHOLE cache to host RAM whatever -ngl says: offload is a+ single scalar on the cache object and the buffer type falls back to+ ggml_backend_cpu_buffer_type() for every layer (llama-kv-cache.cpp:210-219),+ with the same branch in the recurrent and DSV4 caches.++ This planner charges the cache against VRAM via kv_bytes_floor, so it would+ spill FFN blocks to cover a deficit the child never has, and a spilled block+ is read by the CPU backend on every token. --fit on gets it right for free+ because it measures buffer types rather than modelling them: a host-resident+ cache lands in the host bucket (common/fit.cpp:74-79), which the per-device+ fitting loop then ignores (common/fit.cpp:326-347).+ """+ assert _plan(_Stub(), extra_args = extra_args) is None+ # Not vacuous: the same load DOES plan without the argument.+ assert _plan(_Stub()) is not None++[email protected]("env", [{"LLAMA_ARG_KV_OFFLOAD": "0"}, {"LLAMA_ARG_KV_OFFLOAD": "false"}])+def test_an_inherited_kv_offload_env_declines(env):+ assert _plan(_Stub(), env = env) is None+++def test_the_positive_kv_offload_form_still_plans():+ """-kvo / --kv-offload is the enabling half of the same paired argument+ (common/arg.cpp:2402-2409) and argv is last-wins, so a re-enable must not be+ read as a decline."""+ assert _plan(_Stub(), extra_args = ["-kvo"]) is not None+ assert _plan(_Stub(), extra_args = ["-nkvo", "--kv-offload"]) is not None+ assert _plan(_Stub(), env = {"LLAMA_ARG_KV_OFFLOAD": "1"}) is not None+++# --------------------------------------------- embedded MTP blocks when drafting+++def test_an_engaged_draft_charges_the_excluded_mtp_blocks():+ """The layout drops the trailing nextn/MTP blocks, which is right until a+ draft engages.++ --spec-type draft-mtp sets load_mtp on the TARGET's own model params+ (common/common.cpp:1713), which clears the TENSOR_SKIP those blocks+ otherwise carry (models/glm4-moe.cpp:42-44,+ llama-model-loader.cpp:1123-1131), and i_gpu_start counting backwards from+ n_layer_all (llama-model.cpp:1449) places them on a GPU first. Studio's own+ budget already paid for them -- an embedded head contributes 0 to the draft+ weights precisely because they sit inside model_size -- so leaving them out+ here makes the deficit too small, which is the optimistic direction.+ """+ stub = _Stub()+ stub._excluded_bytes = 3 * GIB++ idle = _plan(stub, free_mib = 15 * 1024, mtp = False)+ drafting = _plan(stub, free_mib = 15 * 1024, mtp = True)++ assert idle is not None and drafting is not None+ assert idle.spills_anything and drafting.spills_anything+ assert len(drafting.spilled_blocks) > len(idle.spilled_blocks)+++def test_an_ordinary_model_is_unaffected_by_the_draft_flag():+ """No excluded blocks, nothing to charge: the flag must not move a plan on a+ model that has no MTP head."""+ stub = _Stub()+ assert stub._excluded_bytes == 0+ idle = _plan(stub, free_mib = 15 * 1024, mtp = False)+ drafting = _plan(stub, free_mib = 15 * 1024, mtp = True)+ assert idle.spilled_blocks == drafting.spilled_blocks+++# ------------------------------------------- devices the child can still use+++def test_a_shared_device_the_child_keeps_declines_the_plan():+ """Dropping a shared iGPU from the BUDGET only helps if the child stops using+ it, and nothing here can promise that: the auto-Vulkan arm pins every+ DETECTED gpu, and it runs after this snapshot is taken, so gpu_indices reads+ None right here. llama.cpp then splits rows by free memory, and an iGPU's+ free is the whole host pool, so it draws the majority of the layers and their+ caches -- pinned with --fit off. Decline instead of planning around it.+ """+ stub = _Stub()+ gpus = [(0, 12 * 1024), (1, 12 * 1024)]+ assert _plan(stub, gpus = gpus, shared = {1}) is None+ # Named in the pin: still declined, since the child is told to use it.+ assert _plan(stub, gpus = gpus, shared = {1}, indices = [0, 1]) is None+ # Pinned away from the shared device: the plan may proceed.+ kept = _plan(stub, gpus = gpus, shared = {1}, indices = [0])+ assert kept is not None+ # No shared device at all is the ordinary path.+ assert _plan(stub, gpus = gpus) is not None+++def test_the_compute_buffer_reaches_the_planner():+ """model_size_fit carries the flat compute buffer IN ADDITION to+ soft_overhead, and the fit adds the context-linear _cc_bytes per device ON+ TOP of the pipeline reserve -- so there is nothing double-charged to avoid,+ and omitting them under-reserves on exactly the long-context loads this arm+ exists for. Both must move the deficit."""+ stub = _Stub()+ base = _plan(stub, free_mib = 14 * 1024)+ assert base is not None and base.spills_anything++ per_device = _plan(stub, free_mib = 14 * 1024, ctx_compute = 3 * GIB)+ flat = _plan(stub, free_mib = 14 * 1024, compute_flat = 3 * GIB)+ for tighter in (per_device, flat):+ assert tighter is not None+ assert len(tighter.spilled_blocks) > len(+ base.spilled_blocks+ ), "charging the compute buffer has to spill MORE, not the same"+++def test_the_seam_hands_the_planner_raw_free_vram_for_the_split():+ """llama.cpp sizes its row ranges from raw free VRAM and knows nothing about+ Studio's budget, so the seam has to pass the raw numbers separately. Observed+ through the call rather than the source: the planner records what it was+ given."""+ seen = {}+ stub = _Stub()+ import core.inference.offload_planner as mod++ real = mod.plan_placement++ def spy(*a, **kw):+ seen.update(kw)+ seen["vram"] = a[1]+ return real(*a, **kw)++ mod.plan_placement = spy+ try:+ _plan(stub, gpus = [(0, 8 * 1024), (1, 16 * 1024)], usable_mib = 6 * 1024)+ finally:+ mod.plan_placement = real++ # Index 0 carries a usable_mib override, index 1 falls back to raw free. The+ # split weights must be raw on BOTH, and in the same device order.+ assert seen["split_weights_per_device"] == [8 * 1024 * MIB, 16 * 1024 * MIB]+ assert seen["vram"] == [6 * 1024 * MIB, 16 * 1024 * MIB]+++def test_a_pinned_draft_device_declines_the_plan():+ """A drafter pinned to a card is placement, and it is not in _DEVICE_FLAGS.+ Its reserve rides in extra_resident_bytes, which _per_device_shortfall books+ onto device 0, while llama.cpp puts the drafter where the pin says -- so the+ plan would approve the wrong device's footprint and emit --fit off. cpu and+ none are not pins and must not cost a plan."""+ stub = _Stub()+ assert _plan(stub, extra_args = ["--spec-draft-device", "CUDA1"]) is None+ assert _plan(stub, extra_args = ["--device-draft", "CUDA0,CUDA1"]) is None+ assert _plan(stub, extra_args = ["--spec-draft-device", "cpu"]) is not None+ assert _plan(stub, extra_args = ["--spec-draft-device", "none"]) is not None+ assert _plan(stub) is not None+++def test_a_pass_through_parallel_that_grows_the_cache_declines_the_plan():+ """Slots are sizing, not placement. Studio's --parallel is emitted first and+ the extras are appended after it, so a larger pass-through wins at the child+ while the deficit here was priced for the smaller count -- too few blocks+ spilled, then pinned with --fit off. A SMALLER one only over-reserves, which+ is safe, so it must not cost a plan."""+ stub = _Stub()+ assert _plan(stub, n_parallel = 1, extra_args = ["--parallel", "8"]) is None+ assert _plan(stub, n_parallel = 1, extra_args = ["-np", "4"]) is None+ assert _plan(stub, n_parallel = 1, extra_args = ["--parallel=8"]) is None+ assert _plan(stub, n_parallel = 8, extra_args = ["--parallel", "8"]) is not None+ assert _plan(stub, n_parallel = 8, extra_args = ["--parallel", "2"]) is not None+ assert _plan(stub, n_parallel = 1, env = {"LLAMA_ARG_N_PARALLEL": "8"}) is None+ # Last wins, exactly as llama.cpp parses it.+ assert _plan(stub, n_parallel = 4, extra_args = ["--parallel", "8", "-np", "2"]) is not None+ assert _plan(stub, n_parallel = 1) is not None