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
stop the planner withholding a split reserve from one card, and price physical cores (#9863)
Daniel Han934a03db5bde
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex cfa89079283..1de303273f8 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -3367,9 +3367,250 @@ _CPU_PLACEMENT_PRESENCE_FLAGS = (_MOE_OFFLOAD_FLAGS - _CPU_MOE_COUNT_FLAGS) | fr)_CPU_PLACEMENT_FLAGS = _MOE_OFFLOAD_FLAGS | frozenset({"-ot", "--override-tensor"})_THREAD_OVERRIDE_FLAGS = frozenset({"-t", "--threads"})+_GENERATION_CPU_AFFINITY_FLAGS = frozenset({"-C", "--cpu-mask", "-Cr", "--cpu-range"})_TENSOR_SPLIT_FLAGS = frozenset({"--tensor-split", "-ts"})+def _linux_math_core_count(+ cpu_root: Path = Path("/sys/devices/system/cpu"),+ logical_cpus: Optional[int] = None,+ vendor_id: Optional[str] = None,+ event_source_root: Path = Path("/sys/bus/event_source/devices"),+ pinnable_cpus: Optional[set[int]] = None,+ probe_affinity: Optional[bool] = None,+) -> Optional[int]:+ """Linux x86 cores useful to llama.cpp's default math pool.++ ``thread_siblings`` mirrors llama.cpp's physical-core count. Intel's hybrid+ PMU masks identify performance cores on kernels without ``cpu_capacity``;+ heterogeneous capacity remains the fallback. AMD capacity classes do not+ trigger llama.cpp's hybrid CPUID branch, so they retain every physical core.+ """+ if logical_cpus is not None and logical_cpus < 1:+ return None++ def cpu_list(path: Path) -> Optional[set[int]]:+ try:+ raw = path.read_text(encoding = "utf-8").strip()+ if not raw:+ return set()+ result: set[int] = set()+ for part in raw.split(","):+ bounds = [int(value) for value in part.split("-")]+ if len(bounds) == 1 and bounds[0] >= 0:+ result.add(bounds[0])+ elif len(bounds) == 2 and 0 <= bounds[0] <= bounds[1]:+ result.update(range(bounds[0], bounds[1] + 1))+ else:+ return None+ return result+ except (OSError, ValueError):+ return None++ if vendor_id is None:+ try:+ vendor_match = re.search(+ r"^vendor_id\s*:\s*(\S+)",+ Path("/proc/cpuinfo").read_text(encoding = "utf-8"),+ flags = re.MULTILINE,+ )+ vendor_id = vendor_match.group(1) if vendor_match else ""+ except OSError:+ vendor_id = ""+ siblings: list[str] = []+ capacities: list[Optional[int]] = []+ cpu = 0+ while logical_cpus is None or cpu < logical_cpus:+ cpu_path = cpu_root / f"cpu{cpu}"+ try:+ sibling_set = (+ (cpu_path / "topology" / "thread_siblings").read_text(encoding = "utf-8").strip()+ )+ except OSError:+ break+ if not sibling_set:+ break+ siblings.append(sibling_set)+ try:+ capacities.append(int((cpu_path / "cpu_capacity").read_text(encoding = "utf-8").strip()))+ except (OSError, ValueError):+ capacities.append(None)+ cpu += 1+ if not siblings:+ return None+ online_cpus = cpu_list(cpu_root / "online")+ active_siblings = {+ sibling_set+ for cpu, sibling_set in enumerate(siblings)+ if not online_cpus or cpu in online_cpus+ }+ if not active_siblings:+ return None+ physical_count = len(active_siblings)+ if vendor_id == "GenuineIntel":+ native_count = len(online_cpus) if online_cpus else len(siblings)++ def hybrid_math_count(performance_cpus: set[int]) -> int:+ should_probe = pinnable_cpus is None and (+ cpu_root == Path("/sys/devices/system/cpu")+ if probe_affinity is None+ else probe_affinity+ )++ def count(pin_cpus: bool) -> int:+ result = 0+ cpu = 0+ while cpu < native_count:+ if online_cpus and cpu not in online_cpus:+ return physical_count+ if pinnable_cpus is not None and cpu not in pinnable_cpus:+ return physical_count+ if pin_cpus:+ try:+ os.sched_setaffinity(0, {cpu})+ except OSError:+ return physical_count+ if cpu not in performance_cpus:+ cpu += 1+ continue+ result += 1+ cpu += 2+ return result or physical_count++ if not should_probe:+ return count(False)+ if not hasattr(os, "sched_getaffinity") or not hasattr(os, "sched_setaffinity"):+ return physical_count++ answer = [physical_count]++ def probe() -> None:+ try:+ saved_affinity = os.sched_getaffinity(0)+ except OSError:+ return+ try:+ answer[0] = count(True)+ finally:+ try:+ os.sched_setaffinity(0, saved_affinity)+ except OSError:+ pass++ worker = threading.Thread(target = probe)+ try:+ worker.start()+ worker.join()+ except RuntimeError:+ return physical_count+ return answer[0]++ core_mask = cpu_list(event_source_root / "cpu_core" / "cpus")+ atom_path = event_source_root / "cpu_atom"+ lowpower_path = event_source_root / "cpu_lowpower"+ hybrid_pmu = atom_path.exists() or lowpower_path.exists()+ if core_mask:+ return hybrid_math_count(core_mask)+ if hybrid_pmu:+ atom_mask = cpu_list(atom_path / "cpus") or cpu_list(lowpower_path / "cpus")+ if core_mask == set() and atom_mask:+ return physical_count+ return 1+ active_capacities = [+ capacity+ for cpu, capacity in enumerate(capacities)+ if not online_cpus or cpu in online_cpus+ ]+ if (+ all(capacity is not None for capacity in active_capacities)+ and len(set(active_capacities)) > 1+ ):+ fastest = max(capacity for capacity in active_capacities if capacity is not None)+ return hybrid_math_count(+ {+ cpu+ for cpu, capacity in enumerate(capacities)+ if (not online_cpus or cpu in online_cpus) and capacity == fastest+ }+ )+ return physical_count+++def _spilled_decode_threads(+ n_threads: Optional[int] = None, extra_args: Optional[Iterable[str]] = None+) -> Optional[int]:+ """How many threads the spilled-decode cost model should price.++ A positive override follows the launched command's managed-flag, then+ pass-through precedence. An inherited ``LLAMA_ARG_THREADS`` is ignored here+ because Studio removes it before spawn whenever argv has no thread flag; if+ argv does have one, that later flag wins. Explicit SMT oversubscription and+ explicit or inherited CPU affinity cannot be represented by this+ physical-core model, so those settings return ``None`` and the caller declines.+ Otherwise llama.cpp sizes its pool from+ ``common_cpu_get_num_math``, which counts physical cores+ and skips SMT siblings and efficiency cores. ``os.cpu_count()`` counts every+ hyperthread, so on a 6-core / 12-thread desktop it told the cost model the+ host had twice the cores the child would ever use, and the generation+ penalty came out about half of what a spill really costs there.++ Linux x86 reads the same sibling topology as llama.cpp and uses the kernel's+ capacity classes for hybrid CPUs. psutil is the cross-platform fallback. If+ neither can answer, match llama.cpp's last resort: keep up to four logical+ CPUs, otherwise halve them, and use four when no logical count is available.+ """+ requested: Optional[int] = None+ if n_threads is not None and n_threads > 0:+ requested = int(n_threads)+ args = [str(arg) for arg in extra_args] if extra_args else []+ if any(arg.partition("=")[0] in _GENERATION_CPU_AFFINITY_FLAGS for arg in args):+ return None+ for i, arg in enumerate(args):+ name, _, inline = arg.partition("=")+ if name not in _THREAD_OVERRIDE_FLAGS:+ continue+ value = inline if inline else (args[i + 1] if i + 1 < len(args) else "")+ try:+ requested = int(value.strip())+ except (TypeError, ValueError):+ continue+ physical: Optional[int] = None+ logical: Optional[int] = None+ affinity_count: Optional[int] = None+ if sys.platform.startswith("linux"):+ if hasattr(os, "sched_getaffinity"):+ try:+ affinity_count = len(os.sched_getaffinity(0))+ except OSError:+ pass+ if os.uname().machine.lower() in ("x86_64", "amd64"):+ physical = _linux_math_core_count()+ try:+ import psutil++ answer = psutil.cpu_count(logical = True)+ if answer and answer > 0:+ logical = int(answer)+ if physical is None:+ answer = psutil.cpu_count(logical = False)+ if answer and answer > 0:+ physical = int(answer)+ except Exception:+ pass+ if logical is None:+ logical = os.cpu_count()+ if affinity_count is not None and logical is not None and affinity_count < logical:+ return None+ if physical is None:+ physical = logical if logical and logical <= 4 else (logical // 2 if logical else 4)+ if requested is None:+ return physical+ actual = requested if requested > 0 else (logical or os.cpu_count() or physical)+ if actual > physical:+ return None+ return max(1, actual)++def _strip_flag_pairs(args: Iterable[str], flags: frozenset[str]) -> list[str]:"""Drop each ``flag value`` pair naming one of ``flags``."""out: list[str] = []@@ -4705,8 +4946,12 @@ def _extra_args_tensor_split(if raw is None:return Nonetry:- parts = [float(p) for p in re.split(r"[,/]+", raw) if p.strip()]- except ValueError:+ parts = [+ struct.unpack("=f", struct.pack("=f", float(p)))[0]+ for p in re.split(r"[,/]+", raw)+ if p.strip()+ ]+ except (OverflowError, ValueError):return None# isfinite, not just >= 0: float() takes "nan"/"inf", and NaN passes BOTH the# other tests (every comparison against NaN is false, sum() of a NaN list is@@ -4715,6 +4960,14 @@ def _extra_args_tensor_split(# merely degenerates on. Rejecting here routes it to the unparseable decline.if not parts or any(not math.isfinite(p) or p < 0 for p in parts) or sum(parts) <= 0:return None+ try:+ running = 0.0+ for part in parts:+ running = struct.unpack("=f", struct.pack("=f", running + part))[0]+ except OverflowError:+ return None+ if not math.isfinite(running):+ return Nonereturn parts@@ -19867,6 +20120,7 @@ class LlamaCppBackend:# total, so it can spill the MINIMUM set of blocks."model_path": model_path,"n_ctx": effective_ctx,+ "n_threads": n_threads,# The slot count the KV and recurrent state were PRICED at.# A pass-through --parallel is appended after Unsloth's own# and wins, and both caches scale with it.@@ -25198,8 +25452,7 @@ class LlamaCppBackend:len(kept),)return None- _scale = max(split_weights) if split_weights else 1- split_weights = [int(round(p * _scale)) for p in _ts[: len(kept)]]+ split_weights = _ts[: len(kept)]if not vram_per_device:return Noneavail_mib = self._available_system_memory_mib()@@ -25282,6 +25535,14 @@ class LlamaCppBackend:return Noneextra_gpu_bytes += sidecar_bytes+ decode_threads = _spilled_decode_threads(+ inputs.get("n_threads"),+ extra_args,+ )+ if decode_threads is None:+ logger.debug("Tensor spill: declined, decode CPU settings cannot be priced")+ return None+return plan_placement(layout,vram_per_device,@@ -25292,9 +25553,15 @@ class LlamaCppBackend:opts = PlanOptions(overhead_bytes_per_device = (int(inputs.get("soft_overhead") or 0)- + self._PIPELINE_PER_DEVICE_OVERHEAD_MIB * 1024 * 1024+ int(inputs.get("ctx_compute_per_device") or 0)),+ # Charged for the devices AFTER the first, matching every other+ # use of this constant in this file (:18664, :18922, and the+ # `n > 1` guards at :18761 and :19186). Added to the flat+ # per-device term it also came off device 0, which withheld a GiB+ # of a single card that no split was ever going to allocate --+ # phantom deficit the planner covered by spilling real blocks.+ pipeline_overhead_bytes = self._PIPELINE_PER_DEVICE_OVERHEAD_MIB * 1024 * 1024,# Module-level, unlike the line above, so not reachable through self.host_ram_headroom_bytes = _HOST_RAM_HEADROOM_MIB * 1024 * 1024,# -nkvo is not a reason to decline: it moves the cache and the@@ -25310,7 +25577,7 @@ class LlamaCppBackend:# GPU only at batch >= 32, and decode is batch 1), so the penalty# tracks core count. Read the real one, not a default.host = HostProfile(- threads = os.cpu_count() or 1,+ threads = decode_threads,# Wired, not defaulted. On a unified-memory APU the credited# "VRAM" IS system RAM, so an -ot spill frees no device memory# and only buys the CPU backend's slower read path. The plannerdiff --git a/studio/backend/core/inference/offload_planner.py b/studio/backend/core/inference/offload_planner.pyindex 249e95a45a8..b3409a7ecc2 100644--- a/studio/backend/core/inference/offload_planner.py+++ b/studio/backend/core/inference/offload_planner.py@@ -22,6 +22,7 @@ reads no globals, so the whole decision table is testable directly.from __future__ import annotationsimport os+import structfrom dataclasses import dataclass, fieldfrom enum import Enumfrom typing import Iterable, Mapping, Optional, Sequence@@ -102,6 +103,15 @@ class PlanOptions:# target GGUF's tensor table. Subtracting from the budget also reaches# max_context_for. 0 keeps the pure-layout behaviour.extra_resident_bytes: int = 0+ # The fixed per-device cost of a LAYER SPLIT, charged once for every device+ # after the first. Separate from overhead_bytes_per_device because it is not+ # per-device in the same sense: the first device's share is already folded+ # into the compute buffer above, which is why every other site in+ # llama_cpp.py applies it as ``max(0, n_gpus - 1) * ...`` and skips it+ # entirely at k=1. Folded into the flat per-device term instead, it withheld+ # a GiB of a single card that nothing was ever going to allocate, which is+ # deficit the planner then spilled real blocks to cover.+ pipeline_overhead_bytes: int = 0# Host RAM this planner refuses to spend, so a spill does not push the box# into swap.host_ram_headroom_bytes: int = 2 * GIB@@ -161,9 +171,11 @@ class Plan:def _usable_vram(vram_bytes_per_device: Sequence[int], opts: PlanOptions) -> int:"""Total creditable VRAM: every device pays the fixed per-device overhead,- then the pool pays once for whatever sits on a card outside the layout."""+ the split pays for each device AFTER the first, then the pool pays once for+ whatever sits on a card outside the layout."""pooled = sum(max(0, v - opts.overhead_bytes_per_device) for v in vram_bytes_per_device)- return pooled - max(0, opts.extra_resident_bytes)+ split = max(0, len(vram_bytes_per_device) - 1) * max(0, opts.pipeline_overhead_bytes)+ return pooled - split - max(0, opts.extra_resident_bytes)def _select_blocks(@@ -346,7 +358,7 @@ def plan_placement(*,opts: Optional[PlanOptions] = None,kv_bytes_floor: int = 0,- split_weights_per_device: Sequence[int] = (),+ split_weights_per_device: Sequence[float] = (),kv_layer_weights: Sequence[int] = (),) -> Plan:"""Decide the placement for one launch.@@ -488,7 +500,7 @@ def _kv_modes(opts: PlanOptions) -> tuple[bool, ...]:return (False, True) if opts.allow_kv_quant else (False,)-def _device_slots(n_slots: int, split_weights: Sequence[int]) -> list[list[int]]:+def _device_slots(n_slots: int, split_weights: Sequence[float]) -> list[list[int]]:"""Which of the ``n_slots`` layer rows land on which device.Mirrors llama.cpp's default tensor split exactly: free VRAM per device@@ -497,25 +509,30 @@ def _device_slots(n_slots: int, split_weights: Sequence[int]) -> list[list[int]]the output row (:1467). With every layer offloaded ``i_gpu_start`` is 0 and``act_gpu_layers`` is ``n_layer_all + 1``, which is ``n_slots`` here."""++ def f32(value: float) -> float:+ return struct.unpack("=f", struct.pack("=f", value))[0]+weights = [max(0, v) for v in split_weights]total = sum(weights)if total <= 0:return [list(range(n_slots))] + [[] for _ in weights[1:]]cumulative: list[float] = []- running = 0.0+ running = f32(0.0)for w in weights:- running += w- cumulative.append(running / total)+ running = f32(running + f32(w))+ cumulative.append(running)+ cumulative = [f32(value / running) for value in cumulative]slots: list[list[int]] = [[] for _ in weights]for row in range(n_slots):- fraction = row / n_slots+ fraction = f32(f32(row) / f32(n_slots))# std::upper_bound: first cumulative strictly greater than fraction.device = next((i for i, c in enumerate(cumulative) if c > fraction), len(weights) - 1)slots[device].append(row)return slots-def _per_device_shortfall(+def _per_device_usage(layout: ModelLayout,opts: PlanOptions,n_ctx: int,@@ -525,24 +542,11 @@ def _per_device_shortfall(*,quantised: bool,kv_bytes_floor: int,- split_weights_per_device: Sequence[int] = (),+ split_weights_per_device: Sequence[float] = (),kv_layer_weights: Sequence[int] = (),-) -> Optional[str]:- """``None`` when every device provably fits, else why it cannot be shown to.-- A pooled budget is not a per-device fit test, and it does not become one just- because every spillable block was taken. llama.cpp hands out CONTIGUOUS ROW- RANGES sized by free memory, so a device's share of the ROWS is proportional- to its free VRAM while its share of the BYTES is not: what stays resident- differs row by row (a block with a shared expert keeps more than a plain- dense one), and the budget subtracts a FIXED per-device overhead, which- already breaks proportionality on mixed cards -- 24 GiB and 8 GiB split the- rows 75/25 but the budgets 77.6/22.4, so the small card is over on a load the- pool says fits. A per-device shortfall is a hard throw (llama-model.cpp:1731)- and ``--fit off`` means common/fit.cpp never runs to catch it.- """+) -> tuple[Optional[str], list[int], list[list[int]]]:if len(vram_bytes_per_device) <= 1:- return None+ return None, [], []# These three shapes -- recurrent hybrid, n_attention_layers short of# n_layers, sliding window -- are only a problem when the cache has to be# spread evenly for want of anything better. A vector removes that guess;@@ -555,38 +559,43 @@ def _per_device_shortfall(weights = []if uneven_cache and not weights:if layout.recurrent_bytes > 0:- return "the recurrent state's per-layer split is not visible in the layout"+ return "the recurrent state's per-layer split is not visible in the layout", [], []if layout.n_attention_layers != layout.n_layers:return (f"only {layout.n_attention_layers} of {layout.n_layers} layers hold a cache "- "and the layout does not say which"+ "and the layout does not say which",+ [],+ [],)return ("the cache is per-layer uneven (sliding-window attention) and no per-layer "- "vector was supplied to say which layers are full-context"+ "vector was supplied to say which layers are full-context",+ [],+ [],)if layout.has_excluded_blocks:- return "the GGUF carries trailing blocks that shift llama.cpp's row count"+ return "the GGUF carries trailing blocks that shift llama.cpp's row count", [], []n_slots = layout.n_layers + 1if n_slots <= 1:- return None+ return None, [], []cache = (0if opts.kv_on_hostelse cache_bytes(layout, n_ctx, kv_quantised = quantised, kv_bytes_floor = kv_bytes_floor))- # Scaled to the total the caller already priced. Uniform when unsupplied.+ # Scaled without under-booking the caller's total. Uniform when unsupplied.total_weight = sum(weights)if weights and total_weight > 0:- kv_by_layer = [cache * w // total_weight for w in weights]+ kv_by_layer = [(cache * w + total_weight - 1) // total_weight for w in weights]else:- per = cache // layout.n_layers if layout.n_layers else 0+ per = (cache + layout.n_layers - 1) // layout.n_layers if layout.n_layers else 0kv_by_layer = [per] * layout.n_layersby_index = {b.index: b for b in layout.blocks}output_row_bytes = layout.other_resident_bytes + (0 if spill_lm_head else layout.lm_head_bytes)slots = _device_slots(n_slots, split_weights_per_device or vram_bytes_per_device)+ usage: list[int] = []for device, rows in enumerate(slots):used = 0for row in rows:@@ -605,8 +614,57 @@ def _per_device_shortfall(# devices[0] once -sm none has already pruned the list.if device == 0:used += max(0, opts.extra_resident_bytes)- headroom = max(0, vram_bytes_per_device[device] - opts.overhead_bytes_per_device)- if used > headroom:+ usage.append(used)+ return None, usage, slots+++def _per_device_shortfall(+ layout: ModelLayout,+ opts: PlanOptions,+ n_ctx: int,+ spilled_indices: set[int],+ spill_lm_head: bool,+ vram_bytes_per_device: Sequence[int],+ *,+ quantised: bool,+ kv_bytes_floor: int,+ split_weights_per_device: Sequence[float] = (),+ kv_layer_weights: Sequence[int] = (),+) -> Optional[str]:+ """``None`` when every device provably fits, else why it cannot be shown to.++ A pooled budget is not a per-device fit test, and it does not become one just+ because every spillable block was taken. llama.cpp hands out CONTIGUOUS ROW+ RANGES sized by free memory, so a device's share of the ROWS is proportional+ to its free VRAM while its share of the BYTES is not: what stays resident+ differs row by row (a block with a shared expert keeps more than a plain+ dense one), and the budget subtracts a FIXED per-device overhead, which+ already breaks proportionality on mixed cards -- 24 GiB and 8 GiB split the+ rows 75/25 but the budgets 77.6/22.4, so the small card is over on a load the+ pool says fits. A per-device shortfall is a hard throw (llama-model.cpp:1731)+ and ``--fit off`` means common/fit.cpp never runs to catch it.+ """+ error, usage, slots = _per_device_usage(+ layout,+ opts,+ n_ctx,+ spilled_indices,+ spill_lm_head,+ vram_bytes_per_device,+ quantised = quantised,+ kv_bytes_floor = kv_bytes_floor,+ split_weights_per_device = split_weights_per_device,+ kv_layer_weights = kv_layer_weights,+ )+ if error is not None:+ return error+ for device, (used, rows) in enumerate(zip(usage, slots)):+ fixed_reserve = max(0, opts.overhead_bytes_per_device)+ if device > 0:+ fixed_reserve += max(0, opts.pipeline_overhead_bytes)+ raw_vram = max(0, vram_bytes_per_device[device])+ headroom = max(0, raw_vram - fixed_reserve)+ if used + fixed_reserve > raw_vram:return (f"device {device} would still hold {used / GIB:.2f} GiB of its "f"{len(rows)}-row share against {headroom / GIB:.2f} GiB usable"@@ -614,6 +672,67 @@ def _per_device_shortfall(return None+def _select_blocks_per_device(+ layout: ModelLayout,+ opts: PlanOptions,+ n_ctx: int,+ vram_bytes_per_device: Sequence[int],+ *,+ quantised: bool,+ kv_bytes_floor: int,+ spill_lm_head: bool = False,+ split_weights_per_device: Sequence[float] = (),+ kv_layer_weights: Sequence[int] = (),+) -> Optional[list[BlockLayout]]:+ error, usage, slots = _per_device_usage(+ layout,+ opts,+ n_ctx,+ set(),+ spill_lm_head,+ vram_bytes_per_device,+ quantised = quantised,+ kv_bytes_floor = kv_bytes_floor,+ split_weights_per_device = split_weights_per_device,+ kv_layer_weights = kv_layer_weights,+ )+ if error is not None:+ return None+ by_index = {block.index: block for block in layout.blocks}+ chosen: list[BlockLayout] = []+ for device, (used, rows) in enumerate(zip(usage, slots)):+ fixed_reserve = max(0, opts.overhead_bytes_per_device)+ if device > 0:+ fixed_reserve += max(0, opts.pipeline_overhead_bytes)+ deficit = used + fixed_reserve - max(0, vram_bytes_per_device[device])+ if deficit <= 0:+ continue+ candidates = [+ by_index[row] for row in rows if row in by_index and by_index[row].spillable_bytes > 0+ ]+ local, freed = _select_blocks(candidates, deficit, opts.spill_order)+ if freed < deficit:+ return None+ chosen.extend(local)+ if (+ _per_device_shortfall(+ layout,+ opts,+ n_ctx,+ {block.index for block in chosen},+ spill_lm_head,+ vram_bytes_per_device,+ quantised = quantised,+ kv_bytes_floor = kv_bytes_floor,+ split_weights_per_device = split_weights_per_device,+ kv_layer_weights = kv_layer_weights,+ )+ is not None+ ):+ return None+ return chosen++def _plan_at(layout: ModelLayout,opts: PlanOptions,@@ -623,7 +742,7 @@ def _plan_at(quantised: bool,kv_bytes_floor: int = 0,vram_bytes_per_device: Sequence[int] = (),- split_weights_per_device: Sequence[int] = (),+ split_weights_per_device: Sequence[float] = (),kv_layer_weights: Sequence[int] = (),) -> Optional[Plan]:"""One pass of the ladder at a fixed context and cache dtype."""@@ -650,37 +769,25 @@ def _plan_at(),)- n_devices = len(vram_bytes_per_device)deficit = needed - budgetchosen, freed = _select_blocks(layout.blocks, deficit, opts.spill_order)if freed >= deficit:- spillable = [b for b in layout.blocks if b.spillable_bytes > 0]- if n_devices > 1 and len(chosen) < len(spillable):- # A pooled budget is not a per-device fit test for a PARTIAL spill.- # llama.cpp fixes the split before any override exists -- free memory- # per device at llama-model.cpp:1425-1433, prefix-summed at :1439-1447,- # then upper_bound on the normalised LAYER INDEX at :1457, so each- # device owns a contiguous index range -- and -ot only swaps a tensor's- # buffer type in llama_model_loader::create_tensor- # (llama-model-loader.cpp:1177-1203), leaving dev_layer(il) untouched- # (llama-model.cpp:1467-1474). Nothing rebalances afterwards and with- # --fit off common/fit.cpp never runs, so a subset of indices sitting- # in one device's range relieves only that device: the aggregate- # deficit is covered while a single card is still over, and a- # per-device shortfall is a hard throw (llama-model.cpp:1731-1733).- # Which rows the chosen indices land on is exactly what makes it- # uneven, so no arithmetic rescues it. Abstain: --fit on is per-device- # aware (common/fit.cpp:646-651, :687, :705). A FULL spill IS- # checkable, and is checked below rather than assumed.- return Plan(- n_ctx = n_ctx,- reason = (- f"a partial spill ({len(chosen)} of {len(spillable)} blocks) across "- f"{n_devices} devices cannot be checked against a pooled budget, "- "because llama.cpp assigns contiguous layer ranges per device and "- "-ot does not move a layer; leaving llama.cpp's own fitter to place it"- ),+ if len(vram_bytes_per_device) > 1:+ per_device = _select_blocks_per_device(+ layout,+ opts,+ n_ctx,+ vram_bytes_per_device,+ quantised = quantised,+ kv_bytes_floor = kv_bytes_floor,+ split_weights_per_device = split_weights_per_device,+ kv_layer_weights = kv_layer_weights,)+ if per_device is not None:+ per_device_freed = sum(block.spillable_bytes for block in per_device)+ if needed - per_device_freed <= budget:+ chosen = per_device+ freed = per_device_freeduneven = _per_device_shortfall(layout,opts,@@ -694,10 +801,40 @@ def _plan_at(kv_layer_weights = kv_layer_weights,)if uneven is not None:+ if opts.allow_lm_head_spill and layout.lm_head_bytes:+ with_head = _select_blocks_per_device(+ layout,+ opts,+ n_ctx,+ vram_bytes_per_device,+ quantised = quantised,+ kv_bytes_floor = kv_bytes_floor,+ spill_lm_head = True,+ split_weights_per_device = split_weights_per_device,+ kv_layer_weights = kv_layer_weights,+ )+ if with_head is not None:+ with_head_freed = sum(block.spillable_bytes for block in with_head)+ with_head_freed += layout.lm_head_bytes+ if needed - with_head_freed <= budget:+ return _finish(+ layout,+ opts,+ n_ctx,+ with_head,+ True,+ host_ram_bytes,+ quantised = quantised,+ kv_bytes_floor = kv_bytes_floor,+ reason = (+ "spilled the output head after its device could not cover "+ "the local shortfall with FFN blocks alone"+ ),+ )return Plan(n_ctx = n_ctx,reason = (- f"spilling every block still does not fit device by device: {uneven}; "+ f"the selected spill still does not fit device by device: {uneven}; ""leaving llama.cpp's own fitter to place it"),)diff --git a/studio/backend/tests/test_llama_cpp_placement.py b/studio/backend/tests/test_llama_cpp_placement.pyindex 9dd3fa491fa..34c36f55019 100644--- a/studio/backend/tests/test_llama_cpp_placement.py+++ b/studio/backend/tests/test_llama_cpp_placement.py@@ -105,6 +105,8 @@ def _backend(tmp_path: Path, *, vulkan: bool, memory):backend._wait_for_health = lambda timeout, **_kw: Truebackend._detect_audio_type_strict = lambda: Nonebackend._apply_detected_audio = lambda _detected: True+ backend._record_server_pid = lambda _pid: None+ backend._clear_server_pid = lambda: Nonereturn backend, gguf@@ -3044,9 +3046,9 @@ def test_the_text_only_fallback_reprices_the_projector_it_dropped(tmp_path, monkassert "--mmproj" in captured["cmds"][0], captured["cmds"][0]assert "--mmproj" not in captured["cmds"][-1], captured["cmds"][-1]warning = backend.last_load_warning or ""- assert "unified-memory APU" not in warning, (- "the response still warns about a shortfall the resident model does not have: " f"{warning}"- )+ assert (+ "unified-memory APU" not in warning+ ), f"the response still warns about a shortfall the resident model does not have: {warning}"if unmapped:# The one thing that IS still true of the running child.assert "memory mapping instead" in warning, warning@@ -3265,10 +3267,9 @@ def test_a_model_that_fits_vram_but_not_ram_is_warned_once_it_lands_on_cpu(tmp_p_launch_with_vulkan_cpu_replay(backend, gguf)warning = backend.last_load_warning or ""- assert "does not fit in GPU memory" in warning, (- "the CPU-only child pages the whole model from disk and says nothing about it: "- f"{warning!r}"- )+ assert (+ "does not fit in GPU memory" in warning+ ), f"the CPU-only child pages the whole model from disk and says nothing about it: {warning!r}"assert "About 20 GB" in warning, warningdiff --git a/studio/backend/tests/test_offload_planner.py b/studio/backend/tests/test_offload_planner.pyindex 3b4247938e9..1338da59333 100644--- a/studio/backend/tests/test_offload_planner.py+++ b/studio/backend/tests/test_offload_planner.py@@ -399,6 +399,137 @@ def test_a_partial_spill_across_two_gpus_abstains():assert two_cards.changed is False+def test_a_safe_partial_spill_across_two_gpus_is_planned():+ sizes = [GIB // 2, GIB // 2, GIB // 2, 2 * GIB]+ layout = ModelLayout(+ arch = "qwen35",+ n_layers = 4,+ n_attention_layers = 4,+ blocks = tuple(+ BlockLayout(index = i, spillable_bytes = size, resident_bytes = GIB // 10)+ for i, size in enumerate(sizes)+ ),+ lm_head_bytes = GIB // 10,+ token_embd_bytes = 0,+ kv_bytes_per_token_f16 = 0,+ recurrent_bytes = 0,+ n_ctx_train = 4096,+ complete = True,+ )+ opts = PlanOptions(+ overhead_bytes_per_device = GIB,+ pipeline_overhead_bytes = GIB,+ host_ram_headroom_bytes = 0,+ )++ plan = plan_placement(+ layout,+ [23 * GIB // 10, 22 * GIB // 10],+ 64 * GIB,+ 4096,+ opts = opts,+ )++ assert plan.changed is True+ assert plan.spilled_blocks == (0, 3)+++def test_partial_spill_selection_covers_each_device_shortfall():+ sizes = [1200 * MIB, 0, 0, 600 * MIB, 600 * MIB]+ layout = ModelLayout(+ arch = "qwen35",+ n_layers = 5,+ n_attention_layers = 5,+ blocks = tuple(+ BlockLayout(index = i, spillable_bytes = size, resident_bytes = 0)+ for i, size in enumerate(sizes)+ ),+ lm_head_bytes = 0,+ token_embd_bytes = 0,+ kv_bytes_per_token_f16 = 0,+ recurrent_bytes = 0,+ n_ctx_train = 4096,+ complete = True,+ )+ plan = plan_placement(+ layout,+ [1300 * MIB, 100 * MIB],+ 64 * GIB,+ 4096,+ opts = PlanOptions(overhead_bytes_per_device = 0, host_ram_headroom_bytes = 0),+ split_weights_per_device = [1, 1],+ )++ assert plan.spilled_blocks == (3, 4)+++def test_per_device_selection_cannot_drop_cache_remainder_from_the_pool():+ spillable = [17, 4, 14, 20, 3, 5, 17, 17]+ resident = [1, 5, 5, 1, 6, 6, 5, 0]+ layout = ModelLayout(+ arch = "qwen35",+ n_layers = 8,+ n_attention_layers = 8,+ blocks = tuple(+ BlockLayout(index = i, spillable_bytes = spill, resident_bytes = keep)+ for i, (spill, keep) in enumerate(zip(spillable, resident))+ ),+ lm_head_bytes = 0,+ token_embd_bytes = 0,+ other_resident_bytes = 8,+ kv_bytes_per_token_f16 = 3,+ recurrent_bytes = 0,+ n_ctx_train = 4096,+ complete = True,+ )+ opts = PlanOptions(+ overhead_bytes_per_device = 8,+ pipeline_overhead_bytes = 5,+ extra_resident_bytes = 4,+ host_ram_headroom_bytes = 0,+ )+ plan = plan_placement(+ layout,+ [90, 25],+ 1024,+ 5,+ opts = opts,+ split_weights_per_device = [56, 27],+ )++ assert not plan.changed or plan.vram_bytes <= 90+++def test_output_device_shortfall_can_reach_the_lm_head_rung():+ layout = ModelLayout(+ arch = "qwen35",+ n_layers = 3,+ n_attention_layers = 3,+ blocks = tuple(+ BlockLayout(index = i, spillable_bytes = size, resident_bytes = 0)+ for i, size in enumerate([100, 100, 10])+ ),+ lm_head_bytes = 100,+ token_embd_bytes = 0,+ kv_bytes_per_token_f16 = 0,+ recurrent_bytes = 0,+ n_ctx_train = 4096,+ complete = True,+ )+ plan = plan_placement(+ layout,+ [100, 20],+ 1024,+ 1,+ opts = PlanOptions(overhead_bytes_per_device = 0, host_ram_headroom_bytes = 0),+ split_weights_per_device = [1, 1],+ )++ assert plan.spilled_blocks == (0,)+ assert plan.spilled_lm_head is True+ assert plan.vram_bytes <= 120++def test_a_full_spill_is_checked_per_device_not_assumed():"""A full spill used to be waved through on the theory that "every devicekeeps its layer share". It does keep its ROW share -- llama.cpp splits rows@@ -453,6 +584,46 @@ def test_the_row_split_matches_llama_cpp():assert _device_slots(4, [0, 0]) == [[0, 1, 2, 3], []]+def test_the_row_split_uses_llama_cpp_float32_boundaries():+ rows = _device_slots(353, [39407 * MIB, 12114 * MIB])+ assert len(rows[0]) == 270+ assert 270 in rows[1]+++def test_a_float32_split_boundary_cannot_approve_an_oom():+ blocks = tuple(+ BlockLayout(+ index = i,+ spillable_bytes = 2 * GIB,+ resident_bytes = 2 * GIB if i == 270 else 0,+ )+ for i in range(352)+ )+ layout = ModelLayout(+ arch = "qwen35",+ n_layers = 352,+ n_attention_layers = 352,+ blocks = blocks,+ lm_head_bytes = 0,+ token_embd_bytes = 0,+ kv_bytes_per_token_f16 = 0,+ recurrent_bytes = 0,+ n_ctx_train = 4096,+ complete = True,+ )+ plan = plan_placement(+ layout,+ [2 * GIB, GIB],+ 1024 * GIB,+ 4096,+ opts = PlanOptions(overhead_bytes_per_device = 0, host_ram_headroom_bytes = 0),+ split_weights_per_device = [39407 * MIB, 12114 * MIB],+ )++ assert plan.changed is False+ assert "device 1" in plan.reason++def test_the_per_device_check_passes_when_the_shares_really_fit():"""The check must not be a disguised "never plan on two GPUs". Cards sized sothat each one's row share fits with room to spare return None -- no abstain@@ -489,6 +660,87 @@ def test_the_per_device_check_passes_when_the_shares_really_fit():)+def test_the_per_device_check_charges_each_secondary_pipeline_reserve():+ layout = uneven_layout()+ spilled = {b.index for b in layout.blocks}+ cache_per_layer = layout.kv_bytes(4096, 2) // layout.n_layers+ device_one_used = layout.blocks[3].resident_bytes + cache_per_layer + layout.lm_head_bytes+ pipeline_reserve = GIB+ opts = PlanOptions(overhead_bytes_per_device = 0, pipeline_overhead_bytes = pipeline_reserve)++ below = _per_device_shortfall(+ layout,+ opts,+ 4096,+ spilled,+ False,+ [4 * GIB, device_one_used + pipeline_reserve - 1],+ quantised = False,+ kv_bytes_floor = 0,+ split_weights_per_device = [1, 1],+ )+ exact = _per_device_shortfall(+ layout,+ opts,+ 4096,+ spilled,+ False,+ [4 * GIB, device_one_used + pipeline_reserve],+ quantised = False,+ kv_bytes_floor = 0,+ split_weights_per_device = [1, 1],+ )+ above = _per_device_shortfall(+ layout,+ opts,+ 4096,+ spilled,+ False,+ [4 * GIB, device_one_used + pipeline_reserve + 1],+ quantised = False,+ kv_bytes_floor = 0,+ split_weights_per_device = [1, 1],+ )++ assert below is not None and "device 1" in below+ assert exact is None+ assert above is None+++def test_an_empty_secondary_still_has_to_fit_its_fixed_reserves():+ layout = uneven_layout()+ spilled = {b.index for b in layout.blocks}+ pipeline_reserve = GIB+ opts = PlanOptions(overhead_bytes_per_device = 0, pipeline_overhead_bytes = pipeline_reserve)++ below = _per_device_shortfall(+ layout,+ opts,+ 4096,+ spilled,+ True,+ [4 * GIB, pipeline_reserve - 1],+ quantised = False,+ kv_bytes_floor = 0,+ split_weights_per_device = [1000, 1],+ )+ exact = _per_device_shortfall(+ layout,+ opts,+ 4096,+ spilled,+ True,+ [4 * GIB, pipeline_reserve],+ quantised = False,+ kv_bytes_floor = 0,+ split_weights_per_device = [1000, 1],+ )++ assert _device_slots(layout.n_layers + 1, [1000, 1])[1] == []+ assert below is not None and "device 1" in below+ assert exact is None++def test_multi_gpu_credit_sums():layout = q2_layout()assert (diff --git a/studio/backend/tests/test_offload_planner_seam.py b/studio/backend/tests/test_offload_planner_seam.pyindex 5cf6ce319e3..f79bb40037f 100644--- a/studio/backend/tests/test_offload_planner_seam.py+++ b/studio/backend/tests/test_offload_planner_seam.py@@ -13,6 +13,8 @@ assigned to a GPU so the cache stays with it).from __future__ import annotations+from types import SimpleNamespace+import pytestfrom core.inference.llama_cpp import LlamaCppBackend@@ -150,6 +152,7 @@ def _inputs(shared = None,gpus = None,n_parallel = 1,+ n_threads = None,compute_flat = 0,ctx_compute = 0,env_mmproj = 0,@@ -171,6 +174,7 @@ def _inputs("model_path": "/models/stub.gguf","n_ctx": 32768,"n_parallel": n_parallel,+ "n_threads": n_threads,"shared_gpu_ids": set() if shared is None else set(shared),"separate_draft_on_gpu": separate_draft,**({} if mtp is None else {"mtp_will_engage": mtp}),@@ -342,7 +346,10 @@ def test_a_moe_load_spills_expert_tensors_not_dense_ffn():def test_lm_head_is_only_spilled_after_ffn():"""43% of generation on its own, 16% on top of an already host-bound step, soit is never the first rung."""- tight = _plan(_Stub(), model_size = 60 * GIB, kv = 2 * GIB, free_mib = 5632)+ # 4608, not 5632: the planner no longer withholds a pipeline GiB from a+ # SINGLE card, so the old figure left a deficit the FFN alone covered and+ # lm_head was never reached.+ tight = _plan(_Stub(), model_size = 60 * GIB, kv = 2 * GIB, free_mib = 4608)assert tight is not Noneassert tight.spilled_lm_head is Trueassert tight.spilled_blocks, "lm_head is never the first rung"@@ -375,7 +382,9 @@ def test_a_floor_that_does_not_fit_emits_no_flags():just said does not fit. Checking `insufficient` on the returned plan passeseither way and proves nothing."""- got = _plan(_Stub(), model_size = 30 * GIB, kv = 2 * GIB, free_mib = 4 * 1024)+ # A GiB tighter than before, for the single-card pipeline reserve this no+ # longer charges; the case is still "no rung fits".+ got = _plan(_Stub(), model_size = 30 * GIB, kv = 2 * GIB, free_mib = 3 * 1024)assert got is not Noneassert got.insufficientassert LlamaCppBackend._spill_plan_flags_for(got) == []@@ -743,8 +752,8 @@ def test_the_planner_gets_the_budget_the_fit_tested_not_raw_free():-ot overrides, and then appends --fit off over the result."""stub = _Stub()- on_free = _plan(stub, free_mib = 15 * 1024)- on_budget = _plan(stub, free_mib = 15 * 1024, usable_mib = 13 * 1024)+ on_free = _plan(stub, free_mib = 14 * 1024)+ on_budget = _plan(stub, free_mib = 14 * 1024, usable_mib = 13 * 1024)assert on_free is not None and on_budget is not Noneassert on_free.spills_anything and on_budget.spills_anything@@ -759,8 +768,8 @@ def test_the_projector_and_mtp_reserve_reach_the_planner():already judged not to fit, and the launch then follows that with --fit off."""stub = _Stub()- without = _plan(stub, free_mib = 15 * 1024)- with_extra = _plan(stub, free_mib = 15 * 1024, extra_gpu = 2 * GIB)+ without = _plan(stub, free_mib = 14 * 1024)+ with_extra = _plan(stub, free_mib = 14 * 1024, extra_gpu = 2 * GIB)assert without is not None and with_extra is not Noneassert without.spills_anything and with_extra.spills_anything@@ -867,8 +876,8 @@ def test_an_engaged_draft_charges_the_excluded_mtp_blocks():stub = _Stub()stub._excluded_bytes = 3 * GIB- idle = _plan(stub, free_mib = 15 * 1024, mtp = False)- drafting = _plan(stub, free_mib = 15 * 1024, mtp = True)+ idle = _plan(stub, free_mib = 14 * 1024, mtp = False)+ drafting = _plan(stub, free_mib = 14 * 1024, mtp = True)assert idle is not None and drafting is not Noneassert idle.spills_anything and drafting.spills_anything@@ -880,8 +889,8 @@ def test_an_ordinary_model_is_unaffected_by_the_draft_flag():model that has no MTP head."""stub = _Stub()assert stub._excluded_bytes == 0- idle = _plan(stub, free_mib = 15 * 1024, mtp = False)- drafting = _plan(stub, free_mib = 15 * 1024, mtp = True)+ idle = _plan(stub, free_mib = 14 * 1024, mtp = False)+ drafting = _plan(stub, free_mib = 14 * 1024, mtp = True)assert idle.spilled_blocks == drafting.spilled_blocks@@ -1233,7 +1242,11 @@ def test_a_multi_gpu_separate_drafter_declines_rather_than_booking_it_on_device_model_size = 21 * GIB,kv = 2 * GIB,extra_gpu = 3 * GIB,- gpus = [(0, 10 * 1024), (1, 3 * 1024)],+ # 9 GiB, not 10: the split reserve is charged once for the SECOND card+ # now rather than to both, so the old pair left a deficit a PARTIAL spill+ # covered, and a partial multi-GPU spill abstains before it ever reaches+ # the per-device check this test is about.+ gpus = [(0, 9 * 1024), (1, 3 * 1024)],)# Before this abstain the same inputs produced a real plan -- every block# spilled, -ngl -1 --fit off emitted -- with the whole 3 GiB booked on@@ -1454,9 +1467,9 @@ def test_an_inherited_tensor_split_scrubbed_with_its_mode_is_not_planned_againstmod.plan_placement = realassert scrubbed == [8 * 1024 * MIB, 16 * 1024 * MIB], "the child never sees that -ts"- # Not vacuous: with no inherited mode to drag it out, it IS the row weight,- # scaled onto the same magnitude as the free-VRAM numbers.- assert survives == [9 * 16 * 1024 * MIB, 16 * 1024 * MIB]+ # Not vacuous: with no inherited mode to drag it out, the float shares reach+ # the row model exactly as llama.cpp parsed them.+ assert survives == [9.0, 1.0]@pytest.mark.parametrize("value", ["nan,1", "inf,1", "1,nan", "-nan,1", "infinity,1"])@@ -1478,6 +1491,16 @@ def test_a_non_finite_tensor_split_declines_instead_of_raising(value):assert _plan(_Stub(), gpus = two_cards, extra_args = ["-ts", "3,1"]) is not None+def test_a_cumulative_float32_tensor_split_overflow_declines_instead_of_raising():+ from core.inference.llama_cpp import _extra_args_tensor_split++ value = "3e38,3e38"+ assert _extra_args_tensor_split(["-ts", value], {}) is None+ two_cards = [(0, 14 * 1024), (1, 14 * 1024)]+ assert _plan(_Stub(), gpus = two_cards, extra_args = ["-ts", value]) is None+ assert _plan(_Stub(), gpus = two_cards, env = {"LLAMA_ARG_TENSOR_SPLIT": value}) is None++def test_the_vector_refuses_a_cache_the_estimator_prices_on_another_path():"""_estimate_kv_cache_bytes picks its path BEFORE it looks at the window, andthe earlier paths price a different quantity: path 1 (MLA) caches one@@ -1605,3 +1628,625 @@ def test_the_seam_passes_the_flash_state_and_cache_type_to_the_kv_vector():}assert getattr(passed.get("flash_attn"), "id", None) == "planned_flash_attn"assert getattr(passed.get("cache_type_kv"), "id", None) == "cache_type_kv"+++# ------------------------------- the two inputs the planner was getting wrong+++def test_a_single_card_pays_no_split_reserve():+ """The pipeline reserve is a LAYER-SPLIT cost, so one card owes none of it.++ Every other use of _PIPELINE_PER_DEVICE_OVERHEAD_MIB in llama_cpp.py applies+ it as ``max(0, n_gpus - 1) *`` or guards it behind ``n > 1``; the planner+ folded it into its flat per-device term, so it came off device 0 as well.+ That withheld a GiB of a single card no split was ever going to allocate, and+ the planner then spilled real blocks to cover the deficit it had invented --+ the "spilled into headroom that was there" cells in #9861.++ Asserted through the plan rather than by reading the constant: a load sized+ to fit in exactly the disputed GiB must come back resident.+ """+ from core.inference.offload_planner import ContextPolicy, PlanOptions, plan_placement++ layout = _Stub()._tensor_spill_layout("/models/stub.gguf")+ opts = PlanOptions(+ overhead_bytes_per_device = 0,+ pipeline_overhead_bytes = 1 * GIB,+ context_policy = ContextPolicy.NEVER_REDUCE,+ )+ resident = sum(b.resident_bytes for b in layout.blocks) + layout.token_embd_bytes+ spillable = sum(b.spillable_bytes for b in layout.blocks)+ need = resident + spillable + layout.lm_head_bytes++ one = plan_placement(layout, [need + 512 * MIB], 64 * GIB, 4096, opts = opts)+ assert not one.spills_anything, (+ "a single card paid a split reserve it does not owe, so a load that fits "+ f"was spilled anyway: {one.reason}"+ )++ # The term is not simply deleted: it is charged once per device AFTER the+ # first. Asserted on the budget arithmetic directly, because the plan-level+ # answer for two cards is dominated by the partial-spill abstain and would+ # read the same whether the reserve was charged or not.+ from core.inference.offload_planner import _usable_vram++ card = 8 * GIB+ assert _usable_vram([card], opts) == card+ assert _usable_vram([card, card], opts) == 2 * card - 1 * GIB+ assert _usable_vram([card, card, card], opts) == 3 * card - 2 * GIB+++def test_the_cost_model_is_told_physical_cores_not_hyperthreads(monkeypatch):+ """Spilled decode gets physical cores, so the penalty must be priced on them.++ Studio leaves --threads unset on purpose, and an unset --threads makes+ llama.cpp size its pool from common_cpu_get_num_math, which counts physical+ cores. Passing os.cpu_count() told the cost model a 6-core / 12-thread+ desktop had 12, and the generation penalty came out roughly half of what a+ spill really costs there.+ """+ import core.inference.llama_cpp as llama_mod++ monkeypatch.setattr(llama_mod, "_linux_math_core_count", lambda: None)+ assert llama_mod._spilled_decode_threads() >= 1++ class _FakePsutil:+ @staticmethod+ def cpu_count(logical = True):+ return 12 if logical else 6++ import sys++ saved = sys.modules.get("psutil")+ sys.modules["psutil"] = _FakePsutil+ monkeypatch.setattr(+ llama_mod.os, "sched_getaffinity", lambda _pid: set(range(12)), raising = False+ )+ try:+ assert llama_mod._spilled_decode_threads() == 6, "logical count reached the cost model"+ finally:+ if saved is None:+ del sys.modules["psutil"]+ else:+ sys.modules["psutil"] = saved++ # Match llama.cpp's own last resort when physical topology is unavailable.+ class _NoAnswer:+ @staticmethod+ def cpu_count(logical = True):+ return None++ sys.modules["psutil"] = _NoAnswer+ try:+ for logical, expected in ((2, 2), (4, 4), (8, 4), (16, 8), (None, 4)):+ monkeypatch.setattr(llama_mod.os, "cpu_count", lambda answer = logical: answer)+ monkeypatch.setattr(+ llama_mod.os,+ "sched_getaffinity",+ lambda _pid, answer = logical: set(range(answer or 1)),+ )+ assert llama_mod._spilled_decode_threads() == expected+ finally:+ if saved is None:+ del sys.modules["psutil"]+ else:+ sys.modules["psutil"] = saved+++def test_thread_overrides_reach_the_cost_model(monkeypatch):+ import core.inference.llama_cpp as llama_mod++ seen = []++ def _threads(n_threads = None, extra_args = None):+ seen.append((n_threads, extra_args))+ return int(n_threads or 8)++ monkeypatch.setattr(llama_mod, "_spilled_decode_threads", _threads)+ plan = _plan(+ _Stub(),+ free_mib = 14 * 1024,+ n_threads = 3,+ extra_args = ["--threads", "2"],+ env = {"LLAMA_ARG_THREADS": "1"},+ )++ assert plan is not None and plan.spills_anything+ expected = [(3, ["--threads", "2"])]+ assert seen == expected+++def test_thread_override_precedence_matches_the_launched_command(monkeypatch):+ import core.inference.llama_cpp as llama_mod++ monkeypatch.setattr(llama_mod, "_linux_math_core_count", lambda: None)++ class _FakePsutil:+ @staticmethod+ def cpu_count(logical = True):+ return 12 if logical else 6++ import sys++ monkeypatch.setitem(sys.modules, "psutil", _FakePsutil)+ monkeypatch.setattr(+ llama_mod.os, "sched_getaffinity", lambda _pid: set(range(12)), raising = False+ )+ assert llama_mod._spilled_decode_threads() == 6+ assert llama_mod._spilled_decode_threads(3) == 3+ assert llama_mod._spilled_decode_threads(3, ["--threads", "4"]) == 4+ assert llama_mod._spilled_decode_threads(3, ["-t=5", "--threads=1"]) == 1+++def test_smt_workers_do_not_multiply_math_core_capacity(monkeypatch):+ import core.inference.llama_cpp as llama_mod++ monkeypatch.setattr(llama_mod, "_linux_math_core_count", lambda: None)++ class _SmtHost:+ @staticmethod+ def cpu_count(logical = True):+ return 16 if logical else 8++ import sys++ monkeypatch.setitem(sys.modules, "psutil", _SmtHost)+ monkeypatch.setattr(+ llama_mod.os, "sched_getaffinity", lambda _pid: set(range(16)), raising = False+ )+ monkeypatch.setattr(llama_mod.os, "cpu_count", lambda: 16)+ assert llama_mod._spilled_decode_threads(extra_args = ["--threads", "4"]) == 4+ assert llama_mod._spilled_decode_threads(extra_args = ["--threads", "16"]) is None+ assert llama_mod._spilled_decode_threads(extra_args = ["--threads", "-1"]) is None+ assert llama_mod._spilled_decode_threads(extra_args = ["--threads", "0"]) is None++ class _NonSmtHost:+ @staticmethod+ def cpu_count(logical = True):+ return 8++ monkeypatch.setitem(sys.modules, "psutil", _NonSmtHost)+ monkeypatch.setattr(llama_mod.os, "cpu_count", lambda: 8)+ assert llama_mod._spilled_decode_threads(extra_args = ["--threads", "-1"]) == 8+++def test_default_thread_override_uses_native_logical_count(monkeypatch):+ import core.inference.llama_cpp as llama_mod++ class _SmtHost:+ @staticmethod+ def cpu_count(logical = True):+ return 16 if logical else 8++ import sys++ monkeypatch.setattr(llama_mod, "_linux_math_core_count", lambda: 8)+ monkeypatch.setattr(llama_mod.os, "cpu_count", lambda: 2)+ monkeypatch.setitem(sys.modules, "psutil", _SmtHost)+ assert llama_mod._spilled_decode_threads(extra_args = ["--threads", "-1"]) is None+++def test_inherited_linux_cpu_affinity_declines_spill_pricing(monkeypatch):+ import core.inference.llama_cpp as llama_mod++ class _SmtHost:+ @staticmethod+ def cpu_count(logical = True):+ return 16 if logical else 8++ import sys++ monkeypatch.setattr(llama_mod, "_linux_math_core_count", lambda: 8)+ monkeypatch.setattr(llama_mod.sys, "platform", "linux")+ monkeypatch.setattr(+ llama_mod.os,+ "uname",+ lambda: SimpleNamespace(machine = "x86_64"),+ raising = False,+ )+ monkeypatch.setattr(llama_mod.os, "sched_getaffinity", lambda _pid: {0, 1}, raising = False)+ monkeypatch.setitem(sys.modules, "psutil", _SmtHost)+ assert llama_mod._spilled_decode_threads() is None++ monkeypatch.setattr(llama_mod.os, "sched_getaffinity", lambda _pid: set(range(16)))+ assert llama_mod._spilled_decode_threads() == 8+++def test_inherited_linux_arm_cpu_affinity_declines_spill_pricing(monkeypatch):+ import core.inference.llama_cpp as llama_mod++ class _ArmHost:+ @staticmethod+ def cpu_count(logical = True):+ return 72 if logical else 36++ import sys++ monkeypatch.setattr(llama_mod.sys, "platform", "linux")+ monkeypatch.setattr(+ llama_mod.os,+ "uname",+ lambda: SimpleNamespace(machine = "aarch64"),+ raising = False,+ )+ monkeypatch.setattr(+ llama_mod.os, "sched_getaffinity", lambda _pid: set(range(4)), raising = False+ )+ monkeypatch.setitem(sys.modules, "psutil", _ArmHost)+ assert llama_mod._spilled_decode_threads() is None+++def test_oversubscribed_decode_threads_decline_spill_planning(monkeypatch):+ import core.inference.llama_cpp as llama_mod++ monkeypatch.setattr(llama_mod, "_linux_math_core_count", lambda: 8)+ monkeypatch.setattr(llama_mod.sys, "platform", "linux")+ monkeypatch.setattr(+ llama_mod.os,+ "uname",+ lambda: SimpleNamespace(machine = "x86_64"),+ raising = False,+ )+ monkeypatch.setattr(+ llama_mod.os, "sched_getaffinity", lambda _pid: set(range(16)), raising = False+ )+ assert _plan(_Stub(), free_mib = 14 * 1024, extra_args = ["--threads", "16"]) is None+ plan = _plan(+ _Stub(),+ free_mib = 14 * 1024,+ extra_args = ["--threads", "4"],+ )+ assert plan is not None and plan.spills_anything+++ "extra_args",+ [+ ["--cpu-range", "0-2", "--cpu-strict", "1"],+ ["-C", "0x3"],+ ["--cpu-mask=0x3"],+ ],+)+def test_affinity_constrained_decode_declines_spill_planning(monkeypatch, extra_args):+ import core.inference.llama_cpp as llama_mod+ monkeypatch.setattr(llama_mod, "_linux_math_core_count", lambda: 8)+ assert _plan(_Stub(), free_mib = 14 * 1024, extra_args = extra_args) is None+++def test_linux_hybrid_math_cores_exclude_efficiency_cores(tmp_path):+ from core.inference.llama_cpp import _linux_math_core_count++ sibling_sets = [f"{core},{core + 8}" for core in range(8)]+ sibling_sets.extend(f"{core},{core + 8}" for core in range(8))+ sibling_sets.extend(str(cpu) for cpu in range(16, 32))+ for cpu, sibling_set in enumerate(sibling_sets):+ cpu_path = tmp_path / f"cpu{cpu}"+ (cpu_path / "topology").mkdir(parents = True)+ (cpu_path / "topology" / "thread_siblings").write_text(sibling_set)+ capacity = 1024 if cpu < 16 else 512+ (cpu_path / "cpu_capacity").write_text(str(capacity))++ assert _linux_math_core_count(tmp_path, logical_cpus = 32, vendor_id = "GenuineIntel") == 8+++def test_linux_hybrid_pmu_excludes_efficiency_cores_without_capacity(tmp_path):+ from core.inference.llama_cpp import _linux_math_core_count++ cpu_root = tmp_path / "cpu"+ event_root = tmp_path / "events"+ sibling_sets = [f"{core},{core + 4}" for core in range(4)]+ sibling_sets.extend(f"{core},{core + 4}" for core in range(4))+ sibling_sets.extend(str(cpu) for cpu in range(8, 16))+ for cpu, sibling_set in enumerate(sibling_sets):+ cpu_path = cpu_root / f"cpu{cpu}" / "topology"+ cpu_path.mkdir(parents = True)+ (cpu_path / "thread_siblings").write_text(sibling_set)+ (event_root / "cpu_core").mkdir(parents = True)+ (event_root / "cpu_core" / "cpus").write_text("0-7")+ (event_root / "cpu_atom").mkdir()+ (event_root / "cpu_atom" / "cpus").write_text("8-15")++ assert (+ _linux_math_core_count(+ cpu_root,+ vendor_id = "GenuineIntel",+ event_source_root = event_root,+ )+ == 4+ )++[email protected]("source", ["pmu", "capacity"])+def test_linux_no_smt_hybrid_matches_llama_cpu_loop(tmp_path, source):+ from core.inference.llama_cpp import _linux_math_core_count++ cpu_root = tmp_path / "cpu"+ event_root = tmp_path / "events"+ for cpu in range(8):+ cpu_path = cpu_root / f"cpu{cpu}"+ (cpu_path / "topology").mkdir(parents = True)+ (cpu_path / "topology" / "thread_siblings").write_text(str(cpu))+ if source == "capacity":+ (cpu_path / "cpu_capacity").write_text("1024" if cpu < 4 else "512")+ if source == "pmu":+ (event_root / "cpu_core").mkdir(parents = True)+ (event_root / "cpu_core" / "cpus").write_text("0-3")+ (event_root / "cpu_atom").mkdir()+ (event_root / "cpu_atom" / "cpus").write_text("4-7")++ assert (+ _linux_math_core_count(+ cpu_root,+ vendor_id = "GenuineIntel",+ event_source_root = event_root,+ )+ == 2+ )+++def test_linux_sparse_online_hybrid_matches_llama_physical_fallback(tmp_path):+ from core.inference.llama_cpp import _linux_math_core_count++ cpu_root = tmp_path / "cpu"+ event_root = tmp_path / "events"+ sibling_sets = [f"{cpu},{cpu + 8}" for cpu in range(8)]+ sibling_sets.extend(f"{cpu - 8},{cpu}" for cpu in range(8, 16))+ sibling_sets.extend(str(cpu) for cpu in range(16, 24))+ for cpu, sibling_set in enumerate(sibling_sets):+ cpu_path = cpu_root / f"cpu{cpu}" / "topology"+ cpu_path.mkdir(parents = True)+ (cpu_path / "thread_siblings").write_text(sibling_set)+ (cpu_root / "online").write_text("0-7,16-23")+ (event_root / "cpu_core").mkdir(parents = True)+ (event_root / "cpu_core" / "cpus").write_text("0-7")+ (event_root / "cpu_atom").mkdir()+ (event_root / "cpu_atom" / "cpus").write_text("16-23")++ assert (+ _linux_math_core_count(+ cpu_root,+ vendor_id = "GenuineIntel",+ event_source_root = event_root,+ )+ == 16+ )+++def test_linux_smt_disabled_hybrid_skips_offline_siblings(tmp_path):+ from core.inference.llama_cpp import _linux_math_core_count++ cpu_root = tmp_path / "cpu"+ event_root = tmp_path / "events"+ sibling_sets = [f"{cpu // 2 * 2},{cpu // 2 * 2 + 1}" for cpu in range(16)]+ sibling_sets.extend(str(cpu) for cpu in range(16, 24))+ for cpu, sibling_set in enumerate(sibling_sets):+ cpu_path = cpu_root / f"cpu{cpu}" / "topology"+ cpu_path.mkdir(parents = True)+ (cpu_path / "thread_siblings").write_text(sibling_set)+ (cpu_root / "online").write_text("0,2,4,6,8,10,12,14,16-23")+ (event_root / "cpu_core").mkdir(parents = True)+ (event_root / "cpu_core" / "cpus").write_text("0,2,4,6,8,10,12,14")+ (event_root / "cpu_atom").mkdir()+ (event_root / "cpu_atom" / "cpus").write_text("16-23")++ assert (+ _linux_math_core_count(+ cpu_root,+ vendor_id = "GenuineIntel",+ event_source_root = event_root,+ )+ == 8+ )+++def test_linux_hybrid_unpinnable_cpu_matches_llama_physical_fallback(tmp_path):+ from core.inference.llama_cpp import _linux_math_core_count++ cpu_root = tmp_path / "cpu"+ event_root = tmp_path / "events"+ sibling_sets = [f"{cpu // 2 * 2},{cpu // 2 * 2 + 1}" for cpu in range(16)]+ sibling_sets.extend(str(cpu) for cpu in range(16, 24))+ for cpu, sibling_set in enumerate(sibling_sets):+ cpu_path = cpu_root / f"cpu{cpu}" / "topology"+ cpu_path.mkdir(parents = True)+ (cpu_path / "thread_siblings").write_text(sibling_set)+ (cpu_root / "online").write_text("0-23")+ (event_root / "cpu_core").mkdir(parents = True)+ (event_root / "cpu_core" / "cpus").write_text("0-15")+ (event_root / "cpu_atom").mkdir()+ (event_root / "cpu_atom" / "cpus").write_text("16-23")++ assert (+ _linux_math_core_count(+ cpu_root,+ vendor_id = "GenuineIntel",+ event_source_root = event_root,+ pinnable_cpus = set(range(8)),+ )+ == 16+ )+++def test_linux_hybrid_affinity_probe_failure_matches_physical_fallback(tmp_path, monkeypatch):+ import core.inference.llama_cpp as llama_mod++ cpu_root = tmp_path / "cpu"+ event_root = tmp_path / "events"+ for cpu in range(8):+ cpu_path = cpu_root / f"cpu{cpu}" / "topology"+ cpu_path.mkdir(parents = True)+ (cpu_path / "thread_siblings").write_text(str(cpu))+ (event_root / "cpu_core").mkdir(parents = True)+ (event_root / "cpu_core" / "cpus").write_text("0-3")+ (event_root / "cpu_atom").mkdir()+ (event_root / "cpu_atom" / "cpus").write_text("4-7")++ def fail_affinity(_pid):+ raise OSError("unavailable")++ monkeypatch.setattr(llama_mod.os, "sched_getaffinity", fail_affinity, raising = False)+ monkeypatch.setattr(llama_mod.os, "sched_setaffinity", lambda _pid, _cpus: None, raising = False)+ assert (+ llama_mod._linux_math_core_count(+ cpu_root,+ vendor_id = "GenuineIntel",+ event_source_root = event_root,+ probe_affinity = True,+ )+ == 8+ )+++def test_linux_hybrid_affinity_restore_failure_stays_in_worker(tmp_path, monkeypatch):+ import core.inference.llama_cpp as llama_mod++ cpu_root = tmp_path / "cpu"+ event_root = tmp_path / "events"+ for cpu in range(8):+ cpu_path = cpu_root / f"cpu{cpu}" / "topology"+ cpu_path.mkdir(parents = True)+ (cpu_path / "thread_siblings").write_text(str(cpu))+ (event_root / "cpu_core").mkdir(parents = True)+ (event_root / "cpu_core" / "cpus").write_text("0-3")+ (event_root / "cpu_atom").mkdir()+ (event_root / "cpu_atom" / "cpus").write_text("4-7")+ monkeypatch.setattr(+ llama_mod.os, "sched_getaffinity", lambda _pid: set(range(8)), raising = False+ )+ caller_thread = llama_mod.threading.get_ident()+ affinity_threads = []++ def restore_fails(_pid, cpus):+ affinity_threads.append(llama_mod.threading.get_ident())+ if len(cpus) > 1:+ raise OSError("restore failed")++ monkeypatch.setattr(llama_mod.os, "sched_setaffinity", restore_fails, raising = False)+ assert (+ llama_mod._linux_math_core_count(+ cpu_root,+ vendor_id = "GenuineIntel",+ event_source_root = event_root,+ probe_affinity = True,+ )+ == 2+ )+ assert affinity_threads+ assert all(thread != caller_thread for thread in affinity_threads)+++def test_linux_hybrid_with_unreadable_core_mask_is_conservative(tmp_path):+ from core.inference.llama_cpp import _linux_math_core_count++ cpu_root = tmp_path / "cpu"+ event_root = tmp_path / "events"+ for cpu in range(4):+ cpu_path = cpu_root / f"cpu{cpu}" / "topology"+ cpu_path.mkdir(parents = True)+ (cpu_path / "thread_siblings").write_text(str(cpu))+ (event_root / "cpu_atom").mkdir(parents = True)+ (event_root / "cpu_atom" / "cpus").write_text("2-3")++ assert (+ _linux_math_core_count(+ cpu_root,+ vendor_id = "GenuineIntel",+ event_source_root = event_root,+ )+ == 1+ )+++def test_linux_hybrid_with_only_efficiency_cores_matches_llama_fallback(tmp_path):+ from core.inference.llama_cpp import _linux_math_core_count++ cpu_root = tmp_path / "cpu"+ event_root = tmp_path / "events"+ for cpu in range(4):+ cpu_path = cpu_root / f"cpu{cpu}" / "topology"+ cpu_path.mkdir(parents = True)+ (cpu_path / "thread_siblings").write_text(str(cpu))+ (event_root / "cpu_core").mkdir(parents = True)+ (event_root / "cpu_core" / "cpus").write_text("")+ (event_root / "cpu_atom").mkdir()+ (event_root / "cpu_atom" / "cpus").write_text("0-3")++ assert (+ _linux_math_core_count(+ cpu_root,+ vendor_id = "GenuineIntel",+ event_source_root = event_root,+ )+ == 4+ )+++def test_linux_topology_ignores_python_cpu_count_override(tmp_path, monkeypatch):+ import core.inference.llama_cpp as llama_mod++ for cpu in range(4):+ cpu_path = tmp_path / f"cpu{cpu}" / "topology"+ cpu_path.mkdir(parents = True)+ (cpu_path / "thread_siblings").write_text(str(cpu))+ monkeypatch.setattr(llama_mod.os, "cpu_count", lambda: 2)++ assert llama_mod._linux_math_core_count(tmp_path, vendor_id = "AuthenticAMD") == 4+++def test_linux_non_hybrid_topology_excludes_offline_cores(tmp_path):+ from core.inference.llama_cpp import _linux_math_core_count++ sibling_sets = ["0,4", "1,5", "2,6", "3,7", "0,4", "1,5", "2,6", "3,7"]+ for cpu, sibling_set in enumerate(sibling_sets):+ cpu_path = tmp_path / f"cpu{cpu}" / "topology"+ cpu_path.mkdir(parents = True)+ (cpu_path / "thread_siblings").write_text(sibling_set)+ (tmp_path / "online").write_text("0-2,4-6")++ assert _linux_math_core_count(tmp_path, vendor_id = "AuthenticAMD") == 3+++def test_linux_amd_capacity_classes_keep_all_physical_cores(tmp_path):+ from core.inference.llama_cpp import _linux_math_core_count+ for cpu in range(24):+ cpu_path = tmp_path / f"cpu{cpu}"+ (cpu_path / "topology").mkdir(parents = True)+ (cpu_path / "topology" / "thread_siblings").write_text(str(cpu))+ (cpu_path / "cpu_capacity").write_text("1024" if cpu < 8 else "512")++ assert _linux_math_core_count(tmp_path, logical_cpus = 24, vendor_id = "AuthenticAMD") == 24+++ ("sibling_sets", "expected"),+ [+ (["0,4", "1,5", "2,6", "3,7", "0,4", "1,5", "2,6", "3,7"], 4),+ ([str(cpu) for cpu in range(8)], 8),+ ],+)+def test_linux_smt_and_non_smt_core_counts(tmp_path, sibling_sets, expected):+ from core.inference.llama_cpp import _linux_math_core_count+ for cpu, sibling_set in enumerate(sibling_sets):+ cpu_path = tmp_path / f"cpu{cpu}"+ (cpu_path / "topology").mkdir(parents = True)+ (cpu_path / "topology" / "thread_siblings").write_text(sibling_set)++ assert _linux_math_core_count(tmp_path, logical_cpus = len(sibling_sets)) == expected+++def test_invalid_linux_topology_falls_back_to_psutil(monkeypatch):+ import core.inference.llama_cpp as llama_mod++ class _PhysicalHost:+ @staticmethod+ def cpu_count(logical = True):+ return 24 if logical else 12++ import sys++ monkeypatch.setattr(llama_mod, "_linux_math_core_count", lambda: None)+ monkeypatch.setattr(+ llama_mod.os, "sched_getaffinity", lambda _pid: set(range(24)), raising = False+ )+ monkeypatch.setitem(sys.modules, "psutil", _PhysicalHost)+ assert llama_mod._spilled_decode_threads() == 12