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: stop context checkpoints from filling host RAM on hybrid recurrent models (#11073)
oobaboogac92e450f2690
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 6b9f915ef57..7ce13beda5e 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -86,8 +86,12 @@ from core.inference.llama_server_args import (_effective_tensor_parallel,_flag_name,_tensor_parallel_matches_loaded,+ LLAMA_CTX_CHECKPOINTS_DEFAULT,apply_load_mode_policy,apply_model_memory_policy,+ ctx_checkpoints_within_host_budget,+ effective_ctx_checkpoints,+ parse_ctx_checkpoints_override,resolve_ctx_checkpoints,extra_args_disable_mmproj,extra_args_image_max_tokens,@@ -4467,6 +4471,22 @@ def _env_asks_for_the_native_context(env: Optional[Mapping[str, str]] = None) ->return False+def _env_ctx_checkpoints_override(env: Optional[Mapping[str, str]] = None) -> Optional[int]:+ """An inherited LLAMA_ARG_CTX_CHECKPOINTS count, else None.++ llama.cpp applies the variable before parsing argv (arg.cpp's env loop runs ahead of+ the flag loop), so an emitted --ctx-checkpoints would OVERRULE it. It is as explicit+ an instruction as a typed flag, so the automatic cap stands down for it and the+ estimate prices it. Anything unparseable is left to llama.cpp to reject.+ """+ value = (os.environ if env is None else env).get("LLAMA_ARG_CTX_CHECKPOINTS")+ try:+ count = int(str(value).strip())+ except (AttributeError, TypeError, ValueError):+ return None+ return count if count >= 0 else None++def _kv_offload_from_args(extra_args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None) -> bool:@@ -4920,6 +4940,60 @@ def _paravirtual_mmproj_pinnable(server_caps: Mapping[str, object]) -> bool:)+def ctx_checkpoints_allocated(server_caps: Mapping[str, object]) -> bool:+ """Return false only when a PARSED help listing confirms no checkpoint flag.++ A wrapper that exits 0 and prints nothing leaves help_probe_ok True over an empty+ catalogue, which is silence, not absence -- the same rule the parser applies to its+ own fail-open flags. Reading it as absence priced a recurrent model's whole snapshot+ pool at zero while the child kept llama.cpp's default.+ """+ if server_caps.get("ctx_checkpoints_flag"):+ return True+ if not server_caps.get("help_probe_ok"):+ return True+ return not bool(server_caps.get("flags"))+++def ctx_checkpoints_default_for_caps(server_caps: Mapping[str, object]) -> int:+ """The count this build keeps unflagged: what it advertised, else upstream's today."""+ advertised = server_caps.get("ctx_checkpoints_default")+ if isinstance(advertised, int) and advertised >= 0:+ return advertised+ return LLAMA_CTX_CHECKPOINTS_DEFAULT+++def effective_ctx_checkpoints_for_caps(+ server_caps: Mapping[str, object],+ extra_args: Optional[Iterable[str]],+ requested: Optional[int],+ *,+ per_checkpoint_bytes: int = 0,+ n_parallel: int = 1,+ total_host_bytes: Optional[int] = None,+ env: Optional[Mapping[str, str]] = None,+) -> int:+ """Resolve the count from capabilities, arguments, and host budget.++ A confirmed unsupported build uses zero. If a detected binary has no confirmed alias,+ Studio cannot emit its field or cap, so only pass-through extras override the default.+ """+ if not ctx_checkpoints_allocated(server_caps):+ return 0+ emittable = bool(server_caps.get("ctx_checkpoints_flag"))+ describes_a_child = bool(server_caps.get("found"))+ return effective_ctx_checkpoints(+ extra_args,+ requested if (emittable or not describes_a_child) else None,+ supports_flag = True,+ per_checkpoint_bytes = per_checkpoint_bytes,+ n_parallel = n_parallel,+ total_host_bytes = total_host_bytes if emittable else None,+ upstream_default = ctx_checkpoints_default_for_caps(server_caps),+ inherited = _env_ctx_checkpoints_override(env),+ )++def _idle_slot_clearing_active(cmd: Sequence[str], *, supports_cache_ram: bool) -> bool:"""True when *cmd* leaves llama-server clearing idle slots' KV.@@ -8449,6 +8523,20 @@ class LlamaCppBackend:return Truereturn bool(cls._FLASH_ATTN_ENUM_RE.search(help_text))+ _ADVERTISED_DEFAULT_RE = re.compile(r"\(default:\s*(-?\d+)")++ @classmethod+ def _advertised_int_default(cls, help_block: Optional[str]) -> Optional[int]:+ """The integer a flag's help block declares as its default, else None.++ llama.cpp wraps the block across columns, so the caller passes the joined+ text. None means "this build did not say", never a numeric guess.+ """+ if not help_block:+ return None+ match = cls._ADVERTISED_DEFAULT_RE.search(help_block)+ return int(match.group(1)) if match else None+@classmethoddef probe_server_capabilities(cls, binary: Optional[str] = None) -> dict[str, object]:"""Parse `llama-server --help` for feature flags. Returns@@ -8498,6 +8586,7 @@ class LlamaCppBackend:"supports_cache_ram": False,"supports_ctx_checkpoints": False,"ctx_checkpoints_flag": None,+ "ctx_checkpoints_default": None,"supports_no_cache_prompt": False,"supports_metrics": False,"supports_slot_save": False,@@ -8549,6 +8638,7 @@ class LlamaCppBackend:supports_cache_ram = Falsesupports_ctx_checkpoints = Falsectx_checkpoints_flag = None+ ctx_checkpoints_default = Nonesupports_no_cache_prompt = Falsesupports_metrics = Falsesupports_slot_save = False@@ -8777,6 +8867,12 @@ class LlamaCppBackend:ctx_checkpoints_flag = _aliasbreaksupports_ctx_checkpoints = ctx_checkpoints_flag is not None+ # The default shipped at 3 (ggml-org/llama.cpp#15293) and is 32 today, so a+ # hardcoded 32 would RAISE an older build's count instead of capping it.+ if ctx_checkpoints_flag:+ ctx_checkpoints_default = cls._advertised_int_default(+ blocks.get(ctx_checkpoints_flag)+ )supports_no_cache_prompt = _is_real("--no-cache-prompt")supports_metrics = _is_real("--metrics")supports_slot_save = _is_real("--slot-save-path")@@ -8872,6 +8968,7 @@ class LlamaCppBackend:"supports_cache_ram": supports_cache_ram,"supports_ctx_checkpoints": supports_ctx_checkpoints,"ctx_checkpoints_flag": ctx_checkpoints_flag,+ "ctx_checkpoints_default": ctx_checkpoints_default,"supports_no_cache_prompt": supports_no_cache_prompt,"supports_metrics": supports_metrics,"supports_slot_save": supports_slot_save,@@ -12762,6 +12859,20 @@ class LlamaCppBackend:passreturn None+ @staticmethod+ def _host_memory_capacity_mib() -> Optional[int]:+ """Host RAM this process may actually charge, in MiB.++ MemTotal narrowed by an enforcing cgroup, whose limit a container's own+ /proc/meminfo does not show. The LIMIT, never the remainder, which shrinks as+ the container fills and would price against memory that is merely busy.+ """+ total = LlamaCppBackend._total_system_memory_mib()+ limit = LlamaCppBackend._cgroup_memory_limit_mib()+ if total is None:+ return limit+ return min(total, limit) if limit is not None else total+_ARGV_MODEL = frozenset({"-m", "--model"})_ARGV_RPC = frozenset({"--rpc"})@@ -14804,7 +14915,11 @@ class LlamaCppBackend:per-layer KDA layout; Hybrid Mamba uses its architecture-level intervaland group count in _mamba_recurrent_state_bytes."""- if not self._n_kv_heads_by_layer or not self._n_layers or not self._kda_head_dim:+ # Lightweight probes may omit fields used only by other architectures.+ heads_by_layer = getattr(self, "_n_kv_heads_by_layer", None)+ n_layers_raw = getattr(self, "_n_layers", None)+ kda_head_dim = getattr(self, "_kda_head_dim", None)+ if not heads_by_layer or not n_layers_raw or not kda_head_dim:return 0n_recurrent = sum(1 for i in range(self._n_layers) if self._kv_heads_for_layer(i, 1) == 0)if n_recurrent == 0:@@ -14816,16 +14931,53 @@ class LlamaCppBackend:return int(n_recurrent * (n_embd_r + n_embd_s) * 4 * max(1, n_parallel))def _rollback_state_bytes(self, n_parallel: int = 1) -> int:- """One target-context rollback snapshot, whichever recurrent family this is.-- Both callers price the same thing (llama.cpp's `1 seqs N rs_seq`) and both- used to reach for the Mamba helper alone, which answers 0 for a KDA hybrid- and silently dropped the reserve. Route every caller through here.- """+ """Size one target-context rollback snapshot for either recurrent family."""return self._mamba_recurrent_state_bytes(n_parallel) or self._recurrent_state_bytes(n_parallel)+ def _bounded_ctx_checkpoints(+ self,+ n_parallel: int,+ server_caps: Mapping[str, object],+ extra_args: Optional[Iterable[str]] = None,+ env: Optional[Mapping[str, str]] = None,+ ) -> Optional[int]:+ """Return an automatic recurrent-checkpoint cap, or None to preserve the argv."""+ flag = server_caps.get("ctx_checkpoints_flag")+ if not flag:+ return None+ # Extras and LLAMA_ARG_CTX_CHECKPOINTS are the operator's; emitting overrules them.+ if parse_ctx_checkpoints_override(extra_args) is not None:+ return None+ if _env_ctx_checkpoints_override(env) is not None:+ return None+ per_checkpoint = self._rollback_state_bytes(1)+ if per_checkpoint <= 0:+ return None+ total_ram_mib = self._host_memory_capacity_mib()+ # This build's own default: capping against 32 would raise a build that keeps 3.+ upstream_default = ctx_checkpoints_default_for_caps(server_caps)+ bounded = ctx_checkpoints_within_host_budget(+ per_checkpoint,+ n_parallel,+ (total_ram_mib * 1024 * 1024) if total_ram_mib else None,+ upstream_default = upstream_default,+ )+ if bounded >= upstream_default:+ return None+ logger.info(+ "Capping llama-server context checkpoints at %d per slot (this build's default %d): "+ "each one snapshots this model's whole recurrent state (%.1f MiB), so the default "+ "would hold %.1f GiB of host RAM across %d slot(s).",+ bounded,+ upstream_default,+ per_checkpoint / (1024**2),+ upstream_default * per_checkpoint * max(1, n_parallel) / (1024**3),+ max(1, n_parallel),+ )+ return bounded+def _target_kv_excludes_nextn(self) -> bool:"""Whether this model's TARGET KV cache skips the embedded MTP blocks.@@ -14957,7 +15109,9 @@ class LlamaCppBackend:n_parallel -- --parallel slots: controls per-slot stream padding.kv_unified -- --kv-unified: one shared stream vs one per slot.n_ubatch -- --ubatch-size: SWA cache's processing headroom.- ctx_checkpoints -- --ctx-checkpoints: N SWA snapshots per slot.+ ctx_checkpoints -- --ctx-checkpoints: N snapshots per slot. An SWA+ model snapshots its window; a hybrid recurrent one+ snapshots its WHOLE recurrent state (see path 2).flash_attn -- False pads variable-width V tensors to the model max.Returns 0 if metadata is insufficient.@@ -14993,6 +15147,9 @@ class LlamaCppBackend:int(self._DEFAULT_N_UBATCH if n_ubatch is None else n_ubatch),)+ # A hybrid snapshot is the whole recurrent state, not a context-scaled window.+ recurrent_checkpoints = slots * max(0, ctx_checkpoints) * self._rollback_state_bytes(1)+# Path 1: MLA (DeepSeek-V2/V3, GLM-4.7, GLM-5, Kimi-K2.5)# One compressed KV latent per token/layer (shared across heads); V is# reconstructed from it, no separate V cache. key_length = kv_lora_rank@@ -15014,9 +15171,11 @@ class LlamaCppBackend:1 for i in range(n_layers_kv) if self._kv_heads_for_layer(i, n_kv_mla) > 0)n_mla_layers = max(1, attn)- return int(- n_mla_layers * total_cells * n_kv_mla * key_len * bpe_k- ) + self._recurrent_state_bytes(n_parallel)+ return (+ int(n_mla_layers * total_cells * n_kv_mla * key_len * bpe_k)+ + self._recurrent_state_bytes(n_parallel)+ + recurrent_checkpoints+ )key_len = self._kv_key_lengthval_len = self._kv_value_length@@ -15032,9 +15191,14 @@ class LlamaCppBackend:return (int(n_attn * total_cells * (n_kv * key_len * bpe_k + v_width * bpe_v))+ recurrent+ + recurrent_checkpoints)head_dim = self._legacy_head_dim()- return int(n_attn * total_cells * n_kv * 2 * head_dim * bpe_k) + recurrent+ return (+ int(n_attn * total_cells * n_kv * 2 * head_dim * bpe_k)+ + recurrent+ + recurrent_checkpoints+ )# Path 3: Sliding window (Gemma 2/3/3n/4, gpt-oss, Cohere2 ...). Pattern# from the resolver; if absent, falls through to the legacy 1/4-global@@ -22139,19 +22303,29 @@ class LlamaCppBackend:)_effective_ubatch = _ubatch_for_slots(n_parallel)- # What the SWA checkpoint reserve is priced against. Extras beat the- # field, as at launch: the control emits its flag before them, so a- # typed --ctx-checkpoints is what the child allocates. Only an- # explicit request counts at all: the estimator has always charged 0,- # and adopting llama.cpp's default of 32 would move the fit for every- # model. Gated on the capability the argv builder emits the flag on:- # a build with neither alias allocates nothing, so pricing it costs- # slots and context for bytes no child holds.- _effective_ctx_checkpoints = (++ # The budget is per slot and the fit can still cut n_parallel, so both+ # counts are taken after it settles, as _effective_ubatch is below.+ def _ctx_checkpoints_for_final_slots() -> int:+ return effective_ctx_checkpoints_for_caps(+ server_caps,+ extra_args,+ ctx_checkpoints,+ per_checkpoint_bytes = self._rollback_state_bytes(1),+ n_parallel = n_parallel,+ total_host_bytes = ((self._host_memory_capacity_mib() or 0) * 1024 * 1024)+ or None,+ )++ _requested_ctx_checkpoints = (resolve_ctx_checkpoints(extra_args, ctx_checkpoints)if server_caps.get("ctx_checkpoints_flag")else 0)+ # Recurrent snapshots are host-only; SWA keeps its existing VRAM fit policy.+ _fit_ctx_checkpoints = (+ 0 if self._rollback_state_bytes(1) > 0 else _requested_ctx_checkpoints+ )# --embedding forces n_batch = n_ubatch, which aborts a load below the slots.if (self.is_embedding_gguf@@ -23528,7 +23702,6 @@ class LlamaCppBackend:n_parallel = n_parallel,kv_unified = planned_kv_unified,n_ubatch = _effective_ubatch,- ctx_checkpoints = _effective_ctx_checkpoints,flash_attn = planned_flash_attn,mtp_engaged = False,mtp_overhead_fn = None,@@ -23536,6 +23709,7 @@ class LlamaCppBackend:budget_frac = 1.0,pooled = True,total_mib = None,+ ctx_checkpoints = _fit_ctx_checkpoints,))if _ctx_wo <= 0:@@ -23609,7 +23783,6 @@ class LlamaCppBackend:n_parallel = n_parallel,kv_unified = planned_kv_unified,n_ubatch = _effective_ubatch,- ctx_checkpoints = _effective_ctx_checkpoints,flash_attn = planned_flash_attn,mtp_engaged = True,mtp_overhead_fn = mtp_overhead_fn,@@ -23617,6 +23790,7 @@ class LlamaCppBackend:budget_frac = 1.0,pooled = True,total_mib = None,+ ctx_checkpoints = _fit_ctx_checkpoints,))if (@@ -23865,7 +24039,6 @@ class LlamaCppBackend:n_parallel = n_parallel,kv_unified = planned_kv_unified,n_ubatch = _effective_ubatch,- ctx_checkpoints = _effective_ctx_checkpoints,flash_attn = planned_flash_attn,mtp_engaged = _mtp_reserves_gpu,mtp_overhead_fn = mtp_overhead_fn,@@ -23873,6 +24046,7 @@ class LlamaCppBackend:budget_frac = 1.0,pooled = True,total_mib = None,+ ctx_checkpoints = _fit_ctx_checkpoints,)kv = _kv_bytes(capped)footprint_mib = (@@ -23959,7 +24133,6 @@ class LlamaCppBackend:n_parallel = n_parallel,kv_unified = planned_kv_unified,n_ubatch = _effective_ubatch,- ctx_checkpoints = _effective_ctx_checkpoints,flash_attn = planned_flash_attn,mtp_engaged = _mtp_reserves_gpu,mtp_overhead_fn = mtp_overhead_fn,@@ -23967,6 +24140,7 @@ class LlamaCppBackend:budget_frac = 1.0,pooled = True,total_mib = None,+ ctx_checkpoints = _fit_ctx_checkpoints,)kv = _kv_bytes(capped)footprint_mib = (@@ -24136,7 +24310,6 @@ class LlamaCppBackend:n_parallel = n_parallel,kv_unified = planned_kv_unified,n_ubatch = _effective_ubatch,- ctx_checkpoints = _effective_ctx_checkpoints,flash_attn = planned_flash_attn,mtp_engaged = _mtp_reserves_gpu,mtp_overhead_fn = mtp_overhead_fn,@@ -24144,6 +24317,7 @@ class LlamaCppBackend:budget_frac = 1.0,pooled = True,total_mib = None,+ ctx_checkpoints = _fit_ctx_checkpoints,)def _apple_footprint_mib(ctx: int) -> float:@@ -24350,7 +24524,7 @@ class LlamaCppBackend:split_extra_bytes = _cc_split_extra(_reduce_ctx),ubatch_for_slots = _ubatch_for_slots,mtp_bytes_for_slots = lambda s, ub: _mtp_bytes(_reduce_ctx, s, ub),- ctx_checkpoints = _effective_ctx_checkpoints,+ ctx_checkpoints = _fit_ctx_checkpoints,)if not _uf_slots:_slots_asked = n_parallel@@ -24383,9 +24557,9 @@ class LlamaCppBackend:split_extra_bytes = _cc_split_extra(ctx),ubatch_for_slots = _ubatch_for_slots,mtp_bytes_for_slots = (lambda s, ub, c = ctx: _mtp_bytes(c, s, ub)),- ctx_checkpoints = _effective_ctx_checkpoints,include_requested = True,exact = True, # only n_parallel is accepted below+ ctx_checkpoints = _fit_ctx_checkpoints,)return _gi if not _uf and _got == n_parallel else None@@ -24747,14 +24921,19 @@ class LlamaCppBackend:else _fit_env_mmproj_bytes+ self._inherited_mmproj_soft_overhead(_fit_env_mmproj_bytes, on_host = False))+ # Derive the host-only share from the same estimator as the total.+ _effective_ctx_checkpoints = _ctx_checkpoints_for_final_slots()+ _ckpt_host_bytes = max(+ 0,+ _kv_bytes(effective_ctx, _effective_ctx_checkpoints)+ - _kv_bytes(effective_ctx, 0),+ )_fit_load_mode = self._fit_derived_load_mode(model_size = _fit_model_size,mmproj_pinned_bytes = _mmproj_pinned_bytes+ (_fit_env_mmproj_bytes if _fit_env_mmproj_on_host else 0),- # Re-read WITH the SWA snapshots --ctx-checkpoints allocates;- # the closure leaves them at 0 for the placement paths, which- # price them by their own route.- kv_cache_bytes = _kv_bytes(effective_ctx, _effective_ctx_checkpoints),+ # Checkpoints are split into host_only_bytes below.+ kv_cache_bytes = _kv_bytes(effective_ctx, 0),kv_sized = self._can_estimate_kv(),mtp_bytes = _mtp_bytes(effective_ctx),# _flat_mtp_engages whole: its other arm, _mtp_kv_unsized,@@ -24766,9 +24945,8 @@ class LlamaCppBackend:or _cpu_draft_fit_bytes is Noneor _draft_split_across_host),- # Host-only, not pooled: -ngld 0 puts the drafter in RAM, which- # free VRAM cannot pay for.- host_only_bytes = _cpu_draft_fit_bytes or 0,+ # Neither a CPU drafter nor checkpoints can be covered by free VRAM.+ host_only_bytes = (_cpu_draft_fit_bytes or 0) + _ckpt_host_bytes,# One lump on the layer path, where the graph buffer is# allocated once. A tensor split replicates it on every selected# device, so pricing one LAYER-mode buffer there understates a@@ -25889,6 +26067,13 @@ class LlamaCppBackend:# The exact tokens the tuning appended, so the arch-crash respawn can# take them back off when it lands on a different device class._cache_flags_emitted: list[str] = []+ # llama.cpp reads the variable before argv, so a 0 appended below would+ # overrule the operator while every estimate still priced their value.+ _ctx_checkpoints_owned = (+ ctx_checkpoints+ if ctx_checkpoints is not None+ else _env_ctx_checkpoints_override()+ )# extra_args, not the memory policy's list: that one is built later, and# a gpu_ids pin is the case _strip_device_extra_args removes the flag in.# The env twin counts too: only an explicit gpu_ids clears@@ -25933,7 +26118,7 @@ class LlamaCppBackend:_cache_flags_emitted.extend(["--cache-ram", "0"])else:unsupported_cache_flags.append("--cache-ram")- if ctx_checkpoints is not None:+ if _ctx_checkpoints_owned is not None:passelif server_caps.get("ctx_checkpoints_flag"):_cache_flags_emitted.extend([str(server_caps["ctx_checkpoints_flag"]), "0"])@@ -25946,6 +26131,37 @@ class LlamaCppBackend:", ".join(unsupported_cache_flags),)+ def _decide_auto_ctx_checkpoints() -> Optional[int]:+ """The cap for the slots n_parallel currently names, or None to stand down."""+ return (+ self._bounded_ctx_checkpoints(n_parallel, server_caps, extra_args)+ if ctx_checkpoints is None+ else None+ )++ _auto_ctx_checkpoints = _decide_auto_ctx_checkpoints()+ # Tracked apart from _cache_flags_emitted, which means "the Windows tuning+ # ran", so the arch-crash respawn can re-decide each one on its own.+ _auto_ckpt_emitted: list[str] = []++ def _emit_auto_ctx_checkpoints(command: list[str]) -> list[str]:+ """Append the automatic cap unless the Windows tuning already zeroed it."""+ if _auto_ctx_checkpoints is None:+ return []+ if any(+ _flag_name(str(token)) in _CTX_CHECKPOINTS_FLAGS+ for token in _cache_flags_emitted+ ):+ return []+ pair = [+ str(server_caps["ctx_checkpoints_flag"]),+ str(_auto_ctx_checkpoints),+ ]+ command.extend(pair)+ return pair++ _auto_ckpt_emitted = _emit_auto_ctx_checkpoints(cmd)+# Record the pin actually applied (fit-narrowed gpu_indices, else the raw# request) for the keep-warm loop, dedupe, and /status, so an explicit# [0, 1] narrowed to [0] records [0] and /status never echoes an ordinal@@ -28032,6 +28248,11 @@ class LlamaCppBackend:gpu_indices = _remaining,))+ # Off first, or _retry_cache_tuning_flags reads the cap as a+ # count the user typed and declines to zero it.+ if _auto_ckpt_emitted:+ cmd = self._without_flag_pairs(cmd, _auto_ckpt_emitted)+ _auto_ckpt_emitted = []if _retry_shared and _cache_flags_emitted:# Exactly the tokens this policy appended, each a flag# with its value, so the strip cannot eat a user extra.@@ -28046,7 +28267,7 @@ class LlamaCppBackend:_retry_flags = self._retry_cache_tuning_flags(cmd,cache_ram = cache_ram,- ctx_checkpoints = ctx_checkpoints,+ ctx_checkpoints = _ctx_checkpoints_owned,server_caps = server_caps,)if _retry_flags:@@ -28056,6 +28277,7 @@ class LlamaCppBackend:"Retry lands on a GPU with its own memory: applied the ""Windows full-offload cache tuning.")+ _auto_ckpt_emitted = _emit_auto_ctx_checkpoints(cmd)# GGML_CUDA_ENABLE_UNIFIED_MEMORY was decided for the CRASHED# set. The canonical #7624 shape crashes on the APU and retries# on the dGPU, where it is harmful, so withdraw it, but only@@ -28335,7 +28557,14 @@ class LlamaCppBackend:# Read by admission control; left as-is Studio over-admits.n_parallel = 1 # allow-slot-clamp: llama-server refused morekv_cache_unified = False- healthy = _spawn_and_wait(_kvu_cmd, label = "-single-seq")+ # The cap in argv was sized for slots this retry no longer runs;+ # same re-decide as the arch-crash respawn.+ if _auto_ckpt_emitted:+ cmd = self._without_flag_pairs(cmd, _auto_ckpt_emitted)+ _auto_ckpt_emitted = []+ _auto_ctx_checkpoints = _decide_auto_ctx_checkpoints()+ _auto_ckpt_emitted = _emit_auto_ctx_checkpoints(cmd)+ healthy = _spawn_and_wait(cmd, label = "-single-seq")# Flash-attention kernels hard-crash at startup on some ROCm/GPU# builds (frequently inside the vision tower). Disabling FA keepsdiff --git a/studio/backend/core/inference/llama_server_args.py b/studio/backend/core/inference/llama_server_args.pyindex 3f7bfb6586d..4ab0f65c3fe 100644--- a/studio/backend/core/inference/llama_server_args.py+++ b/studio/backend/core/inference/llama_server_args.py@@ -33,6 +33,15 @@ BATCH_MAX = 65536CTX_CHECKPOINTS_MAX = 256CACHE_RAM_MAX_MIB = 1024 * 1024+# llama.cpp allocates this default even when Studio emits no flag.+LLAMA_CTX_CHECKPOINTS_DEFAULT = 32++# Recurrent checkpoints live in host RAM and can be much larger than SWA snapshots.+CTX_CHECKPOINT_HOST_BUDGET_FRACTION = 0.05+CTX_CHECKPOINT_HOST_BUDGET_FLOOR_BYTES = 1024**3+# Keep rollback available; zero forces a full prompt re-ingest after divergence.+CTX_CHECKPOINTS_MIN_USEFUL = 2+# Slot-count aliases in one place: the denial below, its #9510 hint and the single-sequence retry must cover the same# set, or a spelling one of them misses reaches llama-server unnoticed._PARALLEL_FLAGS: frozenset[str] = frozenset({"-np", "--parallel", "--n-parallel"})@@ -669,11 +678,69 @@ def parse_ctx_checkpoints_override(args: Optional[Iterable[str]]) -> Optional[indef resolve_ctx_checkpoints(args: Optional[Iterable[str]], requested: Optional[int]) -> int:- """The checkpoint count the launch will actually run: extras beat the field."""+ """Resolve explicit counts only, with extra arguments taking precedence."""override = parse_ctx_checkpoints_override(args)return int(override if override is not None else (requested or 0))+def ctx_checkpoints_within_host_budget(+ per_checkpoint_bytes: int,+ n_parallel: int,+ total_host_bytes: Optional[int],+ *,+ upstream_default: Optional[int] = None,+) -> int:+ """Fit checkpoints per slot within the host budget and this build's own default.++ Unknown sizes keep the default. The minimum useful count may exceed the target budget+ but never the default: this caps what the child would keep, it never raises it.+ """+ default = (+ LLAMA_CTX_CHECKPOINTS_DEFAULT if upstream_default is None else max(0, int(upstream_default))+ )+ if per_checkpoint_bytes <= 0 or not total_host_bytes or total_host_bytes <= 0:+ return default+ budget = max(+ CTX_CHECKPOINT_HOST_BUDGET_FLOOR_BYTES,+ int(total_host_bytes * CTX_CHECKPOINT_HOST_BUDGET_FRACTION),+ )+ per_round = int(per_checkpoint_bytes) * max(1, int(n_parallel))+ affordable = budget // per_round+ if affordable >= default:+ return default+ return min(default, max(CTX_CHECKPOINTS_MIN_USEFUL, int(affordable)))+++def effective_ctx_checkpoints(+ args: Optional[Iterable[str]],+ requested: Optional[int],+ *,+ supports_flag: bool,+ per_checkpoint_bytes: int = 0,+ n_parallel: int = 1,+ total_host_bytes: Optional[int] = None,+ upstream_default: Optional[int] = None,+ inherited: Optional[int] = None,+) -> int:+ """Resolve the child count: extras, field, an inherited env value, then the budget.++ ``inherited`` is llama.cpp's own LLAMA_ARG_CTX_CHECKPOINTS, which it applies before+ argv, so argv beats it and it beats the build default.+ """+ if not supports_flag:+ return 0+ override = resolve_ctx_checkpoints(args, requested)+ if override:+ return override+ if parse_ctx_checkpoints_override(args) == 0 or requested == 0:+ return 0+ if inherited is not None:+ return inherited+ return ctx_checkpoints_within_host_budget(+ per_checkpoint_bytes, n_parallel, total_host_bytes, upstream_default = upstream_default+ )++def resolve_requested_ctx(args: Optional[Iterable[str]], fallback_n_ctx: int) -> int:"""Return the context size load_model should treat as requested. Single source of truth forload_model's ctx-override conditional so tests don't reimplement and assert against their owndiff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 1e46fe6dcf1..a0745ddf8ba 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -10642,9 +10642,9 @@ def _gguf_runtime_bytes(one, since a smaller ``-c`` in the extras is the context the user gets."""try:from core.inference.llama_cpp import _batch_ubatch_for_mmproj+ from core.inference.llama_cpp import effective_ctx_checkpoints_for_capsfrom core.inference.llama_server_args import (parse_ctx_override,- resolve_ctx_checkpoints,resolve_requested_ctx,)@@ -10766,24 +10766,23 @@ def _gguf_runtime_bytes(llama_extra_args,default = managed_kv_unified,)- _resolved_checkpoints = resolve_ctx_checkpoints(llama_extra_args, ctx_checkpoints)- if _resolved_checkpoints:- # A build predating both --ctx-checkpoints aliases has the request skipped- # by the command builder, which logs and moves on, so charging for the- # snapshots reserves memory the process never allocates. Same capability- # probe the builder itself asks, and the same default-deny on an- # unanswerable one: this figure also guards a running training job, so an- # unreadable probe keeps the charge rather than dropping it.- try:- _cc_caps = LlamaCppBackend.probe_server_capabilities()- # ``found`` is what separates "this build lacks the flag" from "no- # binary was read": the defaults dict reports every capability False,- # so keying on the flag alone would drop the charge whenever the probe- # simply could not run.- if _cc_caps.get("found") and not _cc_caps.get("ctx_checkpoints_flag"):- _resolved_checkpoints = 0- except Exception as _cc_exc:- logger.debug("ctx-checkpoints capability probe failed: %s", _cc_exc)+ # Resolve the same capability-dependent count that load_model emits.+ _cc_caps: dict = {}+ try:+ _cc_caps = LlamaCppBackend.probe_server_capabilities() or {}+ except Exception as _cc_exc:+ logger.debug("ctx-checkpoints capability probe failed: %s", _cc_exc)+ # Older lightweight probes may not provide the new sizing helpers.+ _per_checkpoint = getattr(probe, "_rollback_state_bytes", lambda _n: 0)(1)+ _host_mib = getattr(probe, "_host_memory_capacity_mib", lambda: None)()+ _resolved_checkpoints = effective_ctx_checkpoints_for_caps(+ _cc_caps,+ llama_extra_args,+ ctx_checkpoints,+ per_checkpoint_bytes = _per_checkpoint,+ n_parallel = slots,+ total_host_bytes = (_host_mib * 1024 * 1024) if _host_mib else None,+ )# load_model appends --flash-attn on to every launch whose build has the flag,# so the default here is ON, not off. The false arm pads variable-width V# tensors to the model-wide maximum (_max_kv_value_width), which on an@@ -10938,11 +10937,19 @@ def _estimate_gguf_kv_gb(is_diffusion: bool = False,model_identifier: Optional[str] = None,launch_required_ubatch: int = 0,+ shared_memory_pool: bool = True,) -> float:"""``_gguf_runtime_bytes`` summed into GB, for the training guard.An unreadable header is 0 GB, as it always was: a cache the guard cannot sizemust not become a refusal on its own.++ Context checkpoints leave this figure only when ``shared_memory_pool`` is False,+ i.e. the caller has CONFIRMED the pool it checks against is separate from host+ RAM. On an iGPU or a unified-memory APU the driver's "free VRAM" IS the host+ heap, so dropping a host-resident allocation there admits a load beside training+ that the one pool cannot hold. Defaults to keeping them, like the rest of this+ guard, which refuses what it cannot size."""runtime = _gguf_runtime_bytes(gguf_path,@@ -10959,7 +10966,12 @@ def _estimate_gguf_kv_gb(model_identifier = model_identifier,launch_required_ubatch = launch_required_ubatch,)- return (runtime.kv_bytes + runtime.compute_bytes) / (1024**3)+ gpu_kv_bytes = (+ runtime.kv_bytes+ if shared_memory_pool+ else max(0, runtime.kv_bytes - runtime.kv_checkpoint_bytes)+ )+ return (gpu_kv_bytes + runtime.compute_bytes) / (1024**3)def _remote_gguf_compute_reserve_gb(@@ -11059,6 +11071,54 @@ def _remote_gguf_compute_reserve_gb(return 0.0+def _admission_pool_shares_host_ram(+ *,+ is_vulkan_backend: bool,+ vulkan_gpu_memory: Optional[list] = None,+ requested_gpu_ids: Optional[list[int]] = None,+ gpu_ids_are_vulkan_ordinals: bool = False,+) -> bool:+ """Whether the pool the training guard checks against is also the host heap.++ Fails CLOSED. An unreadable inventory, a selection this cannot map to devices,+ or any candidate that turns out to be integrated all answer True, so a figure+ that must not under-charge keeps its host-resident terms.+ """+ try:+ from core.inference.llama_cpp import LlamaCppBackend++ if is_vulkan_backend:+ # total 0 means integrated, as _shared_gpu_ids reads it. Narrowed to the pin+ # only when it is confirmed to be in Vulkan's own index space; a physical id+ # read as an ordinal would answer for the wrong adapter.+ rows = list(vulkan_gpu_memory or [])+ if gpu_ids_are_vulkan_ordinals and requested_gpu_ids:+ pinned = {int(i) for i in requested_gpu_ids}+ rows = [row for row in rows if int(row[0]) in pinned]+ return not rows or any(int(total) <= 0 for _idx, _free, total in rows)+ import torch++ if LlamaCppBackend._torch_is_rocm(torch):+ # An empty unified set means "no APU" and "could not read them" alike, since+ # the classifier skips what it cannot query. Only the first is evidence.+ if not LlamaCppBackend._rocm_classification_answered():+ return True+ unified = LlamaCppBackend._rocm_unified_memory_gpu_ids()+ else:+ # Jetson and DGX Spark are CUDA and unified too, but NEVER probe here:+ # _integrated_cuda_gpu_ids pins ~700 MiB per card for the process, and+ # training holds them. Cached answers only, else keep the charge.+ if not LlamaCppBackend._integrated_cuda_probe_is_free():+ return True+ unified = LlamaCppBackend._integrated_cuda_gpu_ids()+ if not unified:+ return False+ return not requested_gpu_ids or any(int(i) in unified for i in requested_gpu_ids)+ except Exception as e: # noqa: BLE001 -- an unreadable device keeps the charge+ logger.debug("Could not classify the admission pool: %s", e)+ return True++def _estimate_gguf_required_gb(config: ModelConfig,hf_token: Optional[str] = None,@@ -11080,6 +11140,9 @@ def _estimate_gguf_required_gb(# every settings change. This skips that listing; the caller marks the total a# floor instead, exactly as it already does for a drafter it cannot weigh.local_only: bool = False,+ # Passed straight to _estimate_gguf_kv_gb: only a caller that has confirmed a+ # discrete pool may drop the host-resident checkpoint share.+ shared_memory_pool: bool = True,) -> Optional[float]:"""Approximate GGUF VRAM (GB): quantized weights + companions, plus the KVcache for local files (unreadable pre-download for remote). None when nothing@@ -11382,6 +11445,7 @@ def _estimate_gguf_required_gb(launch_required_ubatch = _launch_required_ubatch_for_config(config, llama_extra_args, disable_vision),+ shared_memory_pool = shared_memory_pool,)repo = getattr(config, "gguf_hf_repo", None)@@ -11484,6 +11548,8 @@ class _GgufMemoryBreakdown(NamedTuple):n_parallel: intlayer_count: Optional[int]gpu_layers: Optional[int]+ # Host-resident checkpoint share of kv_bytes. Keep last for positional callers.+ kv_checkpoint_bytes: int = 0def _gguf_offloaded_layer_fraction(@@ -12745,6 +12811,7 @@ def _gguf_memory_breakdown(n_parallel = runtime.n_parallel,layer_count = layer_count,gpu_layers = gpu_layers if gpu_memory_mode == "manual" else None,+ kv_checkpoint_bytes = runtime.kv_checkpoint_bytes,)@@ -14088,6 +14155,12 @@ def _guard_chat_load_against_training(# getattr for the same reason as the batch flags above: an older caller# hands this guard a bare request double that does not carry the field.disable_vision = bool(getattr(request, "disable_vision", False)),+ shared_memory_pool = _admission_pool_shares_host_ram(+ is_vulkan_backend = is_vulkan_backend,+ vulkan_gpu_memory = vulkan_gpu_memory,+ requested_gpu_ids = requested_gpu_ids,+ gpu_ids_are_vulkan_ordinals = gpu_ids_are_vulkan_ordinals,+ ),)# A confirmed-diffusion positive split puts only ngl/n_layers of the weights on the GPU (a# split the loader would drop was nulled above). Unknown classification keeps the fulldiff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex 702c24ffc23..2ed8bb52100 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -3888,22 +3888,37 @@ async def get_kv_cache_estimate(except Exception as e:logger.debug(f"cache type resolution failed for '{repo_id}': {e}")- # ctx_checkpoints is not a rounding error: each saved checkpoint is an SWA snapshot per slot, so a- # 4-slot SWA model at 32k measures 5.82 GiB with none and 11.82 GiB at the llama.cpp default of 32.+ # Probe failures keep the unflagged default rather than assuming zero.+ _cc_caps: dict = {}+ _total_ram_mib: Optional[int] = None+ try:+ _cc_caps = be.probe_server_capabilities() or {}+ _total_ram_mib = getattr(be, "_host_memory_capacity_mib", lambda: None)()+ except Exception as e:+ logger.debug(f"checkpoint budget inputs unavailable for '{repo_id}': {e}")++ # A blank field means llama.cpp's default, narrowed only by a cap Studio can emit.+ from core.inference.llama_cpp import effective_ctx_checkpoints_for_caps++ _effective_checkpoints = effective_ctx_checkpoints_for_caps(+ _cc_caps,+ None,+ ctx_checkpoints,+ per_checkpoint_bytes = getattr(be, "_rollback_state_bytes", lambda _n: 0)(1),+ n_parallel = n_parallel,+ total_host_bytes = (_total_ram_mib * 1024 * 1024) if _total_ram_mib else None,+ )kv = be._estimate_kv_cache_bytes(n_ctx,_effective_cache_type,n_parallel = n_parallel,- ctx_checkpoints = ctx_checkpoints or 0,+ ctx_checkpoints = _effective_checkpoints,n_ubatch = n_ubatch,)- # The checkpoint share of that cache, by difference rather than by re-deriving the SWA layer walk: the- # snapshots are the only term separating the two calls. Reported separately because llama.cpp keeps these- # snapshots in HOST heap (the planner's GPU figure is kv_bytes - kv_checkpoint_bytes); folded into the- # bar's VRAM total they warn OOM over memory that never touches the card.+ # Report the host-resident checkpoint share separately from GPU cache bytes.kv_checkpoint = 0- if ctx_checkpoints:+ if _effective_checkpoints:_kv_without = be._estimate_kv_cache_bytes(n_ctx,_effective_cache_type,diff --git a/studio/backend/tests/test_ctx_checkpoint_host_budget.py b/studio/backend/tests/test_ctx_checkpoint_host_budget.pynew file mode 100644index 00000000000..52398e1f4fe--- /dev/null+++ b/studio/backend/tests/test_ctx_checkpoint_host_budget.py@@ -0,0 +1,1079 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Host-memory budgeting and pricing for llama-server context checkpoints."""++from __future__ import annotations++import pytest++from core.inference.llama_cpp import (+ LlamaCppBackend,+ ctx_checkpoints_allocated,+ ctx_checkpoints_default_for_caps,+ effective_ctx_checkpoints_for_caps,+)+from core.inference.llama_server_args import (+ CTX_CHECKPOINTS_MIN_USEFUL,+ LLAMA_CTX_CHECKPOINTS_DEFAULT,+ ctx_checkpoints_within_host_budget,+ effective_ctx_checkpoints,+)++GIB = 1024**3+MIB = 1024**2++# unsloth/Qwen3.8-27B-GGUF, read from the shipped file: arch qwen35, 65 blocks,+# full_attention_interval 4, ssm.inner_size 6144, state_size 128, group_count 16, conv_kernel 4.+QWEN38_27B = {+ "_n_layers": 65,+ "_n_kv_heads": 4,+ "_n_heads": 24,+ "_embedding_length": 5120,+ "_kv_key_length": 256,+ "_kv_value_length": 256,+ "_full_attention_interval": 4,+ "_ssm_inner_size": 6144,+ "_ssm_state_size": 128,+ "_ssm_group_count": 16,+ "_ssm_conv_kernel": 4,+}++[email protected](autouse = True)+def _neutral_host(monkeypatch):+ """Keep every case off the runner's own cgroup and inherited llama.cpp settings."""+ monkeypatch.setattr(LlamaCppBackend, "_cgroup_memory_limit_mib", staticmethod(lambda: None))+ monkeypatch.delenv("LLAMA_ARG_CTX_CHECKPOINTS", raising = False)+++def _backend(**overrides):+ b = LlamaCppBackend()+ for key, value in {**QWEN38_27B, **overrides}.items():+ setattr(b, key, value)+ return b+++def _plain_attention_backend():+ return _backend(+ _full_attention_interval = None,+ _ssm_inner_size = None,+ _ssm_state_size = None,+ _ssm_group_count = None,+ _ssm_conv_kernel = None,+ )+++# --------------------------------------------------------------- the per-snapshot cost+++def test_one_snapshot_is_the_whole_recurrent_state():+ """Cross-check the helper against the model metadata."""+ b = _backend()+ d_inner, d_state, n_group, d_conv = 6144, 128, 16, 4+ n_embd_r = (d_conv - 1) * (d_inner + 2 * n_group * d_state)+ n_embd_s = d_state * d_inner+ n_recurrent = 65 - -(-65 // 4)+ assert b._rollback_state_bytes(1) == n_recurrent * (n_embd_r + n_embd_s) * 4+ assert b._rollback_state_bytes(1) == pytest.approx(149.6 * MIB, rel = 0.01)+ assert b._rollback_state_bytes(1) == _backend()._rollback_state_bytes(1)+++def test_a_plain_attention_model_pays_nothing_per_snapshot():+ assert _plain_attention_backend()._rollback_state_bytes(1) == 0+++# --------------------------------------------------------------- the budget arithmetic+++def test_the_default_stands_where_a_snapshot_costs_nothing():+ assert ctx_checkpoints_within_host_budget(0, 4, 94 * GIB) == LLAMA_CTX_CHECKPOINTS_DEFAULT+++def test_the_default_stands_where_the_host_cannot_be_read():+ assert ctx_checkpoints_within_host_budget(150 * MIB, 4, None) == LLAMA_CTX_CHECKPOINTS_DEFAULT+ assert ctx_checkpoints_within_host_budget(150 * MIB, 4, 0) == LLAMA_CTX_CHECKPOINTS_DEFAULT+++def test_the_default_stands_where_it_already_fits():+ assert ctx_checkpoints_within_host_budget(16 * MIB, 4, 256 * GIB) == (+ LLAMA_CTX_CHECKPOINTS_DEFAULT+ )+++def test_the_budget_binds_on_the_reported_hardware():+ got = ctx_checkpoints_within_host_budget(int(149.625 * MIB), 4, 94 * GIB)+ assert got == 8+ assert got * int(149.625 * MIB) * 4 <= int(94 * GIB * 0.05)+++def test_a_small_host_still_keeps_the_floor():+ assert ctx_checkpoints_within_host_budget(600 * MIB, 4, 8 * GIB) == CTX_CHECKPOINTS_MIN_USEFUL+++def test_more_slots_buy_fewer_snapshots_each():+ one = ctx_checkpoints_within_host_budget(int(149.625 * MIB), 1, 94 * GIB)+ four = ctx_checkpoints_within_host_budget(int(149.625 * MIB), 4, 94 * GIB)+ assert one == LLAMA_CTX_CHECKPOINTS_DEFAULT+ assert four == 8+++# --------------------------------------------------------------- what the launcher emits+++def _caps(flag = "--ctx-checkpoints"):+ return {"found": True, "ctx_checkpoints_flag": flag}+++def test_the_launcher_bounds_a_hybrid_recurrent_load(monkeypatch):+ b = _backend()+ monkeypatch.setattr(+ LlamaCppBackend, "_total_system_memory_mib", staticmethod(lambda: 94 * 1024)+ )+ assert b._bounded_ctx_checkpoints(4, _caps()) == 8+++def test_the_launcher_leaves_every_other_load_alone(monkeypatch):+ monkeypatch.setattr(+ LlamaCppBackend, "_total_system_memory_mib", staticmethod(lambda: 94 * 1024)+ )+ assert _plain_attention_backend()._bounded_ctx_checkpoints(4, _caps()) is None+ assert _backend()._bounded_ctx_checkpoints(+ 4, {"found": True, "ctx_checkpoints_flag": None}+ ) is (None)+ assert _backend()._bounded_ctx_checkpoints(1, _caps()) is None+++def test_the_launcher_reads_the_older_flag_spelling(monkeypatch):+ monkeypatch.setattr(+ LlamaCppBackend, "_total_system_memory_mib", staticmethod(lambda: 94 * 1024)+ )+ assert _backend()._bounded_ctx_checkpoints(4, _caps("--swa-checkpoints")) == 8+++def test_an_unreadable_host_leaves_the_launch_alone(monkeypatch):+ monkeypatch.setattr(LlamaCppBackend, "_total_system_memory_mib", staticmethod(lambda: None))+ assert _backend()._bounded_ctx_checkpoints(4, _caps()) is None+++# --------------------------------------------------------------- what the estimate prices+++def test_the_estimator_charges_the_snapshots_on_the_hybrid_path():+ b = _backend()+ without = b._estimate_kv_cache_bytes(159744, "q4_0", n_parallel = 4, ctx_checkpoints = 0)+ with_32 = b._estimate_kv_cache_bytes(159744, "q4_0", n_parallel = 4, ctx_checkpoints = 32)+ assert with_32 - without == 4 * 32 * b._rollback_state_bytes(1)+ assert (with_32 - without) / GIB == pytest.approx(18.7, rel = 0.01)+++def test_the_estimator_charges_them_on_the_legacy_hybrid_arm_too():+ b = _backend(_kv_key_length = None, _kv_value_length = None)+ without = b._estimate_kv_cache_bytes(8192, "f16", n_parallel = 2, ctx_checkpoints = 0)+ with_8 = b._estimate_kv_cache_bytes(8192, "f16", n_parallel = 2, ctx_checkpoints = 8)+ assert with_8 - without == 2 * 8 * b._rollback_state_bytes(1)+++def test_the_checkpoint_charge_does_not_scale_with_context():+ b = _backend()+ delta = lambda ctx: ( # noqa: E731+ b._estimate_kv_cache_bytes(ctx, "q4_0", n_parallel = 4, ctx_checkpoints = 32)+ - b._estimate_kv_cache_bytes(ctx, "q4_0", n_parallel = 4, ctx_checkpoints = 0)+ )+ assert delta(8192) == delta(159744)+++def test_a_plain_attention_model_is_unchanged_by_the_new_term():+ b = _plain_attention_backend()+ without = b._estimate_kv_cache_bytes(32768, "f16", n_parallel = 4, ctx_checkpoints = 0)+ with_32 = b._estimate_kv_cache_bytes(32768, "f16", n_parallel = 4, ctx_checkpoints = 32)+ assert with_32 == without+++# --------------------------------------------------------------- blank is 32, not 0+++def test_a_blank_field_prices_llama_cpps_own_default():+ assert effective_ctx_checkpoints(None, None, supports_flag = True) == (+ LLAMA_CTX_CHECKPOINTS_DEFAULT+ )+++def test_a_blank_field_on_a_hybrid_prices_the_bound_the_launcher_applies():+ assert (+ effective_ctx_checkpoints(+ None,+ None,+ supports_flag = True,+ per_checkpoint_bytes = int(149.625 * MIB),+ n_parallel = 4,+ total_host_bytes = 94 * GIB,+ )+ == 8+ )+++def test_an_explicit_count_is_honoured_whatever_it_costs():+ common = dict(+ supports_flag = True,+ per_checkpoint_bytes = int(149.625 * MIB),+ n_parallel = 4,+ total_host_bytes = 94 * GIB,+ )+ assert effective_ctx_checkpoints(None, 64, **common) == 64+ assert effective_ctx_checkpoints(["--ctx-checkpoints", "64"], None, **common) == 64+ assert effective_ctx_checkpoints(["--ctx-checkpoints", "64"], 4, **common) == 64+++def test_an_explicit_zero_still_means_zero():+ common = dict(+ supports_flag = True,+ per_checkpoint_bytes = int(149.625 * MIB),+ n_parallel = 4,+ total_host_bytes = 94 * GIB,+ )+ assert effective_ctx_checkpoints(None, 0, **common) == 0+ assert effective_ctx_checkpoints(["--ctx-checkpoints", "0"], None, **common) == 0+++def test_a_build_without_the_flag_allocates_none():+ assert effective_ctx_checkpoints(None, 32, supports_flag = False) == 0+++# --------------------------------------------------------------- the probe's third state+++class TestAnInconclusiveProbeIsNotProofOfAbsence:+ """An unanswered help probe is not proof that checkpoints are absent."""++ # A real successful parse always yields a catalogue, so every "the help ran" case+ # here carries one; an empty catalogue is silence, covered separately below.+ _PARSED = {"--flash-attn": "...", "--cache-ram": "..."}++ def test_a_help_that_ran_and_named_neither_alias_is_zero(self):+ assert (+ ctx_checkpoints_allocated({"found": True, "help_probe_ok": True, "flags": self._PARSED})+ is False+ )++ def test_an_exit_zero_probe_that_parsed_nothing_is_not_absence(self):+ """A wrapper that prints no help would otherwise zero the whole snapshot pool."""+ empty = {"found": True, "help_probe_ok": True, "flags": {}}+ assert ctx_checkpoints_allocated(empty) is True+ assert ctx_checkpoints_allocated({"found": True, "help_probe_ok": True}) is True+ assert (+ effective_ctx_checkpoints_for_caps(+ empty,+ None,+ None,+ per_checkpoint_bytes = int(149.625 * MIB),+ n_parallel = 4,+ total_host_bytes = 94 * GIB,+ )+ == LLAMA_CTX_CHECKPOINTS_DEFAULT+ )++ def test_a_real_empty_help_probe_prices_the_default(self, tmp_path):+ """End to end: a binary that exits 0 and says nothing must not read as absence."""+ fake = tmp_path / "llama-server"+ fake.write_text("#!/bin/sh\nexit 0\n")+ fake.chmod(0o755)+ caps = LlamaCppBackend.probe_server_capabilities(str(fake))+ assert caps["found"] is True and caps["help_probe_ok"] is True+ assert not caps["flags"] and caps["ctx_checkpoints_flag"] is None+ assert ctx_checkpoints_allocated(caps) is True+ backend = _backend()+ assert (+ effective_ctx_checkpoints_for_caps(+ caps,+ None,+ None,+ per_checkpoint_bytes = backend._rollback_state_bytes(1),+ n_parallel = 4,+ total_host_bytes = 94 * GIB,+ )+ == LLAMA_CTX_CHECKPOINTS_DEFAULT+ )++ def test_a_named_flag_is_priced(self):+ assert (+ ctx_checkpoints_allocated(+ {"found": True, "help_probe_ok": True, "ctx_checkpoints_flag": "--ctx-checkpoints"}+ )+ is True+ )++ @pytest.mark.parametrize(+ "caps",+ [+ pytest.param({"found": True, "help_probe_ok": False}, id = "probe-crashed"),+ pytest.param({"found": False, "help_probe_ok": False}, id = "no-binary-read"),+ pytest.param({}, id = "empty-caps"),+ ],+ )+ def test_an_unanswered_probe_keeps_the_default(self, caps):+ assert ctx_checkpoints_allocated(caps) is True+ got = effective_ctx_checkpoints_for_caps(+ caps,+ None,+ None,+ per_checkpoint_bytes = int(149.625 * MIB),+ n_parallel = 4,+ total_host_bytes = 94 * GIB,+ )+ assert got == LLAMA_CTX_CHECKPOINTS_DEFAULT++ def test_the_budget_narrows_only_once_the_flag_is_named(self):+ budget = dict(+ per_checkpoint_bytes = int(149.625 * MIB), n_parallel = 4, total_host_bytes = 94 * GIB+ )+ named = {"found": True, "help_probe_ok": True, "ctx_checkpoints_flag": "--ctx-checkpoints"}+ unnamed = {"found": True, "help_probe_ok": False, "ctx_checkpoints_flag": None}+ assert effective_ctx_checkpoints_for_caps(named, None, None, **budget) == 8+ assert effective_ctx_checkpoints_for_caps(unnamed, None, None, **budget) == (+ LLAMA_CTX_CHECKPOINTS_DEFAULT+ )++ @pytest.mark.parametrize(+ "caps",+ [+ pytest.param(+ {"found": True, "help_probe_ok": True, "ctx_checkpoints_flag": "--ctx-checkpoints"},+ id = "flag-named",+ ),+ pytest.param(+ {"found": True, "help_probe_ok": True, "ctx_checkpoints_flag": "--swa-checkpoints"},+ id = "older-alias",+ ),+ pytest.param(+ {"found": True, "help_probe_ok": False, "ctx_checkpoints_flag": None},+ id = "probe-crashed",+ ),+ pytest.param({"found": False, "help_probe_ok": False}, id = "no-binary-read"),+ pytest.param({}, id = "empty-caps"),+ pytest.param(+ {"found": True, "help_probe_ok": True, "ctx_checkpoints_flag": None},+ id = "help-ran-named-neither",+ ),+ ],+ )+ def test_what_is_priced_is_what_the_launch_will_run(self, caps, monkeypatch):+ """The priced count must match the count Studio can place in the command."""+ monkeypatch.setattr(+ LlamaCppBackend, "_total_system_memory_mib", staticmethod(lambda: 94 * 1024)+ )+ backend = _backend()+ for requested in (None, 0, 4, 64):+ priced = effective_ctx_checkpoints_for_caps(+ caps,+ None,+ requested,+ per_checkpoint_bytes = backend._rollback_state_bytes(1),+ n_parallel = 4,+ total_host_bytes = 94 * GIB,+ )+ if not ctx_checkpoints_allocated(caps):+ expected = 0+ elif not caps.get("ctx_checkpoints_flag") and caps.get("found"):+ expected = LLAMA_CTX_CHECKPOINTS_DEFAULT+ elif not caps.get("ctx_checkpoints_flag"):+ expected = requested if requested is not None else LLAMA_CTX_CHECKPOINTS_DEFAULT+ elif requested is not None:+ expected = requested+ else:+ emitted = backend._bounded_ctx_checkpoints(4, caps)+ expected = emitted if emitted is not None else LLAMA_CTX_CHECKPOINTS_DEFAULT+ assert priced == expected, (caps, requested)++ def test_a_pass_through_count_is_honoured_even_on_an_unreadable_probe(self):+ caps = {"found": True, "help_probe_ok": False, "ctx_checkpoints_flag": None}+ budget = dict(+ per_checkpoint_bytes = int(149.625 * MIB), n_parallel = 4, total_host_bytes = 94 * GIB+ )+ assert (+ effective_ctx_checkpoints_for_caps(caps, ["--ctx-checkpoints", "64"], None, **budget)+ == 64+ )+ assert (+ effective_ctx_checkpoints_for_caps(caps, ["--ctx-checkpoints", "0"], None, **budget)+ == 0+ )+ assert (+ effective_ctx_checkpoints_for_caps(caps, ["--ctx-checkpoints", "64"], 4, **budget) == 64+ )++ def test_the_launcher_still_will_not_name_a_flag_it_cannot_confirm(self, monkeypatch):+ monkeypatch.setattr(+ LlamaCppBackend, "_total_system_memory_mib", staticmethod(lambda: 94 * 1024)+ )+ caps = {"found": True, "help_probe_ok": False, "ctx_checkpoints_flag": None}+ assert ctx_checkpoints_allocated(caps) is True+ assert _backend()._bounded_ctx_checkpoints(4, caps) is None++ def test_every_pricing_site_goes_through_the_one_entry_point(self):+ import inspect++ from routes import inference as inference_routes+ from routes import models as models_routes++ for source in (+ inspect.getsource(inference_routes._gguf_runtime_bytes),+ inspect.getsource(models_routes.get_kv_cache_estimate),+ inspect.getsource(LlamaCppBackend.load_model),+ ):+ assert "effective_ctx_checkpoints_for_caps(" in source+ assert "supports_flag = " not in source+++# --------------------------------------------------------------- and never against VRAM+++class TestCheckpointsNeverReachAVramFigure:+ """Checkpoint storage must not be charged to VRAM."""++ def test_the_planner_and_the_launcher_agree_on_one_count(self):+ import inspect++ source = inspect.getsource(LlamaCppBackend.load_model)+ # One rule, re-asked wherever the slot count changes, never a second spelling.+ assert source.count("def _decide_auto_ctx_checkpoints(") == 1+ assert "self._bounded_ctx_checkpoints(n_parallel, server_caps, extra_args)" in source+ assert source.count("self._bounded_ctx_checkpoints(") == 1+ assert "str(_auto_ctx_checkpoints)" in source++ def test_the_snapshots_are_host_only_in_the_load_mode_footprint(self):+ import inspect++ source = inspect.getsource(LlamaCppBackend.load_model)+ assert "kv_cache_bytes = _kv_bytes(effective_ctx, 0)," in source+ assert "host_only_bytes = (_cpu_draft_fit_bytes or 0) + _ckpt_host_bytes," in source+ assert "_kv_bytes(effective_ctx, _effective_ctx_checkpoints)" in source+ assert "- _kv_bytes(effective_ctx, 0)," in source++ def test_the_windows_tuning_is_not_handed_a_second_count(self):+ import inspect++ source = inspect.getsource(LlamaCppBackend.load_model)+ emit = source.index("str(_auto_ctx_checkpoints)")+ tuning = source.index(+ '_cache_flags_emitted.extend([str(server_caps["ctx_checkpoints_flag"]), "0"])'+ )+ assert emit > tuning, "the automatic cap must be emitted after the Windows tuning"+ assert "_flag_name(str(token)) in _CTX_CHECKPOINTS_FLAGS" in source++ def test_the_fit_does_not_charge_a_recurrent_snapshot(self):+ import inspect++ source = inspect.getsource(LlamaCppBackend.load_model)+ assert "0 if self._rollback_state_bytes(1) > 0 else _requested_ctx_checkpoints" in source+ assert source.count("ctx_checkpoints = _fit_ctx_checkpoints,") == 7+ assert source.count("_kv_bytes(effective_ctx, _effective_ctx_checkpoints)") == 1++ def test_the_fit_is_unmoved_by_the_new_term(self):+ b = _backend()+ assert (+ b._fit_context_to_vram(262144, 24 * 1024, 16 * 1024**3, "q4_0", n_parallel = 4) == 262144+ )+ assert b._estimate_kv_cache_bytes(+ 262144, "q4_0", n_parallel = 4, ctx_checkpoints = 32+ ) > b._estimate_kv_cache_bytes(262144, "q4_0", n_parallel = 4, ctx_checkpoints = 0)++ def test_the_training_guard_nets_them_out(self):+ import inspect++ from routes import inference as inference_routes++ source = inspect.getsource(inference_routes._estimate_gguf_kv_gb)+ assert "runtime.kv_bytes - runtime.kv_checkpoint_bytes" in source+ assert "runtime.kv_bytes + runtime.compute_bytes" not in source+ # ...but only against a pool that is really separate from host RAM.+ assert "if shared_memory_pool" in source+++def test_the_launcher_stands_down_for_a_typed_count(monkeypatch):+ monkeypatch.setattr(+ LlamaCppBackend, "_total_system_memory_mib", staticmethod(lambda: 94 * 1024)+ )+ b = _backend()+ assert b._bounded_ctx_checkpoints(4, _caps(), ["--ctx-checkpoints", "64"]) is None+ assert b._bounded_ctx_checkpoints(4, _caps(), ["--swa-checkpoints=0"]) is None+ assert b._bounded_ctx_checkpoints(4, _caps(), ["--top-k", "20"]) == 8+++def test_a_kda_hybrid_is_priced_wherever_it_is_bounded():+ b = LlamaCppBackend()+ for key, value in {+ "_n_layers": 8,+ "_n_heads": 8,+ "_n_kv_heads": 1,+ "_kv_lora_rank": 512,+ "_key_length_mla": 64,+ "_kda_head_dim": 128,+ "_ssm_conv_kernel": 4,+ "_n_kv_heads_by_layer": [1, 0, 1, 0, 1, 0, 1, 0],+ }.items():+ setattr(b, key, value)+ assert b._rollback_state_bytes(1) > 0+ without = b._estimate_kv_cache_bytes(8192, "f16", n_parallel = 2, ctx_checkpoints = 0)+ with_8 = b._estimate_kv_cache_bytes(8192, "f16", n_parallel = 2, ctx_checkpoints = 8)+ assert with_8 - without == 2 * 8 * b._rollback_state_bytes(1)+++# --------------------------------------------------------------- inside a memory-limited container+++class TestTheBudgetIsWhatThisProcessMayCharge:+ """MemTotal is the host's; a cgroup limit is what the child may actually allocate."""++ def _container(self, monkeypatch, host_gib, cgroup_gib):+ monkeypatch.setattr(+ LlamaCppBackend, "_total_system_memory_mib", staticmethod(lambda: host_gib * 1024)+ )+ monkeypatch.setattr(+ LlamaCppBackend,+ "_cgroup_memory_limit_mib",+ staticmethod(lambda: None if cgroup_gib is None else cgroup_gib * 1024),+ )++ def test_the_capacity_is_the_tighter_of_the_two(self, monkeypatch):+ self._container(monkeypatch, 256, 8)+ assert LlamaCppBackend._host_memory_capacity_mib() == 8 * 1024+ self._container(monkeypatch, 8, 256)+ assert LlamaCppBackend._host_memory_capacity_mib() == 8 * 1024++ def test_an_uncapped_host_keeps_its_own_total(self, monkeypatch):+ self._container(monkeypatch, 94, None)+ assert LlamaCppBackend._host_memory_capacity_mib() == 94 * 1024++ def test_an_unreadable_host_falls_back_to_the_limit(self, monkeypatch):+ monkeypatch.setattr(LlamaCppBackend, "_total_system_memory_mib", staticmethod(lambda: None))+ monkeypatch.setattr(+ LlamaCppBackend, "_cgroup_memory_limit_mib", staticmethod(lambda: 8 * 1024)+ )+ assert LlamaCppBackend._host_memory_capacity_mib() == 8 * 1024+ monkeypatch.setattr(LlamaCppBackend, "_cgroup_memory_limit_mib", staticmethod(lambda: None))+ assert LlamaCppBackend._host_memory_capacity_mib() is None++ def test_the_cap_fits_the_container_not_the_host(self, monkeypatch):+ """A 256 GiB host with an 8 GiB cgroup must not be given the host's 5%."""+ backend = _backend()+ per_slot_round = backend._rollback_state_bytes(1) * 4+ self._container(monkeypatch, 256, None)+ uncapped = backend._bounded_ctx_checkpoints(4, _caps())+ assert uncapped * per_slot_round > 8 * GIB, "the host-wide budget overruns the container"+ self._container(monkeypatch, 256, 8)+ bounded = backend._bounded_ctx_checkpoints(4, _caps())+ assert bounded == CTX_CHECKPOINTS_MIN_USEFUL+ assert bounded * per_slot_round < 8 * GIB++ def test_the_priced_count_is_still_the_emitted_one(self, monkeypatch):+ """The container must not split the planner's figure from the launched argv."""+ self._container(monkeypatch, 256, 8)+ backend = _backend()+ capacity = LlamaCppBackend._host_memory_capacity_mib()+ assert effective_ctx_checkpoints_for_caps(+ _caps(),+ None,+ None,+ per_checkpoint_bytes = backend._rollback_state_bytes(1),+ n_parallel = 4,+ total_host_bytes = capacity * MIB,+ ) == backend._bounded_ctx_checkpoints(4, _caps())++ def test_every_budget_site_reads_the_capacity(self):+ import inspect++ from routes import inference as inference_routes+ from routes import models as models_routes++ for source in (+ inspect.getsource(inference_routes._gguf_runtime_bytes),+ inspect.getsource(models_routes.get_kv_cache_estimate),+ inspect.getsource(LlamaCppBackend.load_model),+ inspect.getsource(LlamaCppBackend._bounded_ctx_checkpoints),+ ):+ assert "_host_memory_capacity_mib" in source+ assert "_total_system_memory_mib" not in source+++# --------------------------------------------------------------- across the arch-crash retry+++class TestTheCapSurvivesAWindowsDeviceRetry:+ """The retry re-decides the Windows cache tuning; the automatic cap must follow it."""++ def test_a_stated_cap_would_swallow_the_windows_zero(self):+ """Why the retry strips the pair first: the skip means 'the user typed one'."""+ caps = {"supports_cache_ram": True, "ctx_checkpoints_flag": "--ctx-checkpoints"}+ with_cap = ["llama-server", "-m", "x.gguf", "--ctx-checkpoints", "8"]+ assert LlamaCppBackend._retry_cache_tuning_flags(+ with_cap, cache_ram = None, ctx_checkpoints = None, server_caps = caps+ ) == ["--cache-ram", "0"]+ stripped = LlamaCppBackend._without_flag_pairs(with_cap, ["--ctx-checkpoints", "8"])+ assert LlamaCppBackend._retry_cache_tuning_flags(+ stripped, cache_ram = None, ctx_checkpoints = None, server_caps = caps+ ) == ["--cache-ram", "0", "--ctx-checkpoints", "0"]++ def test_a_typed_count_still_outranks_the_retry(self):+ caps = {"supports_cache_ram": True, "ctx_checkpoints_flag": "--ctx-checkpoints"}+ typed = ["llama-server", "--ctx-checkpoints", "64"]+ assert LlamaCppBackend._retry_cache_tuning_flags(+ typed, cache_ram = None, ctx_checkpoints = None, server_caps = caps+ ) == ["--cache-ram", "0"]++ def test_the_retry_strips_the_cap_then_re_emits_it(self):+ import inspect++ source = inspect.getsource(LlamaCppBackend.load_model)+ # One emission rule for the launch and every respawn, not a spelling each.+ assert source.count("def _emit_auto_ctx_checkpoints(") == 1+ # The launch, the arch-crash respawn, and the single-sequence retry.+ assert source.count("_emit_auto_ctx_checkpoints(cmd)") == 3+ # Every respawn that re-emits first takes back the pair it is replacing.+ assert source.count("self._without_flag_pairs(cmd, _auto_ckpt_emitted)") == 2+ tuning = source.index("_retry_cache_tuning_flags(")+ strip = source.index("self._without_flag_pairs(cmd, _auto_ckpt_emitted)")+ re_emit = source.index("_emit_auto_ctx_checkpoints(cmd)", tuning)+ assert strip < tuning < re_emit, "strip, re-decide the tuning, then re-apply the cap"++ def test_the_single_sequence_retry_re_decides_the_cap_for_one_slot(self):+ """llama-server refusing a unified cache drops to one slot, which affords more."""+ import inspect++ source = inspect.getsource(LlamaCppBackend.load_model)+ clamp = source.index("n_parallel = 1 # allow-slot-clamp: llama-server refused more")+ strip = source.index("self._without_flag_pairs(cmd, _auto_ckpt_emitted)", clamp)+ decide = source.index("_auto_ctx_checkpoints = _decide_auto_ctx_checkpoints()", clamp)+ emit = source.index("_emit_auto_ctx_checkpoints(cmd)", clamp)+ spawn = source.index('_spawn_and_wait(cmd, label = "-single-seq")')+ assert clamp < strip < decide < emit < spawn, "re-decide for one slot before spawning"+++# --------------------------------------------------------------- what THIS build defaults to+++class TestTheCapNeverRaisesTheBuildsOwnDefault:+ """The flag shipped at 3 as --swa-checkpoints (ggml-org/llama.cpp#15293) and is 32 now."""++ def _caps_with_default(+ self,+ advertised,+ flag = "--ctx-checkpoints",+ ):+ return {+ "found": True,+ "help_probe_ok": True,+ "ctx_checkpoints_flag": flag,+ "ctx_checkpoints_default": advertised,+ }++ @pytest.mark.parametrize(+ "block, expected",+ [+ pytest.param(+ "-ctxcp, --ctx-checkpoints, --swa-checkpoints N max number of context checkpoints"+ " to create per slot (default: 32)[(more info)](https://github.com/ggml-org/"+ "llama.cpp/pull/15293) (env: LLAMA_ARG_CTX_CHECKPOINTS)",+ 32,+ id = "today-wrapped-across-columns",+ ),+ pytest.param(+ "--swa-checkpoints N max number of SWA checkpoints per slot to create"+ " (default: 3)",+ 3,+ id = "as-it-shipped",+ ),+ pytest.param(+ "--ctx-checkpoints N number of context checkpoints (default: 0)", 0, id = "zero"+ ),+ pytest.param("--ctx-checkpoints N number of context checkpoints", None, id = "silent"),+ pytest.param(None, None, id = "no-block"),+ ],+ )+ def test_the_advertised_default_is_read_from_the_help_block(self, block, expected):+ assert LlamaCppBackend._advertised_int_default(block) == expected++ def test_a_silent_build_falls_back_to_upstreams_default_today(self):+ assert ctx_checkpoints_default_for_caps({}) == LLAMA_CTX_CHECKPOINTS_DEFAULT+ assert (+ ctx_checkpoints_default_for_caps(self._caps_with_default(None))+ == LLAMA_CTX_CHECKPOINTS_DEFAULT+ )+ assert ctx_checkpoints_default_for_caps(self._caps_with_default(3)) == 3+ assert ctx_checkpoints_default_for_caps(self._caps_with_default(0)) == 0++ def test_a_build_that_keeps_three_is_never_pushed_to_eight(self, monkeypatch):+ """94 GiB affords 8, but this build would only have kept 3 unflagged."""+ monkeypatch.setattr(+ LlamaCppBackend, "_total_system_memory_mib", staticmethod(lambda: 94 * 1024)+ )+ backend = _backend()+ caps = self._caps_with_default(3, flag = "--swa-checkpoints")+ assert backend._bounded_ctx_checkpoints(4, _caps("--swa-checkpoints")) == 8+ assert backend._bounded_ctx_checkpoints(4, caps) is None++ def test_a_build_that_disables_them_is_left_disabled(self, monkeypatch):+ monkeypatch.setattr(+ LlamaCppBackend, "_total_system_memory_mib", staticmethod(lambda: 94 * 1024)+ )+ backend = _backend()+ caps = self._caps_with_default(0)+ assert backend._bounded_ctx_checkpoints(4, caps) is None+ assert (+ effective_ctx_checkpoints_for_caps(+ caps,+ None,+ None,+ per_checkpoint_bytes = backend._rollback_state_bytes(1),+ n_parallel = 4,+ total_host_bytes = 94 * GIB,+ )+ == 0+ )++ def test_a_small_default_still_gets_capped_on_a_tiny_host(self, monkeypatch):+ """Capping below the build's own default is still allowed, and still floored at 2."""+ monkeypatch.setattr(+ LlamaCppBackend, "_total_system_memory_mib", staticmethod(lambda: 4 * 1024)+ )+ backend = _backend()+ assert backend._bounded_ctx_checkpoints(4, self._caps_with_default(3)) == (+ CTX_CHECKPOINTS_MIN_USEFUL+ )++ def test_the_floor_never_climbs_above_the_default(self):+ for default in (0, 1, 2, 3):+ got = ctx_checkpoints_within_host_budget(+ int(149.625 * MIB), 4, 1 * GIB, upstream_default = default+ )+ assert got <= default, default++ def test_the_priced_count_is_the_builds_own_default_for_a_blank_field(self):+ for default in (0, 3, 32):+ caps = self._caps_with_default(default)+ assert (+ effective_ctx_checkpoints_for_caps(+ caps, None, None, per_checkpoint_bytes = 0, n_parallel = 4, total_host_bytes = None+ )+ == default+ )++ def test_an_explicit_count_still_outranks_the_advertised_default(self):+ caps = self._caps_with_default(3)+ budget = dict(+ per_checkpoint_bytes = int(149.625 * MIB), n_parallel = 4, total_host_bytes = 94 * GIB+ )+ assert effective_ctx_checkpoints_for_caps(caps, None, 64, **budget) == 64+ assert (+ effective_ctx_checkpoints_for_caps(caps, ["--ctx-checkpoints", "64"], None, **budget)+ == 64+ )+++# --------------------------------------------------------------- an inherited env setting+++class TestAnInheritedEnvCountIsTheOperatorsSetting:+ """llama.cpp applies LLAMA_ARG_CTX_CHECKPOINTS before argv, so an emitted flag overrules it."""++ def _host(+ self,+ monkeypatch,+ gib = 94,+ ):+ monkeypatch.setattr(+ LlamaCppBackend, "_total_system_memory_mib", staticmethod(lambda: gib * 1024)+ )++ def test_the_launcher_stands_down_for_an_inherited_count(self, monkeypatch):+ self._host(monkeypatch)+ backend = _backend()+ assert backend._bounded_ctx_checkpoints(4, _caps()) == 8+ monkeypatch.setenv("LLAMA_ARG_CTX_CHECKPOINTS", "256")+ assert backend._bounded_ctx_checkpoints(4, _caps()) is None+ monkeypatch.setenv("LLAMA_ARG_CTX_CHECKPOINTS", "0")+ assert backend._bounded_ctx_checkpoints(4, _caps()) is None++ def test_an_unparseable_env_value_is_left_to_llama_cpp(self, monkeypatch):+ self._host(monkeypatch)+ for raw in ("", " ", "many", "-1"):+ monkeypatch.setenv("LLAMA_ARG_CTX_CHECKPOINTS", raw)+ assert _backend()._bounded_ctx_checkpoints(4, _caps()) == 8, raw++ def test_the_estimate_prices_the_inherited_count(self, monkeypatch):+ backend = _backend()+ budget = dict(+ per_checkpoint_bytes = backend._rollback_state_bytes(1),+ n_parallel = 4,+ total_host_bytes = 94 * GIB,+ )+ monkeypatch.setenv("LLAMA_ARG_CTX_CHECKPOINTS", "256")+ assert effective_ctx_checkpoints_for_caps(_caps(), None, None, **budget) == 256+ monkeypatch.setenv("LLAMA_ARG_CTX_CHECKPOINTS", "0")+ assert effective_ctx_checkpoints_for_caps(_caps(), None, None, **budget) == 0+ monkeypatch.delenv("LLAMA_ARG_CTX_CHECKPOINTS")+ assert effective_ctx_checkpoints_for_caps(_caps(), None, None, **budget) == 8++ def test_argv_still_outranks_the_environment(self, monkeypatch):+ """Studio appends its flag after llama.cpp has read the variable, so argv wins."""+ monkeypatch.setenv("LLAMA_ARG_CTX_CHECKPOINTS", "256")+ budget = dict(+ per_checkpoint_bytes = int(149.625 * MIB), n_parallel = 4, total_host_bytes = 94 * GIB+ )+ assert effective_ctx_checkpoints_for_caps(_caps(), None, 4, **budget) == 4+ assert (+ effective_ctx_checkpoints_for_caps(_caps(), ["--ctx-checkpoints", "64"], None, **budget)+ == 64+ )+ assert (+ effective_ctx_checkpoints_for_caps(_caps(), ["--ctx-checkpoints", "0"], None, **budget)+ == 0+ )++ def test_the_windows_tuning_does_not_zero_an_inherited_count(self):+ """The tuning stands down for the field; the variable is the same instruction."""+ import inspect++ source = inspect.getsource(LlamaCppBackend.load_model)+ assert "_ctx_checkpoints_owned = (" in source+ assert "else _env_ctx_checkpoints_override()" in source+ # The tuning's zero and the arch-crash retry both read the combined value.+ assert "if _ctx_checkpoints_owned is not None:" in source+ assert "ctx_checkpoints = _ctx_checkpoints_owned," in source+ owned = source.index("_ctx_checkpoints_owned = (")+ zero = source.index(+ '_cache_flags_emitted.extend([str(server_caps["ctx_checkpoints_flag"]), "0"])'+ )+ assert owned < zero, "decide ownership before the tuning would zero it"++ def test_the_retry_tuning_also_respects_an_inherited_count(self):+ """_retry_cache_tuning_flags reads the same combined value as the launch."""+ caps = {"supports_cache_ram": True, "ctx_checkpoints_flag": "--ctx-checkpoints"}+ cmd = ["llama-server", "-m", "x.gguf"]+ assert LlamaCppBackend._retry_cache_tuning_flags(+ cmd, cache_ram = None, ctx_checkpoints = None, server_caps = caps+ ) == ["--cache-ram", "0", "--ctx-checkpoints", "0"]+ # What load_model now passes when LLAMA_ARG_CTX_CHECKPOINTS is set.+ assert LlamaCppBackend._retry_cache_tuning_flags(+ cmd, cache_ram = None, ctx_checkpoints = 256, server_caps = caps+ ) == ["--cache-ram", "0"]++ def test_an_explicit_env_map_is_used_over_the_process_environment(self, monkeypatch):+ self._host(monkeypatch)+ monkeypatch.delenv("LLAMA_ARG_CTX_CHECKPOINTS", raising = False)+ assert (+ _backend()._bounded_ctx_checkpoints(+ 4, _caps(), None, {"LLAMA_ARG_CTX_CHECKPOINTS": "256"}+ )+ is None+ )+ assert (+ effective_ctx_checkpoints_for_caps(+ _caps(),+ None,+ None,+ per_checkpoint_bytes = int(149.625 * MIB),+ n_parallel = 4,+ total_host_bytes = 94 * GIB,+ env = {"LLAMA_ARG_CTX_CHECKPOINTS": "256"},+ )+ == 256+ )+++# --------------------------------------------------------------- after the fit picks the slots+++class TestTheCapFollowsTheSlotCountTheChildGets:+ """The fit can cut n_parallel below the request; a cap sized for the request is wrong."""++ def test_the_cap_is_slot_sensitive_at_all(self, monkeypatch):+ monkeypatch.setattr(+ LlamaCppBackend, "_total_system_memory_mib", staticmethod(lambda: 94 * 1024)+ )+ backend = _backend()+ assert backend._bounded_ctx_checkpoints(32, _caps()) == CTX_CHECKPOINTS_MIN_USEFUL+ # One slot affords the whole default, so nothing is emitted and nothing is lost.+ assert backend._bounded_ctx_checkpoints(1, _caps()) is None++ def test_both_counts_are_decided_after_the_fit_rebinds_the_slots(self):+ """Structural, because the reduction sits ~2000 lines inside one function."""+ import ast+ import inspect+ import textwrap++ source, first = inspect.getsourcelines(LlamaCppBackend.load_model)+ tree = ast.parse(textwrap.dedent("".join(source)))+ fit_rebinds = [+ node.lineno+ for node in ast.walk(tree)+ if isinstance(node, ast.Assign)+ and any(+ isinstance(t, ast.Tuple)+ and any(isinstance(e, ast.Name) and e.id == "n_parallel" for e in t.elts)+ for t in node.targets+ )+ ]+ assert fit_rebinds, "the fit no longer rebinds n_parallel; re-check this ordering"+ decisions = [+ node.lineno+ for node in ast.walk(tree)+ if isinstance(node, ast.Assign)+ and any(+ isinstance(t, ast.Name) and t.id == "_auto_ctx_checkpoints" for t in node.targets+ )+ ] + [+ node.lineno+ for node in ast.walk(tree)+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Name)+ and node.func.id == "_ctx_checkpoints_for_final_slots"+ ]+ assert len(decisions) >= 2, decisions+ assert min(decisions) > max(fit_rebinds), (decisions, fit_rebinds)+++# --------------------------------------------------------------- one pool or two+++class TestTheGuardOnlyDropsHostBytesFromADiscretePool:+ """On an iGPU or an APU the driver's free VRAM IS the host heap, so nothing may leave."""++ def _shares(self, **kwargs):+ from routes import inference as inference_routes+ return inference_routes._admission_pool_shares_host_ram(**kwargs)++ def test_an_integrated_vulkan_device_shares(self):+ # Vulkan reports total 0 only for an integrated GPU.+ assert self._shares(is_vulkan_backend = True, vulkan_gpu_memory = [(0, 8192, 0)]) is True++ def test_a_discrete_vulkan_device_does_not(self):+ assert self._shares(is_vulkan_backend = True, vulkan_gpu_memory = [(0, 8192, 24576)]) is False++ def test_a_confirmed_ordinal_pin_narrows_the_rows(self):+ """A mixed host pinned to the discrete adapter is checked against that adapter."""+ mixed = [(0, 8192, 0), (1, 8192, 24576)]+ assert (+ self._shares(+ is_vulkan_backend = True,+ vulkan_gpu_memory = mixed,+ requested_gpu_ids = [1],+ gpu_ids_are_vulkan_ordinals = True,+ )+ is False+ )+ assert (+ self._shares(+ is_vulkan_backend = True,+ vulkan_gpu_memory = mixed,+ requested_gpu_ids = [0],+ gpu_ids_are_vulkan_ordinals = True,+ )+ is True+ )++ def test_a_pin_in_an_unconfirmed_index_space_reads_every_row(self):+ """A physical id read as a Vulkan ordinal would answer for the wrong adapter."""+ mixed = [(0, 8192, 0), (1, 8192, 24576)]+ assert (+ self._shares(is_vulkan_backend = True, vulkan_gpu_memory = mixed, requested_gpu_ids = [1])+ is True+ )++ def test_a_pin_that_matches_no_row_fails_closed(self):+ assert (+ self._shares(+ is_vulkan_backend = True,+ vulkan_gpu_memory = [(0, 8192, 24576)],+ requested_gpu_ids = [7],+ gpu_ids_are_vulkan_ordinals = True,+ )+ is True+ )++ def test_a_mixed_or_unreadable_vulkan_inventory_fails_closed(self):+ assert self._shares(is_vulkan_backend = True, vulkan_gpu_memory = []) is True+ assert self._shares(is_vulkan_backend = True, vulkan_gpu_memory = None) is True+ assert (+ self._shares(is_vulkan_backend = True, vulkan_gpu_memory = [(0, 8192, 24576), (1, 4096, 0)])+ is True+ )++ def _rocm(self, monkeypatch, *, answered, unified):+ monkeypatch.setattr(LlamaCppBackend, "_torch_is_rocm", staticmethod(lambda _t: True))+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_classification_answered", staticmethod(lambda: answered)+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_rocm_unified_memory_gpu_ids", staticmethod(lambda: unified)+ )++ def _cuda(self, monkeypatch, *, probe_free, integrated):+ monkeypatch.setattr(LlamaCppBackend, "_torch_is_rocm", staticmethod(lambda _t: False))+ monkeypatch.setattr(+ LlamaCppBackend, "_integrated_cuda_probe_is_free", staticmethod(lambda: probe_free)+ )++ def _must_not_probe():+ raise AssertionError("must not probe CUDA while training holds the card")++ monkeypatch.setattr(+ LlamaCppBackend,+ "_integrated_cuda_gpu_ids",+ staticmethod((lambda: integrated) if probe_free else _must_not_probe),+ )++ def test_a_discrete_cuda_host_keeps_the_subtraction(self, monkeypatch):+ self._cuda(monkeypatch, probe_free = True, integrated = set())+ assert self._shares(is_vulkan_backend = False, requested_gpu_ids = [0]) is False++ def test_an_integrated_cuda_part_shares(self, monkeypatch):+ """Jetson and DGX Spark set cudaDeviceProp::integrated and have one pool."""+ self._cuda(monkeypatch, probe_free = True, integrated = {0})+ assert self._shares(is_vulkan_backend = False, requested_gpu_ids = [0]) is True++ def test_an_uncached_cuda_classification_is_never_probed_for(self, monkeypatch):+ """The probe pins ~700 MiB per card for the process, and training holds them."""+ self._cuda(monkeypatch, probe_free = False, integrated = set())+ assert self._shares(is_vulkan_backend = False, requested_gpu_ids = [0]) is True++ def test_a_rocm_apu_shares_whether_or_not_it_is_pinned(self, monkeypatch):+ self._rocm(monkeypatch, answered = True, unified = {0})+ assert self._shares(is_vulkan_backend = False, requested_gpu_ids = [0]) is True+ assert self._shares(is_vulkan_backend = False, requested_gpu_ids = None) is True+ # A discrete sibling that is explicitly pinned is its own pool.+ assert self._shares(is_vulkan_backend = False, requested_gpu_ids = [1]) is False++ def test_a_rocm_host_with_no_apu_is_discrete(self, monkeypatch):+ self._rocm(monkeypatch, answered = True, unified = set())+ assert self._shares(is_vulkan_backend = False, requested_gpu_ids = [0]) is False++ def test_an_unanswered_rocm_classification_is_not_evidence_of_a_discrete_pool(+ self, monkeypatch+ ):+ """The classifier skips a device it cannot query, so empty is ambiguous there."""+ self._rocm(monkeypatch, answered = False, unified = set())+ assert self._shares(is_vulkan_backend = False, requested_gpu_ids = [0]) is True++ def test_an_unreadable_classifier_keeps_the_charge(self, monkeypatch):+ def _boom():+ raise RuntimeError("no driver")++ monkeypatch.setattr(LlamaCppBackend, "_torch_is_rocm", staticmethod(lambda _t: True))+ monkeypatch.setattr(LlamaCppBackend, "_rocm_classification_answered", staticmethod(_boom))+ assert self._shares(is_vulkan_backend = False, requested_gpu_ids = [0]) is True++ def test_the_figure_follows_the_verdict(self, tmp_path, monkeypatch):+ """The same runtime, priced against one pool and against two."""+ from routes import inference as inference_routes++ class _Runtime:+ kv_bytes = 10 * GIB+ kv_checkpoint_bytes = 4 * GIB+ compute_bytes = 1 * GIB++ monkeypatch.setattr(inference_routes, "_gguf_runtime_bytes", lambda *a, **k: _Runtime())+ shared = inference_routes._estimate_gguf_kv_gb("x.gguf", 4096)+ discrete = inference_routes._estimate_gguf_kv_gb("x.gguf", 4096, shared_memory_pool = False)+ assert shared == 11.0 and discrete == 7.0+ assert shared > discrete, "the shared pool must not be credited the host share"diff --git a/studio/backend/tests/test_kv_cache_estimate_route.py b/studio/backend/tests/test_kv_cache_estimate_route.pyindex ae216573966..578d3b27879 100644--- a/studio/backend/tests/test_kv_cache_estimate_route.py+++ b/studio/backend/tests/test_kv_cache_estimate_route.py@@ -522,13 +522,20 @@ class TestTheEstimateMatchesTheConfiguredLoad:"attention.sliding_window_pattern": [True, True, True, False],}gguf = _write_gguf(tmp_path / "swa-Q4_K_M.gguf", fields)- none = _call_std_route(monkeypatch, path = gguf, repo_id = "org/swa", n_parallel = 4)+ # Blank means llama.cpp's default, so use an explicit zero as the baseline.+ none = _call_std_route(+ monkeypatch,+ path = gguf,+ repo_id = "org/swa",+ n_parallel = 4,+ ctx_checkpoints = 0,+ )many = _call_std_route(monkeypatch,path = gguf,repo_id = "org/swa",n_parallel = 4,- ctx_checkpoints = 32,+ ctx_checkpoints = 64,)assert (many["kv_bytes"] > none["kv_bytes"]@@ -677,9 +684,19 @@ class TestHostMemoryIsNotChargedToTheCard:def test_no_checkpoints_means_no_host_share(self, monkeypatch, tmp_path):gguf = _write_gguf(tmp_path / "swa-model-Q4_K_M.gguf", _SWA_MODEL)- out = _call_std_route(monkeypatch, path = gguf, repo_id = "org/swa", ctx_checkpoints = None)+ out = _call_std_route(monkeypatch, path = gguf, repo_id = "org/swa", ctx_checkpoints = 0)assert out["kv_checkpoint_bytes"] is None+ def test_a_blank_field_reports_the_share_llama_cpp_allocates_anyway(+ self, monkeypatch, tmp_path+ ):+ gguf = _write_gguf(tmp_path / "swa-model-Q4_K_M.gguf", _SWA_MODEL)+ blank = _call_std_route(monkeypatch, path = gguf, repo_id = "org/swa", ctx_checkpoints = None)+ explicit = _call_std_route(monkeypatch, path = gguf, repo_id = "org/swa", ctx_checkpoints = 32)+ assert blank["kv_checkpoint_bytes"], "a blank field reported no checkpoint host RAM"+ assert blank["kv_checkpoint_bytes"] == explicit["kv_checkpoint_bytes"]+ assert blank["kv_bytes"] == explicit["kv_bytes"]+class TestAutoAbstainsOverASidecar:"""Auto promotes to DSpark or DFlash when the model ships one, so the routediff --git a/studio/backend/tests/test_load_mode_fit_matrix.py b/studio/backend/tests/test_load_mode_fit_matrix.pyindex 9b4672b8ee1..385aeb4752c 100644--- a/studio/backend/tests/test_load_mode_fit_matrix.py+++ b/studio/backend/tests/test_load_mode_fit_matrix.py@@ -315,9 +315,8 @@ def test_the_launch_charges_the_cpu_pinned_drafter_to_the_fit():assert compact.index("_cpu_draft_path=_mtp_draft_for_budget") < compact.index("if_draft_on_cpu:_mtp_draft_for_budget=None")- # ... and charged to the footprint as a HOST-ONLY term (free VRAM cannot pay for- # an allocation the child only ever makes in RAM), abstaining when unpriceable.- assert "host_only_bytes=_cpu_draft_fit_bytesor0" in compact+ # CPU-pinned drafter and checkpoint bytes are host-only.+ assert "host_only_bytes=(_cpu_draft_fit_bytesor0)+_ckpt_host_bytes," in compactassert "or_cpu_draft_fit_bytesisNone" in compact@@ -1726,13 +1725,16 @@ def test_context_checkpoint_snapshots_move_the_fit_verdict(monkeypatch):def test_the_fit_prices_the_effective_checkpoint_count():- """...and the call site really passes it, while the closure default leaves the- placement paths -- which price the snapshots by their own route -- unmoved."""+ """The load-mode footprint prices checkpoints as host-only bytes."""from core.inference.llama_cpp import LlamaCppBackend as Bimport inspectcompact = "".join(inspect.getsource(B.load_model).split())- assert "kv_cache_bytes=_kv_bytes(effective_ctx,_effective_ctx_checkpoints)," in compact+ assert "kv_cache_bytes=_kv_bytes(effective_ctx,0)," in compact+ assert "_kv_bytes(effective_ctx,_effective_ctx_checkpoints)-_kv_bytes(effective_ctx,0)," in (+ compact+ )+ assert "host_only_bytes=(_cpu_draft_fit_bytesor0)+_ckpt_host_bytes," in compactassert "def_kv_bytes(ctx:int,ctx_checkpoints:int=0)->int:" in compactdiff --git a/studio/backend/tests/test_memory_estimate.py b/studio/backend/tests/test_memory_estimate.pyindex 09b5926feea..4b957320c24 100644--- a/studio/backend/tests/test_memory_estimate.py+++ b/studio/backend/tests/test_memory_estimate.py@@ -1848,11 +1848,15 @@ class TestLaunchShapedPricing:full = ri._gguf_memory_breakdown(spec_config, swa, n_ctx = 131072, llama_extra_args = ["--swa-full"])- assert full.kv_bytes > windowed.kv_bytes- # Same header on both sides, so the drafter's cache moves exactly as the- # target's does rather than staying at the windowed figure.- assert full.drafter_runtime_bytes == full.kv_bytes- assert windowed.drafter_runtime_bytes == windowed.kv_bytes+ # Compare GPU cache bytes; checkpoints are host-only and absent under --swa-full.+ assert full.kv_bytes - full.kv_checkpoint_bytes > (+ windowed.kv_bytes - windowed.kv_checkpoint_bytes+ )+ assert full.kv_checkpoint_bytes == 0+ assert windowed.kv_checkpoint_bytes > 0+ # Drafter runtime follows the cache proper; its checkpoint share is not estimated.+ assert full.drafter_runtime_bytes == full.kv_bytes - full.kv_checkpoint_bytes+ assert windowed.drafter_runtime_bytes == windowed.kv_bytes - windowed.kv_checkpoint_bytesdef test_a_cpu_device_selection_takes_the_weights_off_the_gpu(self, spec_config, swa):"""``--device none`` runs on the CPU whatever the layer count says.diff --git a/studio/backend/tests/test_server_tuning_flags.py b/studio/backend/tests/test_server_tuning_flags.pyindex dab11687c70..e89d706ff23 100644--- a/studio/backend/tests/test_server_tuning_flags.py+++ b/studio/backend/tests/test_server_tuning_flags.py@@ -433,8 +433,9 @@ def test_the_coexistence_estimate_charges_the_requested_checkpoints():inference_routes._estimate_gguf_kv_gb)kv_source = inspect.getsource(inference_routes._gguf_runtime_bytes)- # priced on what the launch runs, so a typed --ctx-checkpoints wins here too- assert "resolve_ctx_checkpoints(llama_extra_args, ctx_checkpoints)" in kv_source+ # Pricing uses the same effective count as the launch.+ assert "effective_ctx_checkpoints_for_caps(" in kv_source+ assert "llama_extra_args," in kv_source# ------------------------------------------------------------------- override storage