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: widen what the offload planner can place instead of declining (#9778)
Daniel Han20100c16a43f
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 4a1cb4c1d20..43463a600f2 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -4390,6 +4390,71 @@ 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_split_mode(+ extra_args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None+) -> Optional[str]:+ """Last-wins ``-sm`` / ``--split-mode`` value, lowercased, or None."""+ source_env = os.environ if env is None else env+ found: Optional[str] = None+ raw = source_env.get("LLAMA_ARG_SPLIT_MODE")+ if raw and str(raw).strip():+ found = str(raw).strip().lower()+ 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 _SPLIT_MODE_FLAGS:+ continue+ value = inline if inline else (args[i + 1] if i + 1 < len(args) else "")+ if value.strip():+ found = value.strip().lower()+ return found+++def _extra_args_tensor_split(+ extra_args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None+) -> Optional[list[float]]:+ """Last-wins ``-ts`` / ``--tensor-split`` proportions, or None.++ llama.cpp copies these into ``splits`` verbatim and prefix-sums them+ (llama-model.cpp:1436-1447), so they ARE the row-ownership weights that+ ``split_weights_per_device`` carries. Malformed parses to None rather than+ raising, which puts the load back on the decline path.++ The delimiter set is llama.cpp's own ``[,/]+`` (common/arg.cpp:2791-2804) and+ nothing else: ``-ts 3/1`` is exactly ``-ts 3,1`` to the child, while inventing+ extra delimiters is the same bug pointing the other way -- ``std::stof`` stops+ at the first non-numeric character, so ``-ts 3;1`` is ``[3, 0]``, not+ ``[3, 1]``.+ """+ source_env = os.environ if env is None else env+ raw: Optional[str] = None+ env_value = source_env.get("LLAMA_ARG_TENSOR_SPLIT")+ if env_value and str(env_value).strip():+ raw = str(env_value).strip()+ 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 _TENSOR_SPLIT_FLAGS:+ continue+ value = inline if inline else (args[i + 1] if i + 1 < len(args) else "")+ if value.strip():+ raw = value.strip()+ if raw is None:+ return None+ try:+ parts = [float(p) for p in re.split(r"[,/]+", raw) if p.strip()]+ except ValueError:+ return None+ # isfinite, not just >= 0: float() takes "nan"/"inf", and NaN passes BOTH the+ # other tests (every comparison against NaN is false, sum() of a NaN list is+ # NaN). The caller's int(round(p * scale)) would then raise ValueError /+ # OverflowError with nothing catching it, aborting a load llama.cpp itself+ # merely degenerates on. Rejecting here routes it to the unparseable decline.+ if not parts or any(not math.isfinite(p) or p < 0 for p in parts) or sum(parts) <= 0:+ return None+ return parts++def _extra_args_n_parallel(extra_args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None) -> Optional[int]:@@ -9904,6 +9969,114 @@ class LlamaCppBackend:or self._n_kv_heads_by_layer is not None)+ def _kv_layer_weights(+ self,+ n_ctx: int,+ *,+ swa_full: bool = False,+ n_parallel: int = 1,+ kv_unified: bool = True,+ n_ubatch: Optional[int] = None,+ flash_attn: bool = True,+ cache_type_kv: Optional[str] = None,+ ) -> "list[int]":+ """Relative KV size per layer, or [] when the shape is uniform/unknown.++ Only the RATIOS matter: the planner scales this to the byte-accurate total+ it already has, so it never becomes a second, competing estimate of the+ cache size. It exists because the total says nothing about WHERE the big+ caches land, which on a multi-device split is the whole question -- a+ sliding-window layer holds a window's worth of cells while a+ full-attention layer holds the entire context, ~100x more at 128K against+ a 1K window (llama-kv-cache-iswa.cpp:69-104).++ The cell geometry MUST be the one the total was priced at, so the launch+ knobs that change it travel too: ``--swa-full`` collapses the two cache+ sizes into one, and the compact SWA allowance is per-slot plus a+ micro-batch and padded (_estimate_kv_cache_bytes path 3), not a bare+ ``min(window, n_ctx)``. Pricing a ratio the total does not have moves cache+ bytes onto the wrong card, a per-device shortfall under the ``--fit off``+ the plan pins.++ Trailing layers that reuse an earlier layer's cache get weight 0: Gemma 3n+ / Gemma 4 set ``n_layer_kv_from_start = n_layer_all - shared_kv_layers``+ and ``llama_hparams::has_kv`` is false past it (llama-hparams.cpp:275-279),+ so they allocate nothing. Giving them weight would spread the same total+ over layers that hold no cache.++ Only ever describes _estimate_kv_cache_bytes PATH 3, which picks its path+ before it looks at the window. The earlier paths price a different+ quantity: path 1 (MLA) caches one compressed K latent per layer with NO V+ and no window/full distinction, path 2 (hybrid recurrent) caches only 1 in+ full_attention_interval layers. A window-shaped vector against either is a+ different model of the cache, not an approximation, so answer [] and let+ the planner abstain. Reachable, not hypothetical: dots3note reads+ KV_LORA_RANK and ATTENTION_SLIDING_WINDOW(_PATTERN) in the same loader.++ Omits the per-slot context-checkpoint extra deliberately: llama.cpp's+ checkpoints are HOST buffers (common/common.cpp:2282-2297), so no VRAM+ total this is scaled against contains them either.+ """+ pattern = self._sliding_window_pattern+ n_layers = self._n_layers or 0+ if not pattern or n_layers <= 0:+ return []+ # Mirror _estimate_kv_cache_bytes' branch order: anything it returns before+ # path 3 is a shape this vector cannot describe.+ if self._kv_lora_rank is not None:+ return []+ if self._ssm_inner_size is not None and self._full_attention_interval is not None:+ return []+ swa = self._sliding_window or 0+ if swa <= 0:+ return []+ n_kv = self._n_kv_heads or self._n_heads or 1+ key_len = self._kv_key_length or 0+ val_len = self._kv_value_length or 0+ if not key_len or not val_len:+ return []+ key_len_swa = self._kv_key_length_swa or key_len+ val_len_swa = self._kv_value_length_swa or val_len+ # Same floor as _estimate_kv_cache_bytes: a bad GGUF cannot zero the vector.+ n_layers_kv = max(1, n_layers - (self._shared_kv_layers or 0))+ # Same cell layout the byte total was computed with.+ slots, streams, cells_per_stream = _kv_cache_cell_layout(n_ctx, n_parallel, kv_unified)+ full_cells = max(1, cells_per_stream * streams)+ if swa_full:+ swa_cells = full_cells+ else:+ ubatch = max(0, int(self._DEFAULT_N_UBATCH if n_ubatch is None else n_ubatch))+ swa_limit = int(swa) * (slots if kv_unified else 1) + ubatch+ swa_cells = max(1, _pad_kv_cells(min(cells_per_stream, swa_limit)) * streams)+ # With flash attention OFF llama.cpp cannot use a ragged V cache: every+ # layer's V is padded to hparams.n_embd_v_gqa_max() over the WHOLE model,+ # which is what _estimate_kv_cache_bytes charges (_max_kv_value_width). The+ # V half goes constant while K stays per-layer, so an unpadded vector+ # prices a ratio the total does not have. Not an edge case: load_model pins+ # planned_flash_attn = False unconditionally (llama_cpp.py:16690), so the+ # padded branch is the only one the total ever takes. bpe_v is floored at+ # f16 for a quantised cache, and with V constant that asymmetry moves the+ # ratio too, so carry both rather than cancelling one.+ bpe_k = _kv_bytes_per_elem(cache_type_kv)+ bpe_v = bpe_k if flash_attn else max(bpe_k, _kv_bytes_per_elem("f16"))+ padded_v_width = None if flash_attn else self._max_kv_value_width(val_len, val_len_swa)+ weights: list[int] = []+ for layer_idx in range(n_layers):+ if layer_idx >= n_layers_kv:+ weights.append(0)+ continue+ layer_n_kv = self._kv_heads_for_layer(layer_idx, n_kv)+ is_swa = layer_idx < len(pattern) and bool(pattern[layer_idx])+ key_bytes = layer_n_kv * (key_len_swa if is_swa else key_len) * bpe_k+ value_bytes = (+ layer_n_kv * (val_len_swa if is_swa else val_len)+ if padded_v_width is None+ else padded_v_width+ ) * bpe_v+ width = key_bytes + value_bytes+ weights.append(int(width * (swa_cells if is_swa else full_cells)))+ return weights if any(weights) else []+def _kv_heads_for_layer(self, layer_idx: int, fallback: int) -> int:if self._n_kv_heads_by_layer is not None and layer_idx < len(self._n_kv_heads_by_layer):return self._n_kv_heads_by_layer[layer_idx]@@ -18826,6 +18999,20 @@ class LlamaCppBackend:# A pass-through --parallel is appended after Unsloth's own# and wins, and both caches scale with it."n_parallel": int(n_parallel or 1),+ # Relative cache size per layer: only the ratios are used+ # (the planner scales them to kv_cache_bytes), but they say+ # WHERE the big caches land, which the total cannot. Same+ # launch settings kv_cache_bytes was priced at, so the+ # vector describes the same cache geometry.+ "kv_layer_weights": self._kv_layer_weights(+ effective_ctx,+ swa_full = swa_full,+ n_parallel = n_parallel,+ kv_unified = planned_kv_unified,+ n_ubatch = _effective_ubatch,+ flash_attn = planned_flash_attn,+ cache_type_kv = cache_type_kv,+ ),# 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 ()),@@ -23605,18 +23792,31 @@ class LlamaCppBackend:# 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()+ # -sm row and -sm tensor split WITHIN a tensor rather than handing out+ # whole rows of layers, so the row model below does not describe them.+ # `tensor` is a real accepted value (common/arg.cpp:2762-2776) and goes+ # further than `row`: llama.cpp collapses every card into ONE meta+ # device (llama.cpp:157-215), so per-device budgets are meaningless,+ # and llama.cpp's own fitter refuses it (common/fit.cpp:182-183).+ # `none` and `layer` ARE describable and are handled after this gate.+ or (_extra_args_split_mode(extra_args, source_env) in ("row", "tensor"))+ # An INHERITED -sm none may never reach the child: on a layer-split+ # launch load_model pops LLAMA_ARG_SPLIT_MODE (plus the paired+ # LLAMA_ARG_TENSOR_SPLIT) for any non-"layer" mode+ # (llama_cpp.py:20452-20458). That runs AFTER this and its predicate is+ # not visible here, so budgeting the single main GPU below would plan+ # against a mode the child never sees and skip the per-device check+ # entirely (it short-circuits on one device). argv is the only spelling+ # that provably survives to the child.+ or (+ _extra_args_split_mode(extra_args, source_env) == "none"+ and _extra_args_split_mode(extra_args, {}) != "none"+ )+ # -mg is declined above as a device flag; its env twin is not a flag+ # and reaches the child anyway. Under -sm none llama.cpp keeps+ # devices[main_gpu] (llama.cpp:288-299), so budgeting the first+ # retained card would price the wrong GPU.+ or str(source_env.get("LLAMA_ARG_MAIN_GPU", "")).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@@ -23626,17 +23826,6 @@ class LlamaCppBackend: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@@ -23695,6 +23884,15 @@ class LlamaCppBackend:for idx, free_mib in rowsif idx not in shared and (pinned_set is None or idx in pinned_set)]+ # -sm none is not a reason to decline, it is a device list of one:+ # llama.cpp keeps only devices[main_gpu] (llama.cpp:288-299), the+ # single-GPU case this planner has the most evidence for. -mg and+ # LLAMA_ARG_MAIN_GPU are declined above, so main_gpu is llama.cpp's default+ # of 0 -- the first kept row. ARGV only, deliberately: the env spelling is+ # declined above because load_model may strip it before launch, so it does+ # not describe the child's device list.+ if _extra_args_split_mode(extra_args, {}) == "none" and kept:+ kept = kept[:1]vram_per_device = [int(usable_mib.get(idx, free_mib) * 1024 * 1024) for idx, free_mib in kept]@@ -23704,6 +23902,39 @@ class LlamaCppBackend:# 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]+ # -ts REPLACES that free-memory split rather than skewing it: llama.cpp+ # copies tensor_split into `splits` verbatim and prefix-sums it+ # (llama-model.cpp:1436-1447), so it IS the row-ownership weight, not a+ # reason to decline. A share of 0 draws no rows, which _device_slots+ # already models, and the length must match `kept` or the two lists stop+ # describing the same devices.+ # Read the env the CHILD will get: load_model pops LLAMA_ARG_TENSOR_SPLIT+ # together with a non-layer LLAMA_ARG_SPLIT_MODE (llama_cpp.py:20505-20511),+ # so an inherited -ts riding alongside such a mode never reaches the child+ # -- proving row ownership against the scrubbed shares approves the wrong+ # device and pins it with --fit off. argv is untouched by that+ # reconciliation, so it is always read.+ _inherited_sm = str(source_env.get("LLAMA_ARG_SPLIT_MODE", "")).strip().lower()+ _ts_env = source_env if _inherited_sm in ("", "layer") else {}+ _ts = _extra_args_tensor_split(extra_args, _ts_env)+ if _ts is None and (+ _extra_args_set_any_flag(extra_args, _TENSOR_SPLIT_FLAGS)+ or str(_ts_env.get("LLAMA_ARG_TENSOR_SPLIT", "")).strip()+ ):+ # A -ts we could not read is NOT "no -ts": the child still gets one,+ # and free-VRAM proportions under it are the shortfall this avoids.+ logger.debug("Tensor spill: declined, -ts is present but could not be parsed")+ return None+ if _ts is not None:+ if len(_ts) < len(kept):+ logger.debug(+ "Tensor spill: declined, -ts names %d shares for %d devices",+ len(_ts),+ len(kept),+ )+ return None+ _scale = max(split_weights) if split_weights else 1+ split_weights = [int(round(p * _scale)) for p in _ts[: len(kept)]]if not vram_per_device:return Noneavail_mib = self._available_system_memory_mib()@@ -23730,6 +23961,7 @@ class LlamaCppBackend:avail_mib * 1024 * 1024,int(inputs.get("n_ctx") or 0),split_weights_per_device = split_weights,+ kv_layer_weights = list(inputs.get("kv_layer_weights") or ()),opts = PlanOptions(overhead_bytes_per_device = (int(inputs.get("soft_overhead") or 0)@@ -23737,6 +23969,10 @@ class LlamaCppBackend:+ int(inputs.get("ctx_compute_per_device") or 0)),host_ram_headroom_bytes = self._HOST_RAM_HEADROOM_MIB * 1024 * 1024,+ # -nkvo is not a reason to decline: it moves the cache and the+ # recurrent state OUT of VRAM, so the deficit is smaller, not+ # larger.+ kv_on_host = not _kv_offload_from_args(extra_args, env = source_env),# 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_fitdiff --git a/studio/backend/core/inference/offload_layout.py b/studio/backend/core/inference/offload_layout.pyindex fa30c6b3ae7..db14cda0958 100644--- a/studio/backend/core/inference/offload_layout.py+++ b/studio/backend/core/inference/offload_layout.py@@ -22,7 +22,13 @@ _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$")+# Fused (ffn_gate_up_exps, cohere2moe/deepseek2/dots3note) and chunked+# (ffn_*_chexps, grovemoe) spellings are experts too: created per expert and+# dispatched with GGML_OP_MUL_MAT_ID, so read just as sparsely as the split form.+# NOT ffn_routed_up/down: kimi-k3 creates it {n_embd, n_embd_latent} with no+# expert axis and plain GGML_OP_MUL_MAT, so every token crosses it -- spilling it+# would send a hot tensor to the host at the rate reserved for cold ones.+_MOE_EXPERT_RE = re.compile(r"^ffn_(up|gate|down|gate_up)_(exps|chexps)\.weight$")# Dense FFN. Fully activated: every byte crosses the bus every token._DENSE_FFN_RE = re.compile(r"^ffn_(up|gate|down)\.weight$")@@ -308,7 +314,9 @@ def spill_pattern_for(layout: ModelLayout, indices: Optional[list[int]] = None)``\\.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)"+ # Same set _MOE_EXPERT_RE selected, or the plan credits itself bytes the+ # emitted pattern never moves.+ body = "ffn_(up|gate|down|gate_up)_(exps|chexps)" if layout.is_moe else "ffn_(up|gate|down)"if indices is None:block = r"\d+"else:diff --git a/studio/backend/core/inference/offload_planner.py b/studio/backend/core/inference/offload_planner.pyindex 215dfbd61f8..efd203bf565 100644--- a/studio/backend/core/inference/offload_planner.py+++ b/studio/backend/core/inference/offload_planner.py@@ -120,6 +120,13 @@ class PlanOptions:# to CPU and stalls). Off by default; matched pairs only when enabled.allow_kv_quant: bool = Falsekv_quant_type: str = "q8_0"+ # The caller passed -nkvo (or a false LLAMA_ARG_KV_OFFLOAD), so llama.cpp puts+ # the WHOLE cache on the host: offload is one scalar and the buffer type falls+ # back to the CPU one for every layer (llama-kv-cache.cpp:210-219), same branch+ # in the recurrent and DSV4 caches. The cache and the recurrent state move out+ # of the VRAM footprint and into the host one; charging them to VRAM anyway+ # would spill FFN blocks for a deficit the child never has.+ kv_on_host: bool = False@dataclass(frozen = True)@@ -257,6 +264,7 @@ def resident_floor_bytes(*,kv_quantised: bool = False,kv_bytes_floor: int = 0,+ kv_on_host: bool = False,) -> int:"""VRAM needed with EVERY spillable tensor already on the host.@@ -264,6 +272,9 @@ def resident_floor_bytes(cache and lm_head. Below this, ``-ot`` has nothing left to give and only asmaller quant or less context can help."""+ if kv_on_host:+ # Both caches follow the same scalar, so neither is VRAM here.+ return layout.block_resident_bytes + layout.lm_head_bytes + layout.other_resident_bytesreturn (layout.block_resident_bytes+ layout.lm_head_bytes@@ -279,12 +290,17 @@ def all_resident_bytes(*,kv_quantised: bool = False,kv_bytes_floor: int = 0,+ kv_on_host: bool = False,) -> int:"""VRAM needed with nothing spilled. token_embd is excluded: it is neverGPU-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,+ n_ctx,+ kv_quantised = kv_quantised,+ kv_bytes_floor = kv_bytes_floor,+ kv_on_host = kv_on_host,)+ layout.spillable_bytes)@@ -331,6 +347,7 @@ def plan_placement(opts: Optional[PlanOptions] = None,kv_bytes_floor: int = 0,split_weights_per_device: Sequence[int] = (),+ kv_layer_weights: Sequence[int] = (),) -> Plan:"""Decide the placement for one launch.@@ -341,6 +358,10 @@ def plan_placement(split. Empty falls back to the budget, which is right whenever the caller hasapplied no per-card adjustment at all.+ ``kv_layer_weights`` is each layer's RELATIVE cache size, scaled to the total+ the planner already trusts: it PLACES the cache, never re-sizes it. Empty+ means the caller cannot say, and the per-device check then abstains.+``kv_bytes_floor`` is an attention-cache size the caller has already computedbyte-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@@ -381,7 +402,10 @@ def plan_placement(# 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+ and all_resident_bytes(+ layout, n_ctx, kv_bytes_floor = kv_bytes_floor, kv_on_host = opts.kv_on_host+ )+ > budget):shrunk = max_context_for(layout, vram_bytes_per_device, opts = opts)if shrunk >= opts.min_ctx:@@ -409,6 +433,7 @@ def plan_placement(kv_bytes_floor,vram_bytes_per_device,split_weights_per_device or vram_bytes_per_device,+ kv_layer_weights,)if plan is not None:return plan@@ -436,11 +461,14 @@ def plan_placement(kv_bytes_floor,vram_bytes_per_device,split_weights_per_device or vram_bytes_per_device,+ kv_layer_weights,)if plan is not None:return plan- floor = resident_floor_bytes(layout, n_ctx, kv_bytes_floor = kv_bytes_floor)+ floor = resident_floor_bytes(+ layout, n_ctx, kv_bytes_floor = kv_bytes_floor, kv_on_host = opts.kv_on_host+ )return Plan(changed = False,n_ctx = n_ctx,@@ -498,6 +526,7 @@ def _per_device_shortfall(quantised: bool,kv_bytes_floor: int,split_weights_per_device: Sequence[int] = (),+ kv_layer_weights: Sequence[int] = (),) -> Optional[str]:"""``None`` when every device provably fits, else why it cannot be shown to.@@ -514,29 +543,46 @@ def _per_device_shortfall("""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:+ # These three shapes -- recurrent hybrid, n_attention_layers short of+ # n_layers, sliding window -- are only a problem when the cache has to be+ # spread evenly for want of anything better. A vector removes that guess;+ # without one they still abstain.+ uneven_cache = (+ layout.recurrent_bytes > 0 or layout.n_attention_layers != layout.n_layers or layout.has_swa+ )+ weights = [max(0, int(w)) for w in kv_layer_weights]+ if len(weights) != layout.n_layers or not any(weights):+ weights = []+ if uneven_cache and not weights:+ 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"+ )return (- f"only {layout.n_attention_layers} of {layout.n_layers} layers hold a cache "- "and the layout does not say which"+ "the cache is per-layer uneven (sliding-window attention) and no per-layer "+ "vector was supplied to say which layers are full-context")- 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 + 1if 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+ cache = (+ 0+ if opts.kv_on_host+ else cache_bytes(layout, n_ctx, kv_quantised = quantised, kv_bytes_floor = kv_bytes_floor)+ )+ # Scaled to the total the caller already priced. Uniform when unsupplied.+ total_weight = sum(weights)+ if weights and total_weight > 0:+ kv_by_layer = [cache * w // total_weight for w in weights]+ else:+ per = cache // layout.n_layers if layout.n_layers else 0+ kv_by_layer = [per] * layout.n_layersby_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)@@ -550,7 +596,9 @@ def _per_device_shortfall(block = by_index.get(row)if block is None:continue- used += block.resident_bytes + kv_per_layer+ used += block.resident_bytes+ if row < len(kv_by_layer):+ used += kv_by_layer[row]if row not in spilled_indices:used += block.spillable_bytes# Everything outside the layout sits on the main device, which is@@ -576,10 +624,15 @@ def _plan_at(kv_bytes_floor: int = 0,vram_bytes_per_device: Sequence[int] = (),split_weights_per_device: Sequence[int] = (),+ kv_layer_weights: 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+ layout,+ n_ctx,+ kv_quantised = quantised,+ kv_bytes_floor = kv_bytes_floor,+ kv_on_host = opts.kv_on_host,)if needed <= budget:return _finish(@@ -638,6 +691,7 @@ def _plan_at(quantised = quantised,kv_bytes_floor = kv_bytes_floor,split_weights_per_device = split_weights_per_device,+ kv_layer_weights = kv_layer_weights,)if uneven is not None:return Plan(@@ -678,6 +732,7 @@ def _plan_at(quantised = quantised,kv_bytes_floor = kv_bytes_floor,split_weights_per_device = split_weights_per_device,+ kv_layer_weights = kv_layer_weights,)if uneven is not None:return Plan(@@ -739,8 +794,22 @@ def _finish(# 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+ if opts.kv_on_host:+ # -nkvo moved the cache and the recurrent state out of VRAM, not out of+ # existence: they are host RAM now, and the mmap decision below has to see+ # them or it answers against a footprint short by the whole cache.+ host_bytes += (+ cache_bytes(layout, n_ctx, kv_quantised = quantised, kv_bytes_floor = kv_bytes_floor)+ + layout.recurrent_bytes+ )vram_bytes = (- all_resident_bytes(layout, n_ctx, kv_quantised = quantised, kv_bytes_floor = kv_bytes_floor)+ all_resident_bytes(+ layout,+ n_ctx,+ kv_quantised = quantised,+ kv_bytes_floor = kv_bytes_floor,+ kv_on_host = opts.kv_on_host,+ )- spilled_bytes)diff --git a/studio/backend/tests/test_offload_planner.py b/studio/backend/tests/test_offload_planner.pyindex 6bff0309ca5..3b4247938e9 100644--- a/studio/backend/tests/test_offload_planner.py+++ b/studio/backend/tests/test_offload_planner.py@@ -1086,3 +1086,155 @@ def test_a_sliding_window_model_abstains_on_a_multi_gpu_split():# 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)+++def _moe_reader(names):+ """A 2-block MoE GGUF whose expert tensors use ``names``."""+ fields = dict(_shard_fields())+ fields["llama.block_count"] = 2+ fields["llama.expert_count"] = 64+ fields["llama.expert_used_count"] = 8+ tensors = []+ for i in range(2):+ for n in names:+ tensors.append(_StubTensor(f"blk.{i}.{n}.weight", 400 * MIB))+ tensors.append(_StubTensor(f"blk.{i}.attn_q.weight", 10 * MIB))+ tensors.append(_StubTensor("token_embd.weight", 100 * MIB))+ tensors.append(_StubTensor("output.weight", 100 * MIB))+ return _StubReader(fields, tensors)+++ "label,names,expect_mib",+ [+ ("split", ["ffn_up_exps", "ffn_gate_exps", "ffn_down_exps"], 1200),+ # Fused gate+up: the same two matrices under one tensor name.+ ("fused", ["ffn_gate_up_exps", "ffn_down_exps"], 800),+ # grovemoe's chunked experts, one tensor per chunk-expert.+ ("chunked", ["ffn_up_chexps", "ffn_gate_chexps", "ffn_down_chexps"], 1200),+ ],+)+def test_every_expert_spelling_is_spillable(label, names, expect_mib):+ """ffn_gate_up_exps and ffn_*_chexps are experts under another name: created+ per expert and dispatched with GGML_OP_MUL_MAT_ID, so just as cheap to spill.+ Matching only the split form left every fused-expert GGUF with nothing the+ planner was allowed to move."""+ layout = _layout_from_reader(_moe_reader(names))+ assert layout.is_moe+ assert layout.blocks[0].spillable_bytes == expect_mib * MIB++ # The pattern must move exactly what the layout counted.+ pattern = spill_pattern_for(layout, None)+ for n in names:+ assert re.search(pattern, f"blk.0.{n}.weight"), f"{label}: {n} not matched"+++def test_routed_latent_projections_are_never_spilled():+ """kimi-k3's ffn_routed_up/down read like experts and are not: no expert axis+ and plain GGML_OP_MUL_MAT, so every token crosses them. Spilling one puts a+ hot tensor on the host at the rate the cost model reserves for cold ones."""+ layout = _layout_from_reader(_moe_reader(["ffn_routed_up", "ffn_routed_down"]))+ assert layout.blocks[0].spillable_bytes == 0+ pattern = spill_pattern_for(layout, None)+ assert not re.search(pattern, "blk.0.ffn_routed_up.weight")+ assert not re.search(pattern, "blk.0.ffn_routed_down.weight")+++def _swa_layout(n_blocks = 64):+ """Every layer is attention AND the cache is per-layer uneven -- the shape+ n_attention_layers cannot describe."""+ layout = _layout_from_reader(_StubReader(_shard_fields(), _shard_tensors(range(n_blocks))))+ return replace(layout, has_swa = True)+++def test_a_per_layer_vector_replaces_the_sliding_window_abstain():+ """Gemma3 interleaves 5:1, so a window layer's cache is a fraction of a+ full-context one. Without a vector the planner would have to spread the cache+ evenly, so it refuses; with one it knows where the big caches land."""+ layout = _swa_layout()+ half = _ALL_SPILL_VRAM // 2+ spilled = {b.index for b in layout.blocks}++ without = _per_device_shortfall(+ layout,+ _NO_OVERHEAD,+ 4096,+ spilled,+ False,+ [half, half],+ quantised = False,+ kv_bytes_floor = 0,+ )+ assert without is not None and "sliding-window" in without++ # 1 full-attention layer in every 5, the rest windowed at a 64th of the cost.+ weights = [64 if (i % 5 == 0) else 1 for i in range(layout.n_layers)]+ with_vector = _per_device_shortfall(+ layout,+ _NO_OVERHEAD,+ 4096,+ spilled,+ False,+ [half, half],+ quantised = False,+ kv_bytes_floor = 0,+ kv_layer_weights = weights,+ )+ assert with_vector is None or "sliding-window" not in with_vector+++def test_the_vector_places_the_cache_it_does_not_resize_it():+ """Scaled to the total the caller already priced, so changing only its SHAPE+ moves the cache between devices without changing how much cache there is."""+ layout = _swa_layout()+ spilled = {b.index for b in layout.blocks}+ n = layout.n_layers+ budgets = [_ALL_SPILL_VRAM // 2, _ALL_SPILL_VRAM // 2]++ # All the cache on the rows device 0 owns, then all on device 1's.+ front = [1] * (n // 2) + [0] * (n - n // 2)+ back = [0] * (n // 2) + [1] * (n - n // 2)+ a = _per_device_shortfall(+ layout,+ _NO_OVERHEAD,+ 32768,+ spilled,+ False,+ budgets,+ quantised = False,+ kv_bytes_floor = 8 * GIB,+ kv_layer_weights = front,+ )+ b = _per_device_shortfall(+ layout,+ _NO_OVERHEAD,+ 32768,+ spilled,+ False,+ budgets,+ quantised = False,+ kv_bytes_floor = 8 * GIB,+ kv_layer_weights = back,+ )+ assert a is not None and b is not None+ assert "device 0" in a, "the front-loaded cache overflows the first card"+ assert "device 1" in b, "the back-loaded cache overflows the second"+++def test_a_wrong_length_vector_is_ignored_rather_than_trusted():+ """A vector of the wrong length is not evidence: abstain, do not stretch it."""+ layout = _swa_layout()+ spilled = {b.index for b in layout.blocks}+ half = _ALL_SPILL_VRAM // 2+ got = _per_device_shortfall(+ layout,+ _NO_OVERHEAD,+ 4096,+ spilled,+ False,+ [half, half],+ quantised = False,+ kv_bytes_floor = 0,+ kv_layer_weights = [1, 2, 3],+ )+ assert got is not None and "sliding-window" in gotdiff --git a/studio/backend/tests/test_offload_planner_seam.py b/studio/backend/tests/test_offload_planner_seam.pyindex bc48eeb4589..e8769082bb1 100644--- a/studio/backend/tests/test_offload_planner_seam.py+++ b/studio/backend/tests/test_offload_planner_seam.py@@ -29,6 +29,19 @@ GIB = 1024**3MIB = 1024 * 1024[email protected](autouse = True)+def _discrete_host(monkeypatch):+ """Pin the one host fact the seam reads live.++ _planned_tensor_spill calls is_apple_silicon() directly, so on an arm64 Mac+ every case here would decline and the suite would grade the runner instead of+ the planner. Every test here means "a discrete host"; the Apple answer is+ asserted deliberately, below.+ """+ import utils.hardware+ monkeypatch.setattr(utils.hardware, "is_apple_silicon", lambda: False)++class _Stub:"""Only what the seam touches."""@@ -518,40 +531,130 @@ def test_a_unified_memory_apu_is_declared_to_the_planner():# ------------------------------------------- the budget the fit actually tested[email protected]("extra_args", [["--split-mode", "row"], ["-sm", "row"]])+def test_tensor_parallel_split_still_declines(extra_args):+ """-sm row is tensor parallelism: llama.cpp splits each TENSOR across cards+ instead of handing out rows, so the row model does not describe it."""+ assert _plan(_Stub(), extra_args = extra_args) is None+ assert _plan(_Stub()) is not None, "not vacuous: the same load plans without it"++@pytest.mark.parametrize("extra_args",+ [["--split-mode", "none"], ["-sm", "none"], ["-sm=none"]],+)+def test_split_mode_none_plans_against_one_card(extra_args):+ """-sm none is a device list of ONE, not a reason to decline: llama.cpp keeps+ only devices[main_gpu] (llama.cpp:288-299). Planning it as a two-card pool was+ the bug."""+ two_cards = [(0, 14 * 1024), (1, 14 * 1024)]+ got = _plan(_Stub(), gpus = two_cards, extra_args = extra_args)+ assert got is not None++ # Proof it used ONE card: the same plan as a genuine single card, where+ # crediting both would spill less.+ one_card = _plan(_Stub(), gpus = [(0, 14 * 1024)])+ assert len(got.spilled_blocks) == len(one_card.spilled_blocks)+++ "extra_args,env",[- ["--split-mode", "none"],- ["-sm", "none"],- ["--split-mode", "row"],- ["--tensor-split", "3,1"],- ["-ts", "3,1"],+ (["--split-mode", "tensor"], None),+ (["-sm", "tensor"], None),+ (["-sm=tensor"], None),+ (None, {"LLAMA_ARG_SPLIT_MODE": "tensor"}),],)-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+def test_tensor_parallel_split_mode_tensor_declines(extra_args, env):+ """`tensor` is a real accepted -sm value (common/arg.cpp:2762-2776) and goes+ further than `row`: llama.cpp replaces the device list with a SINGLE meta+ device (llama.cpp:157-215), so a per-device budget describes nothing, and+ llama.cpp's own fitter refuses the mode outright (common/fit.cpp:182-183)."""+ two_cards = [(0, 14 * 1024), (1, 14 * 1024)]+ assert _plan(_Stub(), gpus = two_cards, extra_args = extra_args, env = env) is None+ assert _plan(_Stub(), gpus = two_cards) is not None, "not vacuous"+++def test_split_mode_none_with_an_explicit_main_gpu_still_declines():+ """--main-gpu keeps declining, so -sm none is supported only at llama.cpp's+ default main GPU of 0. The env twin declines for the same reason: it is not an+ argv flag, so _DEVICE_FLAGS never sees it, yet llama.cpp keeps+ devices[main_gpu] under -sm none all the same (llama.cpp:288-299), and+ budgeting the first retained card approves a GPU the child never loads onto."""+ two_cards = [(0, 14 * 1024), (1, 14 * 1024)]+ assert _plan(_Stub(), gpus = two_cards, extra_args = ["-sm", "none", "-mg", "1"]) is None+ assert (+ _plan(+ _Stub(),+ gpus = two_cards,+ extra_args = ["-sm", "none"],+ env = {"LLAMA_ARG_MAIN_GPU": "1"},+ )+ is None+ )+ # Not vacuous, and not a blanket refusal of the env var's absence.+ assert _plan(_Stub(), gpus = two_cards, extra_args = ["-sm", "none"]) is not None+ assert (+ _plan(_Stub(), gpus = two_cards, env = {"LLAMA_ARG_MAIN_GPU": "0"}) is None+ ), "0 is still a pin the guard cannot verify against its own device order"@pytest.mark.parametrize(- "env",- [{"LLAMA_ARG_SPLIT_MODE": "none"}, {"LLAMA_ARG_TENSOR_SPLIT": "3,1"}],+ "extra_args,env",+ [+ (["--tensor-split", "3,1"], None),+ (["-ts", "3,1"], None),+ (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_tensor_split_becomes_the_row_weights(extra_args, env):+ """-ts REPLACES llama.cpp's free-memory split rather than skewing it: the+ values are copied into `splits` verbatim and prefix-summed+ (llama-model.cpp:1436-1447), so they are the row-ownership weight the+ per-device check needs -- data to use, not a reason to stop."""+ two_cards = [(0, 14 * 1024), (1, 14 * 1024)]+ assert _plan(_Stub(), gpus = two_cards, extra_args = extra_args, env = env) is not None+++ "extra_args,env",+ [+ (["--tensor-split", "3/1"], None),+ (["-ts", "3/1"], None),+ (None, {"LLAMA_ARG_TENSOR_SPLIT": "3/1"}),+ ],+)+def test_a_slash_delimited_tensor_split_is_the_same_override(extra_args, env):+ """llama.cpp splits -ts on ``[,/]+`` (common/arg.cpp:2791-2804), so ``3/1`` IS+ ``3,1`` to the child. Failing to parse it returned None, which the caller+ cannot tell from "no override": it planned 1:1 while the child ran 3:1."""+ from core.inference.llama_cpp import _extra_args_tensor_split++ assert _extra_args_tensor_split(extra_args, env or {}) == [3.0, 1.0]++ # And it reaches the planner as the row weights: the 3:1 plan, not free-VRAM.+ two_cards = [(0, 14 * 1024), (1, 14 * 1024)]+ skewed = _plan(_Stub(), gpus = two_cards, extra_args = extra_args, env = env)+ comma = _plan(_Stub(), gpus = two_cards, extra_args = ["-ts", "3,1"])+ assert skewed is not None and comma is not None+ assert skewed.spilled_blocks == comma.spilled_blocks+++def test_a_malformed_or_short_tensor_split_declines():+ """Unparseable or fewer shares than cards leaves the row model undefined.+ Unparseable must DECLINE, not fall through: the parser returns None for both+ "no -ts" and "a -ts I could not read", and the child gets the flag either way.+ ``;`` is not one of llama.cpp's delimiters -- std::stof stops at it, so+ ``3;1`` is [3, 0] to the child, never [3, 1]."""+ two_cards = [(0, 14 * 1024), (1, 14 * 1024)]+ assert _plan(_Stub(), gpus = two_cards, extra_args = ["-ts", "3"]) is None+ assert _plan(_Stub(), gpus = two_cards, extra_args = ["-ts", "abc"]) is None+ assert _plan(_Stub(), gpus = two_cards, extra_args = ["-ts", "3;1"]) is None+ assert _plan(_Stub(), gpus = two_cards, env = {"LLAMA_ARG_TENSOR_SPLIT": "abc"}) is None+ # Not vacuous: the same load plans with no -ts and with a readable one.+ assert _plan(_Stub(), gpus = two_cards) is not None+ assert _plan(_Stub(), gpus = two_cards, extra_args = ["-ts", "3,1"]) is not Nonedef test_the_planner_gets_the_budget_the_fit_tested_not_raw_free():@@ -625,31 +728,40 @@ def test_the_layout_cache_notices_a_gguf_replaced_in_place(tmp_path, monkeypatch# ------------------------------------------------- KV placement is placement too- "extra_args",- [["-nkvo"], ["--no-kv-offload"]],-)-def test_a_forced_cpu_kv_cache_declines(extra_args):[email protected]("extra_args", [["-nkvo"], ["--no-kv-offload"]])+def test_a_forced_cpu_kv_cache_is_priced_not_declined(extra_args):"""-nkvo sends the WHOLE cache to host RAM whatever -ngl says: offload is asingle scalar on the cache object and the buffer type falls back toggml_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).+ That makes the deficit SMALLER, so declining was the pessimistic reading: it+ charged a cache to VRAM the child never puts there and spilled FFN blocks to+ cover it. Now it is priced -- out of VRAM, into host RAM."""- 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+ baseline = _plan(_Stub(), free_mib = 14 * 1024)+ forced = _plan(_Stub(), free_mib = 14 * 1024, extra_args = extra_args)+ assert forced is not None, "a host-resident cache is not a reason to abstain"++ # Out of VRAM: the 2 GiB cache left the footprint, so the deficit it was+ # spilling to cover is gone.+ assert len(forced.spilled_blocks) < len(baseline.spilled_blocks)++ # Into host RAM: with nothing spilled host_bytes would be token_embd alone+ # (512 MiB), so it must carry the cache too or the mmap decision is made+ # against a footprint short by the whole cache.+ assert forced.host_bytes >= 512 * MIB + 2 * GIB@pytest.mark.parametrize("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_an_inherited_kv_offload_env_is_priced_too(env):+ """Same resolution as argv: LLAMA_ARG_ is rewritten to LLAMA_ARG_NO_ and+ presence alone forces the value (common/arg.cpp:127-141)."""+ forced = _plan(_Stub(), free_mib = 14 * 1024, env = env)+ baseline = _plan(_Stub(), free_mib = 14 * 1024)+ assert forced is not None+ assert len(forced.spilled_blocks) < len(baseline.spilled_blocks)+ assert forced.host_bytes >= 512 * MIB + 2 * GIBdef test_the_positive_kv_offload_form_still_plans():@@ -798,3 +910,335 @@ def test_a_pass_through_parallel_that_grows_the_cache_declines_the_plan():# Last wins, exactly as llama.cpp parses it.assert _plan(stub, n_parallel = 4, extra_args = ["--parallel", "8", "-np", "2"]) is not Noneassert _plan(stub, n_parallel = 1) is not None+++def test_the_seam_computes_a_per_layer_kv_vector():+ """The data already existed on the backend (_sliding_window_pattern); it just+ never crossed into the planner. Only the RATIOS travel: full attention holds+ the whole context, a window layer its window, ~100x apart at 128K vs 1K."""+ b = LlamaCppBackend.__new__(LlamaCppBackend)+ b._n_layers = 6+ b._n_kv_heads = 8+ b._n_heads = 8+ b._kv_key_length = 128+ b._kv_value_length = 128+ b._kv_key_length_swa = None+ b._kv_value_length_swa = None+ b._sliding_window = 1024+ b._sliding_window_pattern = [False, True, True, True, True, True]+ b._n_kv_heads_by_layer = None+ b._shared_kv_layers = None+ # None/None picks _estimate_kv_cache_bytes path 3, the one this describes.+ b._kv_lora_rank = None+ b._ssm_inner_size = None+ b._full_attention_interval = None++ weights = b._kv_layer_weights(131072)+ assert len(weights) == 6+ assert weights[0] == max(weights), "the full-attention layer is the big one"+ # The compact SWA allowance is window + one micro-batch, padded to 256 cells,+ # exactly as _estimate_kv_cache_bytes sizes the total it is scaled to.+ assert weights[0] // weights[1] == 131072 // (1024 + 512)++ # No pattern, no window, or no dimensions: say nothing rather than guess.+ b._sliding_window_pattern = None+ assert b._kv_layer_weights(131072) == []+ b._sliding_window_pattern = [False, True, True, True, True, True]+ b._sliding_window = 0+ assert b._kv_layer_weights(131072) == []+++def _swa_backend(n_layers = 6, shared = None):+ b = LlamaCppBackend.__new__(LlamaCppBackend)+ b._n_layers = n_layers+ b._n_kv_heads = 8+ b._n_heads = 8+ b._kv_key_length = 128+ b._kv_value_length = 128+ b._kv_key_length_swa = None+ b._kv_value_length_swa = None+ b._sliding_window = 1024+ b._sliding_window_pattern = [i % 2 == 1 for i in range(n_layers)]+ b._n_kv_heads_by_layer = None+ b._shared_kv_layers = shared+ b._kv_lora_rank = None+ b._ssm_inner_size = None+ b._full_attention_interval = None+ return b+++def test_shared_kv_layers_carry_no_weight():+ """Gemma 3n / Gemma 4 reuse an earlier layer's cache for the trailing+ ``attention.shared_kv_layers`` blocks: has_kv is false past+ n_layer_kv_from_start (llama-hparams.cpp:275-279), so they allocate nothing.+ Giving them weight spreads the same byte total over layers that hold no cache+ and under-books whichever card draws the real ones."""+ plain = _swa_backend(shared = None)+ gemma = _swa_backend(shared = 2)++ w = gemma._kv_layer_weights(131072)+ assert len(w) == 6, "length must still match layout.n_layers or the vector is dropped"+ assert w[4] == 0 and w[5] == 0, "the shared-KV tail allocates no cache"+ assert w[:4] == plain._kv_layer_weights(131072)[:4], "the cached layers are unchanged"++ # A GGUF claiming every layer is shared must not zero the vector out.+ assert any(_swa_backend(shared = 99)._kv_layer_weights(131072))+++def test_swa_weights_follow_the_effective_cache_geometry():+ """The vector places a total priced with the LAUNCH settings, so it has to+ describe the same geometry. --swa-full makes an SWA layer hold the full+ context, and the compact allowance is per-slot plus a micro-batch, not+ min(window, n_ctx). A window-sized ratio against a full-context total moves+ cache bytes onto the wrong card under the --fit off the plan pins."""+ b = _swa_backend()++ full = b._kv_layer_weights(131072, swa_full = True)+ assert len(set(full)) == 1, "--swa-full: every layer holds the full context"++ # Slots multiply the compact window allowance in unified mode.+ one = b._kv_layer_weights(131072, n_parallel = 1)+ four = b._kv_layer_weights(131072, n_parallel = 4)+ assert four[1] > one[1], "4 slots hold 4 windows' worth of SWA cells"+ assert four[0] == one[0], "the full-attention layer is unaffected in unified mode"++ # A bigger micro-batch is real headroom on the SWA cache too.+ assert b._kv_layer_weights(131072, n_ubatch = 4096)[1] > one[1]+++def test_the_seam_passes_the_launch_geometry_to_the_kv_vector():+ """Reachability: the knobs must travel from the launch path, or the two fixes+ above only hold in a unit test."""+ import inspect++ src = inspect.getsource(LlamaCppBackend.load_model)+ call = src[src.index('"kv_layer_weights"') :][:400]+ compact = "".join(call.split())+ assert "swa_full=swa_full" in compact+ assert "n_parallel=n_parallel" in compact+ assert "kv_unified=planned_kv_unified" in compact+ assert "n_ubatch=_effective_ubatch" in compact+++def test_an_inherited_split_mode_none_declines():+ """An env -sm none may never reach the child: on a layer-split launch+ load_model pops LLAMA_ARG_SPLIT_MODE (plus the paired LLAMA_ARG_TENSOR_SPLIT)+ for any non-"layer" mode (llama_cpp.py:20452-20458), so the child runs the+ default layer split. Budgeting the single main GPU there plans against a mode+ the child never sees AND skips the per-device check, which short-circuits on+ one device. argv is the only spelling that provably survives."""+ two_cards = [(0, 14 * 1024), (1, 14 * 1024)]+ assert _plan(_Stub(), gpus = two_cards, env = {"LLAMA_ARG_SPLIT_MODE": "none"}) is None+ # argv still plans, and still against one card.+ assert _plan(_Stub(), gpus = two_cards, extra_args = ["-sm", "none"]) is not None+ # An argv override of the env is argv, so it plans.+ assert (+ _plan(+ _Stub(),+ gpus = two_cards,+ extra_args = ["-sm", "none"],+ env = {"LLAMA_ARG_SPLIT_MODE": "none"},+ )+ is not None+ )+ # Not vacuous, and an inherited "layer" is the default and costs nothing.+ assert _plan(_Stub(), gpus = two_cards) is not None+ assert _plan(_Stub(), gpus = two_cards, env = {"LLAMA_ARG_SPLIT_MODE": "layer"}) is not None+++def test_a_reconciliation_still_strips_a_non_layer_split_mode_env():+ """Reachability anchor for the decline above: if load_model ever stops+ scrubbing the inherited mode, the env form becomes plannable again and this is+ the test that should fail and say so."""+ import inspect++ src = inspect.getsource(LlamaCppBackend.load_model)+ compact = "".join(src.split())+ assert 'if_inherited_smand_inherited_sm!="layer":' in compact+ assert 'env.pop("LLAMA_ARG_SPLIT_MODE",None)' in compact+ # The paired -ts goes with it, which is what the test below relies on.+ assert 'env.pop("LLAMA_ARG_SPLIT_MODE",None)env.pop("LLAMA_ARG_TENSOR_SPLIT",None)' in compact+++def test_an_inherited_tensor_split_scrubbed_with_its_mode_is_not_planned_against():+ """The -ts mirror of the decline above. An inherited LLAMA_ARG_TENSOR_SPLIT is+ popped together with a non-layer LLAMA_ARG_SPLIT_MODE, so with `-sm layer` on+ argv the child ends up with NEITHER and splits the rows by free VRAM. Proving+ row ownership against the scrubbed 9:1 shares can approve a device that then+ overflows under --fit off."""+ import core.inference.offload_planner as mod++ two_cards = [(0, 8 * 1024), (1, 16 * 1024)]+ seen = {}+ real = mod.plan_placement++ def spy(*a, **kw):+ seen["w"] = kw.get("split_weights_per_device")+ return real(*a, **kw)++ mod.plan_placement = spy+ try:+ _plan(+ _Stub(),+ gpus = two_cards,+ extra_args = ["-sm", "layer"],+ env = {"LLAMA_ARG_SPLIT_MODE": "row", "LLAMA_ARG_TENSOR_SPLIT": "9,1"},+ )+ scrubbed = seen.pop("w", None)+ _plan(_Stub(), gpus = two_cards, env = {"LLAMA_ARG_TENSOR_SPLIT": "9,1"})+ survives = seen.pop("w", None)+ finally:+ mod.plan_placement = real++ assert scrubbed == [8 * 1024 * MIB, 16 * 1024 * MIB], "the child never sees that -ts"+ # Not vacuous: with no inherited mode to drag it out, it IS the row weight,+ # scaled onto the same magnitude as the free-VRAM numbers.+ assert survives == [9 * 16 * 1024 * MIB, 16 * 1024 * MIB]++[email protected]("value", ["nan,1", "inf,1", "1,nan", "-nan,1", "infinity,1"])+def test_a_non_finite_tensor_split_declines_instead_of_raising(value):+ """float() accepts "nan"/"inf", and NaN then passes BOTH remaining guards:+ every comparison against NaN is false, and sum() of a NaN list is NaN. It+ reaches int(round(p * scale)), which raises ValueError / OverflowError with no+ try around the _planned_tensor_spill call, aborting the load -- while+ llama.cpp merely degenerates on the same value."""+ from core.inference.llama_cpp import _extra_args_tensor_split++ assert _extra_args_tensor_split(["-ts", value], {}) is None+ two_cards = [(0, 14 * 1024), (1, 14 * 1024)]+ # Declines (unparseable -ts is not "no -ts"), and above all does not raise.+ assert _plan(_Stub(), gpus = two_cards, extra_args = ["-ts", value]) is None+ assert _plan(_Stub(), gpus = two_cards, env = {"LLAMA_ARG_TENSOR_SPLIT": value}) is None+ # Not vacuous: finite shares still parse and still plan.+ assert _extra_args_tensor_split(["-ts", "3,1"], {}) == [3.0, 1.0]+ assert _plan(_Stub(), gpus = two_cards, extra_args = ["-ts", "3,1"]) is not None+++def test_the_vector_refuses_a_cache_the_estimator_prices_on_another_path():+ """_estimate_kv_cache_bytes picks its path BEFORE it looks at the window, and+ the earlier paths price a different quantity: path 1 (MLA) caches one+ compressed K latent per layer with no V and no window/full split, path 2+ (hybrid recurrent) caches only 1 in full_attention_interval layers. Either way+ a window-shaped vector is a different model of the cache, so it must answer []+ and let the planner abstain.++ Not hypothetical for path 1: dots3note reads KV_LORA_RANK and+ ATTENTION_SLIDING_WINDOW(_PATTERN) in the same loader. Path 2 is the+ recurrent-hybrid hole -- the abstain is `uneven_cache and not weights`, so a+ hybrid that ever produced a vector would walk past it and the device loop+ never places layout.recurrent_bytes."""+ b = _swa_backend()+ assert b._kv_layer_weights(131072), "the plain SWA model still answers"++ mla = _swa_backend()+ mla._kv_lora_rank = 512+ assert mla._kv_layer_weights(131072) == []++ hybrid = _swa_backend()+ hybrid._ssm_inner_size = 4096+ hybrid._full_attention_interval = 4+ assert hybrid._kv_layer_weights(131072) == []++ # One of the two alone is not the hybrid path and must not cost the vector.+ half = _swa_backend()+ half._ssm_inner_size = 4096+ assert half._kv_layer_weights(131072)+++def test_a_recurrent_hybrid_stays_on_the_abstain_path():+ """With no vector the recurrent abstain in _per_device_shortfall fires, so+ recurrent_bytes is never silently left unplaced by the device loop."""+ from core.inference.offload_planner import PlanOptions, _per_device_shortfall++ layout = ModelLayout(+ arch = "qwen35moe",+ n_layers = 4,+ n_attention_layers = 1,+ blocks = tuple(+ BlockLayout(index = i, spillable_bytes = GIB, resident_bytes = GIB // 4) for i in range(4)+ ),+ lm_head_bytes = GIB // 2,+ kv_bytes_per_token_f16 = 65536,+ recurrent_bytes = 2 * GIB,+ complete = True,+ )+ why = _per_device_shortfall(+ layout,+ PlanOptions(),+ 32768,+ set(),+ False,+ [8 * GIB, 8 * GIB],+ quantised = False,+ kv_bytes_floor = 0,+ kv_layer_weights = (),+ )+ assert why is not None and "recurrent" in why+++def test_flash_disabled_v_padding_reaches_the_layer_weights():+ """With flash attention OFF llama.cpp cannot keep a ragged V cache: every+ layer's V is padded to hparams.n_embd_v_gqa_max() over the whole model, which+ is what _estimate_kv_cache_bytes charges via _max_kv_value_width. V goes+ constant while K stays per-layer, so an unpadded vector prices a ratio the+ total does not have. Not an edge case: load_model pins planned_flash_attn =+ False unconditionally (llama_cpp.py:16690), so the padded branch is the one+ every spill plan's total is built from."""+ b = _swa_backend()+ # SWA layers wider than global ones, so the model-wide max is the SWA width+ # and the padding actually moves: n_embd_v_gqa_max = 8 * 256.+ b._kv_key_length_swa = 256+ b._kv_value_length_swa = 256++ assert b._max_kv_value_width(128, 256) == 8 * 256++ on = b._kv_layer_weights(131072, flash_attn = True)+ off = b._kv_layer_weights(131072, flash_attn = False)+ assert on and off+ assert off != on, "the padding has to reach the vector"++ # Exactly the estimator's own per-layer arithmetic, f16 both axes.+ full_cells, swa_cells = 131072, 1024 + 512+ pad = 8 * 256+ glob = (8 * 128 * 2 + pad * 2) * full_cells # layer 0: global+ swa = (8 * 256 * 2 + pad * 2) * swa_cells # layer 1: sliding window+ assert off[0] == glob and off[1] == swa++ # A quantised K cache floors bpe_v at f16 on the same branch, and with V+ # constant across layers that asymmetry moves the ratio too.+ from core.inference.llama_cpp import _kv_bytes_per_elem++ bpe_k = _kv_bytes_per_elem("q8_0")+ q8 = b._kv_layer_weights(131072, flash_attn = False, cache_type_kv = "q8_0")+ assert q8 != off+ assert q8[0] == int((8 * 128 * bpe_k + pad * 2) * full_cells)+++def test_the_seam_passes_the_flash_state_and_cache_type_to_the_kv_vector():+ """Reachability: both knobs must travel from the launch path too.++ load_model is far too large to drive from here, so this reads the call site+ through the AST: matching source text would pass on a mention in a comment and+ fail on a reflow, neither of which says what the seam passes.+ """+ import ast+ import inspect+ import textwrap++ tree = ast.parse(textwrap.dedent(inspect.getsource(LlamaCppBackend.load_model)))+ calls = [+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "_kv_layer_weights"+ ]+ assert calls, "the launch path no longer builds a KV layer vector"++ for call in calls:+ passed = {+ kw.arg: kw.value for kw in call.keywords if kw.arg and isinstance(kw.value, ast.Name)+ }+ assert getattr(passed.get("flash_attn"), "id", None) == "planned_flash_attn"+ assert getattr(passed.get("cache_type_kv"), "id", None) == "cache_type_kv"