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: reserve CUDA context and mmproj/MTP soft overhead in the GGUF fit budget (#6718)
Daniel Han9c2eacc35e3f
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 035e5d12c7a..3ccfc5cdfe1 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -801,7 +801,11 @@ _MTP_MIN_SIZE_B = 3.0# Cap total GPU occupancy at this fraction of the card. The fit reserves an# absolute (1 - frac) * total per GPU when total VRAM is known, else a fraction# of free (see _fit_context_to_vram), plus a byte-accurate MTP draft reserve.-_CTX_FIT_VRAM_FRACTION = 0.95+# 3%: the context-linear compute buffer is now modelled (_compute_buffer_ctx_bytes),+# so this cushion no longer covers it - only fragmentation, the per-device CUDA+# context on a multi-GPU split, and MoE routing, which measure ~2-3% (Qwen3.5-397B on+# 3 GPUs under-predicts by 2.7%). Below 3% one fragmentation spike overflows to CPU.+_CTX_FIT_VRAM_FRACTION = 0.97# Apple unified memory is shared with the OS, so tighter than VRAM. Matches the# 0.85 MLX uses in mlx_inference.py (_configure_memory_limits); not kept in sync.@@ -2464,9 +2468,10 @@ class LlamaCppBackend:prev = curr# Free-VRAM fraction at which Studio pins the GPU directly instead of- # deferring to ``--fit on``. 5% headroom covers CUDA context + compute- # buffers; 0.90 dropped 91-94% fits to CPU offload (#5106).- _GPU_PIN_VRAM_FRACTION = 0.95+ # deferring to ``--fit on``. 3% headroom: the compute buffer is now modelled in+ # the fit, so this only guards fragmentation + multi-GPU per-device CUDA context+ # (~2-3%); kept >= 3% as a floor (0.90 dropped 91-94% fits to CPU offload, #5106).+ _GPU_PIN_VRAM_FRACTION = 0.97# Fallback per-device tensor-mode compute buffer (MiB), used only when GGUF# dims are unavailable so _estimate_compute_buffer_bytes (the primary, derived@@ -3022,6 +3027,27 @@ class LlamaCppBackend:_DEFAULT_N_UBATCH = 512 # llama.cpp --ubatch default; Studio does not override it_COMPUTE_BUFFER_SAFETY = 1.15 # upper-bound margin on the compute-buffer estimate+ # Soft VRAM the modeled terms omit; charged to the fit budget on tight tiers (#6682).+ _CUDA_CONTEXT_RESERVE_BYTES = 320 * 1024 * 1024 # CUDA ctx + cuBLAS workspace (~330 MiB)+ _MMPROJ_VRAM_SAFETY = 1.4 # mmproj worst-case buffer vs file size (runtime ~1.3x)+ _MTP_DRAFT_COMPUTE_BYTES = 224 * 1024 * 1024 # MTP draft decode graph beyond its KV+ # The flash-attn KQ mask + attention scratch grow ~linearly with context; the flat+ # _estimate_compute_buffer_bytes term only covers ctx -> 0. The per-token rate+ # depends on the KV cache type: a QUANTIZED cache (q8_0/q5/q4/iq4) needs a+ # context-sized dequant scratch that scales with n_embd, measured at 0.74-2.02 x+ # n_embd across Qwen3.5/3.6 (2B/4B/9B/27B) and Gemma-4 (12B/31B) at q8_0; an+ # f16/bf16/f32 cache skips the dequant and pays only the KQ mask, a flat n_ubatch*2+ # bytes per context token regardless of n_embd (measured 1024 B/tok on Qwen-9B and+ # Gemma-31B alike). So Qwen3.5-4B at 256k is 1.30 GiB at q8_0 vs 0.31 GiB at f16.+ # 2.25 covers the worst quantized case (Qwen3.5-4B, ~2.0x) plus the under-modeled+ # flat base; the mask safety covers the f16 base gap. Without this term, tight tiers+ # at extreme context over-pin and spill to CPU (the 3% cushion is only ~0.25 GiB on+ # an 8 GB card, far below the ~1-2.4 GiB quantized buffer at 256k): e.g. Qwen3.5-4B+ # Q4 at 256k needs ~8.5 GiB on a real 8 GB card (weights 2.4 + KV 4.3 + compute 1.3+ # + CUDA ctx) -> CPU spill; with this reserve the auto context caps to ~210k, fits.+ _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)def _estimate_compute_buffer_bytes(self,@@ -3052,6 +3078,85 @@ class LlamaCppBackend:compute = act_scratch + out_buffer * max(0, par - 1)return int(compute * self._COMPUTE_BUFFER_SAFETY)+ def _compute_buffer_ctx_bytes(+ self,+ n_ctx: int,+ n_ubatch: Optional[int] = None,+ cache_type_kv: Optional[str] = None,+ ) -> int:+ """Context-linear growth of the per-device compute buffer (bytes), charged+ on top of the flat ``_estimate_compute_buffer_bytes``. The flash-attn KQ+ mask + attention scratch scale ~linearly with context and with the micro-+ batch; the flat term only covers ctx -> 0. A quantized KV cache adds a+ context-sized dequant scratch that scales with n_embd; f16/bf16/f32 pays only+ 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 on+ the KV side, whose over-reservation absorbs the dequant scratch). Returns 0+ when dims are missing or ``n_ctx`` <= 0."""+ n_embd = self._embedding_length or 0+ if n_embd <= 0 or n_ctx <= 0:+ return 0+ ub = max(1, int(n_ubatch if n_ubatch else self._DEFAULT_N_UBATCH))+ 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+ # GLM-5.2 and Kimi-K2.7 vs up to 2.02x on regular attention.+ ub_scale = ub / self._DEFAULT_N_UBATCH+ rate = (+ self._CTX_COMPUTE_BYTES_PER_EMBD_MLA+ if self._key_length_mla+ else self._CTX_COMPUTE_BYTES_PER_EMBD+ )+ per_tok = rate * n_embd * ub_scale+ else:+ # 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)++ def _slots_that_fit_on_gpu(+ self,+ n_parallel: int,+ effective_ctx: int,+ gpus: list[tuple[int, int]],+ total_by_idx: Optional[dict[int, int]],+ base_footprint_bytes: int,+ cache_type_kv: Optional[str],+ pin_fraction: float,+ per_device_overhead_bytes: int,+ min_gpus: int,+ n_ubatch: Optional[int] = None,+ ) -> tuple[Optional[list[int]], bool, int]:+ """Largest serving-slot count in [1, n_parallel) whose fully-on-GPU footprint fits,+ so Studio keeps the model on GPU (-ngl -1) instead of --fit on, which offloads layers+ to host and collapses decode ~3x (oobabooga #6718). ``base_footprint_bytes`` is the+ slot-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."""+ 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+ )+ if cb <= 0:+ cb = self._TENSOR_PARALLEL_BUFFER_RESERVE_MIB * 1024 * 1024+ total = (+ base_footprint_bytes+ + cb+ + self._estimate_kv_cache_bytes(effective_ctx, cache_type_kv, n_parallel = slots)+ )+ gpu_indices, use_fit = self._select_gpus(+ total,+ gpus,+ usable_fraction = pin_fraction,+ total_by_idx = total_by_idx,+ per_device_overhead_bytes = per_device_overhead_bytes,+ min_gpus = min_gpus,+ )+ if not use_fit:+ return gpu_indices, False, slots+ return None, True, n_parallel+def _fit_context_to_vram(self,requested_ctx: int,@@ -3067,6 +3172,7 @@ class LlamaCppBackend:kv_on_gpu: bool = True,mtp_engaged: bool = False,mtp_overhead_fn: Optional[Callable[[int], int]] = None,+ compute_ctx_bytes_fn: Optional[Callable[[int], int]] = None,budget_frac: Optional[float] = None,total_mib: Optional[int] = None,) -> int:@@ -3118,9 +3224,14 @@ class LlamaCppBackend:def _mtp_at(ctx: int) -> int:return mtp_overhead_fn(ctx) if mtp_overhead_fn is not None else 0+ def _cc_at(ctx: int) -> int:+ # Context-linear compute-buffer growth (flash-attn KQ mask + scratch);+ # the flat term in model_footprint only covers ctx -> 0.+ return compute_ctx_bytes_fn(ctx) if compute_ctx_bytes_fn is not None else 0+# Already fits?kv = self._estimate_kv_cache_bytes(requested_ctx, cache_type_kv, **kv_kwargs)- if model_footprint + kv + _mtp_at(requested_ctx) <= budget_bytes:+ if model_footprint + kv + _mtp_at(requested_ctx) + _cc_at(requested_ctx) <= budget_bytes:return requested_ctx# Weights + compute buffer alone exceed budget -- reducing ctx can't help.@@ -3141,7 +3252,7 @@ class LlamaCppBackend:while lo <= hi:mid = (lo + hi) // 2kv = self._estimate_kv_cache_bytes(mid, cache_type_kv, **kv_kwargs)- if kv + _mtp_at(mid) <= remaining:+ if kv + _mtp_at(mid) + _cc_at(mid) <= remaining:best = midlo = mid + 1else:@@ -4288,6 +4399,7 @@ class LlamaCppBackend:max_target_ctx: Optional[int] = None,total_by_idx: Optional[dict[int, int]] = None,n_ubatch: Optional[int] = None,+ soft_overhead_bytes: int = 0,) -> tuple[int, int, list[int], Optional[list[int]]]:"""Plan a ``--split-mode tensor`` load. Pure: no model or GPU needed.@@ -4299,9 +4411,11 @@ class LlamaCppBackend:``(effective_ctx, max_available_ctx, gpu_indices, tensor_split)``.Policy (assumes >= 2 GPUs; the caller drops the toggle below that):- - Cap context to the KV that fits the pooled VRAM after the weights and- one per-device compute-graph buffer (``_estimate_compute_buffer_bytes``,- deterministic from dims; flat fallback when dims are unavailable).+ - Cap context to the KV that fits the pooled VRAM after the weights, one+ per-device flat compute-graph buffer (``_estimate_compute_buffer_bytes``,+ deterministic from dims; flat fallback when dims are unavailable), and the+ per-device context-linear compute growth (``_compute_buffer_ctx_bytes``,+ replicated on every device in tensor mode, so summed over the split).llama.cpp's ``--fit`` is a no-op in tensor mode, so this is the onlycap, honored even for an explicit ``-c``. It is more accurate than the0.80 whole-pool heuristic, which over-reserves and leaves VRAM unused.@@ -4310,7 +4424,9 @@ class LlamaCppBackend:share fits the smallest GPU; otherwise it is weighted by usable budgetso the roomier GPU absorbs more weight and the smallest keeps room for KV.``total_by_idx`` enables the total-based occupancy cap; ``n_ubatch`` sizes- the compute buffer.+ the compute buffer. ``soft_overhead_bytes`` is the CUDA-context / mmproj /+ MTP-draft-graph reserve the layer path folds into ``model_size_fit``;+ charged against the pooled budget so tensor mode reserves the same overhead."""# Per-GPU usable budget: free - (1-frac)*total, else (unknown total, e.g. a@@ -4356,16 +4472,40 @@ class LlamaCppBackend:flat_mtp_bytes = max(0, mtp_flat_reserve_bytes)if mtp_engaged and mtp_overhead_fn is None:flat_mtp_bytes = max(flat_mtp_bytes, 2 * 1024**3)+ # soft_overhead_bytes is the CUDA-context / mmproj / MTP-draft-graph reserve+ # the layer path folds into model_size_fit. Tensor mode has no --fit valve, so+ # an unreserved overshoot OOMs at startup rather than offloading; charge it here+ # too. Once (pooled), mirroring the layer path -- the per-device CUDA context is+ # a known slight under-charge, left for real multi-GPU data.kv_budget_b = (- (pool_mib - len(gpu_indices) * reserve_mib) * 1024 * 1024 - model_size - flat_mtp_bytes+ (pool_mib - len(gpu_indices) * reserve_mib) * 1024 * 1024+ - model_size+ - flat_mtp_bytes+ - max(0, soft_overhead_bytes))def _mtp_at(ctx: int) -> int:return mtp_overhead_fn(ctx) if mtp_overhead_fn is not None else 0+ # Context-linear compute buffer, summed over the split. Tensor mode+ # replicates the compute graph on EVERY device (measured: the per-device+ # buffer grows a flat n_ubatch*2 bytes/token, ~1024 B/tok on Qwen3.5-9B at+ # f16, independent of n_embd), so the growth is n_dev x the per-device+ # term. cache_type_kv here is always non-quantized (tensor forces f16), so+ # _compute_buffer_ctx_bytes returns the light KQ-mask term, not the heavy+ # quantized dequant scratch. The flat reserve_mib above only covers ctx->0;+ # without this the fit over-pins and OOMs at high context on a tight pool+ # (0.5-4 GiB unreserved at 262k-1M across 2-4 GPUs), the tensor-mode analog+ # of the layer-split compute bug.+ n_dev = len(gpu_indices)++ def _cc_ctx(ctx: int) -> int:+ return n_dev * self._compute_buffer_ctx_bytes(ctx, n_ubatch, cache_type_kv)+def _fit_ctx(ctx: int) -> int:- # Largest context whose KV (+ MTP draft reserve) fits the pooled- # budget. Floors small, but never raises an explicit ctx above asked.+ # Largest context whose KV (+ MTP draft reserve + context-linear+ # compute) fits the pooled budget. Floors small, but never raises an+ # explicit ctx above asked.if self._can_estimate_kv() and ctx > 0:ctx_floor = min(2048, ctx)if kv_budget_b <= 0:@@ -4373,11 +4513,13 @@ class LlamaCppBackend:# falls back to layer split.return ctx_floorif mtp_overhead_fn is not None:- # kv(ctx)+mtp(ctx) is not single-linear, so binary search.+ # kv(ctx)+mtp(ctx)+compute(ctx) is not single-linear, so binary search.def _consumer(c: int) -> int:- return self._estimate_kv_cache_bytes(- c, cache_type_kv, n_parallel = n_parallel- ) + _mtp_at(c)+ return (+ self._estimate_kv_cache_bytes(c, cache_type_kv, n_parallel = n_parallel)+ + _mtp_at(c)+ + _cc_ctx(c)+ )if _consumer(ctx) <= kv_budget_b:return ctx@@ -4391,9 +4533,10 @@ class LlamaCppBackend:hi = mid - 1return bestkv_at = self._estimate_kv_cache_bytes(ctx, cache_type_kv, n_parallel = n_parallel)- if kv_at <= kv_budget_b:+ total_at = kv_at + _cc_ctx(ctx) # both ~linear through the origin+ if total_at <= kv_budget_b:return ctx- return max(ctx_floor, int(ctx * kv_budget_b / kv_at))+ return max(ctx_floor, int(ctx * kv_budget_b / total_at))# KV size unknown -> can't prove a safe cap; floor.return min(4096, ctx) if ctx > 0 else 4096@@ -4413,10 +4556,23 @@ class LlamaCppBackend:# The MTP reserve also has to fit the even split (mirror the pooled budget):# byte-accurate per-ctx (0 when no fn) plus the same flat cushion as above.mtp_bytes = (_mtp_at(effective_ctx) if effective_ctx > 0 else 0) + flat_mtp_bytes- even_share_mib = (model_size + kv_bytes + mtp_bytes) / len(gpu_indices) / (1024 * 1024)+ # Context-linear compute is replicated per device; charge the whole split so+ # the weighted ratio reflects it (mirrors kv_budget_b's per-device reserve).+ cc_bytes = _cc_ctx(effective_ctx) if effective_ctx > 0 else 0+ even_share_mib = (+ (model_size + kv_bytes + mtp_bytes + cc_bytes) / len(gpu_indices) / (1024 * 1024)+ )tensor_split: Optional[list[int]] = Noneif even_share_mib > (min_usable_mib - reserve_mib):- adj = [max(0, int(usable_by_idx[i] - reserve_mib)) for i in gpu_indices]+ # Each device also holds its replicated share of the context-linear+ # compute (cc_bytes/n_dev) on top of the flat reserve. The even-share+ # gate above charges cc_bytes; the split weights must subtract it too, or+ # the smaller card is weighted above its real usable budget and OOMs (the+ # per-device analog of the layer path's per-GPU overhead in _select_gpus).+ cc_per_dev_mib = (cc_bytes // len(gpu_indices)) // (1024 * 1024) if cc_bytes else 0+ adj = [+ max(0, int(usable_by_idx[i] - reserve_mib - cc_per_dev_mib)) for i in gpu_indices+ ]if sum(adj) > 0:tensor_split = adjreturn effective_ctx, max_available_ctx, gpu_indices, tensor_split@@ -5179,6 +5335,20 @@ class LlamaCppBackend:# compute buffer); None -> the 512 default in the estimate._effective_ubatch = _extra_args_n_ubatch(extra_args)+ def _cc_bytes(ctx: int, n_gpus: int = 1) -> int:+ # Context-linear compute-buffer growth (flash-attn KQ mask ++ # attention scratch); the flat _compute_buffer_pipeline folded+ # into model_size_fit only covers ctx -> 0. Charged per+ # candidate context so the fit can't over-pin and spill. The+ # rate depends on the KV cache type (quantized adds a dequant+ # 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).+ return max(1, n_gpus) * self._compute_buffer_ctx_bytes(+ ctx, _effective_ubatch, cache_type_kv+ )+# 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@@ -5193,7 +5363,6 @@ class LlamaCppBackend:_compute_buffer_pipeline = (self._TENSOR_PARALLEL_BUFFER_RESERVE_MIB * 1024 * 1024)- model_size_fit = model_size + _compute_buffer_pipeline# Layer split adds a fixed per-device overhead on every GPU. The# folded buffer covers one device; reserve the extra devices'@@ -5201,9 +5370,6 @@ class LlamaCppBackend:# (k=1 adds nothing)._pipeline_overhead_bytes = self._PIPELINE_PER_DEVICE_OVERHEAD_MIB * 1024 * 1024- def _subset_model_size(n_gpus: int) -> int:- return model_size_fit + max(0, n_gpus - 1) * _pipeline_overhead_bytes-# Auto-cap context to fit VRAM and select GPUs. Explicit n_ctx:# honor it, cap only if it fits no combination. Auto (native):# prefer fewer GPUs with reduced context (multi-GPU is slower).@@ -5230,6 +5396,21 @@ class LlamaCppBackend:else 0.0)_pin_fraction = self._GPU_PIN_VRAM_FRACTION - _flat_mtp_reserve++ # Charge the soft overhead _CTX_FIT_VRAM_FRACTION under-covers on tight+ # tiers, gated so plain dense loads (#5106) only pay the CUDA-ctx base.+ # CUDA/cuBLAS context is discrete-GPU only (not Metal); the mmproj and+ # MTP draft-graph buffers exist on every backend.+ _soft_overhead = self._CUDA_CONTEXT_RESERVE_BYTES if gpus else 0+ if effective_is_vision and mmproj_size > 0:+ _soft_overhead += int(mmproj_size * (self._MMPROJ_VRAM_SAFETY - 1.0))+ if _mtp_reserves_gpu:+ _soft_overhead += self._MTP_DRAFT_COMPUTE_BYTES+ model_size_fit = model_size + _compute_buffer_pipeline + _soft_overhead++ def _subset_model_size(n_gpus: int) -> int:+ return model_size_fit + max(0, n_gpus - 1) * _pipeline_overhead_bytes+# Unified-memory budget (0 off Apple Silicon) for the no-GPU Metal cap below._apple_budget_mib = self._apple_metal_memory_budget_bytes() // (1024 * 1024)@@ -5334,7 +5515,9 @@ class LlamaCppBackend:_tp_flat_mtp,_mtp_bytes(min(2048, effective_ctx) if effective_ctx > 0 else 2048),)- _tp_required_mib = (model_size + _tp_mtp_floor) / (1024 * 1024)+ _tp_required_mib = (model_size + _tp_mtp_floor + _soft_overhead) / (+ 1024 * 1024+ )if _tp_weight_budget_mib <= _tp_required_mib:logger.info("Tensor parallelism requested but the pooled VRAM "@@ -5383,6 +5566,7 @@ class LlamaCppBackend:max_target_ctx = self._context_length or target_ctx,total_by_idx = total_by_idx,n_ubatch = _effective_ubatch,+ soft_overhead_bytes = _soft_overhead,)use_fit = Falseelif gpus and self._can_estimate_kv() and effective_ctx > 0:@@ -5407,6 +5591,9 @@ class LlamaCppBackend:# budget so the fit and the check below agree.pool_budget = _pool_budget_mib(subset, _cap_fraction)_ms = _subset_model_size(n_gpus)+ # Compute buffer is replicated per device in a layer+ # split, so scale the context term by the subset size.+ _cc_sub = lambda c, n = n_gpus: _cc_bytes(c, n)capped = self._fit_context_to_vram(native_ctx_for_cap,pool_budget,@@ -5415,13 +5602,16 @@ class LlamaCppBackend:n_parallel = n_parallel,mtp_engaged = _mtp_reserves_gpu,mtp_overhead_fn = mtp_overhead_fn,+ compute_ctx_bytes_fn = _cc_sub,budget_frac = 1.0,total_mib = None,)kv = self._estimate_kv_cache_bytes(capped, cache_type_kv, n_parallel = n_parallel)- footprint_mib = (_ms + kv + _mtp_bytes(capped)) / (1024 * 1024)+ footprint_mib = (+ _ms + kv + _mtp_bytes(capped) + _cc_sub(capped)+ ) / (1024 * 1024)if footprint_mib <= pool_budget:best_cap = max(best_cap, capped)if best_cap > 0:@@ -5442,13 +5632,18 @@ class LlamaCppBackend:effective_ctx, cache_type_kv, n_parallel = n_parallel)+ _mtp_bytes(effective_ctx)+ + _cc_bytes(effective_ctx))+ # 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(requested_total,gpus,usable_fraction = _pin_fraction,total_by_idx = total_by_idx,- per_device_overhead_bytes = _pipeline_overhead_bytes,+ per_device_overhead_bytes = _pipeline_overhead_bytes+ + _cc_bytes(effective_ctx),min_gpus = _layer_min_gpus,)# No silent shrink: effective_ctx stays == requested_ctx.@@ -5479,6 +5674,9 @@ class LlamaCppBackend:subset = ranked[:n_gpus]pool_budget = _pool_budget_mib(subset, pin_fraction)_ms = _subset_model_size(n_gpus)+ # Compute buffer is replicated per device in a layer+ # split, so scale the context term by the subset size.+ _cc_sub = lambda c, n = n_gpus: _cc_bytes(c, n)capped = self._fit_context_to_vram(effective_ctx,pool_budget,@@ -5487,13 +5685,16 @@ class LlamaCppBackend:n_parallel = n_parallel,mtp_engaged = _mtp_reserves_gpu,mtp_overhead_fn = mtp_overhead_fn,+ compute_ctx_bytes_fn = _cc_sub,budget_frac = 1.0,total_mib = None,)kv = self._estimate_kv_cache_bytes(capped, cache_type_kv, n_parallel = n_parallel)- footprint_mib = (_ms + kv + _mtp_bytes(capped)) / (1024 * 1024)+ footprint_mib = (+ _ms + kv + _mtp_bytes(capped) + _cc_sub(capped)+ ) / (1024 * 1024)if footprint_mib <= pool_budget:effective_ctx = cappedgpu_indices = sorted(idx for idx, _ in subset)@@ -5516,6 +5717,7 @@ class LlamaCppBackend:_subset_model_size(n_gpus)+ kv+ _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)@@ -5570,6 +5772,7 @@ class LlamaCppBackend:n_parallel = n_parallel,mtp_engaged = _mtp_reserves_gpu,mtp_overhead_fn = mtp_overhead_fn,+ compute_ctx_bytes_fn = _cc_bytes,budget_frac = 1.0,total_mib = None,)@@ -5579,6 +5782,7 @@ class LlamaCppBackend:cap, cache_type_kv, n_parallel = n_parallel)+ _mtp_bytes(cap)+ + _cc_bytes(cap)) / (1024 * 1024)# Fit returns the request unchanged when it fits OR weights# exceed budget; only the latter over-commits, so floor to 4096.@@ -5594,6 +5798,48 @@ class LlamaCppBackend:if not explicit_ctx:effective_ctx = max_available_ctx+ # Prefer fewer serving slots on GPU over --fit on offload: when the extra+ # --parallel slots push the footprint past the pin budget, llama-server+ # offloads layers to host and decode collapses ~3x (#6718). Retry the fit+ # at fewer slots, keeping the largest count that stays fully on GPU and the+ # chosen context. Skips tensor mode / Metal / KV-inestimable paths.+ if (+ use_fit+ and n_parallel > 1+ and gpus+ and self._can_estimate_kv()+ and effective_ctx > 0+ ):+ # Slot-independent footprint (folded compute buffer swapped out so the+ # helper re-adds a slot-sized one per candidate).+ _base_footprint = (+ model_size_fit+ - _compute_buffer_pipeline+ + _mtp_bytes(effective_ctx)+ + _cc_bytes(effective_ctx)+ )+ _gi_slots, _uf_slots, _slots = self._slots_that_fit_on_gpu(+ n_parallel,+ effective_ctx,+ gpus,+ total_by_idx,+ _base_footprint,+ cache_type_kv,+ _pin_fraction,+ _pipeline_overhead_bytes + _cc_bytes(effective_ctx),+ _layer_min_gpus,+ _effective_ubatch,+ )+ if not _uf_slots:+ logger.info(+ "Serving slots reduced %d -> %d to keep the model on GPU "+ "(avoid --fit offload) at context %d.",+ n_parallel,+ _slots,+ effective_ctx,+ )+ gpu_indices, use_fit, n_parallel = _gi_slots, False, _slots+# MTP reserve at the final context, for the logs below._mtp_reserve_bytes = _mtp_bytes(effective_ctx) if _mtp_will_engage else 0if _mtp_will_engage:@@ -5692,8 +5938,10 @@ class LlamaCppBackend:if use_fit:cmd.extend(["--fit", "on"])elif gpu_indices is not None:- # Fits on selected GPU(s) -- offload all layers- cmd.extend(["-ngl", "-1"])+ # Fits on selected GPU(s) -- force all layers on GPU. --fit off is+ # required: without it llama.cpp's default --fit on second-guesses+ # and offloads ~1 GB at --parallel 4 even though the model fits.+ cmd.extend(["-ngl", "-1", "--fit", "off"])fully_gpu_offloaded = Trueserver_caps = self.probe_server_capabilities(binary)@@ -6078,6 +6326,33 @@ class LlamaCppBackend:_split_axis_crash = self._is_tensor_split_assert("\n".join(self._stdout_lines[-50:]))+ if (+ _spawn_attempt == 0+ and fully_gpu_offloaded+ and _startup_crashed+ and not _split_axis_crash+ ):+ # We forced --fit off because Studio's (conservative) VRAM+ # math placed the model fully on GPU. A startup crash here+ # means that estimate was optimistic, so fall back to --fit+ # on and let llama.cpp offload rather than fail the load.+ logger.warning(+ "llama-server crashed during startup (exit code %s) "+ "with forced --fit off; the fit estimate was optimistic, "+ "retrying once with --fit on so it can offload. "+ "Crash log: %s",+ self._process.returncode,+ self._llama_log_path,+ )+ # Flip Studio's own --fit off (added first, before any+ # user extra args) to on; a user's later --fit still wins+ # by last-arg. Defensive: if absent, the default is already+ # --fit on, so leave it.+ _run = list(run_cmd)+ if "--fit" in _run:+ _run[_run.index("--fit") + 1] = "on"+ run_cmd = _run+ continueif (_spawn_attempt == 0and _fit_retry_alloweddiff --git a/studio/backend/tests/test_compute_buffer.py b/studio/backend/tests/test_compute_buffer.pyindex 42c400383eb..5d14c5c5bd3 100644--- a/studio/backend/tests/test_compute_buffer.py+++ b/studio/backend/tests/test_compute_buffer.py@@ -61,11 +61,16 @@ from core.inference.llama_cpp import LlamaCppBackendMIB = 1024 * 1024-def _backend(vocab = 248320, embd = 5120):+def _backend(+ vocab = 248320,+ embd = 5120,+ mla = None,+):"""Backend with just the dims the compute-buffer estimate reads."""b = LlamaCppBackend.__new__(LlamaCppBackend)b._vocab_size = vocabb._embedding_length = embd+ b._key_length_mla = mla # non-None -> MLA (compressed attention)return b@@ -150,3 +155,138 @@ class TestParallel1Default:def test_default_n_parallel(self):est = _backend()._estimate_compute_buffer_bytes() / MIBassert est < 128+++class TestContextLinearBuffer:+ """``_compute_buffer_ctx_bytes``: the flash-attn KQ-mask + attention scratch+ grow ~linearly with context; the flat estimate above only covers ctx -> 0.+ Measured slope (q8_0 KV, ubatch 512) was 0.74-2.02 x n_embd; 2 x n_embd is the+ worst-case upper bound the term must hold to."""++ # (model, n_embd, ctx, measured CUDA0 compute buffer MiB at that ctx, q8_0/ub512)+ _MEASURED = [+ ("Qwen3.5-2B", 2048, 262144, 796),+ ("Qwen3.5-4B", 2560, 262144, 1330), # worst slope, 2.02 x n_embd+ ("Qwen3.5-9B", 4096, 262144, 1336),+ ("Qwen3.6-27B", 5120, 262144, 1360),+ ("Gemma-4-31B", 5376, 262144, 2392),+ ]++ def test_zero_by_default(self):+ # Omitted/zero ctx -> no term (keeps the flat callers unchanged).+ assert _backend()._compute_buffer_ctx_bytes(0) == 0++ def test_zero_when_embd_missing(self):+ assert _backend(embd = None)._compute_buffer_ctx_bytes(262144) == 0++ def test_grows_linearly_with_context(self):+ b = _backend(embd = 4096)+ a = b._compute_buffer_ctx_bytes(65536)+ d = b._compute_buffer_ctx_bytes(131072)+ assert d == pytest.approx(2 * a, rel = 1e-6)++ def test_scales_with_embd(self):+ # The quantized (dequant-scratch) rate scales with n_embd; f16 (mask) does not.+ small = _backend(embd = 2048)._compute_buffer_ctx_bytes(131072, cache_type_kv = "q8_0")+ big = _backend(embd = 5120)._compute_buffer_ctx_bytes(131072, cache_type_kv = "q8_0")+ assert big > small++ def test_scales_with_ubatch(self):+ b = _backend(embd = 4096)+ lo = b._compute_buffer_ctx_bytes(131072, n_ubatch = 256)+ hi = b._compute_buffer_ctx_bytes(131072, n_ubatch = 1024)+ assert hi > lo++ @pytest.mark.parametrize("name,embd,ctx,measured", _MEASURED)+ def test_upper_bounds_measured_compute_growth(self, name, embd, ctx, measured):+ # flat term + context-linear term must cover the real (q8_0) buffer at full ctx.+ b = _backend(embd = embd)+ flat = b._estimate_compute_buffer_bytes(n_parallel = 1)+ total = (flat + b._compute_buffer_ctx_bytes(ctx, cache_type_kv = "q8_0")) / MIB+ assert total >= measured, f"{name}: under-reserved {total:.0f} < {measured}"++ def test_worst_case_rate_covers_two_x_embd(self):+ # >= 2 x n_embd bytes per context token at the default micro-batch (the worst+ # measured quantized slope, Qwen3.5-4B), so flat + term upper-bounds the buffer.+ embd = 4096+ b = _backend(embd = embd)+ per_tok = b._compute_buffer_ctx_bytes(100000, cache_type_kv = "q8_0") / 100000+ assert per_tok >= 2 * embd+++class TestContextBufferKVQuant:+ """The context-linear rate depends on the KV cache type: a quantized cache adds a+ context-sized dequant scratch (heavy); f16/bf16/f32 only pays the KQ mask (light).+ Measured Qwen3.5-4B at 256k: 1.30 GiB (q8_0) vs 0.31 GiB (f16)."""++ def test_quantized_heavier_than_f16(self):+ b = _backend(embd = 4096)+ q = b._compute_buffer_ctx_bytes(131072, cache_type_kv = "q8_0")+ f = b._compute_buffer_ctx_bytes(131072, cache_type_kv = "f16")+ assert q > f++ def test_none_cache_type_is_f16(self):+ # None -> f16 (llama.cpp's default); the env-quantized case is covered by the+ # KV budget's f16 over-reservation, so we take the lighter mask-only rate.+ b = _backend(embd = 4096)+ assert b._compute_buffer_ctx_bytes(+ 131072, cache_type_kv = None+ ) == b._compute_buffer_ctx_bytes(131072, cache_type_kv = "f16")++ @pytest.mark.parametrize("ct", ["f16", "bf16", "f32"])+ def test_unquantized_uses_mask_only_rate(self, ct):+ # f16/bf16/f32: KQ mask only, n_ubatch*2 B/tok, independent of n_embd.+ b_small = _backend(embd = 2048)+ b_big = _backend(embd = 8192)+ per_small = b_small._compute_buffer_ctx_bytes(100000, cache_type_kv = ct) / 100000+ per_big = b_big._compute_buffer_ctx_bytes(100000, cache_type_kv = ct) / 100000+ assert per_small == per_big # no n_embd scaling on the f16 path+ expected = 512 * 2 * LlamaCppBackend._CTX_COMPUTE_F16_MASK_SAFETY # ubatch 512+ assert per_small == pytest.approx(expected, rel = 1e-6)++ @pytest.mark.parametrize("ct", ["q8_0", "q5_1", "q4_0", "iq4_nl"])+ def test_quantized_types_use_heavy_rate(self, ct):+ embd = 4096+ b = _backend(embd = embd)+ per_tok = b._compute_buffer_ctx_bytes(100000, cache_type_kv = ct) / 100000+ assert per_tok == pytest.approx(+ LlamaCppBackend._CTX_COMPUTE_BYTES_PER_EMBD * embd, rel = 1e-6+ )++ def test_f16_covers_measured_mask(self):+ # f16 buffer is ~mask only (~n_ubatch*2 B/tok); 0.5 x n_embd must cover the+ # measured Qwen3.5-4B f16 slope (~0.4 x n_embd = 0.31 GiB at 256k).+ b = _backend(embd = 2560) # Qwen3.5-4B+ est = b._compute_buffer_ctx_bytes(262144, cache_type_kv = "f16") / MIB+ assert est >= 320 # measured 0.31 GiB growth+++class TestContextBufferMLA:+ """MLA (compressed attention) needs a smaller quantized dequant scratch than+ regular attention: measured 0.94 x n_embd on GLM-5.2 and Kimi-K2.7 vs up to+ 2.02x on Qwen/Gemma. Charging the regular rate would badly over-reserve a tight+ multi-GPU MLA pin (per-device scaling multiplies the error)."""++ def test_mla_lighter_than_regular(self):+ reg = _backend(embd = 6144, mla = None)._compute_buffer_ctx_bytes(262144, cache_type_kv = "q8_0")+ mla = _backend(embd = 6144, mla = 256)._compute_buffer_ctx_bytes(262144, cache_type_kv = "q8_0")+ assert mla < reg++ @pytest.mark.parametrize(+ "name,embd,ctx,measured",+ [+ ("GLM-5.2", 6144, 754688, 4141), # per-device compute MiB at q8_0+ ("Kimi-K2.7", 7168, 262144, 1690),+ ],+ )+ def test_mla_rate_covers_measured(self, name, embd, ctx, measured):+ b = _backend(embd = embd, mla = 256)+ est = b._compute_buffer_ctx_bytes(ctx, cache_type_kv = "q8_0") / MIB+ assert est >= measured, f"{name}: MLA under-reserved {est:.0f} < {measured}"++ def test_mla_not_wildly_over(self):+ # 1.25 x n_embd should stay within ~1.6x of the measured 0.94x (not 2.4x like+ # the regular 2.25 rate would), so a multi-GPU MLA pin keeps its context.+ b = _backend(embd = 6144, mla = 256)+ est = b._compute_buffer_ctx_bytes(754688, cache_type_kv = "q8_0") / MIB+ assert est <= 4141 * 1.7diff --git a/studio/backend/tests/test_slot_offload_fit.py b/studio/backend/tests/test_slot_offload_fit.pynew file mode 100644index 00000000000..ac606e46274--- /dev/null+++ b/studio/backend/tests/test_slot_offload_fit.py@@ -0,0 +1,115 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Tests for the offload-avoidance serving-slot reduction (`_slots_that_fit_on_gpu`).++When a pinned context does not fit at the requested `--parallel` slot count, Studio would+flip to `--fit on` and llama-server offloads layers to host RAM, collapsing decode ~3x+(oobabooga #6718). Instead the loader retries the on-GPU fit at fewer slots and keeps the+largest count that stays fully on GPU (`-ngl -1`). These tests drive the real helper with+synthetic VRAM maps; the KV term is mocked so totals are controlled and the reduction logic+is asserted directly (no GPU, network, or subprocess).+"""++from __future__ import annotations++import sys+import types as _types+from pathlib import Path++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++_loggers_stub = _types.ModuleType("loggers")+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)+sys.modules.setdefault("loggers", _loggers_stub)++from core.inference.llama_cpp import LlamaCppBackend++MIB = 1024 * 1024+CTX = 90624+FRAC = LlamaCppBackend._GPU_PIN_VRAM_FRACTION # 0.97; usable = free - 0.03*total+++def _backend(+ vocab = 248320,+ embd = 5120,+ kv_fixed_mib = 0,+):+ """Backend with the dims the compute buffer reads; KV mocked to a fixed size so the+ only slot-dependent term is the compute buffer (485 MiB/slot f32 output x 1.15)."""+ b = LlamaCppBackend.__new__(LlamaCppBackend)+ b._vocab_size = vocab+ b._embedding_length = embd+ b._key_length_mla = None+ b._estimate_kv_cache_bytes = lambda ctx, t = None, **k: kv_fixed_mib * MIB+ b._can_estimate_kv = lambda: True+ return b+++def _run(+ b,+ n_parallel,+ base_mib,+ gpus,+ total_by_idx,+ overhead_mib = 0,+):+ return b._slots_that_fit_on_gpu(+ n_parallel,+ CTX,+ gpus,+ total_by_idx,+ int(base_mib * MIB),+ "q8_0",+ FRAC,+ int(overhead_mib * MIB),+ 1,+ 512,+ )+++class TestSlotsThatFitOnGpu:+ """Compute-buffer per slot (vocab 248320, embd 5120): cb(1)=46, cb(2)=604, cb(3)=1162,+ cb(4)=1719 MiB. Single 24 GB card usable = 24576 - 0.03*24576 = 23839 MiB."""++ def test_reduces_to_largest_fitting_slot(self):+ # base+KV = 22500: par4 (24219) over 23839, par3 (23662) fits -> 3 slots on GPU.+ gi, use_fit, slots = _run(_backend(), 4, 22500, [(0, 24576)], {0: 24576})+ assert use_fit is False and gi == [0] and slots == 3++ def test_floor_when_only_one_slot_fits(self):+ # base 23400: par2 (24004) over, par1 (23446) fits -> drop all the way to 1.+ gi, use_fit, slots = _run(_backend(), 4, 23400, [(0, 24576)], {0: 24576})+ assert use_fit is False and gi == [0] and slots == 1++ def test_none_fit_stays_offload(self):+ # Even a single slot (24046) exceeds usable -> genuine offload, unchanged.+ gi, use_fit, slots = _run(_backend(), 4, 24000, [(0, 24576)], {0: 24576})+ assert use_fit is True and gi is None and slots == 4++ def test_roomy_would_keep_all_but_helper_only_reduces(self):+ # On a roomy card par4 fits, so load_model never calls this helper; if called it+ # still only searches < n_parallel and never raises the count above the request.+ gi, use_fit, slots = _run(_backend(), 4, 5000, [(0, 183000)], {0: 183000})+ assert use_fit is False and slots == 3 and slots < 4++ def test_single_slot_request_is_noop(self):+ # n_parallel == 1: nothing to reduce (range empty) -> report offload unchanged.+ gi, use_fit, slots = _run(_backend(), 1, 22500, [(0, 24576)], {0: 24576})+ assert use_fit is True and gi is None and slots == 1++ def test_multi_gpu_reduces_across_devices(self):+ # Needs 2 GPUs: usable/GPU = 23839, cumulative 47677. base+KV 46200: par4 (47919)+ # over, par3 (47362) fits across both -> 3 slots spanning [0, 1].+ gi, use_fit, slots = _run(+ _backend(), 4, 46200, [(0, 24576), (1, 24576)], {0: 24576, 1: 24576}+ )+ assert use_fit is False and gi == [0, 1] and slots == 3++ def test_kv_counted_per_candidate(self):+ # A non-zero (slot-independent) KV shifts the threshold: with 3000 MiB KV and+ # base 19500 (= 22500 total at par-independent terms) the same par3 fit holds.+ gi, use_fit, slots = _run(_backend(kv_fixed_mib = 3000), 4, 19500, [(0, 24576)], {0: 24576})+ assert use_fit is False and slots == 3diff --git a/studio/backend/tests/test_tensor_parallel.py b/studio/backend/tests/test_tensor_parallel.pyindex 1f09f9a0915..0d71b89d876 100644--- a/studio/backend/tests/test_tensor_parallel.py+++ b/studio/backend/tests/test_tensor_parallel.py@@ -746,10 +746,14 @@ def test_tp_plan_weighted_split_on_asymmetric_big_model():b, (ec, mac, gi, ts) = _plan(50)reserve = b._TENSOR_PARALLEL_BUFFER_RESERVE_MIBassert gi == [0, 1]- # split weighted by (usable - buffer); with no totals usable is free*frac+ # split weighted by (usable - flat buffer - per-device context compute); with+ # no totals usable is free*frac. The per-device cc is subtracted so the smaller+ # card isn't weighted above its real usable budget (see below).+ cc_per_dev = b._compute_buffer_ctx_bytes(ec, None, None) // (1024 * 1024)+ assert cc_per_dev > 0assert ts == [- int(48000 * _CTX_FIT_VRAM_FRACTION - reserve),- int(24000 * _CTX_FIT_VRAM_FRACTION - reserve),+ int(48000 * _CTX_FIT_VRAM_FRACTION - reserve - cc_per_dev),+ int(24000 * _CTX_FIT_VRAM_FRACTION - reserve - cc_per_dev),]assert ec < 131072 # capped below native@@ -819,6 +823,75 @@ def test_tp_plan_mtp_reserves_extra_and_shrinks_context():assert ec_mtp < ec_no+def test_tp_plan_reserves_context_linear_compute_buffer():+ # Tensor mode replicates the compute graph on every device; measured on+ # Qwen3.5-9B at f16 the per-device buffer grows ~n_ubatch*2 B/token (~1024+ # B/tok), so the fit must reserve n_dev x that on top of the flat reserve or+ # it over-pins and OOMs at high context. The chosen KV must leave room for it.+ b, (ec, mac, gi, ts) = _plan(50)+ cc = len(gi) * b._compute_buffer_ctx_bytes(ec, None, "f16")+ assert cc > 0+ assert b._estimate_kv_cache_bytes(ec) + cc <= _kv_budget_b(50)+++def test_tp_plan_context_shrinks_vs_compute_unaware():+ # With the context-linear term the pinned context is strictly below what a+ # KV-only (compute-unaware) fit at the same budget would allow.+ b, (ec, *_r) = _plan(50)+ b2 = _kv_seeded_backend()+ b2._embedding_length = 0 # kills the context-linear compute term (returns 0)+ ec_naive, *_r2 = b2._plan_tensor_parallel(_ASYM, int(50 * _GB), 131072)+ assert ec < ec_naive+++def test_tp_plan_soft_overhead_shrinks_context():+ # The CUDA-ctx / mmproj / MTP-draft reserve the layer path folds into the fit+ # budget (model_size_fit) must also shrink the tensor context. Tensor mode has+ # no --fit valve, so an unreserved overshoot OOMs at startup instead of+ # offloading. A non-zero soft_overhead must pin a strictly smaller context.+ b = _kv_seeded_backend()+ ec_no, *_r = b._plan_tensor_parallel(_ASYM, int(50 * _GB), 131072)+ ec_soft, *_r2 = b._plan_tensor_parallel(+ _ASYM, int(50 * _GB), 131072, soft_overhead_bytes = 2 * _GB+ )+ assert 2048 < ec_soft < ec_no+++def test_tp_plan_soft_overhead_reserved_against_budget():+ # The pinned context must leave the whole soft reserve free on top of KV and+ # the replicated context compute, so the real footprint stays within the pool.+ b = _kv_seeded_backend()+ soft = 2 * _GB+ ec, *_r = b._plan_tensor_parallel(_ASYM, int(50 * _GB), 131072, soft_overhead_bytes = soft)+ cc = len(_ASYM) * b._compute_buffer_ctx_bytes(ec, None, None)+ assert b._estimate_kv_cache_bytes(ec) + cc + soft <= _kv_budget_b(50)+++def test_tp_plan_weighted_split_keeps_small_gpu_within_budget():+ # Regression: the weighted split must subtract each device's replicated context+ # compute (cc_bytes/n_dev), not just the flat reserve. Otherwise the smaller+ # card is weighted above its usable budget and OOMs at launch. Model the split:+ # llama.cpp distributes weights+KV by the tensor-split weights; every device+ # also holds the flat reserve plus its per-device context compute.+ b, (ec, mac, gi, ts) = _plan(50)+ assert ts is not None and len(ts) == len(gi) == 2+ reserve = b._TENSOR_PARALLEL_BUFFER_RESERVE_MIB+ cc_per_dev = b._compute_buffer_ctx_bytes(ec, None, None) // (1024 * 1024)+ free_by_idx = {0: 48000, 1: 24000}+ split_content_mib = (int(50 * _GB) + b._estimate_kv_cache_bytes(ec)) / (1024 * 1024)+ total_weight = sum(ts)+ for w, idx in zip(ts, gi):+ placed = split_content_mib * w / total_weight+ usable = free_by_idx[idx] * _CTX_FIT_VRAM_FRACTION+ assert placed + reserve + cc_per_dev <= usable + 1 # +1 MiB for int rounding++ # Lock the regression: under the old formula (flat reserve only) the smaller+ # card was placed over its budget; the cc term is what pulls it back.+ old_adj = [int(free_by_idx[i] * _CTX_FIT_VRAM_FRACTION - reserve) for i in gi]+ old_small_placed = split_content_mib * old_adj[1] / sum(old_adj)+ assert old_small_placed + reserve + cc_per_dev > free_by_idx[1] * _CTX_FIT_VRAM_FRACTION++def test_tp_plan_no_kv_metadata_floors_context():b = LlamaCppBackend() # no KV metadata -> can't size safelyec, mac, gi, ts = b._plan_tensor_parallel(_ASYM, int(50 * _GB), 131072)