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: charge the split compute-buffer rate on a multi-GPU auto fit (#7637)
Daniel Han5495cdcf5388
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 8a28ae3bf29..cf7f2d9350a 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -49,6 +49,7 @@ from core.inference.llama_server_args import (parse_cache_override,parse_cache_override_per_axis,parse_ctx_override,+ parse_gpu_layers_override,parse_split_mode_override,resolve_requested_ctx,strip_shadowing_flags,@@ -1757,6 +1758,93 @@ def _swa_full_from_args_or_env(return value in _LLAMA_ARG_TRUE_VALUES+def _kv_offload_from_args(+ extra_args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None+) -> bool:+ """Resolve llama.cpp's environment and last-wins KV-offload flags (default on):+ LLAMA_ARG_KV_OFFLOAD parses before argv, and ``-kvo`` / ``--kv-offload`` is the+ positive form, so a CLI re-enable beats a false env."""+ enabled = True+ value = (os.environ if env is None else env).get("LLAMA_ARG_KV_OFFLOAD")+ if value in _LLAMA_ARG_FALSE_VALUES:+ enabled = False+ elif value in _LLAMA_ARG_TRUE_VALUES:+ enabled = True+ for raw in extra_args or ():+ flag = _flag_name(str(raw))+ if flag in {"-kvo", "--kv-offload"}:+ enabled = True+ elif flag in {"-nkvo", "--no-kv-offload"}:+ enabled = False+ return enabled+++def _is_positive_int(value: Optional[str]) -> bool:+ """Whether ``value`` parses as an int > 0 (llama.cpp's std::stoi)."""+ try:+ return int(str(value).strip()) > 0+ except (TypeError, ValueError):+ return False+++def _pipeline_parallel_disabled_by_args(+ extra_args: Optional[Iterable[str]],+ env: Optional[Mapping[str, str]] = None,+ n_layers: Optional[int] = None,+) -> bool:+ """Whether the launch turns OFF llama.cpp's pipeline parallelism, i.e. the 4x in+ ``_CTX_COMPUTE_SPLIT_MULT``. llama-context.cpp requires ``-sm layer``, KV offload+ on and an empty tensor-override list (among other things); anything here is back to+ 1x, and charging the multiplier anyway would waste context. Studio passes none of+ it, but extra_args and the environment can.++ ``-cmoe`` / ``-ncmoe`` count: both push into ``tensor_buft_overrides`` exactly like+ ``-ot`` (common/arg.cpp). ``-otd`` does not - it targets the draft model.+ LLAMA_ARG_SPLIT_MODE is not read here: the launch pops a non-layer inherited value+ on the layer path, so it never reaches the child. Ambiguous input resolves to+ "still pipelined" - over-reserving only costs context, under-reserving OOMs the+ split. ``n_layers`` is the GGUF block count for the ``-ngl`` check below; None/0+ means unknown."""+ source_env = os.environ if env is None else env+ if source_env.get("LLAMA_ARG_OVERRIDE_TENSOR"):+ return True+ if source_env.get("LLAMA_ARG_CPU_MOE") in _LLAMA_ARG_TRUE_VALUES:+ return True+ if _is_positive_int(source_env.get("LLAMA_ARG_N_CPU_MOE")):+ return True+ if not _kv_offload_from_args(extra_args, env = env):+ return True+ # -sm none/row keep the layer path and pass through, so they really do disable+ # it. -sm tensor does not: the layer branch is only reached after a downgrade,+ # which strips the flag (strip_split_mode_only) and leaves the child on layer.+ split_mode = parse_split_mode_override(extra_args)+ if split_mode is not None and split_mode.strip().lower() not in {"layer", "tensor"}:+ return True+ # Pipelining needs n_gpu_layers > n_layer_all, so a user -ngl (appended after+ # Studio's -ngl -1, last-wins) that cannot exceed the count loads a prefix and+ # turns it off. Negative (all layers) or above the count keeps the step, even+ # in between: n_layers is block_count and can undercount n_layer_all (MTP layers).+ if n_layers:+ try:+ gpu_layers = parse_gpu_layers_override(extra_args)+ except ValueError:+ gpu_layers = None # malformed: unknown, so keep the step+ if gpu_layers is not None and 0 <= gpu_layers <= n_layers:+ return True+ values = [str(raw) for raw in extra_args or ()]+ for i, raw in enumerate(values):+ flag = _flag_name(raw)+ # Any -ot counts even if it matches nothing: the list need only be non-empty.+ if flag in {"-ot", "--override-tensor", "-cmoe", "--cpu-moe"}:+ return True+ if flag in {"-ncmoe", "--n-cpu-moe"}:+ # -ncmoe 0 pushes no override, so it leaves pipelining on.+ _, eq, inline = raw.partition("=")+ if _is_positive_int(inline if eq else (values[i + 1] if i + 1 < len(values) else "")):+ return True+ return False++def _kv_unified_from_args(extra_args: Optional[Iterable[str]],default: bool = False,@@ -4376,6 +4464,103 @@ class LlamaCppBackend:)return None, True+ @staticmethod+ def _select_gpus_split_aware(+ model_size_bytes: int,+ gpus: list[tuple[int, int]],+ usable_fraction: Optional[float] = None,+ total_by_idx: Optional[dict[int, int]] = None,+ per_device_overhead_bytes: int = 0,+ min_gpus: int = 1,+ split_extra_bytes: int = 0,+ ) -> tuple[Optional[list[int]], bool]:+ """``_select_gpus``, re-checked at the multi-device context-compute rate.++ The device count comes out of the footprint, so the first pass must price the+ compute buffer at the single-device rate -- but a layer split replicates a BIGGER+ one per card (see ``_CTX_COMPUTE_SPLIT_MULT``). ``split_extra_bytes`` is that+ per-device step (0 when llama.cpp declines pipeline parallelism): charge it and+ re-select once the count is known to be > 1, exact in one retry since the step is+ count-independent. The bigger overhead can cut ``_select_gpus``'s usable-card+ count to one, and a lone card is not a split, so a retry landing below two+ devices is re-priced without the delta. Still no fit returns (None, True) ->+ --fit on, i.e. CPU offload rather than a pin that OOMs at launch."""+ gpu_indices, use_fit = LlamaCppBackend._select_gpus(+ model_size_bytes,+ gpus,+ usable_fraction = usable_fraction,+ total_by_idx = total_by_idx,+ per_device_overhead_bytes = per_device_overhead_bytes,+ min_gpus = min_gpus,+ )+ if use_fit or split_extra_bytes <= 0 or not gpu_indices or len(gpu_indices) < 2:+ return gpu_indices, use_fit+ retry_indices, retry_fit = LlamaCppBackend._select_gpus(+ model_size_bytes + split_extra_bytes,+ gpus,+ usable_fraction = usable_fraction,+ total_by_idx = total_by_idx,+ per_device_overhead_bytes = per_device_overhead_bytes + split_extra_bytes,+ min_gpus = min_gpus,+ )+ if not retry_fit and retry_indices and len(retry_indices) >= 2:+ return retry_indices, retry_fit+ single, single_fit = LlamaCppBackend._select_gpus(+ model_size_bytes,+ gpus,+ usable_fraction = usable_fraction,+ total_by_idx = total_by_idx,+ per_device_overhead_bytes = per_device_overhead_bytes,+ min_gpus = 1,+ )+ if not single_fit and single is not None and len(single) == 1:+ return single, False+ return retry_indices, retry_fit++ @staticmethod+ def _every_gpu_holds_reserve(usable_mib: Iterable[float], reserve_bytes: int) -> bool:+ """Whether every card in a layer-split subset can hold the reserve it replicates+ (flat per-device overhead + its own context-compute copy). A pooled budget cannot+ see this: in the sum a roomy card's spare VRAM covers a nearly full card's copy,+ and the small card OOMs at launch. Bites when the subset loop cannot start at+ one GPU (``_auto_min_gpus`` >= 2, set by every tensor -> layer downgrade);+ starting at one, the failed n-1 subset already bounds the smallest card from+ below by the reserve."""+ reserve_mib = reserve_bytes / (1024 * 1024)+ values = list(usable_mib)+ return bool(values) and all(usable >= reserve_mib for usable in values)++ @staticmethod+ def _cap_ctx_to_per_device_reserve(+ ctx: int,+ usable_mib: Iterable[float],+ reserve_bytes_fn: Callable[[int], int],+ min_ctx: int = 4096,+ ) -> int:+ """Largest context in [``min_ctx``, ``ctx``] whose replicated per-device reserve+ still fits the SMALLEST card of a layer-split subset; 0 when even ``min_ctx``+ does not. The reserve shrinks with the context, so a subset+ ``_every_gpu_holds_reserve`` turns down at the pooled context usually serves a+ lower one: 40000 + 2500 MiB free holds 31488, not the 4096 a drop would leave.+ Bisects the reserve, which is monotone in context on every branch but+ proportional on only some: deepseek4's flat indexer term makes a closed form+ answer 43341 on a 4000 MiB card, whose reserve there is 6048 MiB. The MiB+ comparison mirrors ``_every_gpu_holds_reserve``, so that gate accepts what this+ returns."""+ values = list(usable_mib)+ if not values or ctx < min_ctx:+ return 0+ smallest = min(values)+ lo, hi, best = min_ctx, ctx, 0+ while lo <= hi:+ mid = (lo + hi) // 2+ if reserve_bytes_fn(mid) / (1024 * 1024) <= smallest:+ best, lo = mid, mid + 1+ else:+ hi = mid - 1+ best = (best // 256) * 256 # same alignment _fit_context_to_vram uses+ return best if best >= min_ctx else 0+# ── KV cache VRAM estimation ─────────────────────────────────────def _can_estimate_kv(self) -> bool:@@ -4820,6 +5005,14 @@ class LlamaCppBackend:_CTX_COMPUTE_BYTES_PER_EMBD = 2.25 # quantized KV, regular attention (dequant scratch)_CTX_COMPUTE_BYTES_PER_EMBD_MLA = 1.25 # quantized KV, MLA (compressed attn: measured 0.94x)_CTX_COMPUTE_F16_MASK_SAFETY = 1.5 # f16/bf16/f32 KV: KQ mask only (n_ubatch*2 B/tok)+ # Per-device f16 ctx-linear rate steps 4x once the model spans >1 device under+ # `-sm layer`: pipeline parallelism sets the ggml scheduler's n_copies to+ # GGML_SCHED_MAX_COPIES == 4, and the [n_kv, n_ubatch] f16 KQ mask is a+ # GGML_TENSOR_FLAG_INPUT, so 1 live copy becomes 4. Hence a step on "is split", not+ # a ramp in device count: measured 2.00 B/tok/ubatch on 1 GPU and 8.00 on 2-8 GPUs,+ # architecture- and --parallel-independent. Charging 1x on a split under-reserves+ # 2.67x (= 8/(2*1.5)). llama.cpp declines it in _pipeline_parallel_disabled_by_args.+ _CTX_COMPUTE_SPLIT_MULT = 4# DeepSeek-V4 (deepseek4): its lightning indexer + sparse attention reserve a large# context-scaling compute buffer the rates above miss (present even with an f16# cache). Measured on UD-Q4_K_XL (ub=512): ~2 GiB at 16k -> ~65.5 GiB at 1M. Without@@ -4877,6 +5070,8 @@ class LlamaCppBackend:n_ctx: int,n_ubatch: Optional[int] = None,cache_type_kv: Optional[str] = None,+ *,+ layer_split: bool = False,) -> int:"""Context-linear growth of the per-device compute buffer (bytes), chargedon top of the flat ``_estimate_compute_buffer_bytes``. The flash-attn KQ@@ -4886,7 +5081,12 @@ class LlamaCppBackend:the KQ mask, a flat n_ubatch*2 bytes per context token. ``cache_type_kv`` None-> f16 (llama.cpp's default; an env-set quantized cache is budgeted as f16 onthe KV side, whose over-reservation absorbs the dequant scratch). Returns 0- when dims are missing or ``n_ctx`` <= 0."""+ when dims are missing or ``n_ctx`` <= 0.++ ``layer_split`` adds the extra KQ-mask copies a multi-device split pays (see+ ``_CTX_COMPUTE_SPLIT_MULT``) on every architecture except deepseek4, whose own+ rate already subsumes them. Tensor mode passes False, having been measured+ separately at the single-device rate (see ``_plan_tensor_parallel``)."""n_embd = self._embedding_length or 0if n_embd <= 0 or n_ctx <= 0:return 0@@ -4894,9 +5094,15 @@ class LlamaCppBackend:1,int(self._DEFAULT_N_UBATCH if n_ubatch is None else n_ubatch),)+ # One KQ mask copy ([n_kv, n_ubatch] f16), n_embd-independent. Every rate below+ # is a single-GPU total containing exactly one, so a split adds the extra copies.+ mask_rate = ub * 2 * self._CTX_COMPUTE_F16_MASK_SAFETY+ split_extra = (self._CTX_COMPUTE_SPLIT_MULT - 1) * mask_rate if layer_split else 0.0if getattr(self, "_architecture", None) == "deepseek4":# DSV4 indexer/CSA buffer (see constants): flat + linear, ub-scaled. Fires# for any KV type -- the indexer scratch is present even with an f16 cache.+ # No split_extra, unlike every other arch: 72000 already clears the measured+ # 65.5 KiB/tok by 4928 B/tok, more than the 4608 the mask copies cost.ub_scale = ub / self._DEFAULT_N_UBATCHreturn int(self._DSV4_CTX_COMPUTE_FLAT_BYTES@@ -4910,9 +5116,13 @@ class LlamaCppBackend:# fit for that so a q8_0 cache gets a small honest context instead of an# unloadable one that crash-loops the server.if cache_type_kv and _kv_bytes_per_elem(cache_type_kv) < 2.0:- return int(self._INKLING_CTX_COMPUTE_DENSE_BYTES_PER_TOK * n_ctx * ub_scale)- # Banded flash path (see constants): linear, ub-scaled.- return int(self._INKLING_CTX_COMPUTE_BYTES_PER_TOK * n_ctx * ub_scale)+ rate = self._INKLING_CTX_COMPUTE_DENSE_BYTES_PER_TOK+ else:+ # Banded flash path (see constants): linear, ub-scaled.+ rate = self._INKLING_CTX_COMPUTE_BYTES_PER_TOK+ # Both paths allocate the mask, and 8192 has only ~1.5x headroom over the+ # 5.6 KiB/tok banded measurement -- a split alone would overrun it.+ return int(rate * n_ctx * ub_scale + split_extra * n_ctx)if _kv_bytes_per_elem(cache_type_kv) < 2.0:# Quantized cache: the dequant scratch dominates and scales with n_embd.# MLA (compressed KV) needs far less of it: measured 0.94 x n_embd on@@ -4925,9 +5135,11 @@ class LlamaCppBackend:)per_tok = rate * n_embd * ub_scaleelse:- # f16/bf16/f32: only the KQ mask ([n_kv, n_ubatch] f16), n_embd-independent.- per_tok = ub * 2 * self._CTX_COMPUTE_F16_MASK_SAFETY- return int(per_tok * n_ctx)+ # f16/bf16/f32: only the KQ mask.+ per_tok = mask_rate+ # Only the mask goes 1x -> 4x, not the dequant scratch, so ADD the extra copies:+ # max() would under-reserve the quantized path by the whole dequant scratch.+ return int((per_tok + split_extra) * n_ctx)def _slots_that_fit_on_gpu(self,@@ -4944,15 +5156,17 @@ class LlamaCppBackend:swa_full: bool = False,kv_unified: bool = True,flash_attn: bool = True,+ split_extra_bytes: int = 0,) -> tuple[Optional[list[int]], bool, int]:"""Largest serving-slot count in [1, n_parallel) whose fully-on-GPU footprint fits,so Unsloth keeps the model on GPU (-ngl -1) instead of --fit on, which offloads layersto host and collapses decode ~3x (oobabooga #6718). ``base_footprint_bytes`` is theslot-independent footprint (weights + soft overhead + MTP + context-linear compute,minus the folded compute buffer); each candidate re-adds the slot-sized compute buffer- and KV, then re-selects GPUs like the explicit-context path. Returns (gpu_indices,- use_fit=False, slots) for the largest fitting count, else (None, True, n_parallel).- Only ever reduces; deterministic and unit-testable with synthetic VRAM maps."""+ and KV, then re-selects GPUs like the explicit-context path -- ``split_extra_bytes``+ included, so a multi-GPU candidate is re-checked at the split rate. Returns+ (gpu_indices, use_fit=False, slots) for the largest fitting count, else (None, True,+ n_parallel). Only ever reduces; unit-testable with synthetic VRAM maps."""for slots in range(n_parallel - 1, 0, -1):cb = self._estimate_compute_buffer_bytes(n_ubatch = n_ubatch, n_parallel = slots, per_device_tensor = False@@ -4972,13 +5186,14 @@ class LlamaCppBackend:flash_attn = flash_attn,))- gpu_indices, use_fit = self._select_gpus(+ gpu_indices, use_fit = self._select_gpus_split_aware(total,gpus,usable_fraction = pin_fraction,total_by_idx = total_by_idx,per_device_overhead_bytes = per_device_overhead_bytes,min_gpus = min_gpus,+ split_extra_bytes = split_extra_bytes,)if not use_fit:return gpu_indices, False, slots@@ -7285,6 +7500,9 @@ class LlamaCppBackend:extra_args,default = n_parallel > 1 and server_caps.get("supports_kv_unified", False),)+ _pipeline_parallel_off = _pipeline_parallel_disabled_by_args(+ extra_args, n_layers = self._n_layers+ )# A hard-crash recovery may relaunch this same plan with FA off.# Size that larger cache up front so the recovery cannot OOM.planned_flash_attn = False@@ -7801,11 +8019,22 @@ class LlamaCppBackend:# scratch), so pass it through. In a layer split this buffer is# replicated on EVERY device (measured ~equal per GPU), so scale# by the device count; a large model at high context otherwise- # under-reserves ~(n-1)x it (e.g. Qwen3.5-397B on 3 GPUs).+ # under-reserves ~(n-1)x it (e.g. Qwen3.5-397B on 3 GPUs). The+ # per-device rate also steps up once split, unless llama.cpp+ # declines the pipeline parallelism that causes the step.return max(1, n_gpus) * self._compute_buffer_ctx_bytes(- ctx, _effective_ubatch, cache_type_kv+ ctx,+ _effective_ubatch,+ cache_type_kv,+ layer_split = n_gpus > 1 and not _pipeline_parallel_off,)+ def _cc_split_extra(ctx: int) -> int:+ # Per-device step from the single-device rate to the split one,+ # for the paths that must select GPUs before they know the+ # count. 0 when llama.cpp declines pipeline parallelism.+ return max(0, _cc_bytes(ctx, 2) // 2 - _cc_bytes(ctx))+# Layer-split compute buffer (one lump; tensor mode reserves it# per device in _plan_tensor_parallel). Context-independent, so# fold it into the model footprint for the branches below. Falls@@ -8102,8 +8331,10 @@ class LlamaCppBackend:)# The compute buffer is replicated on every device in a# layer split; fold it into the per-device reserve so a- # multi-GPU pin sizes each card for its own copy.- gpu_indices, use_fit = self._select_gpus(+ # multi-GPU pin sizes each card for its own copy. Priced+ # single-device (the count comes out of this figure), then+ # re-checked at the split rate, falling back to --fit on.+ gpu_indices, use_fit = self._select_gpus_split_aware(requested_total,gpus,usable_fraction = _pin_fraction,@@ -8111,6 +8342,7 @@ class LlamaCppBackend:per_device_overhead_bytes = _pipeline_overhead_bytes+ _cc_bytes(effective_ctx),min_gpus = _layer_min_gpus,+ split_extra_bytes = _cc_split_extra(effective_ctx),)# No silent shrink: effective_ctx stays == requested_ctx.else:@@ -8163,11 +8395,43 @@ class LlamaCppBackend:footprint_mib = (_ms + kv + _mtp_bytes(capped) + _cc_sub(capped)) / (1024 * 1024)- if footprint_mib <= pool_budget:- effective_ctx = capped- gpu_indices = sorted(idx for idx, _ in subset)- use_fit = False- break+ if footprint_mib > pool_budget:+ continue+ # Pooling admits a subset whose per-device reserve+ # does not fit the smallest card, which then OOMs at+ # launch; only knowable once `capped` is chosen.+ _usable_mib = [_gpu_usable(g, pin_fraction) for g in subset]+ _reserve_at = lambda c, n = n_gpus: (+ (_pipeline_overhead_bytes if n > 1 else 0)+ + _cc_bytes(c, n) // n+ )+ if not self._every_gpu_holds_reserve(+ _usable_mib, _reserve_at(capped)+ ):+ # Keep the largest context the smallest card holds+ # rather than lose the subset to the 4096 drop below.+ # Costs no context: subsets are prefixes of a+ # usable-descending ranking and the reserve is the+ # same function of context for every n > 1, so any+ # later subset clears the gate no higher than this.+ capped = self._cap_ctx_to_per_device_reserve(+ capped, _usable_mib, _reserve_at+ )+ if capped <= 0:+ continue+ # Pooled terms only shrink with the context, so this+ # cannot newly fail; re-price rather than lean on that+ # across the KV and MTP branches.+ kv = _kv_bytes(capped)+ footprint_mib = (+ _ms + kv + _mtp_bytes(capped) + _cc_sub(capped)+ ) / (1024 * 1024)+ if footprint_mib > pool_budget:+ continue+ effective_ctx = capped+ gpu_indices = sorted(idx for idx, _ in subset)+ use_fit = False+ breakelse:# Native ctx doesn't fit. Drop to 4096 and# re-check before --fit on: a model overflowing@@ -8183,10 +8447,18 @@ class LlamaCppBackend:+ _mtp_bytes(effective_ctx)+ _cc_bytes(effective_ctx, n_gpus)) / (1024 * 1024)- if footprint_mib <= _pool_budget_mib(subset, pin_fraction):- gpu_indices = sorted(idx for idx, _ in subset)- use_fit = False- break+ if footprint_mib > _pool_budget_mib(subset, pin_fraction):+ continue+ # Pooling hides the per-device reserve here too.+ if not self._every_gpu_holds_reserve(+ (_gpu_usable(g, pin_fraction) for g in subset),+ (_pipeline_overhead_bytes if n_gpus > 1 else 0)+ + _cc_bytes(effective_ctx, n_gpus) // n_gpus,+ ):+ continue+ gpu_indices = sorted(idx for idx, _ in subset)+ use_fit = False+ breakelif gpus:# Can't estimate KV -- file-size-only check; keep the@@ -8295,6 +8567,7 @@ class LlamaCppBackend:swa_full = swa_full,kv_unified = planned_kv_unified,flash_attn = planned_flash_attn,+ split_extra_bytes = _cc_split_extra(effective_ctx),)if not _uf_slots:logger.info(diff --git a/studio/backend/tests/test_compute_buffer.py b/studio/backend/tests/test_compute_buffer.pyindex 3e95acc98d1..a6950130479 100644--- a/studio/backend/tests/test_compute_buffer.py+++ b/studio/backend/tests/test_compute_buffer.py@@ -59,6 +59,7 @@ except ImportError:from core.inference.llama_cpp import LlamaCppBackendMIB = 1024 * 1024+GIB = 1024 * MIBdef _backend(@@ -351,3 +352,831 @@ class TestContextBufferDSV4:per_tok = b._compute_buffer_ctx_bytes(100000, cache_type_kv = "f16") / 100000expected = 512 * 2 * LlamaCppBackend._CTX_COMPUTE_F16_MASK_SAFETYassert per_tok == pytest.approx(expected, rel = 1e-6)+++class TestContextBufferLayerSplit:+ """The per-device f16 (KQ-mask) rate steps 4x once the model spans >1 device under+ ``-sm layer``: a step on "is split", not a ramp in device count. ``_MEASURED`` is+ from llama.cpp's memory breakdown: compute-column ctx slope / n_ctx / n_ubatch."""++ _RATE_SINGLE = 2.0 # B/tok/ubatch, per device+ _RATE_SPLIT = 8.0+ # (model, n_gpus, n_ubatch, measured B/tok/ubatch/device)+ _MEASURED = [+ ("Qwen3.5-9B-MTP", 1, 512, 2.0),+ ("Qwen3.5-9B-MTP", 2, 512, 8.0),+ ("Qwen3.6-27B-MTP", 1, 512, 2.0),+ ("Qwen3.6-27B-MTP", 4, 512, 8.0),+ ("Qwen3.6-35B-A3B", 1, 2048, 2.0),+ ("Qwen3.6-35B-A3B", 2, 2048, 8.0),+ ("gemma-4-12b-it", 1, 512, 2.0),+ ("gemma-4-12b-it", 3, 512, 8.0),+ ("gemma-4-12b-it", 5, 512, 8.0),+ ("gemma-4-12b-it", 6, 512, 8.0),+ ("gemma-4-12b-it", 8, 512, 8.0),+ ("gemma-4-26B-A4B-it", 1, 512, 2.0),+ ("gemma-4-26B-A4B-it", 2, 512, 8.0),+ ("Kimi-K3", 4, 512, 8.0),+ ]++ def test_default_is_single_device(self):+ # Existing callers are unaffected: the flag defaults off.+ b = _backend(embd = 4096)+ assert b._compute_buffer_ctx_bytes(+ 131072, cache_type_kv = "f16"+ ) == b._compute_buffer_ctx_bytes(131072, cache_type_kv = "f16", layer_split = False)++ def test_split_is_exactly_the_multiplier(self):+ b = _backend(embd = 4096)+ one = b._compute_buffer_ctx_bytes(131072, cache_type_kv = "f16")+ many = b._compute_buffer_ctx_bytes(131072, cache_type_kv = "f16", layer_split = True)+ assert many == pytest.approx(one * LlamaCppBackend._CTX_COMPUTE_SPLIT_MULT, rel = 1e-9)++ @pytest.mark.parametrize("name,n_gpus,ub,measured", _MEASURED)+ def test_upper_bounds_measured_per_device_rate(self, name, n_gpus, ub, measured):+ # Never under-reserve.+ b = _backend(embd = 4096)+ per_tok = (+ b._compute_buffer_ctx_bytes(+ 100000, n_ubatch = ub, cache_type_kv = "f16", layer_split = n_gpus > 1+ )+ / 100000+ )+ assert per_tok >= measured * ub, f"{name} n={n_gpus}: {per_tok:.0f} < {measured * ub:.0f}"++ @pytest.mark.parametrize("name,n_gpus,ub,measured", _MEASURED)+ def test_not_wildly_over_measured_per_device_rate(self, name, n_gpus, ub, measured):+ # The step is a correction, not extra headroom: still the 1.5 safety factor.+ b = _backend(embd = 4096)+ per_tok = (+ b._compute_buffer_ctx_bytes(+ 100000, n_ubatch = ub, cache_type_kv = "f16", layer_split = n_gpus > 1+ )+ / 100000+ )+ expected = measured * ub * LlamaCppBackend._CTX_COMPUTE_F16_MASK_SAFETY+ assert per_tok == pytest.approx(expected, rel = 1e-6)++ def test_pre_fix_split_reserve_was_short(self):+ # The bug: without the step a split reserved 8/(2*1.5) = 2.67x too little.+ b = _backend(embd = 4096)+ one = b._compute_buffer_ctx_bytes(1048576, cache_type_kv = "f16")+ measured = self._RATE_SPLIT * 512 * 1048576+ assert one < measured+ assert (+ b._compute_buffer_ctx_bytes(1048576, cache_type_kv = "f16", layer_split = True) >= measured+ )++ def test_kimi_k3_1m_four_gpu_reserve(self):+ # The reported case: Kimi-K3 UD-IQ1_M, 1M ctx, 4 GPUs, ub 512. llama.cpp+ # allocated 4.0 GiB per device; Studio reserved 1.5 GiB.+ b = _backend(embd = 7168, mla = 576)+ gib = b._compute_buffer_ctx_bytes(1048576, cache_type_kv = "f16", layer_split = True) / (+ 1024**3+ )+ assert 4.0 <= gib <= 6.5++ @pytest.mark.parametrize("ct", ["q8_0", "q4_0"])+ @pytest.mark.parametrize("embd,mla", [(2048, None), (8192, None), (7168, 576)])+ def test_quantized_adds_the_mask_delta(self, ct, embd, mla):+ # The quantized rate is a single-GPU TOTAL holding mask*1 + dequant scratch.+ # Only the mask replicates, so a split adds exactly 3 more masks.+ b = _backend(embd = embd, mla = mla)+ mask = b._compute_buffer_ctx_bytes(131072, cache_type_kv = "f16")+ single = b._compute_buffer_ctx_bytes(131072, cache_type_kv = ct)+ split = b._compute_buffer_ctx_bytes(131072, cache_type_kv = ct, layer_split = True)+ delta = (LlamaCppBackend._CTX_COMPUTE_SPLIT_MULT - 1) * mask+ assert split == pytest.approx(single + delta, rel = 1e-9)++ @pytest.mark.parametrize("embd,mla", [(2048, None), (2560, None), (8192, None), (7168, 576)])+ def test_quantized_split_beats_the_old_max_floor(self, embd, mla):+ # The pre-fix floor max(quantized, 4x mask) treated the dequant scratch and+ # the enlarged mask as alternatives, leaving the smaller one unbudgeted.+ b = _backend(embd = embd, mla = mla)+ old_floor = max(+ b._compute_buffer_ctx_bytes(262144, cache_type_kv = "q8_0"),+ b._compute_buffer_ctx_bytes(262144, cache_type_kv = "f16", layer_split = True),+ )+ assert b._compute_buffer_ctx_bytes(262144, cache_type_kv = "q8_0", layer_split = True) > (+ old_floor+ )++ def test_quantized_split_covers_measured_plus_mask(self):+ # Qwen3.5-4B (n_embd 2560) at 256k q8_0: 1330 MiB measured single-device,+ # + 3 replicated [n_kv, ub] f16 masks (768 MiB) = 2098 MiB per device. The+ # old floor reserved 1536 MiB and left ~560 MiB/device unbudgeted.+ b = _backend(embd = 2560)+ ctx, ub = 262144, 512+ mask_mib = 3 * ub * 2 * ctx / MIB+ assert mask_mib == pytest.approx(768.0, rel = 1e-6)+ split_mib = b._compute_buffer_ctx_bytes(ctx, ub, "q8_0", layer_split = True) / MIB+ assert split_mib >= 1330 + mask_mib++ def test_deepseek4_rate_unchanged(self):+ # Its own rate already carries the mask copies: 72000 - 65.5 KiB/tok measured+ # = 4928 B/tok of margin against the 4608 a split adds.+ b = _backend(embd = 4096, arch = "deepseek4")+ assert b._compute_buffer_ctx_bytes(+ 131072, cache_type_kv = "f16", layer_split = True+ ) == b._compute_buffer_ctx_bytes(131072, cache_type_kv = "f16")+ measured = TestContextBufferDSV4._MEASURED_1M_GIB * 1024**3 / 1048576+ split_masks = (LlamaCppBackend._CTX_COMPUTE_SPLIT_MULT - 1) * (+ 512 * 2 * LlamaCppBackend._CTX_COMPUTE_F16_MASK_SAFETY+ )+ assert LlamaCppBackend._DSV4_CTX_COMPUTE_BYTES_PER_TOK - measured >= split_masks+++class TestContextBufferInklingSplit:+ """Inkling's rates are single-device totals too, and the banded 8192 B/tok has only+ ~1.5x headroom over its 5.6 KiB/tok measurement, too little for a split's masks."""++ _MEASURED_BANDED = 5734 # ~5.6 KiB/tok compute at ub 512 (see the constant)+ _CTX = 1048576+ _UB = 512++ def _rate(+ self,+ ct,+ layer_split,+ ub = 512,+ ):+ b = _backend(embd = 4096, arch = "inkling")+ return (+ b._compute_buffer_ctx_bytes(self._CTX, ub, cache_type_kv = ct, layer_split = layer_split)+ / self._CTX+ )++ def test_pre_fix_banded_split_reserve_was_short(self):+ # The bug: the banded rate alone does not cover measured + 3 more masks.+ measured_split = self._MEASURED_BANDED + 3 * self._UB * 2+ assert LlamaCppBackend._INKLING_CTX_COMPUTE_BYTES_PER_TOK < measured_split+ assert self._rate("f16", True) >= measured_split++ @pytest.mark.parametrize("ct", ["f16", None, "q8_0"])+ def test_split_adds_exactly_the_extra_mask_copies(self, ct):+ delta = (LlamaCppBackend._CTX_COMPUTE_SPLIT_MULT - 1) * (+ self._UB * 2 * LlamaCppBackend._CTX_COMPUTE_F16_MASK_SAFETY+ )+ assert self._rate(ct, True) == pytest.approx(self._rate(ct, False) + delta, rel = 1e-9)++ def test_dense_fallback_delta_is_present_but_tiny(self):+ # ~402 KiB/tok dwarfs the 4608 B/tok of masks, yet the masks are allocated on+ # that path too, so charge them rather than argue about the margin.+ single, split = self._rate("q8_0", False), self._rate("q8_0", True)+ assert single < split <= single * 1.02++ def test_split_delta_scales_with_ubatch(self):+ assert self._rate("f16", True, ub = 1024) - self._rate("f16", False, ub = 1024) == (+ pytest.approx(2 * (self._rate("f16", True) - self._rate("f16", False)), rel = 1e-9)+ )++ def test_single_device_rates_unchanged(self):+ # No context is lost on a single GPU: the flag defaults off.+ for ct in ("f16", "q8_0"):+ assert self._rate(ct, False) == pytest.approx(+ (+ LlamaCppBackend._INKLING_CTX_COMPUTE_DENSE_BYTES_PER_TOK+ if ct == "q8_0"+ else LlamaCppBackend._INKLING_CTX_COMPUTE_BYTES_PER_TOK+ ),+ rel = 1e-6,+ )+++class TestLayerSplitWiring:+ """``_cc_bytes`` in ``load_model`` learns the device count, so it is the one place+ that can set ``layer_split``. Source-level: the closure needs a real load."""++ def _cc_bytes_source(self):+ import inspect++ src = inspect.getsource(LlamaCppBackend.load_model).splitlines()+ start = next(i for i, l in enumerate(src) if "def _cc_bytes(" in l)+ indent = len(src[start]) - len(src[start].lstrip())+ body = [src[start]]+ for line in src[start + 1 :]:+ if line.strip() and len(line) - len(line.lstrip()) <= indent:+ break+ body.append(line)+ return "\n".join(body)++ def test_forwards_layer_split_from_device_count(self):+ assert "layer_split = n_gpus > 1" in self._cc_bytes_source()++ def test_still_scales_by_device_count(self):+ # Per device on top of the replication, not instead of it: n x the split rate.+ assert "max(1, n_gpus) * self._compute_buffer_ctx_bytes" in self._cc_bytes_source()+++class TestPipelineParallelPredicate:+ """The 4x step is llama.cpp's pipeline parallelism (ggml n_copies == 4), which+ llama-context.cpp declines unless the split mode is layer, KV offload is on and the+ tensor-override list is empty; charging it then wastes context. Causal check: on 2+ GPUs a -ot matching nothing changes no placement yet takes the rate 8.00 -> 2.00."""++ def _off(+ self,+ args = None,+ env = None,+ n_layers = None,+ ):+ from core.inference.llama_cpp import _pipeline_parallel_disabled_by_args+ return _pipeline_parallel_disabled_by_args(args, env = env or {}, n_layers = n_layers)++ def test_plain_launch_keeps_the_step(self):+ assert self._off([]) is False+ assert self._off(None) is False+ assert self._off(["-c", "131072", "--parallel", "4"]) is False++ @pytest.mark.parametrize("flag", ["-ot", "--override-tensor"])+ def test_any_tensor_override_disables(self, flag):+ # Even a pattern matching nothing: has_tensor_overrides only checks non-empty.+ assert self._off([flag, "zzz_matches_nothing=CUDA0"]) is True++ @pytest.mark.parametrize("flag", ["-nkvo", "--no-kv-offload"])+ def test_kv_offload_off_disables(self, flag):+ assert self._off([flag]) is True++ def test_env_tensor_override_disables(self):+ assert self._off([], env = {"LLAMA_ARG_OVERRIDE_TENSOR": "exps=CPU"}) is True+ assert self._off([], env = {"LLAMA_ARG_OVERRIDE_TENSOR": ""}) is False++ @pytest.mark.parametrize("val", ["off", "0", "false", "disabled"])+ def test_env_kv_offload_off_disables(self, val):+ assert self._off([], env = {"LLAMA_ARG_KV_OFFLOAD": val}) is True++ def test_env_kv_offload_on_keeps_the_step(self):+ assert self._off([], env = {"LLAMA_ARG_KV_OFFLOAD": "1"}) is False++ def test_unrelated_flags_do_not_disable(self):+ assert self._off(["--kv-unified", "-fa", "on", "-ngl", "-1"]) is False++ @pytest.mark.parametrize(+ "flag", ["-otd", "--override-tensor-draft", "--spec-draft-override-tensor"]+ )+ def test_draft_override_does_not_disable(self, flag):+ # -otd targets the draft model, not the main model's tensor_buft_overrides.+ assert self._off([flag, "exps=CPU"]) is False++ # -- KV offload is last-wins across env then CLI (arg.cpp parses env first) --++ @pytest.mark.parametrize("flag", ["-kvo", "--kv-offload"])+ def test_cli_kv_offload_reenable_beats_a_false_env(self, flag):+ # The positive form exists, so this launch pipelines: 1x here would OOM it.+ assert self._off([flag], env = {"LLAMA_ARG_KV_OFFLOAD": "0"}) is False++ def test_last_kv_offload_flag_wins(self):+ assert self._off(["-kvo", "-nkvo"]) is True+ assert self._off(["-nkvo", "-kvo"]) is False++ def test_kv_offload_env_junk_value_keeps_the_default(self):+ assert self._off([], env = {"LLAMA_ARG_KV_OFFLOAD": "maybe"}) is False++ # -- pipeline parallelism requires LLAMA_SPLIT_MODE_LAYER --++ @pytest.mark.parametrize("mode", ["none", "row", "NONE", " row "])+ def test_non_layer_split_mode_disables(self, mode):+ assert self._off(["-sm", mode]) is True+ assert self._off([f"--split-mode={mode}"]) is True++ def test_explicit_layer_split_mode_keeps_the_step(self):+ assert self._off(["-sm", "layer"]) is False+ assert self._off(["-sm", "row", "-sm", "layer"]) is False # last-wins++ def test_tensor_split_mode_keeps_the_step(self):+ # The layer branch is an elif on tensor_parallel, so it is only reached+ # after a downgrade -- which strips -sm and leaves the child pipelined.+ assert self._off(["-sm", "tensor"]) is False++ def test_layer_branch_is_only_reached_after_the_flag_is_stripped(self):+ # Guards the assumption above.+ import inspect++ compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())+ assert "iftensor_parallelandtp_gpus:" in compact+ assert "extra_args=strip_split_mode_only(" in compact+ assert "elifgpusandself._can_estimate_kv()andeffective_ctx>0:" in compact++ def test_env_split_mode_is_ignored(self):+ # load_model pops a non-layer inherited LLAMA_ARG_SPLIT_MODE on the layer path,+ # so the child always runs -sm layer; honoring it would reserve 1x for a split.+ assert self._off([], env = {"LLAMA_ARG_SPLIT_MODE": "row"}) is False++ def test_layer_path_scrubs_a_non_layer_split_mode_env(self):+ # Guards the assumption the test above rests on.+ import inspect++ compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())+ assert 'if_inherited_smand_inherited_sm!="layer":' in compact+ assert 'env.pop("LLAMA_ARG_SPLIT_MODE",None)' in compact++ # -- -cmoe / -ncmoe set tensor_buft_overrides exactly like -ot --++ @pytest.mark.parametrize("flag", ["-cmoe", "--cpu-moe"])+ def test_cpu_moe_disables(self, flag):+ assert self._off([flag]) is True++ @pytest.mark.parametrize("flag", ["-ncmoe", "--n-cpu-moe"])+ def test_n_cpu_moe_disables(self, flag):+ assert self._off([flag, "8"]) is True+ assert self._off([f"{flag}=8"]) is True++ @pytest.mark.parametrize("flag", ["-ncmoe", "--n-cpu-moe"])+ def test_n_cpu_moe_zero_keeps_the_step(self, flag):+ # The handler loops N times, so 0 pushes no override at all.+ assert self._off([flag, "0"]) is False++ def test_env_cpu_moe_disables(self):+ assert self._off([], env = {"LLAMA_ARG_CPU_MOE": "1"}) is True+ # handler_void only fires on a truthy env value.+ assert self._off([], env = {"LLAMA_ARG_CPU_MOE": "0"}) is False+ assert self._off([], env = {"LLAMA_ARG_CPU_MOE": ""}) is False++ def test_env_n_cpu_moe_disables(self):+ assert self._off([], env = {"LLAMA_ARG_N_CPU_MOE": "4"}) is True+ assert self._off([], env = {"LLAMA_ARG_N_CPU_MOE": "0"}) is False+ assert self._off([], env = {"LLAMA_ARG_N_CPU_MOE": "not-a-number"}) is False++ # -- a finite -ngl override loads a layer prefix, so pipelining is off --++ @pytest.mark.parametrize("flag", ["-ngl", "--gpu-layers", "--n-gpu-layers"])+ def test_finite_gpu_layers_below_the_count_disables(self, flag):+ # User extras land after Studio's -ngl -1, so this last-wins.+ assert self._off([flag, "1"], n_layers = 93) is True+ assert self._off([f"{flag}=1"], n_layers = 93) is True++ def test_all_layers_keeps_the_step(self):+ # n_gpu_layers() is n_layer_all + 1 for any negative value.+ assert self._off(["-ngl", "-1"], n_layers = 93) is False++ def test_gpu_layers_above_the_count_keeps_the_step(self):+ # 999 > n_layer_all, so llama.cpp still pipelines.+ assert self._off(["-ngl", "999"], n_layers = 93) is False++ def test_gpu_layers_at_the_boundary(self):+ # Pipelining needs n_gpu_layers > n_layer_all, so equal is off; one above+ # keeps the step because block_count can undercount n_layer_all.+ assert self._off(["-ngl", "93"], n_layers = 93) is True+ assert self._off(["-ngl", "94"], n_layers = 93) is False++ def test_zero_gpu_layers_disables(self):+ assert self._off(["-ngl", "0"], n_layers = 93) is True++ def test_unknown_layer_count_keeps_the_step(self):+ assert self._off(["-ngl", "1"]) is False+ assert self._off(["-ngl", "1"], n_layers = 0) is False++ def test_last_gpu_layers_flag_wins(self):+ assert self._off(["-ngl", "1", "--gpu-layers", "-1"], n_layers = 93) is False+ assert self._off(["-ngl", "-1", "--gpu-layers", "1"], n_layers = 93) is True++ def test_malformed_gpu_layers_keeps_the_step(self):+ # validate_extra_args rejects these upstream; ambiguous here means keep.+ assert self._off(["-ngl", "abc"], n_layers = 93) is False+ assert self._off(["-ngl", "-2"], n_layers = 93) is False+ assert self._off(["-ngl"], n_layers = 93) is False++ def test_wired_into_the_fit(self):+ # The flag has to reach _cc_bytes, else the predicate is dead code.+ import inspect++ src = inspect.getsource(LlamaCppBackend.load_model)+ compact = "".join(src.split())+ assert "_pipeline_parallel_disabled_by_args(extra_args,n_layers=self._n_layers)" in compact+ assert "layer_split = n_gpus > 1 and not _pipeline_parallel_off" in src+ # The count is only real if the GGUF header was parsed first.+ assert src.index("_read_gguf_metadata(model_path)") < src.index(+ "_pipeline_parallel_disabled_by_args("+ )+++class TestPerDeviceSplitReserve:+ """The auto-context loop admits a GPU subset on the POOLED budget, but the per-device+ reserve (flat layer overhead + this PR's enlarged context-compute copy) is replicated+ on every card: in the sum a roomy card's spare VRAM covers a nearly full card's copy,+ and the small card OOMs at launch. Exposed when the loop cannot start at one GPU+ (``_auto_min_gpus >= 2``, set by every tensor -> layer downgrade); starting at one,+ the pooled test charges n copies where the per-card test charges one, so size n is+ reached only after n-1 failed, which bounds the smallest card below by the reserve -+ the check is then provably redundant, homogeneous or not."""++ _OH = LlamaCppBackend._PIPELINE_PER_DEVICE_OVERHEAD_MIB * MIB+ _UB = 2048+ # 48 GB / 24 GB cards, the small one mostly occupied. Its usable budget still+ # clears the flat overhead alone, so _auto_min_gpus keeps counting it.+ _HETEROGENEOUS = ([(0, 40_000), (1, 2_500)], {0: 49_152, 1: 24_576})+ _HOMOGENEOUS = ([(0, 40_000), (1, 40_000)], {0: 49_152, 1: 49_152})++ def _fit_backend(self, kv_per_tok = 20_000):+ b = _backend(embd = 8192)+ b._can_estimate_kv = lambda: True+ b._estimate_kv_cache_bytes = lambda ctx, ct = None, **kw: max(0, ctx) * kv_per_tok+ return b++ def _drive(+ self,+ b,+ gpus,+ totals,+ model_mib,+ native_ctx,+ min_gpus = 2,+ enforce = True,+ cap = True,+ ):+ """Mirror of load_model's auto-context subset loop over the production fit+ and reserve helpers. Returns (gpu_indices, chosen_ctx)."""+ frac = LlamaCppBackend._GPU_PIN_VRAM_FRACTION+ model_bytes = model_mib * MIB++ def usable(g):+ return g[1] - (1.0 - frac) * totals[g[0]]++ ranked = sorted(gpus, key = usable, reverse = True)+ for n in range(min_gpus, len(ranked) + 1):+ subset = ranked[:n]+ pool = sum(max(0.0, usable(g)) for g in subset)+ ms = model_bytes + (n - 1) * self._OH+ cc = lambda c, n = n: n * b._compute_buffer_ctx_bytes(+ c, self._UB, "f16", layer_split = n > 1+ )+ capped = b._fit_context_to_vram(+ native_ctx,+ pool,+ ms,+ "f16",+ n_ubatch = self._UB,+ compute_ctx_bytes_fn = cc,+ budget_frac = 1.0,+ total_mib = None,+ )+ if (ms + b._estimate_kv_cache_bytes(capped) + cc(capped)) / MIB > pool:+ continue+ usable_mib = [usable(g) for g in subset]+ reserve_at = lambda c, n = n: (self._OH if n > 1 else 0) + cc(c, n) // n+ if enforce and not LlamaCppBackend._every_gpu_holds_reserve(+ usable_mib, reserve_at(capped)+ ):+ if not cap:+ continue+ capped = LlamaCppBackend._cap_ctx_to_per_device_reserve(+ capped, usable_mib, reserve_at+ )+ if capped <= 0:+ continue+ if (ms + b._estimate_kv_cache_bytes(capped) + cc(capped)) / MIB > pool:+ continue+ return sorted(idx for idx, _ in subset), capped+ return None, 0++ def _drive_reduced(+ self,+ b,+ gpus,+ totals,+ model_mib,+ min_gpus = 2,+ enforce = True,+ ):+ """Mirror of the reduced-to-4096 loop the native loop falls through to. Same+ pooled admission, so it needs the same per-device gate."""+ frac = LlamaCppBackend._GPU_PIN_VRAM_FRACTION+ ctx = 4096++ def usable(g):+ return g[1] - (1.0 - frac) * totals[g[0]]++ ranked = sorted(gpus, key = usable, reverse = True)+ for n in range(min_gpus, len(ranked) + 1):+ subset = ranked[:n]+ pool = sum(max(0.0, usable(g)) for g in subset)+ cc = n * b._compute_buffer_ctx_bytes(ctx, self._UB, "f16", layer_split = n > 1)+ ms = model_mib * MIB + (n - 1) * self._OH+ if (ms + b._estimate_kv_cache_bytes(ctx) + cc) / MIB > pool:+ continue+ if enforce and not LlamaCppBackend._every_gpu_holds_reserve(+ (usable(g) for g in subset),+ (self._OH if n > 1 else 0) + cc // n,+ ):+ continue+ return sorted(idx for idx, _ in subset), ctx+ return None, 0++ def test_reduced_context_fallback_enforces_the_same_reserve(self):+ # Card 1 sized one MiB under the reserve it replicates at 4096 ctx: the pooled+ # budget still admits the pair, so dropping to 4096 pinned a card that OOMs.+ b = self._fit_backend()+ totals = {0: 49_152, 1: 24_576}+ reserve_mib = (+ self._OH + b._compute_buffer_ctx_bytes(4096, self._UB, "f16", layer_split = True)+ ) / MIB+ gpus = [(0, 40_000), (1, round(reserve_mib - 1 + 0.03 * totals[1]))]+ assert self._drive_reduced(b, gpus, totals, 20_480, enforce = False) == ([0, 1], 4096)+ assert self._drive_reduced(b, gpus, totals, 20_480) == (None, 0)++ def test_reduced_context_fallback_keeps_a_card_that_holds_it(self):+ b = self._fit_backend()+ totals = {0: 49_152, 1: 24_576}+ reserve_mib = (+ self._OH + b._compute_buffer_ctx_bytes(4096, self._UB, "f16", layer_split = True)+ ) / MIB+ gpus = [(0, 40_000), (1, round(reserve_mib + 1 + 0.03 * totals[1]))]+ assert self._drive_reduced(b, gpus, totals, 20_480) == ([0, 1], 4096)++ def test_pooled_budget_hides_the_small_cards_shortfall(self):+ # Pre-fix: the pair is admitted at native context even though card 1 has+ # ~1.7 GiB usable and owes 1 GiB overhead + 6 GiB of replicated KQ mask.+ b = self._fit_backend()+ gpus, totals = self._HETEROGENEOUS+ gpu_indices, ctx = self._drive(b, gpus, totals, 20_480, 262144, enforce = False)+ assert gpu_indices == [0, 1] and ctx == 262144+ reserve_mib = (+ self._OH + b._compute_buffer_ctx_bytes(ctx, self._UB, "f16", layer_split = True)+ ) / MIB+ card1_usable = 2_500 - 0.03 * 24_576+ assert card1_usable < reserve_mib # would OOM card 1 at load++ def test_subset_is_capped_not_rejected_when_a_card_cannot_hold_its_reserve(self):+ # 1762.72 MiB usable on card 1 holds 31488, not the pooled 262144. Rejecting+ # the subset instead drops auto to the 4096 fallback for no reason.+ b = self._fit_backend()+ gpus, totals = self._HETEROGENEOUS+ assert self._drive(b, gpus, totals, 20_480, 262144, cap = False) == (None, 0)+ assert self._drive(b, gpus, totals, 20_480, 262144) == ([0, 1], 31_488)++ def test_homogeneous_gpus_are_unaffected(self):+ b = self._fit_backend()+ gpus, totals = self._HOMOGENEOUS+ with_gate = self._drive(b, gpus, totals, 20_480, 262144)+ without = self._drive(b, gpus, totals, 20_480, 262144, enforce = False)+ assert with_gate == without == ([0, 1], 262144)++ @pytest.mark.parametrize("model_mib", [8_192, 20_480, 30_720])+ def test_no_op_when_the_loop_may_start_at_one_gpu(self, model_mib):+ # _auto_min_gpus == 1: the n-1 subset having failed already bounds the+ # smallest card below by the reserve, so the gate changes nothing.+ b = self._fit_backend()+ for gpus, totals in (self._HETEROGENEOUS, self._HOMOGENEOUS):+ with_gate = self._drive(b, gpus, totals, model_mib, 262144, min_gpus = 1)+ without = self._drive(b, gpus, totals, model_mib, 262144, min_gpus = 1, enforce = False)+ assert with_gate == without+ assert with_gate[0] is not None++ def test_reserve_check_rejects_only_the_short_card(self):+ reserve = 3072 * MIB # bytes in, MiB compared+ assert LlamaCppBackend._every_gpu_holds_reserve([4000.0, 3072.0], reserve) is True+ assert LlamaCppBackend._every_gpu_holds_reserve([40000.0, 3071.0], reserve) is False+ assert LlamaCppBackend._every_gpu_holds_reserve([-10.0], reserve) is False+ assert LlamaCppBackend._every_gpu_holds_reserve([], reserve) is False++ def test_wired_into_the_auto_context_loop(self):+ import inspect++ compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())+ # Native-context loop and the reduced-to-4096 fallback below it.+ assert compact.count("ifnotself._every_gpu_holds_reserve(") == 2+ # Gated on the chosen context, and only reachable after the pooled test.+ assert "_usable_mib=[_gpu_usable(g,pin_fraction)forginsubset]" in compact+ assert "(_gpu_usable(g,pin_fraction)forginsubset)," in compact+ assert "+_cc_bytes(c,n)//n)" in compact+ assert "+_cc_bytes(effective_ctx,n_gpus)//n_gpus," in compact+ # The cap runs only on gate failure, and the pooled price is redone after it.+ assert (+ compact.count(+ "capped=self._cap_ctx_to_per_device_reserve("+ "capped,_usable_mib,_reserve_at)ifcapped<=0:continue"+ )+ == 1+ )+ assert "kv=_kv_bytes(capped)footprint_mib=(_ms+kv+_mtp_bytes(capped)" in compact+++class TestPerDeviceReserveCap:+ """Rejecting a subset outright costs context the smallest card could have held.+ Reuses the gate class's fixtures; the cap only changes what "reject" means."""++ _OH = TestPerDeviceSplitReserve._OH+ _UB = TestPerDeviceSplitReserve._UB+ _HETEROGENEOUS = TestPerDeviceSplitReserve._HETEROGENEOUS+ _HOMOGENEOUS = TestPerDeviceSplitReserve._HOMOGENEOUS+ _fit_backend = TestPerDeviceSplitReserve._fit_backend+ _drive = TestPerDeviceSplitReserve._drive++ def test_cap_is_exact_at_the_256_boundary(self):+ b = self._fit_backend()+ usable = 2_500 - 0.03 * 24_576 # 1762.72 MiB+ reserve = (+ lambda c: (self._OH + b._compute_buffer_ctx_bytes(c, self._UB, "f16", layer_split = True))+ / MIB+ )+ assert reserve(31_488) == 1762.0 <= usable+ assert reserve(31_744) == 1768.0 > usable++ def test_capped_context_still_fits_the_pooled_budget(self):+ b = self._fit_backend()+ gpus, totals = self._HETEROGENEOUS+ idx, ctx = self._drive(b, gpus, totals, 20_480, 262144)+ assert idx == [0, 1] and ctx == 31_488+ pool = sum(g[1] - 0.03 * totals[g[0]] for g in gpus)+ cc = 2 * b._compute_buffer_ctx_bytes(ctx, self._UB, "f16", layer_split = True)+ footprint = (20_480 * MIB + self._OH + b._estimate_kv_cache_bytes(ctx) + cc) / MIB+ assert footprint <= pool++ def test_homogeneous_gpus_are_unaffected_by_the_cap(self):+ b = self._fit_backend()+ gpus, totals = self._HOMOGENEOUS+ assert self._drive(b, gpus, totals, 20_480, 262144) == ([0, 1], 262144)++ def test_cap_floors_at_4096_and_still_rejects_below_it(self):+ # usable 1118.72 < reserve(4096) == 1120.0: nothing to salvage.+ b = self._fit_backend()+ assert self._drive(+ b, [(0, 40_000), (1, 1_856)], {0: 49_152, 1: 24_576}, 20_480, 262144+ ) == (None, 0)++ def test_cap_keeps_a_card_that_holds_exactly_4096(self):+ b = self._fit_backend()+ assert self._drive(+ b, [(0, 40_000), (1, 1_858)], {0: 49_152, 1: 24_576}, 20_480, 262144+ ) == ([0, 1], 4096)++ def test_flat_arch_term_is_not_rate_inverted(self):+ # deepseek4 carries a flat indexer term, so inverting the per-token rate+ # answers 43341, whose reserve is 6048 MiB on a 4000 MiB card.+ b = _backend(embd = 7168, arch = "deepseek4")+ reserve = lambda c: self._OH + b._compute_buffer_ctx_bytes(c, 512, "q8_0", layer_split = True)+ cap = LlamaCppBackend._cap_ctx_to_per_device_reserve(200_000, [4000.0], reserve)+ assert cap == 13_312+ assert reserve(cap) / MIB <= 4000.0 < reserve(cap + 256) / MIB+ assert reserve(43_341) / MIB > 4000.0++ def test_flat_arch_below_the_floor_is_infeasible(self):+ b = _backend(embd = 7168, arch = "deepseek4")+ reserve = lambda c: self._OH + b._compute_buffer_ctx_bytes(c, 512, "q8_0", layer_split = True)+ assert LlamaCppBackend._cap_ctx_to_per_device_reserve(200_000, [2500.0], reserve) == 0++ @pytest.mark.parametrize("model_mib", [8_192, 16_384, 20_480, 30_720])+ def test_capping_never_loses_to_continuing_with_more_gpus(self, model_mib):+ # A third small card cannot rescue the subset: it stays in the ranking, so+ # the reserve there is no smaller. Capping at 2 beats falling through.+ b = self._fit_backend()+ gpus = [(0, 40_000), (1, 2_500), (2, 2_400)]+ totals = {0: 49_152, 1: 24_576, 2: 24_576}+ assert self._drive(b, gpus, totals, model_mib, 262144, cap = False) == (None, 0)+ idx, ctx = self._drive(b, gpus, totals, model_mib, 262144)+ assert idx == [0, 1] and ctx == 31_488++ def test_helper_edges(self):+ cap = LlamaCppBackend._cap_ctx_to_per_device_reserve+ assert cap(262144, [], lambda c: 0) == 0+ assert cap(1024, [4000.0], lambda c: 0) == 0 # ctx below the 4096 floor+ assert cap(262144, [4000.0], lambda c: 0) == 262144 # free reserve, no cap+ linear = lambda c: c * 16384 # 16 KiB per ctx token, so 2000 MiB buys 128000+ best = cap(262144, [2000.0], linear)+ assert best == 128_000 and best % 256 == 0+ assert linear(best) / MIB <= 2000.0 < linear(best + 256) / MIB+++class TestSplitRateRecheckAfterSelection:+ """``_select_gpus`` derives the device count FROM the footprint, so its callers can+ only price the context-compute buffer at the single-device rate. A multi-GPU answer+ then has to be re-priced at the split rate before it is pinned with+ ``use_fit = False``, or a high-context explicit request OOMs at launch. Synthetic+ VRAM maps over the production helper: 24 GB cards at 0.97 (usable 23838 MiB each),+ ctx 1M at ub 512 f16 -> 1536 MiB of compute per device single-device, 6144 MiB split,+ so each card in a split owes 4608 MiB more than the first pass charged it."""++ _OH = LlamaCppBackend._PIPELINE_PER_DEVICE_OVERHEAD_MIB * MIB+ _UB = 512+ _CTX = 1048576+ _FRAC = LlamaCppBackend._GPU_PIN_VRAM_FRACTION+ _CARD = 24_576++ def _cards(self, n):+ return [(i, self._CARD) for i in range(n)], {i: self._CARD for i in range(n)}++ def _pin(+ self,+ total_mib,+ n_cards,+ recheck = True,+ min_gpus = 1,+ ctx = None,+ ):+ """Mirror of the explicit-context branch: total_mib is its weights + KV + MTP+ footprint, to which each path adds one single-device compute copy."""+ b = _backend(embd = 4096)+ ctx = ctx or self._CTX+ cc1 = b._compute_buffer_ctx_bytes(ctx, self._UB, "f16")+ cc_split = b._compute_buffer_ctx_bytes(ctx, self._UB, "f16", layer_split = True)+ gpus, totals = self._cards(n_cards)+ return LlamaCppBackend._select_gpus_split_aware(+ total_mib * MIB + cc1,+ gpus,+ usable_fraction = self._FRAC,+ total_by_idx = totals,+ per_device_overhead_bytes = self._OH + cc1,+ min_gpus = min_gpus,+ split_extra_bytes = (cc_split - cc1) if recheck else 0,+ )++ def test_pre_fix_pinned_a_pair_that_cannot_hold_the_split_rate(self):+ # The bug, over the plain selector this branch used to call: the pair needs+ # 44096 MiB of its 47677 MiB pool at the single-device rate, but 53312 at the+ # split rate -- pinned ~5.5 GiB short, with no --fit fallback after -ngl -1.+ b = _backend(embd = 4096)+ cc1 = b._compute_buffer_ctx_bytes(self._CTX, self._UB, "f16")+ ccs = b._compute_buffer_ctx_bytes(self._CTX, self._UB, "f16", layer_split = True)+ gpus, totals = self._cards(2)+ assert LlamaCppBackend._select_gpus(+ 40_000 * MIB + cc1,+ gpus,+ usable_fraction = self._FRAC,+ total_by_idx = totals,+ per_device_overhead_bytes = self._OH + cc1,+ ) == ([0, 1], False)+ pool = 2 * (self._CARD - (1.0 - self._FRAC) * self._CARD)+ assert (40_000 * MIB + ccs + self._OH + ccs) / MIB > pool++ def test_recheck_falls_back_to_fit_when_no_subset_holds_it(self):+ # Honest failure: --fit on degrades to CPU offload, matching this branch's+ # documented behaviour, instead of pinning a launch that OOMs.+ assert self._pin(40_000, 2) == (None, True)++ def test_recheck_widens_the_subset_when_a_card_is_spare(self):+ # Three cards: the first pass still answers 2, the re-check takes all 3.+ assert self._pin(40_000, 3, recheck = False) == ([0, 1], False)+ assert self._pin(40_000, 3) == ([0, 1, 2], False)++ def test_single_gpu_pin_is_untouched(self):+ assert self._pin(20_000, 2) == ([0], False)+ assert self._pin(20_000, 2, recheck = False) == ([0], False)++ def test_equal_cards_never_collapse_to_one_gpu(self):+ # Every card clears the enlarged overhead, so the retry keeps min_gpus.+ for total in range(24_000, 46_000, 2_000):+ gi, use_fit = self._pin(total, 4)+ assert use_fit or (gi is not None and len(gi) >= 2)++ def test_collapse_to_one_gpu_is_repriced_without_the_delta(self):+ # Unequal cards: only the big one clears overhead + delta, so _select_gpus cuts+ # its usable-card count to one. A lone card is not a split and pays no delta,+ # so charging it there sent a load that fits alone to --fit on (CPU offload).+ gpus = [(0, 16 * 1024), (1, 3 * 1024)]+ kw = dict(usable_fraction = 1.0, per_device_overhead_bytes = int(2.5 * GIB))+ assert LlamaCppBackend._select_gpus(int(14 * GIB), gpus, min_gpus = 2, **kw) == (+ [0, 1],+ False,+ )+ assert LlamaCppBackend._select_gpus_split_aware(+ int(14 * GIB), gpus, min_gpus = 2, split_extra_bytes = int(4.5 * GIB), **kw+ ) == ([0], False)+ # Exactly the plain single-device answer, not a relaxed split.+ assert LlamaCppBackend._select_gpus(int(14 * GIB), gpus, min_gpus = 1, **kw) == (+ [0],+ False,+ )++ def test_reprice_still_reports_fit_when_no_single_card_holds_it(self):+ # 30 GiB over two 20 GiB cards: the split no longer fits and neither does one+ # card, so the honest answer stays --fit on.+ assert LlamaCppBackend._select_gpus_split_aware(+ int(30 * GIB),+ [(0, 20 * 1024), (1, 20 * 1024)],+ usable_fraction = 1.0,+ per_device_overhead_bytes = int(1 * GIB),+ min_gpus = 2,+ split_extra_bytes = int(15 * GIB),+ ) == (None, True)++ def test_zero_step_reduces_to_plain_selection(self):+ # llama.cpp declining pipeline parallelism makes the step 0 (_cc_split_extra+ # reads the same layer_split gate), and the helper is then a pass-through.+ b = _backend(embd = 4096)+ cc1 = b._compute_buffer_ctx_bytes(self._CTX, self._UB, "f16")+ gpus, totals = self._cards(3)+ for total_mib in (20_000, 40_000, 90_000):+ assert self._pin(total_mib, 3, recheck = False) == LlamaCppBackend._select_gpus(+ total_mib * MIB + cc1,+ gpus,+ usable_fraction = self._FRAC,+ total_by_idx = totals,+ per_device_overhead_bytes = self._OH + cc1,+ )++ def test_small_context_is_unaffected(self):+ # 4096 ctx: the 18 MiB of extra masks changes no decision.+ assert self._pin(40_000, 2, ctx = 4096) == self._pin(40_000, 2, recheck = False, ctx = 4096)++ def test_wired_into_both_call_sites(self):+ import inspect++ load = "".join(inspect.getsource(LlamaCppBackend.load_model).split())+ # Explicit-context pin and the reduced-slot retry both pass the step.+ assert load.count("split_extra_bytes=_cc_split_extra(effective_ctx)") == 2+ assert "gpu_indices,use_fit=self._select_gpus_split_aware(" in load+ # The step rides _cc_bytes' pipelining gate, so it is 0 when llama.cpp declines.+ assert "returnmax(0,_cc_bytes(ctx,2)//2-_cc_bytes(ctx))" in load+ slots = "".join(inspect.getsource(LlamaCppBackend._slots_that_fit_on_gpu).split())+ assert "self._select_gpus_split_aware(" in slots+ assert "split_extra_bytes=split_extra_bytes," in slotsdiff --git a/studio/backend/tests/test_slot_offload_fit.py b/studio/backend/tests/test_slot_offload_fit.pyindex 63449053327..4441f3afc4d 100644--- a/studio/backend/tests/test_slot_offload_fit.py+++ b/studio/backend/tests/test_slot_offload_fit.py@@ -67,7 +67,10 @@ def _run(total_by_idx,overhead_mib = 0,swa_full = False,+ split_extra_mib = 0,):+ # Split step passed only when set, so the other cases keep exercising the default.+ extra = {"split_extra_bytes": int(split_extra_mib * MIB)} if split_extra_mib else {}return b._slots_that_fit_on_gpu(n_parallel,CTX,@@ -80,6 +83,7 @@ def _run(1,n_ubatch = 512,swa_full = swa_full,+ **extra,)@@ -127,6 +131,20 @@ class TestSlotsThatFitOnGpu:gi, use_fit, slots = _run(_backend(kv_fixed_mib = 3000), 4, 19500, [(0, 24576)], {0: 24576})assert use_fit is False and slots == 3+ def test_split_rate_is_rechecked_on_multi_gpu_candidates(self):+ # The base footprint carries the context-compute buffer at the single-device+ # rate, so a candidate that lands on 2 GPUs owes one enlarged copy per card.+ # Charging it drops the count further (3 -> 1) rather than pinning an OOM.+ gpus, totals = [(0, 24576), (1, 24576)], {0: 24576, 1: 24576}+ assert _run(_backend(), 4, 46200, gpus, totals, split_extra_mib = 500) == ([0, 1], False, 1)+ # And when no count clears it, offload (the pre-existing failure mode).+ assert _run(_backend(), 4, 46200, gpus, totals, split_extra_mib = 1000) == (None, True, 4)++ def test_split_step_does_not_touch_a_single_gpu_candidate(self):+ assert _run(_backend(), 4, 22500, [(0, 24576)], {0: 24576}, split_extra_mib = 500) == (+ _run(_backend(), 4, 22500, [(0, 24576)], {0: 24576})+ )+def test_swa_full_is_used_for_every_candidate(self):calls = []_run(