Skip to content

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.

Add Model memory settings to keep a loaded model in VRAM (#8002)

Michael Han1b3c31e718f6
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 2a4e1a7ecb3..42ecf2dd66f 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -45,11 +45,19 @@ from typing import (
import httpx
from core.inference.llama_server_args import (
+ _GPU_LAYER_FLAGS,
_LAYER_OFFLOAD_FLAGS,
+ _MOE_OFFLOAD_FLAGS,
_effective_tensor_parallel,
_flag_name,
_tensor_parallel_matches_loaded,
+ apply_model_memory_policy,
extra_args_disable_mmproj,
+ fit_is_enabled_in,
+ memory_state_satisfies_settings,
+ fit_is_effectively_on,
+ resolve_effective_memory_state,
+ scrub_memory_env,
parse_cache_override,
parse_cache_override_per_axis,
parse_ctx_override,
@@ -1896,6 +1904,16 @@ def _extra_args_set_spec_type(extra_args: Optional[Iterable[str]]) -> bool:
# also strips these (plus the MoE flags) from inherited extras; sharing the layer
# set keeps detection and stripping from drifting.
_GPU_OFFLOAD_OVERRIDE_FLAGS = _LAYER_OFFLOAD_FLAGS
+# Extras that keep weights on the CPU regardless of the layer count, so a
+# full offload cannot be inferred from -ngl alone. -ncmoe carries a COUNT, and
+# zero places nothing, so it is parsed rather than merely spotted; the rest are
+# presence-only (-cmoe takes no value, and an -ot pattern is not worth guessing
+# at, which matches how the env side reads LLAMA_ARG_OVERRIDE_TENSOR).
+_CPU_MOE_COUNT_FLAGS = frozenset({"-ncmoe", "--n-cpu-moe"})
+_CPU_PLACEMENT_PRESENCE_FLAGS = (_MOE_OFFLOAD_FLAGS - _CPU_MOE_COUNT_FLAGS) | frozenset(
+ {"-ot", "--override-tensor"}
+)
+_CPU_PLACEMENT_FLAGS = _MOE_OFFLOAD_FLAGS | frozenset({"-ot", "--override-tensor"})
_THREAD_OVERRIDE_FLAGS = frozenset({"-t", "--threads"})
# common_params defaults in the bundled llama.cpp runtime.
_DEFAULT_LLAMA_N_BATCH = 2048
@@ -2030,6 +2048,41 @@ def _is_positive_int(value: Optional[str]) -> bool:
return False
+def _args_place_tensors_on_cpu(extra_args: Optional[Iterable[str]] = None) -> bool:
+ """True when extras keep weights on the CPU, whatever the layer count says.
+
+ The arg-side twin of ``_env_places_tensors_on_cpu``, including its rule that
+ a CPU-MoE count only counts when positive: ``--n-cpu-moe 0`` places nothing.
+ """
+ values = [str(raw) for raw in extra_args or ()]
+ for i, raw in enumerate(values):
+ flag = _flag_name(raw)
+ # Any -ot counts even if it matches nothing: the list need only be
+ # non-empty, and guessing at the pattern is not worth it.
+ if flag in _CPU_PLACEMENT_PRESENCE_FLAGS:
+ return True
+ if flag in _CPU_MOE_COUNT_FLAGS:
+ _, eq, inline = raw.partition("=")
+ if _is_positive_int(inline if eq else (values[i + 1] if i + 1 < len(values) else "")):
+ return True
+ return False
+
+
+def _env_places_tensors_on_cpu(env: Optional[Mapping[str, str]] = None) -> bool:
+ """True when inherited env keeps weights on the CPU, whatever the argv says.
+
+ The child inherits these, so they survive stripping the equivalent flags.
+ Shared with the Model Memory host-residency gate, which must not call a load
+ fully offloaded while one of them is holding tensors in RAM.
+ """
+ source_env = os.environ if env is None else env
+ return bool(
+ source_env.get("LLAMA_ARG_OVERRIDE_TENSOR")
+ or source_env.get("LLAMA_ARG_CPU_MOE") in _LLAMA_ARG_TRUE_VALUES
+ or _is_positive_int(source_env.get("LLAMA_ARG_N_CPU_MOE"))
+ )
+
+
def _pipeline_parallel_disabled_by_args(
extra_args: Optional[Iterable[str]],
env: Optional[Mapping[str, str]] = None,
@@ -2049,11 +2102,7 @@ def _pipeline_parallel_disabled_by_args(
split. ``n_layers`` is the GGUF block count for the ``-ngl`` check below; None/0
means unknown."""
source_env = os.environ if env is None else env
- if source_env.get("LLAMA_ARG_OVERRIDE_TENSOR"):
- return True
- if source_env.get("LLAMA_ARG_CPU_MOE") in _LLAMA_ARG_TRUE_VALUES:
- return True
- if _is_positive_int(source_env.get("LLAMA_ARG_N_CPU_MOE")):
+ if _env_places_tensors_on_cpu(source_env):
return True
if not _kv_offload_from_args(extra_args, env = env):
return True
@@ -2066,7 +2115,8 @@ def _pipeline_parallel_disabled_by_args(
# Pipelining needs n_gpu_layers > n_layer_all, so a user -ngl (appended after
# Studio's -ngl -1, last-wins) that cannot exceed the count loads a prefix and
# turns it off. Negative (all layers) or above the count keeps the step, even
- # in between: n_layers is block_count and can undercount n_layer_all (MTP layers).
+ # in between: n_layers is block_count, which IS n_layer_all (llama-model.cpp
+ # reads the key straight into it); hparams.n_layer() is the smaller MTP-less one.
if n_layers:
try:
gpu_layers = parse_gpu_layers_override(extra_args)
@@ -2074,18 +2124,9 @@ def _pipeline_parallel_disabled_by_args(
gpu_layers = None # malformed: unknown, so keep the step
if gpu_layers is not None and 0 <= gpu_layers <= n_layers:
return True
- values = [str(raw) for raw in extra_args or ()]
- for i, raw in enumerate(values):
- flag = _flag_name(raw)
- # Any -ot counts even if it matches nothing: the list need only be non-empty.
- if flag in {"-ot", "--override-tensor", "-cmoe", "--cpu-moe"}:
- return True
- if flag in {"-ncmoe", "--n-cpu-moe"}:
- # -ncmoe 0 pushes no override, so it leaves pipelining on.
- _, eq, inline = raw.partition("=")
- if _is_positive_int(inline if eq else (values[i + 1] if i + 1 < len(values) else "")):
- return True
- return False
+ # Same predicate the Model Memory host-residency gate uses; -ncmoe 0 pushes
+ # no override, so it leaves pipelining on.
+ return _args_place_tensors_on_cpu(extra_args)
def _kv_unified_from_args(
@@ -2640,6 +2681,41 @@ def _extra_args_main_device(extra_args: Optional[Iterable[str]]) -> Optional[str
return _extra_args_device(extra_args, {"--device", "-dev"})
+def _without_subsequence(tokens: List[str], run: List[str]) -> List[str]:
+ """``tokens`` with the first contiguous occurrence of ``run`` removed.
+
+ Only the exact flags Unsloth appended go, so a user's own identical flag
+ elsewhere in the command survives. Unchanged when ``run`` is not present.
+ """
+ if not run:
+ return list(tokens)
+ for i in range(len(tokens) - len(run) + 1):
+ if tokens[i : i + len(run)] == run:
+ return [*tokens[:i], *tokens[i + len(run) :]]
+ return list(tokens)
+
+
+_CPU_DEVICE_VALUES = frozenset({"cpu", "none"})
+
+
+def _device_selection_is_cpu(
+ extra_args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None
+) -> bool:
+ """True when the effective ``--device`` selection names no GPU.
+
+ llama.cpp then runs the model on the CPU whatever the layer count says, so
+ the weights are in pageable host RAM. argv wins over the env twin, and an
+ unreadable value answers True like every other unknown in the gate.
+ """
+ value = _extra_args_main_device(extra_args)
+ if value is None and env:
+ value = env.get("LLAMA_ARG_DEVICE")
+ if value is None:
+ return False
+ devices = [d.strip().lower() for d in str(value).split(",") if d.strip()]
+ return not devices or all(d in _CPU_DEVICE_VALUES for d in devices)
+
+
def _extra_args_draft_device(extra_args: Optional[Iterable[str]]) -> Optional[str]:
"""Return the last explicit draft-device value, if any."""
return _extra_args_device(extra_args, {"--spec-draft-device", "-devd", "--device-draft"})
@@ -3156,6 +3232,19 @@ class LlamaCppBackend:
self._prompt_cache_disabled: bool = False
self._swa_full: bool = False
self._kv_cache_unified: bool = False
+ # (mlock, reserves_ram) the running process was launched with, or None
+ # when this policy does not govern it (the diffusion runner has no
+ # load-mode). _memory_policy_active records that the launch differed
+ # from an unmanaged one, so disabling the toggles can undo it.
+ self._memory_state: Optional[tuple[bool, bool]] = None
+ self._memory_policy_active: bool = False
+ # False when a launch is fully offloaded to a discrete GPU, where
+ # page-locking host RAM is skipped on purpose.
+ self._memory_mlock_applicable: bool = True
+ # True between recording a launch's placement and the child being
+ # spawned, so a save landing in that window still has a launch to
+ # compare against.
+ self._memory_launch_pending: bool = False
self._n_ubatch: int = self._DEFAULT_N_UBATCH
self._flash_attn_enabled: bool = True
self._effective_cache_types: tuple[str, str] = ("f16", "f16")
@@ -4125,6 +4214,7 @@ class LlamaCppBackend:
"supports_metrics": False,
"supports_slot_save": False,
"supports_no_mmproj_offload": False,
+ "supports_load_mode": False,
"spec_draft_ngl_flag": None,
}
try:
@@ -4149,6 +4239,7 @@ class LlamaCppBackend:
supports_metrics = False
supports_slot_save = False
supports_no_mmproj_offload = False
+ supports_load_mode = False
spec_draft_ngl_flag = None
saw_spec_type = False
probe_ok = False
@@ -4263,6 +4354,9 @@ class LlamaCppBackend:
supports_metrics = _is_real("--metrics")
supports_slot_save = _is_real("--slot-save-path")
supports_no_mmproj_offload = _is_real("--no-mmproj-offload")
+ # --load-mode supersedes --mlock / --no-mmap, which are deprecated.
+ # Pre-initialised above: a failed probe must fall back, not raise.
+ supports_load_mode = _is_real("--load-mode")
# Record WHICH alias this build has: --spec-draft-ngl only landed in
# b8955, and a build exposing only --gpu-layers-draft would refuse to
# start on the newer name. Long forms only, since the block parser above
@@ -4324,6 +4418,7 @@ class LlamaCppBackend:
"supports_metrics": supports_metrics,
"supports_slot_save": supports_slot_save,
"supports_no_mmproj_offload": supports_no_mmproj_offload,
+ "supports_load_mode": supports_load_mode,
"spec_draft_ngl_flag": spec_draft_ngl_flag,
}
cls._capability_cache[cache_key] = info
@@ -4528,6 +4623,134 @@ class LlamaCppBackend:
env, ",".join(str(i) for i in order), prefer_rocr = prefer_rocr
)
+ @staticmethod
+ def _vulkan_targets_are_igpus(binary: Optional[str], gpu_indices = None) -> bool:
+ """True when any Vulkan device in play is integrated.
+
+ An iGPU's reported "VRAM" is shared system RAM (see
+ ``_apply_igpu_host_reserve_mib``), so a model "fully offloaded" onto one
+ is still backed by pageable host memory and is worth page-locking. Any,
+ not every: a mixed selection splits weights onto the iGPU too, and those
+ pages are as evictable as if it were the only device. An unreadable probe
+ answers False.
+ """
+ try:
+ rows = LlamaCppBackend._run_vulkan_probe(binary)
+ except Exception:
+ return False
+ if not rows:
+ return False
+ wanted = set(gpu_indices) if gpu_indices else None
+ selected = [r for r in rows if wanted is None or r["index"] in wanted]
+ return any(r["is_igpu"] for r in selected)
+
+ def _weights_in_host_memory(
+ self,
+ *,
+ fully_gpu_offloaded: bool,
+ gpu_memory_mode: Optional[str],
+ gpu_layers: Optional[int],
+ extra_args: Optional[Iterable[str]],
+ gpu_indices = None,
+ is_vulkan_backend: bool = False,
+ binary: Optional[str] = None,
+ env: Optional[Mapping[str, str]] = None,
+ probe_vulkan: bool = True,
+ fit_active: bool = False,
+ ) -> bool:
+ """True when the weights will sit in pageable host RAM, so mlock helps.
+
+ Only the Model Memory gate uses this, and only to SKIP page-locking, so
+ it errs towards True: that is the pre-existing behaviour.
+
+ ``probe_vulkan`` False skips the Vulkan probe, the one subprocess in
+ here, for a bookkeeping-only call; that keeps the conservative True.
+ """
+ from utils.hardware import is_apple_silicon
+
+ # A CPU placement extra keeps weights in RAM whatever the layer count,
+ # so it applies to the auto path too and cannot be short-circuited past.
+ # Inherited env does the same and outlives any token stripping.
+ if _args_place_tensors_on_cpu(extra_args):
+ return True
+ if _env_places_tensors_on_cpu(env):
+ return True
+ # A --device that names no GPU beats any layer count: llama.cpp has
+ # nowhere to offload to, so the whole model stays in host RAM.
+ if _device_selection_is_cpu(extra_args, env):
+ return True
+ # fully_gpu_offloaded predicts OUR "-ngl -1 --fit off", but auto keeps the
+ # user's extras and appends them after, and llama.cpp is last-wins, so an
+ # -ngl 0 lands the model in RAM. Only a fit that is switched ON voids the
+ # prediction: "--fit off" is what we already pass, and a disabled fitter
+ # cannot move anything to the CPU.
+ if _extra_args_set_any_flag(extra_args, _GPU_LAYER_FLAGS) or fit_is_enabled_in(extra_args):
+ fully_gpu_offloaded = False
+ all_on_gpu = fully_gpu_offloaded or self._offloads_every_layer(
+ gpu_memory_mode = gpu_memory_mode,
+ gpu_layers = gpu_layers,
+ extra_args = extra_args,
+ fit_active = fit_active,
+ )
+ if not all_on_gpu:
+ return True
+ # Unified memory: the "VRAM" is host RAM, so the weights stay pageable
+ # however fully they are offloaded.
+ if is_apple_silicon():
+ return True
+ if is_vulkan_backend:
+ # gpu_indices are Vulkan ordinals here, which the ROCm APU helper
+ # would read as physical ids and answer for the wrong device. The
+ # Vulkan probe owns device type; unprobed keeps the True answer.
+ return not probe_vulkan or self._vulkan_targets_are_igpus(binary, gpu_indices)
+ return self._amd_apu_wants_unified_memory(gpu_indices)
+
+ def _offloads_every_layer(
+ self,
+ *,
+ gpu_memory_mode: Optional[str],
+ gpu_layers: Optional[int],
+ extra_args: Optional[Iterable[str]],
+ fit_active: bool = False,
+ ) -> bool:
+ """True when every layer lands on the GPU by a route ``fully_gpu_offloaded``
+ does not cover: manual mode at its full-offload maximum, or a user -ngl.
+
+ Only the Model Memory gate uses this, and only to SKIP page-locking, so
+ every unknown answers False and keeps the pre-existing behaviour: an
+ unreadable block count, CPU-side experts, a tensor override that places
+ weights by name, or an unparseable -ngl.
+ """
+ n_layers = self.n_layers
+ if not n_layers:
+ return False
+ if self._n_cpu_moe:
+ return False
+ # The parsed predicate, not flag presence: --n-cpu-moe 0 places nothing,
+ # and answering False here would pin host RAM for an all-GPU launch.
+ if _args_place_tensors_on_cpu(extra_args):
+ return False
+ requested: Optional[int] = None
+ if gpu_memory_mode == "manual" and gpu_layers is not None and gpu_layers >= 0:
+ # Manual owns offload and strips -ngl from the extras, so the field
+ # is what the child gets. The picker's maximum is n_layers + 1.
+ requested = gpu_layers
+ else:
+ try:
+ requested = parse_gpu_layers_override(extra_args)
+ except ValueError:
+ return False
+ if requested is None:
+ return False
+ # -1 is "all layers"; llama.cpp needs a count ABOVE the block count to
+ # cover the output layer too, which is what the picker's maximum sends.
+ # -1 is also llama.cpp's DEFAULT, so an active fitter is free to lower it
+ # (common/fit.cpp aborts only on a count the user really set); a concrete
+ # count stands, which is why only this arm is gated.
+ if requested == -1:
+ return not fit_active
+ return requested > n_layers
+
@staticmethod
def _amd_apu_wants_unified_memory(gpu_indices = None) -> bool:
"""True only for AMD unified-memory APUs (gfx1150/gfx1151/gfx1152), where
@@ -5315,6 +5538,12 @@ class LlamaCppBackend:
for name in cls._MANUAL_PLACEMENT_ENV_VARS:
env.pop(name, None)
+ @classmethod
+ def _clear_device_placement_env(cls, env: dict[str, str]) -> None:
+ """Remove inherited device placement owned by an explicit ``gpu_ids``."""
+ for name in ("LLAMA_ARG_DEVICE", "LLAMA_ARG_MAIN_GPU"):
+ env.pop(name, None)
+
@staticmethod
def _select_gpus(
model_size_bytes: int,
@@ -6950,6 +7179,10 @@ class LlamaCppBackend:
self._cache_type_kv = None
self._swa_full = False
self._kv_cache_unified = False
+ self._memory_state = None
+ self._memory_policy_active = False
+ self._memory_mlock_applicable = True
+ self._memory_launch_pending = False
self._n_ubatch = self._DEFAULT_N_UBATCH
self._requested_n_batch = None
self._requested_n_ubatch = None
@@ -10709,8 +10942,7 @@ class LlamaCppBackend:
if _paravirtual_cpu_forced and _paravirtual_mmproj_pinnable(server_caps):
_pv_mmproj_cpu_pin = ["--no-mmproj-offload"]
logger.warning(
- "Disabling mmproj GPU offload: this Mac's Metal device "
- "is virtualised."
+ "Disabling mmproj GPU offload: this Mac's Metal device is virtualised."
)
# Option C: --api-key for direct client access when enabled
@@ -10783,10 +11015,84 @@ class LlamaCppBackend:
if is_vulkan_backend and _vulkan_pin_ids is not None:
cmd += LlamaCppBackend._vulkan_pin_args(_vulkan_pin_ids)
+ # Model Memory settings. Managed flag lands before the extras, and
+ # vetoed ones are dropped from a launch-only copy: extra_args keeps
+ # None-vs-[] (inherit vs clear) for the commit block below, and the
+ # user's saved flags survive turning the toggle back off.
+ # mlock pins a mapping in HOST RAM, so it only implements
+ # residency where the weights actually live there: unified
+ # memory, or any load that is not fully offloaded. On a discrete
+ # GPU with full offload it would hold a second copy of the model
+ # in system RAM and do nothing for VRAM, so it is not emitted
+ # and the idle-unload veto carries residency by itself.
+ from utils.model_memory_settings import should_mlock
+
+ # fully_gpu_offloaded is only set by the auto branch. Manual mode
+ # and a user -ngl reach the same placement by their own routes,
+ # so derive those too or they would still be pinned. The CPU
+ # placement guard applies to BOTH: an auto fit that offloads
+ # every layer still leaves weights in RAM if an extra pins them
+ # there, so it cannot short-circuit past the check.
+ # Asked on EVERY launch, not just when a lock is on the table:
+ # _memory_mlock_applicable is recorded from it, and a LATER
+ # "keep resident" save is compared against that. Assuming host
+ # residency by default made enabling the toggle demand a reload
+ # and reject the duplicate-load fast path, tearing down a healthy
+ # server to relaunch identical argv. Only the Vulkan probe stays
+ # gated, so the default path still spawns nothing.
+ # The same view of the environment the child will get: manual
+ # mode drops the placement vars below, so reading os.environ
+ # would pin for a CPU-MoE setting the child never sees.
+ _mem_env = dict(os.environ)
+ if gpu_memory_mode == "manual":
+ self._clear_manual_placement_env(_mem_env)
+ # A gpu_ids pin drops the device flags from argv and env below,
+ # so classifying on them would pin for a --device cpu the child
+ # never sees. Same helpers the launch uses, so they cannot drift.
+ _mem_extra_args = extra_args
+ if gpu_ids is not None:
+ _mem_extra_args = self._strip_device_extra_args(extra_args)
+ self._clear_device_placement_env(_mem_env)
+ _mem_host_resident = self._weights_in_host_memory(
+ fully_gpu_offloaded = fully_gpu_offloaded,
+ gpu_memory_mode = gpu_memory_mode,
+ gpu_layers = gpu_layers,
+ extra_args = _mem_extra_args,
+ gpu_indices = gpu_indices,
+ is_vulkan_backend = is_vulkan_backend,
+ binary = binary,
+ env = _mem_env,
+ probe_vulkan = should_mlock(),
+ # Over the built cmd AND the extras, so Studio's own --fit
+ # counts and a later user --fit still wins by last-arg.
+ fit_active = fit_is_effectively_on([*cmd, *(_mem_extra_args or [])], _mem_env),
+ )
+ _mem_managed, _mem_extras = apply_model_memory_policy(
+ extra_args,
+ supports_load_mode = bool(server_caps.get("supports_load_mode")),
+ weights_in_host_memory = _mem_host_resident,
+ )
+ # Remembered so the reload hint and the duplicate-load
+ # comparator don't demand an mlock this launch deliberately
+ # skipped, which no relaunch could ever satisfy.
+ self._memory_mlock_applicable = _mem_host_resident
+ if should_mlock() and not _mem_host_resident:
+ logger.info(
+ "Model Memory: skipping page-lock, the weights are fully "
+ "offloaded to a discrete GPU; residency is kept by not "
+ "unloading the model."
+ )
+ if _mem_managed:
+ cmd.extend(_mem_managed)
+ logger.info(
+ "Model Memory: keeping weights pinned in place (%s)",
+ " ".join(_mem_managed),
+ )
+
# User pass-through args go last. Placement flags are removed
# below when the Studio picker owns the GPU selection.
- if extra_args:
- _emit_extra_args = list(extra_args)
+ if _mem_extras:
+ _emit_extra_args = list(_mem_extras)
if gpu_ids is not None:
# gpu_ids owns placement, so remove competing device flags.
_before_device_strip = list(_emit_extra_args)
@@ -10823,6 +11129,31 @@ class LlamaCppBackend:
env = self._llama_server_env_for_binary(binary)
if gpu_memory_mode == "manual":
self._clear_manual_placement_env(env)
+ # llama.cpp reads LLAMA_ARG_MLOCK / _MMAP / _LOAD_MODE before argv,
+ # so stripping the tokens alone would leave an inherited value in
+ # force. Only when a toggle is on, so existing setups are untouched.
+ _mem_scrubbed = scrub_memory_env(env)
+ if _mem_scrubbed:
+ logger.info(
+ "Model Memory owns placement; dropped inherited %s",
+ ", ".join(_mem_scrubbed),
+ )
+ # Record what the child will ACTUALLY run with (env defaults plus
+ # last-wins argv), not just what Unsloth emitted, so the reload
+ # hint also catches a user-supplied --mlock / --no-mmap.
+ self._memory_state = resolve_effective_memory_state(
+ list(_mem_managed) + list(_mem_extras), env
+ )
+ # Did the policy change this launch at all: emitted a flag,
+ # suppressed a requested one, or scrubbed an inherited env var.
+ # Turning both toggles off must relaunch to undo any of those,
+ # but must not fight a launch it never touched.
+ # Split out: the fit-off retry can drop _mem_managed, and what is
+ # left decides whether that child still differs from an unmanaged one.
+ _mem_policy_touched_extras = bool(_mem_scrubbed) or _mem_extras != list(
+ extra_args or []
+ )
+ self._memory_policy_active = bool(_mem_managed) or _mem_policy_touched_extras
# Omitting --threads relies on llama.cpp's physical-core default, so
# drop an inherited LLAMA_ARG_THREADS that would otherwise feed the
# arg handler and silently force hardware_concurrency(). #5692
@@ -10856,8 +11187,7 @@ class LlamaCppBackend:
# A gpu_ids pin also owns inherited device placement.
if gpu_ids is not None:
- env.pop("LLAMA_ARG_DEVICE", None)
- env.pop("LLAMA_ARG_MAIN_GPU", None)
+ self._clear_device_placement_env(env)
# The unpinnable-drafter drop above rewrites argv, which cannot reach the
# drafter the child picks up from its own env. The spec type goes too,
@@ -10985,7 +11315,10 @@ class LlamaCppBackend:
crashes during startup and run_cmd is eligible (see
_fit_off_retry_eligible).
"""
- nonlocal _last_spawn_cmd
+ # _mem_host_resident too: the --fit on retry re-arms the
+ # page-lock and writes it back, which without this makes the
+ # read below an UnboundLocalError instead.
+ nonlocal _last_spawn_cmd, _mem_host_resident
_fit_retry_allowed = self._fit_off_retry_eligible(run_cmd, use_fit)
for _spawn_attempt in (0, 1):
# Defensive kill: drop an orphan Popen a concurrent load may
@@ -11033,6 +11366,8 @@ class LlamaCppBackend:
**_child_popen_kwargs(),
)
self._record_server_pid(self._process.pid)
+ # is_active covers it from here, so drop the pre-spawn flag.
+ self._memory_launch_pending = False
# Background thread to drain stdout (prevents pipe deadlock)
self._stdout_thread = threading.Thread(
@@ -11076,7 +11411,27 @@ class LlamaCppBackend:
_run = list(run_cmd)
if "--fit" in _run:
_run[_run.index("--fit") + 1] = "on"
+ # The full-offload prediction that suppressed the
+ # page-lock was the very thing that just proved
+ # wrong, so llama.cpp may now leave weights in host
+ # RAM. Re-arm residency for the retry (last-wins, so
+ # appending is enough) and re-record the state.
+ if should_mlock() and not _mem_host_resident:
+ _run.extend(
+ ["--load-mode", "mmap+mlock"]
+ if server_caps.get("supports_load_mode")
+ else ["--mlock"]
+ )
+ _mem_host_resident = True
+ self._memory_mlock_applicable = True
+ self._memory_policy_active = True
+ logger.info(
+ "Model Memory: re-applying the page-lock for "
+ "the --fit on retry; the full-offload "
+ "prediction did not hold."
+ )
run_cmd = _run
+ self._memory_state = resolve_effective_memory_state(_run, env)
continue
if (
_spawn_attempt == 0
@@ -11093,6 +11448,39 @@ class LlamaCppBackend:
self._llama_log_path,
)
run_cmd = [*run_cmd, "--fit", "off"]
+ # The mirror of the --fit on retry above. Turning the
+ # fitter off leaves -ngl at its default, which llama.cpp
+ # resolves to every layer, so the fitted attempt's
+ # host-resident verdict can stop holding. Drop a
+ # page-lock the retry no longer needs rather than
+ # reserving a full host copy of a fully offloaded model.
+ if _mem_managed and _mem_host_resident:
+ if not self._weights_in_host_memory(
+ fully_gpu_offloaded = True,
+ gpu_memory_mode = gpu_memory_mode,
+ gpu_layers = gpu_layers,
+ extra_args = _mem_extra_args,
+ gpu_indices = gpu_indices,
+ is_vulkan_backend = is_vulkan_backend,
+ binary = binary,
+ env = _mem_env,
+ ):
+ run_cmd = _without_subsequence(run_cmd, _mem_managed)
+ _mem_host_resident = False
+ # Recorded so a later "keep resident" save is not
+ # compared against a lock this launch dropped,
+ # which would demand a pointless reload.
+ self._memory_mlock_applicable = False
+ # The managed flag was the policy's only mark on
+ # this child unless it also scrubbed or stripped,
+ # and a child equal to an unmanaged one must not
+ # be torn down when the toggles go off.
+ self._memory_policy_active = _mem_policy_touched_extras
+ logger.info(
+ "Model Memory: dropping the page-lock for "
+ "the --fit off retry; it offloads every layer."
+ )
+ self._memory_state = resolve_effective_memory_state(run_cmd, env)
continue
return False
@@ -11128,7 +11516,16 @@ class LlamaCppBackend:
max_available_ctx if max_available_ctx > 0 else self._effective_context_length
)
- healthy = _spawn_and_wait(cmd)
+ # The placement above is now fixed for this child, but _process
+ # is not set until Popen. Without this, a save landing in that
+ # window sees no active backend and reports no reload while the
+ # child is already committed. Popen clears it, and so does every
+ # exit below, so a failed spawn cannot leave it stuck on.
+ self._memory_launch_pending = True
+ try:
+ healthy = _spawn_and_wait(cmd)
+ finally:
+ self._memory_launch_pending = False
# #6415 split-mode tensor warmup abort. Latch it on THIS first spawn:
# the flash-attn-off retry below can't run tensor (needs flash_attn),
# so its output drops the marker and recording later would miss it,
@@ -11999,6 +12396,16 @@ class LlamaCppBackend:
candidate_extra_args = list(effective_extra_args) if effective_extra_args else []
if intent.extra_args is not None and intent.gpu_ids is not None:
candidate_extra_args = self._strip_device_extra_args(candidate_extra_args)
+ # A Model Memory toggle changes only the launch flags, so the intent is
+ # unchanged and this would otherwise report already-loaded and leave the
+ # running process on the old placement.
+ if not memory_state_satisfies_settings(
+ self._memory_state,
+ self._memory_policy_active,
+ self._memory_mlock_applicable,
+ ):
+ logger.info("Model Memory policy changed since launch; forcing a reload")
+ return False
if not self._runtime_matches_intent(intent, candidate_extra_args):
return False
self._record_matching_gpu_request(
@@ -12150,6 +12557,10 @@ class LlamaCppBackend:
self._prompt_cache_disabled = False
self._swa_full = False
self._kv_cache_unified = False
+ self._memory_state = None
+ self._memory_policy_active = False
+ self._memory_mlock_applicable = True
+ self._memory_launch_pending = False
self._n_ubatch = self._DEFAULT_N_UBATCH
self._flash_attn_enabled = True
self._effective_cache_types = ("f16", "f16")
diff --git a/studio/backend/core/inference/llama_server_args.py b/studio/backend/core/inference/llama_server_args.py
index a1894681fac..651c100b4c2 100644
--- a/studio/backend/core/inference/llama_server_args.py
+++ b/studio/backend/core/inference/llama_server_args.py
@@ -221,6 +221,37 @@ _LAYER_OFFLOAD_FLAGS: frozenset[str] = _GPU_LAYER_FLAGS | _FIT_FLAGS
_MOE_OFFLOAD_FLAGS: frozenset[str] = frozenset({"-ncmoe", "--n-cpu-moe", "-cmoe", "--cpu-moe"})
_OFFLOAD_SHADOWING_FLAGS: frozenset[str] = _LAYER_OFFLOAD_FLAGS | _MOE_OFFLOAD_FLAGS
+# Host-memory placement flags. Both are full-model RAM reservations (--mlock pins
+# it, --no-mmap mallocs a copy), so the Model Memory settings own them: stripped
+# only when a toggle vetoes them, never unconditionally.
+_MLOCK_FLAGS: frozenset[str] = frozenset({"--mlock", "-mlock"})
+# Modern spelling of both, as an enum value. Takes a value, so NOT boolean.
+_LOAD_MODE_FLAGS: frozenset[str] = frozenset({"--load-mode", "-lm"})
+_NO_MMAP_FLAGS: frozenset[str] = frozenset({"--no-mmap", "-no-mmap"})
+# Deprecated selectors for the same load-mode enum. Measured: ANY of them
+# trailing the managed flag resets the WHOLE mode and drops the mlock, in both
+# polarities ("--mmap" and "--no-direct-io" do it too). Affirmative dio streams
+# and holds no full copy; the negative spellings are NOT plain mmap, upstream
+# maps them to mode `none` like --no-mmap, so no-reserve must veto those too.
+_DIO_ON_FLAGS: frozenset[str] = frozenset({"--direct-io", "-dio"})
+_DIO_OFF_FLAGS: frozenset[str] = frozenset({"--no-direct-io", "-ndio"})
+_DIO_FLAGS: frozenset[str] = _DIO_ON_FLAGS | _DIO_OFF_FLAGS
+_LOAD_MODE_ALIAS_FLAGS: frozenset[str] = _NO_MMAP_FLAGS | frozenset({"--mmap"}) | _DIO_FLAGS
+# Every spelling that asks for a full-model host buffer.
+_RAM_RESERVING_FLAGS: frozenset[str] = _NO_MMAP_FLAGS | _DIO_OFF_FLAGS
+# llama.cpp reads these before argv, so an inherited value survives stripping the
+# equivalent tokens. Scrubbed whenever a toggle is on, like the spec/placement
+# env groups, so the setting owns memory placement outright.
+MEMORY_ENV_VARS: tuple[str, ...] = (
+ "LLAMA_ARG_MLOCK",
+ "LLAMA_ARG_MMAP",
+ "LLAMA_ARG_LOAD_MODE",
+ "LLAMA_ARG_DIO",
+ # Legacy negative aliases, honoured by PRESENCE whatever the value.
+ "LLAMA_ARG_NO_MMAP",
+ "LLAMA_ARG_NO_DIO",
+)
+
_SHADOWING_FLAGS: frozenset[str] = (
_CONTEXT_FLAGS | _CACHE_FLAGS | _SPEC_FLAGS | _TEMPLATE_FLAGS | _SPLIT_SHADOWING_FLAGS
)
@@ -233,6 +264,15 @@ _BOOLEAN_SHADOWING_FLAGS: frozenset[str] = frozenset(
"--no-jinja",
"-cmoe",
"--cpu-moe",
+ "--mlock",
+ "-mlock",
+ "--no-mmap",
+ "-no-mmap",
+ "--mmap",
+ "--direct-io",
+ "-dio",
+ "--no-direct-io",
+ "-ndio",
}
)
@@ -354,6 +394,35 @@ def parse_gpu_layers_override(args: Optional[Iterable[str]]) -> Optional[int]:
return value
+def fit_is_enabled_in(args: Optional[Iterable[str]]) -> bool:
+ """Whether the last ``--fit`` in extras turns the fitter ON.
+
+ Only ``--fit on`` hands placement back to llama.cpp; ``--fit off`` disables
+ it and so cannot move weights to the CPU. Upstream requires a value and
+ rejects anything that is neither truthy nor falsey, so an absent or
+ unreadable value is not an enable.
+ """
+ raw_value = _last_flag_value(args, _FIT_FLAGS)
+ return raw_value is not None and raw_value.strip().lower() in _ENV_TRUE_VALUES
+
+
+def fit_is_effectively_on(
+ args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None
+) -> bool:
+ """Whether the fitter actually runs, over the WHOLE argv and the env twin.
+
+ ``fit_is_enabled_in`` answers for the extras alone; this answers for the
+ child. llama.cpp defaults the fitter ON and applies the env before argv, so
+ only an explicit "off" turns it off, and an unreadable value keeps it on.
+ """
+ raw_value = _last_flag_value(args, _FIT_FLAGS)
+ if raw_value is None and env:
+ raw_value = env.get("LLAMA_ARG_FIT")
+ if raw_value is None:
+ return True
+ return str(raw_value).strip().lower() not in _ENV_FALSE_VALUES
+
+
def parse_cache_override_per_axis(
args: Optional[Iterable[str]],
) -> tuple[Optional[str], Optional[str]]:
@@ -490,6 +559,10 @@ def strip_shadowing_flags(
strip_tensor_split: bool = False,
strip_offload: bool = False,
strip_device: bool = False,
+ strip_mlock: bool = False,
+ strip_no_mmap: bool = False,
+ strip_load_mode_aliases: bool = False,
+ strip_load_mode: bool = False,
strip_batch: bool = False,
strip_ubatch: bool = False,
) -> list[str]:
@@ -507,6 +580,11 @@ def strip_shadowing_flags(
replace an inherited per-GPU ratio while leaving the user's ``--split-mode``
row/none/layer choice intact. ``strip_device`` is enabled when ``gpu_ids``
owns placement.
+
+ ``strip_mlock`` / ``strip_no_mmap`` are enabled by the Model Memory settings
+ so a RAM-reservation flag cannot survive a load the user asked to keep
+ RAM-free. ``strip_no_mmap`` covers every spelling of mode `none`, so the
+ negative DirectIO forms go with it. All boolean: only the token is dropped.
"""
shadowing: set[str] = set()
if strip_context:
@@ -525,6 +603,14 @@ def strip_shadowing_flags(
shadowing |= _OFFLOAD_SHADOWING_FLAGS
if strip_device:
shadowing |= _DEVICE_FLAGS
+ if strip_mlock:
+ shadowing |= _MLOCK_FLAGS
+ if strip_no_mmap:
+ shadowing |= _RAM_RESERVING_FLAGS
+ if strip_load_mode_aliases:
+ shadowing |= _LOAD_MODE_ALIAS_FLAGS
+ if strip_load_mode:
+ shadowing |= _LOAD_MODE_FLAGS
if strip_batch:
shadowing |= _BATCH_FLAGS
if strip_ubatch:
@@ -566,3 +652,303 @@ def strip_split_mode_only(args: Optional[Iterable[str]]) -> Optional[list[str]]:
strip_template = False,
strip_split_mode = True,
)
+
+
+def apply_model_memory_policy(
+ extra_args: Optional[Iterable[str]],
+ *,
+ supports_load_mode: bool = False,
+ weights_in_host_memory: bool = True,
+) -> tuple[list[str], list[str]]:
+ """Resolve the Model Memory settings into llama-server flags.
+
+ Returns ``(managed_flags, extras)``: what Unsloth emits itself, and the
+ user's extras with any vetoed flag removed.
+
+ "Keep model in GPU memory" page-locks the weights (``--load-mode mmap+mlock``,
+ or the deprecated ``--mlock``) but ONLY when ``weights_in_host_memory``.
+ mlock pins a whole mapping in host RAM, so for a model fully offloaded to a
+ discrete GPU it would hold a second full copy of the weights in system RAM
+ without doing anything for VRAM residency; there, residency is carried by
+ the idle-unload veto alone. Every other load-mode-bearing flag is stripped
+ from the emitted extras, because a trailing one resets the whole mode and
+ would drop the mlock.
+
+ "Don't reserve system RAM" drops ``--mlock`` / ``--no-mmap``, leaving the
+ default mmap path. With both off nothing is stripped, so a hand-typed flag
+ still applies.
+ """
+ try:
+ from utils.model_memory_settings import get_model_memory_settings
+ except Exception:
+ # Settings unavailable (bare unit-test import): behave as before.
+ return [], list(extra_args or [])
+
+ # One snapshot for both decisions: read separately, a save landing between
+ # them strips for one setting and locks for the other, so a saved --mlock
+ # could survive a committed no-reserve.
+ keep_resident, no_ram_reserve = get_model_memory_settings()
+ tokens = list(extra_args or [])
+ if no_ram_reserve:
+ tokens = strip_shadowing_flags(
+ tokens,
+ strip_context = False,
+ strip_cache = False,
+ strip_spec = False,
+ strip_template = False,
+ strip_split_mode = False,
+ strip_mlock = True,
+ strip_no_mmap = True,
+ )
+ tokens = _strip_reserving_load_modes(tokens)
+
+ managed: list[str] = []
+ if keep_resident and not no_ram_reserve and weights_in_host_memory:
+ # Before the extras, like the rest of the managed block. mmap+mlock, not
+ # bare mlock: it matches what --mlock meant alongside the default mmap.
+ managed.extend(["--load-mode", "mmap+mlock"] if supports_load_mode else ["--mlock"])
+ tokens = strip_shadowing_flags(
+ tokens,
+ strip_context = False,
+ strip_cache = False,
+ strip_spec = False,
+ strip_template = False,
+ strip_split_mode = False,
+ strip_mlock = True,
+ strip_load_mode_aliases = True,
+ strip_load_mode = True,
+ )
+ return managed, tokens
+
+
+def _strip_reserving_load_modes(tokens: list[str]) -> list[str]:
+ """Drop only ``--load-mode`` values that lock or reserve host RAM.
+
+ No-reserve vetoes the reservation, not the loader. ``mmap`` and ``dio``
+ hold no full host copy, so a DirectIO preset survives instead of silently
+ falling back to mmap. Unknown values are left alone rather than rewritten.
+ """
+ out: list[str] = []
+ i, n = 0, len(tokens)
+ while i < n:
+ token = tokens[i]
+ if _flag_name(token) not in _LOAD_MODE_FLAGS:
+ out.append(token)
+ i += 1
+ continue
+ if "=" in token:
+ value, step = token.split("=", 1)[1], 1
+ elif i + 1 < n and _flag_name(tokens[i + 1]) is None:
+ value, step = tokens[i + 1], 2
+ else:
+ value, step = "", 1
+ value = value.strip().lower()
+ if value in _LOAD_MODE_MLOCK_VALUES or value in _LOAD_MODE_RESERVING_VALUES:
+ i += step
+ continue
+ out.extend(tokens[i : i + step])
+ i += step
+ return out
+
+
+def model_memory_owns_placement() -> bool:
+ """True when either toggle is on, so the child env must be scrubbed."""
+ try:
+ from utils.model_memory_settings import get_keep_resident, get_no_ram_reserve
+ except Exception:
+ return False
+ return get_keep_resident() or get_no_ram_reserve()
+
+
+def _env_var_locks_or_reserves(name: str, value: str) -> bool:
+ """Whether this inherited var, as set, locks or reserves host RAM.
+
+ Mirrors the argv rule: the settings own the RESERVATION, not the loader, so
+ a DirectIO or mmap choice made through the environment survives the same way
+ ``--load-mode dio`` does. An unrecognised value is left alone.
+ """
+ normalized = value.strip().lower()
+ if name == "LLAMA_ARG_MLOCK":
+ return normalized in _ENV_TRUE_VALUES
+ if name in {"LLAMA_ARG_NO_MMAP", "LLAMA_ARG_NO_DIO"}:
+ # Presence alone selects mode "none", which is a full host buffer.
+ return True
+ if name in {"LLAMA_ARG_MMAP", "LLAMA_ARG_DIO"}:
+ # Falsy selects "none"; truthy selects mmap / dio, neither of which
+ # holds a full copy.
+ return normalized in _ENV_FALSE_VALUES
+ if name == "LLAMA_ARG_LOAD_MODE":
+ return normalized in _LOAD_MODE_MLOCK_VALUES or normalized in _LOAD_MODE_RESERVING_VALUES
+ return False
+
+
+def scrub_memory_env(env: dict) -> list[str]:
+ """Drop inherited memory placement the settings override.
+
+ Returns the names removed, for logging. A no-op with both toggles off, so an
+ existing LLAMA_ARG_MLOCK deployment keeps working untouched. Only the values
+ that actually lock or reserve go: an inherited ``LLAMA_ARG_DIO=1`` is a
+ loader choice, not a reservation, and no-reserve has no quarrel with it.
+ """
+ if not model_memory_owns_placement():
+ return []
+ removed = [
+ name
+ for name in MEMORY_ENV_VARS
+ if name in env and _env_var_locks_or_reserves(name, env[name])
+ ]
+ for name in removed:
+ env.pop(name, None)
+ return removed
+
+
+# Mirrors llama_cpp's _LLAMA_ARG_TRUE/FALSE_VALUES; duplicated so this module
+# stays dependency-free (llama_cpp imports from here, not the other way).
+_ENV_TRUE_VALUES = frozenset({"on", "enabled", "true", "1"})
+_ENV_FALSE_VALUES = frozenset({"off", "disabled", "false", "0"})
+
+_LOAD_MODE_MLOCK_VALUES = frozenset({"mlock", "mmap+mlock"})
+# Modes that read the weights into a full host buffer. "dio" streams via
+# DirectIO and "mmap" maps, so neither reserves RAM for the whole model.
+_LOAD_MODE_RESERVING_VALUES = frozenset({"none", "mlock"})
+
+
+def resolve_effective_memory_state(
+ argv: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None
+) -> tuple[bool, bool]:
+ """``(mlock, reserves_ram)`` the child will actually run with.
+
+ Mirrors llama.cpp: env supplies defaults, argv overrides last-wins. Used to
+ compare a running process against the current settings, so the reload hint
+ reflects the launched state rather than only what Unsloth emitted.
+ """
+ env = env or {}
+ mlock = False
+ reserves_ram = False
+ # Each var runs the SAME handler as its flag, so it assigns the whole mode
+ # and a later one overwrites an earlier one, in llama.cpp's registration
+ # order. Measured: LLAMA_ARG_MLOCK=1 with LLAMA_ARG_MMAP=on or
+ # LLAMA_ARG_DIO=0 leaves the child unlocked.
+ # Only the mlock bit, like the argv --mlock below: "mlock" vs "mmap+mlock"
+ # is not observable and changes no decision.
+ if str(env.get("LLAMA_ARG_MLOCK", "")).strip().lower() in _ENV_TRUE_VALUES:
+ mlock = True
+ # Every option with a negative form also answers to LLAMA_ARG_NO_<NAME>:
+ # upstream rewrites the name and, if that var EXISTS, forces the value
+ # falsey whatever it says, before reading the affirmative one. Measured:
+ # LLAMA_ARG_NO_MMAP=0 still disables mmap, and it beats LLAMA_ARG_MMAP=on.
+ # --mlock has no negative form, so LLAMA_ARG_NO_MLOCK does nothing.
+ # LLAMA_ARG_MMAP is whether to mmap, so "off" means mmap disabled ("none").
+ _mmap_env = "0" if "LLAMA_ARG_NO_MMAP" in env else str(env.get("LLAMA_ARG_MMAP", ""))
+ _mmap_env = _mmap_env.strip().lower()
+ if _mmap_env in _ENV_TRUE_VALUES:
+ mlock, reserves_ram = False, False
+ elif _mmap_env in _ENV_FALSE_VALUES:
+ mlock, reserves_ram = False, True
+ # LLAMA_ARG_DIO likewise: on selects DirectIO, off selects "none".
+ _dio_env = "0" if "LLAMA_ARG_NO_DIO" in env else str(env.get("LLAMA_ARG_DIO", ""))
+ _dio_env = _dio_env.strip().lower()
+ if _dio_env in _ENV_TRUE_VALUES:
+ mlock, reserves_ram = False, False
+ elif _dio_env in _ENV_FALSE_VALUES:
+ mlock, reserves_ram = False, True
+ _mode_env = str(env.get("LLAMA_ARG_LOAD_MODE", "")).strip().lower()
+ if _mode_env:
+ mlock = _mode_env in _LOAD_MODE_MLOCK_VALUES
+ reserves_ram = _mode_env in _LOAD_MODE_RESERVING_VALUES
+
+ tokens = [str(a) for a in (argv or [])]
+ i, n = 0, len(tokens)
+ while i < n:
+ tok = tokens[i]
+ flag = _flag_name(tok)
+ if flag is None:
+ i += 1
+ continue
+ if flag in _MLOCK_FLAGS:
+ # Only the mlock bit: the enum has both "mlock" and "mmap+mlock" and
+ # which one this maps to is not observable. It changes no decision,
+ # since mlock alone already counts as a reservation for no-reserve.
+ mlock = True
+ i += 1
+ elif flag in _NO_MMAP_FLAGS:
+ # Deprecated selector for the whole "none" mode, so it clears the
+ # mlock too: measured, "--mlock --no-mmap" leaves the child unlocked
+ # while "--no-mmap --mlock" locks it.
+ mlock = False
+ reserves_ram = True
+ i += 1
+ elif flag in _DIO_ON_FLAGS:
+ # Deprecated load-mode selector: resets the mode, so the mlock goes.
+ # DirectIO streams the weights, so it holds no full host copy.
+ mlock = False
+ reserves_ram = False
+ i += 1
+ elif flag in _DIO_OFF_FLAGS:
+ # Not "plain mmap": upstream maps these to mode `none`, like
+ # --no-mmap, which reads the weights into a full host buffer.
+ mlock = False
+ reserves_ram = True
+ i += 1
+ elif flag == "--mmap":
+ mlock = False
+ reserves_ram = False
+ i += 1
+ elif flag in _LOAD_MODE_FLAGS:
+ if "=" in tok:
+ value, step = tok.split("=", 1)[1], 1
+ elif i + 1 < n and _flag_name(tokens[i + 1]) is None:
+ value, step = tokens[i + 1], 2
+ else:
+ value, step = "", 1
+ value = value.strip().lower()
+ if value:
+ mlock = value in _LOAD_MODE_MLOCK_VALUES
+ reserves_ram = value in _LOAD_MODE_RESERVING_VALUES
+ i += step
+ else:
+ i += 1
+ return mlock, reserves_ram
+
+
+def memory_state_satisfies_settings(
+ state: Optional[tuple[bool, bool]],
+ policy_active: bool = False,
+ mlock_applicable: bool = True,
+) -> bool:
+ """True when a launched ``(mlock, reserves_ram)`` matches the settings.
+
+ Shared by the duplicate-load comparator (so toggling a setting forces a real
+ relaunch instead of returning already-loaded) and the settings route (so the
+ reload hint agrees with it).
+
+ ``state`` is None for a process this policy does not govern, such as the
+ diffusion runner, which has no load-mode of its own; nothing about it can
+ contradict the settings, so it always matches.
+
+ ``policy_active`` says the launch differed from an unmanaged one, because a
+ flag was emitted, a requested one suppressed, or an inherited env var
+ scrubbed. With both toggles off the policy no longer applies, so any of
+ those has to be undone on the next launch, while a launch it never touched
+ is left alone.
+
+ ``mlock_applicable`` is False when the launch is fully offloaded to a
+ discrete GPU, where page-locking host RAM buys nothing and is deliberately
+ not emitted. Residency there is the idle-unload veto, which needs no
+ relaunch, so demanding mlock would ask for a reload that can never satisfy
+ the check.
+ """
+ if state is None:
+ return True
+ try:
+ from utils.model_memory_settings import get_keep_resident, get_no_ram_reserve
+ except Exception:
+ return True
+ mlock, reserves_ram = state
+ if get_no_ram_reserve():
+ # mlock_applicable only excuses a MISSING lock; a live reservation
+ # still has to go, wherever the weights are.
+ return not (mlock or reserves_ram)
+ if get_keep_resident():
+ return mlock or not mlock_applicable
+ return not policy_active
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 5c6dac917dd..a48ae231597 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -4207,12 +4207,17 @@ def disable_openai_auto_switch_for_request(scope) -> None:
def _automatic_model_load_may_run() -> bool:
"""True when a request can trigger an automatic load: either resolver-based
auto-switch is on, or a standalone idle TTL can reload an idle-freed model. The
- validate-before-switch guards key off this so an invalid request never loads."""
+ validate-before-switch guards key off this so an invalid request never loads.
+
+ Reads the configured setting, not the effective TTL: Model Memory residency
+ zeroes the latter, and a model the idle loop freed BEFORE residency was
+ enabled still has to be reloadable. Residency stops unloads, not reloads.
+ """
from utils.openai_auto_switch_settings import (
get_openai_auto_switch_enabled,
- get_auto_unload_idle_seconds,
+ idle_unload_is_configured,
)
- return get_openai_auto_switch_enabled() or get_auto_unload_idle_seconds() > 0
+ return get_openai_auto_switch_enabled() or idle_unload_is_configured()
def _no_model_loaded_detail(base: str) -> str:
@@ -4745,8 +4750,8 @@ async def _maybe_auto_switch_model(
"""
from utils.openai_auto_switch_settings import (
get_openai_auto_switch_enabled,
- get_auto_unload_idle_seconds,
get_model_override,
+ idle_unload_is_configured,
model_override_load_kwargs,
)
from core.inference.local_model_resolver import resolve_local_gguf
@@ -4769,7 +4774,9 @@ async def _maybe_auto_switch_model(
# standalone UNSLOTH_MODEL_IDLE_TTL with auto-switch off), so a model the idle
# loop freed is restored on the next request. The resolver-based switch still
# requires the auto-switch toggle.
- if not auto_switch_on and get_auto_unload_idle_seconds() <= 0:
+ # Configured, not effective: residency zeroes the TTL, and the stash still
+ # has to be restorable after it is turned on.
+ if not auto_switch_on and not idle_unload_is_configured():
# No switching to do, but a named model must still not be answered by another.
await _reject_unservable_model(requested_model, fastapi_request)
return
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index f20348f1bf9..0342f166ef5 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -38,6 +38,14 @@ from utils.helper_precache_settings import (
)
from picker.schemas import MAX_CHAT_TEMPLATE_BYTES, chat_template_byte_length
from utils.coding_agents import CODING_AGENTS, detect_installed_coding_agents
+from utils.model_memory_settings import (
+ DEFAULT_KEEP_RESIDENT,
+ DEFAULT_NO_RAM_RESERVE,
+ get_model_memory_settings,
+ memlock_limit_bytes,
+ set_model_memory_settings,
+ should_mlock,
+)
from utils.openai_auto_switch_settings import (
BATCH_SIZE_MAX,
BATCH_SIZE_MIN,
@@ -56,6 +64,7 @@ from utils.openai_auto_switch_settings import (
resolve_model_override_keys,
get_stored_auto_unload_idle_seconds,
get_stored_openai_auto_download_enabled,
+ idle_unload_is_configured,
set_model_override,
set_openai_auto_switch,
)
@@ -110,6 +119,27 @@ class HelperPrecacheResponse(BaseModel):
disabled_by_env: bool
+class ModelMemoryPayload(BaseModel):
+ # None leaves the stored value untouched, so the switches save independently.
+ keep_resident: Optional[bool] = None
+ no_ram_reserve: Optional[bool] = None
+
+
+class ModelMemoryResponse(BaseModel):
+ keep_resident: bool
+ no_ram_reserve: bool
+ default_keep_resident: bool = DEFAULT_KEEP_RESIDENT
+ default_no_ram_reserve: bool = DEFAULT_NO_RAM_RESERVE
+ # Whether --mlock is passed on the next load. False when no_ram_reserve
+ # vetoes it; the UI surfaces that rather than failing silently.
+ mlock_active: bool
+ reload_required: bool
+ # Soft RLIMIT_MEMLOCK when finite. mlock cannot exceed it, so the UI warns
+ # that residency will not fully pin a model larger than this. None means
+ # unlimited (macOS) or not applicable (Windows).
+ memlock_limit_bytes: Optional[int] = None
+
+
class HuggingFaceCachePayload(BaseModel):
cache_home: Optional[str] = Field(default = None, max_length = 4096)
@@ -259,6 +289,88 @@ def _helper_precache_response(enabled: bool | None = None) -> HelperPrecacheResp
)
+# Distinct from None, which is a real launch this policy does not govern.
+_NO_LAUNCH = object()
+
+
+def _active_launch_placement():
+ """``(state, policy_active, mlock_applicable)`` for the running child.
+
+ ``state`` is ``_NO_LAUNCH`` when nothing is running or coming up, so the
+ caller can tell "no process" apart from "a process with no load-mode".
+ """
+ try:
+ from routes.inference import get_llama_cpp_backend
+
+ backend = get_llama_cpp_backend()
+ pending = bool(getattr(backend, "_memory_launch_pending", False))
+ if not backend.is_active and not pending:
+ return _NO_LAUNCH, False, True
+ return (
+ getattr(backend, "_memory_state", None),
+ bool(getattr(backend, "_memory_policy_active", False)),
+ bool(getattr(backend, "_memory_mlock_applicable", True)),
+ )
+ except Exception:
+ return _NO_LAUNCH, False, True
+
+
+def _model_memory_reload_required() -> bool:
+ """True when the loaded process's memory placement contradicts the settings.
+
+ Compares the state the child ACTUALLY launched with -- env defaults plus
+ last-wins argv, so a user-supplied --mlock / --no-mmap counts -- against
+ what the current settings would produce. The idle-unload veto applies
+ immediately (the loop re-reads each poll), so only placement can be stale.
+
+ Keyed on is_active, not is_loaded: a save that lands while a load is still
+ passing its health check would otherwise report no reload while the child is
+ already committed to the pre-save flags. _memory_launch_pending covers the
+ same window before Popen, where the placement is decided but _process is
+ still None.
+ """
+ state, policy_active, mlock_applicable = _active_launch_placement()
+ if state is _NO_LAUNCH:
+ return False
+
+ # Same predicate the duplicate-load comparator uses, so the reload hint and
+ # the reload path can never disagree.
+ from core.inference.llama_server_args import memory_state_satisfies_settings
+
+ return not memory_state_satisfies_settings(state, policy_active, mlock_applicable)
+
+
+def _model_memory_mlock_active(want_mlock: bool) -> bool:
+ """Whether page-locking is actually in force, not merely asked for.
+
+ This drives the locked-memory cap warning, so taking it from the toggles
+ alone would tell a discrete-GPU user to raise a limit nothing consults.
+ With nothing running this is the intent, so the UI reflects the toggle. Once
+ a child exists it is what that child got: a full offload to a discrete GPU
+ skips the lock, and a diffusion runner has no load-mode at all, so claiming
+ otherwise would warn about ulimit -l for a lock nobody took. A user's own
+ --mlock counts, since the resolver reads the launched argv.
+ """
+ if not want_mlock:
+ return False
+ state, _policy_active, _applicable = _active_launch_placement()
+ if state is _NO_LAUNCH:
+ return True
+ return bool(state and state[0])
+
+
+def _model_memory_response() -> ModelMemoryResponse:
+ keep_resident, no_ram_reserve = get_model_memory_settings()
+ mlock_active = _model_memory_mlock_active(should_mlock())
+ return ModelMemoryResponse(
+ keep_resident = keep_resident,
+ no_ram_reserve = no_ram_reserve,
+ mlock_active = mlock_active,
+ reload_required = _model_memory_reload_required(),
+ memlock_limit_bytes = memlock_limit_bytes() if mlock_active else None,
+ )
+
+
def _hugging_face_cache_response() -> HuggingFaceCacheResponse:
return HuggingFaceCacheResponse(**cache_status(get_hf_cache_paths()))
@@ -329,6 +441,31 @@ def update_helper_precache(
return _helper_precache_response(enabled)
[email protected]("/model-memory", response_model = ModelMemoryResponse)
+def get_model_memory(current_subject: str = Depends(get_current_subject)) -> ModelMemoryResponse:
+ return _model_memory_response()
+
+
[email protected]("/model-memory", response_model = ModelMemoryResponse)
+def update_model_memory(
+ payload: ModelMemoryPayload, current_subject: str = Depends(get_current_subject)
+) -> ModelMemoryResponse:
+ try:
+ set_model_memory_settings(
+ keep_resident = payload.keep_resident,
+ no_ram_reserve = payload.no_ram_reserve,
+ )
+ except ValueError as exc:
+ raise log_and_http_error(
+ exc,
+ 400,
+ safe_error_detail(exc, fallback = "Invalid model memory setting."),
+ event = "settings.update_model_memory_failed",
+ log = logger,
+ ) from exc
+ return _model_memory_response()
+
+
class CodingAgentsResponse(BaseModel):
# All agents `unsloth start` supports, in the CLI's declared order.
agents: tuple[str, ...] = CODING_AGENTS
@@ -375,8 +512,9 @@ def update_openai_auto_switch(
log = logger,
) from exc
idle_unload_active = get_auto_unload_idle_seconds() > 0
- if not keep_kv or not idle_unload_active:
- # Keep-KV off or idle unload disabled: drop already-saved chat context too.
+ if not keep_kv or not idle_unload_is_configured():
+ # Drop already-saved chat context too. Configured, not effective: residency
+ # zeroes the TTL, and that must not discard KV the user still wants.
from core.inference.llama_keepwarm import purge_kv_resume
purge_kv_resume()
return OpenAIAutoSwitchResponse(
diff --git a/studio/backend/tests/test_model_memory_settings.py b/studio/backend/tests/test_model_memory_settings.py
new file mode 100644
index 00000000000..bd41e088d94
--- /dev/null
+++ b/studio/backend/tests/test_model_memory_settings.py
@@ -0,0 +1,2454 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Unit tests for the Model Memory residency settings.
+
+Pins what the toggles promise: which llama-server flags reach the subprocess,
+and that residency vetoes the idle-unload TTL without destroying the stored one.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+from pathlib import Path
+
+import pytest
+
+_BACKEND = Path(__file__).resolve().parent.parent
+
+# Load directly, like test_llama_server_args.py: importing the package would
+# drag in the whole inference chain.
+_spec = importlib.util.spec_from_file_location(
+ "_lsa_model_memory_test_only", _BACKEND / "core" / "inference" / "llama_server_args.py"
+)
+_lsa = importlib.util.module_from_spec(_spec)
+_spec.loader.exec_module(_lsa)
+apply_model_memory_policy = _lsa.apply_model_memory_policy
+memory_state_satisfies_settings = _lsa.memory_state_satisfies_settings
+resolve_effective_memory_state = _lsa.resolve_effective_memory_state
+scrub_memory_env = _lsa.scrub_memory_env
+
+import utils.model_memory_settings as mm_settings # noqa: E402
+
+strip_shadowing_flags = _lsa.strip_shadowing_flags
+
+
+def policy(monkeypatch):
+ """Run the policy under a given toggle pair.
+
+ The policy imports the settings module lazily, so patch that module.
+ """
+ import utils.model_memory_settings as mm
+
+ def run(
+ keep_resident: bool,
+ no_ram_reserve: bool,
+ extras,
+ supports_load_mode = False,
+ weights_in_host_memory = True,
+ ):
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: keep_resident)
+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: no_ram_reserve)
+ monkeypatch.setattr(mm, "should_mlock", lambda: keep_resident and not no_ram_reserve)
+ return apply_model_memory_policy(
+ extras,
+ supports_load_mode = supports_load_mode,
+ weights_in_host_memory = weights_in_host_memory,
+ )
+
+ return run
+
+
+class TestFlagPolicy:
+ def test_both_off_is_a_pure_pass_through(self, policy):
+ # Pre-feature contract: hand-typed flags survive, nothing is added.
+ extras = ["--mlock", "--no-mmap", "--temp", "0.7"]
+ managed, out = policy(False, False, extras)
+ assert managed == []
+ assert out == extras
+
+ def test_keep_resident_emits_mlock(self, policy):
+ # Legacy build: --mlock is deprecated upstream but still accepted.
+ managed, out = policy(True, False, ["--temp", "0.7"])
+ assert managed == ["--mlock"]
+ assert out == ["--temp", "0.7"]
+
+ def test_keep_resident_prefers_load_mode_when_supported(self, policy):
+ managed, out = policy(True, False, ["--temp", "0.7"], supports_load_mode = True)
+ assert managed == ["--load-mode", "mmap+mlock"]
+ assert out == ["--temp", "0.7"]
+
+ def test_load_mode_is_stripped_from_extras(self, policy):
+ # A user --load-mode would last-wins-override the managed one, and
+ # "--load-mode mlock" is a RAM reservation no-reserve must veto.
+ _, out = policy(
+ True, False, ["--load-mode", "none", "--temp", "0.7"], supports_load_mode = True
+ )
+ assert out == ["--temp", "0.7"]
+ _, out = policy(False, True, ["-lm", "mlock", "--temp", "0.7"])
+ assert out == ["--temp", "0.7"]
+
+ def test_load_mode_strip_is_not_boolean(self, policy):
+ # It takes a value, so the value must go with the flag, not survive.
+ _, out = policy(False, True, ["--load-mode", "mmap+mlock"])
+ assert out == []
+
+ def test_keep_resident_does_not_double_emit_mlock(self, policy):
+ # A user --mlock folds into the managed one, not a second copy.
+ managed, out = policy(True, False, ["--mlock", "--temp", "0.7"])
+ assert managed == ["--mlock"]
+ assert "--mlock" not in out
+
+ def test_no_ram_reserve_strips_both_reservation_flags(self, policy):
+ managed, out = policy(False, True, ["--mlock", "--no-mmap", "-ngl", "99"])
+ assert managed == []
+ # Unrelated flags (and their values) survive untouched.
+ assert out == ["-ngl", "99"]
+
+ def test_no_ram_reserve_wins_over_keep_resident(self, policy):
+ # --mlock is itself a RAM reservation, so no-reserve vetoes it.
+ managed, out = policy(True, True, ["--mlock", "--no-mmap", "--temp", "0.7"])
+ assert managed == []
+ assert out == ["--temp", "0.7"]
+
+ def test_handles_absent_extras(self, policy):
+ assert policy(True, False, None) == (["--mlock"], [])
+ assert policy(False, False, None) == ([], [])
+
+ def test_caller_extras_are_not_mutated(self, policy):
+ # load_model reads extra_args after this: None must stay None (inherit
+ # previous) rather than becoming [] (clear), and the user's saved flags
+ # must survive, so the policy only ever returns a launch-only copy.
+ original = ["--mlock", "--no-mmap", "--temp", "0.7"]
+ passed = list(original)
+ _, out = policy(True, True, passed)
+ assert passed == original
+ assert out is not passed
+
+ @pytest.mark.parametrize("flag", ["--mlock", "-mlock", "--no-mmap", "-no-mmap"])
+ def test_aliases_are_stripped(self, policy, flag):
+ _, out = policy(False, True, [flag, "--temp", "0.7"])
+ assert out == ["--temp", "0.7"]
+
+ def test_strip_is_boolean_and_keeps_the_next_token(self):
+ # --mlock takes no value, so stripping it must not swallow "0.7".
+ assert strip_shadowing_flags(
+ ["--mlock", "0.7"],
+ strip_context = False,
+ strip_cache = False,
+ strip_spec = False,
+ strip_template = False,
+ strip_split_mode = False,
+ strip_mlock = True,
+ ) == ["0.7"]
+
+
+class TestIdleUnloadVeto:
+ def test_keep_resident_zeroes_the_effective_ttl(self, monkeypatch):
+ import utils.model_memory_settings as mm
+ import utils.openai_auto_switch_settings as aus
+
+ monkeypatch.setattr(aus, "_stored_idle_seconds", lambda: 300)
+ monkeypatch.setattr(aus, "get_openai_auto_switch_enabled", lambda: True)
+
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: False)
+ assert aus.get_auto_unload_idle_seconds() == 300
+
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: True)
+ assert aus.get_auto_unload_idle_seconds() == 0
+ # The stored value survives, so turning residency off restores it.
+ assert aus.get_stored_auto_unload_idle_seconds() == 300
+
+
+class TestPersistence:
+ def test_partial_update_leaves_the_other_key_alone(self, monkeypatch):
+ import utils.model_memory_settings as mm
+
+ store: dict = {}
+ monkeypatch.setattr(mm, "_cached_setting", lambda key: store.get(key))
+ monkeypatch.setattr(
+ "storage.studio_db.upsert_app_settings", lambda updates: store.update(updates)
+ )
+
+ assert mm.set_model_memory_settings(keep_resident = True) == (True, False)
+ assert mm.set_model_memory_settings(no_ram_reserve = True) == (True, True)
+ # Only keep_resident is sent; no_ram_reserve must not reset.
+ assert mm.set_model_memory_settings(keep_resident = False) == (False, True)
+
+ @pytest.mark.parametrize("value", ["banana", 2.5, object()])
+ def test_rejects_non_boolean(self, value):
+ import utils.model_memory_settings as mm
+ with pytest.raises(ValueError):
+ mm.set_model_memory_settings(keep_resident = value)
+
+ @pytest.mark.parametrize(
+ ("stored", "expected"),
+ [
+ (True, True),
+ ("true", True),
+ ("on", True),
+ (False, False),
+ ("off", False),
+ ("", False),
+ (None, False),
+ ("nonsense", False),
+ ],
+ )
+ def test_coercion_defaults_to_off(self, monkeypatch, stored, expected):
+ import utils.model_memory_settings as mm
+
+ monkeypatch.setattr(mm, "_cached_setting", lambda key: stored)
+ assert mm.get_keep_resident() is expected
+ assert mm.get_no_ram_reserve() is expected
+
+
+class TestMemlockLimit:
+ """mlock cannot exceed RLIMIT_MEMLOCK. Linux commonly defaults to 8 MB,
+ where llama.cpp warns and carries on, so residency silently does nothing.
+ The settings response reports the cap so the UI can say so."""
+
+ def test_unlimited_reports_none(self, monkeypatch):
+ import resource
+
+ import utils.model_memory_settings as mm
+
+ monkeypatch.setattr(
+ resource,
+ "getrlimit",
+ lambda _w: (resource.RLIM_INFINITY, resource.RLIM_INFINITY),
+ )
+ assert mm.memlock_limit_bytes() is None
+
+ @pytest.mark.parametrize("soft", [0, 64 * 1024, 8 * 1024 * 1024])
+ def test_finite_limits_are_reported(self, monkeypatch, soft):
+ import resource
+
+ import utils.model_memory_settings as mm
+
+ monkeypatch.setattr(resource, "getrlimit", lambda _w: (soft, soft))
+ assert mm.memlock_limit_bytes() == soft
+
+ def test_negative_is_treated_as_unlimited(self, monkeypatch):
+ import resource
+
+ import utils.model_memory_settings as mm
+
+ monkeypatch.setattr(resource, "getrlimit", lambda _w: (-1, -1))
+ assert mm.memlock_limit_bytes() is None
+
+ @pytest.mark.parametrize("exc", [ValueError, OSError, AttributeError])
+ def test_probe_failure_never_raises(self, monkeypatch, exc):
+ import resource
+
+ import utils.model_memory_settings as mm
+
+ def boom(_w):
+ raise exc("nope")
+
+ monkeypatch.setattr(resource, "getrlimit", boom)
+ assert mm.memlock_limit_bytes() is None
+
+
+class TestMemoryEnv:
+ """llama.cpp reads LLAMA_ARG_MLOCK / _MMAP / _LOAD_MODE before argv, so
+ stripping the tokens alone leaves an inherited value in force."""
+
+ @pytest.fixture
+ def toggles(self, monkeypatch):
+ import utils.model_memory_settings as mm
+ def set(keep, no_res):
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: keep)
+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: no_res)
+
+ return set
+
+ @pytest.mark.parametrize(
+ ("var", "value"),
+ [
+ ("LLAMA_ARG_MLOCK", "1"),
+ ("LLAMA_ARG_MMAP", "off"), # mmap disabled -> mode none
+ ("LLAMA_ARG_NO_MMAP", "0"), # presence alone -> mode none
+ ("LLAMA_ARG_DIO", "off"), # DirectIO disabled -> mode none
+ ("LLAMA_ARG_NO_DIO", "0"),
+ ("LLAMA_ARG_LOAD_MODE", "none"),
+ ("LLAMA_ARG_LOAD_MODE", "mlock"),
+ ("LLAMA_ARG_LOAD_MODE", "mmap+mlock"),
+ ],
+ )
+ def test_a_toggle_scrubs_inherited_reservations(self, toggles, var, value):
+ toggles(False, True)
+ env = {var: value, "PATH": "/usr/bin"}
+ assert var in scrub_memory_env(env)
+ assert var not in env
+ assert env["PATH"] == "/usr/bin"
+
+ @pytest.mark.parametrize(
+ ("var", "value"),
+ [
+ ("LLAMA_ARG_MLOCK", "0"), # measured: falsy does not lock
+ ("LLAMA_ARG_MMAP", "1"), # mmap: maps, holds no full copy
+ ("LLAMA_ARG_DIO", "1"), # DirectIO: streams
+ ("LLAMA_ARG_LOAD_MODE", "mmap"),
+ ("LLAMA_ARG_LOAD_MODE", "dio"),
+ ("LLAMA_ARG_LOAD_MODE", "future-mode"), # unknown: leave it alone
+ ],
+ )
+ def test_a_non_reserving_loader_choice_survives(self, toggles, var, value):
+ """The settings own the reservation, not the loader, exactly as on the
+ argv side where --load-mode dio is kept."""
+ toggles(False, True)
+ env = {var: value, "PATH": "/usr/bin"}
+ assert scrub_memory_env(env) == []
+ assert env == {var: value, "PATH": "/usr/bin"}
+
+ def test_a_kept_choice_really_does_satisfy_no_reserve(self, toggles):
+ """Otherwise keeping it would just make the reload hint fire forever."""
+ toggles(False, True)
+ for env in (
+ {"LLAMA_ARG_DIO": "1"},
+ {"LLAMA_ARG_LOAD_MODE": "dio"},
+ {"LLAMA_ARG_MMAP": "1"},
+ ):
+ scrub_memory_env(dict(env))
+ assert resolve_effective_memory_state([], env) == (False, False)
+
+ def test_residency_still_clears_a_conflicting_inherited_lock_setting(self, toggles):
+ toggles(True, False)
+ env = {"LLAMA_ARG_LOAD_MODE": "none"}
+ assert scrub_memory_env(env) == ["LLAMA_ARG_LOAD_MODE"]
+ assert env == {}
+
+ def test_both_off_leaves_the_env_untouched(self, toggles):
+ toggles(False, False)
+ env = {"LLAMA_ARG_MLOCK": "1"}
+ assert scrub_memory_env(env) == []
+ assert env == {"LLAMA_ARG_MLOCK": "1"}
+
+
+class TestEffectiveMemoryState:
+ """What the child really runs with: env defaults, argv last-wins on top."""
+
+ @pytest.mark.parametrize(
+ ("argv", "env", "expected"),
+ [
+ ([], {}, (False, False)),
+ (["--mlock"], {}, (True, False)),
+ (["--no-mmap"], {}, (False, True)),
+ (["--load-mode", "mmap+mlock"], {}, (True, False)),
+ (["--load-mode=mmap+mlock"], {}, (True, False)),
+ (["-lm", "mlock"], {}, (True, True)), # mlock without mmap
+ (["--load-mode", "dio"], {}, (False, False)), # DirectIO streams
+ (["--load-mode", "none"], {}, (False, True)),
+ ([], {"LLAMA_ARG_MLOCK": "1"}, (True, False)),
+ ([], {"LLAMA_ARG_MMAP": "off"}, (False, True)),
+ ([], {"LLAMA_ARG_LOAD_MODE": "mmap+mlock"}, (True, False)),
+ # argv beats env, matching llama.cpp.
+ (["--load-mode", "mmap"], {"LLAMA_ARG_MLOCK": "1"}, (False, False)),
+ (["--mlock", "--load-mode", "mmap"], {}, (False, False)),
+ # --no-mmap is the deprecated selector for the whole "none" mode, so
+ # it clears the mlock. Both orderings measured against the binary.
+ (["--mlock", "--no-mmap"], {}, (False, True)),
+ (["--no-mmap", "--mlock"], {}, (True, True)),
+ (["--mlock", "--mmap"], {}, (False, False)),
+ (["--mlock", "--direct-io"], {}, (False, False)),
+ ],
+ )
+ def test_precedence(self, argv, env, expected):
+ assert resolve_effective_memory_state(argv, env) == expected
+
+ def test_degenerate_inputs(self):
+ assert resolve_effective_memory_state(None, None) == (False, False)
+ assert resolve_effective_memory_state(["--load-mode"], {}) == (False, False)
+ # A following flag is not swallowed as the value.
+ assert resolve_effective_memory_state(["--load-mode", "--mlock"], {}) == (True, False)
+
+
+class TestReloadRequired:
+ """The reload hint must reflect the launched state, not only what Unsloth
+ emitted, so a user-supplied --mlock / --no-mmap counts too."""
+
+ @staticmethod
+ def _required(
+ keep,
+ no_res,
+ state,
+ monkeypatch,
+ *,
+ is_loaded = True,
+ is_active = True,
+ ):
+ import routes.inference
+ import routes.settings as rs
+ import utils.model_memory_settings as mm
+
+ backend = type(
+ "_B",
+ (),
+ {
+ "is_loaded": is_loaded,
+ "is_active": is_active,
+ "_memory_state": state,
+ "_memory_policy_active": True,
+ "_memory_mlock_applicable": True,
+ },
+ )()
+ monkeypatch.setattr(routes.inference, "get_llama_cpp_backend", lambda: backend)
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: keep)
+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: no_res)
+ return rs._model_memory_reload_required()
+
+ @pytest.mark.parametrize(
+ ("keep", "no_res", "state", "expected"),
+ [
+ # no_ram_reserve: neither reservation may survive, whoever asked.
+ (False, True, (True, False), True), # user --mlock still live
+ (False, True, (False, True), True), # user --no-mmap still live
+ (False, True, (False, False), False),
+ # keep_resident: satisfied by any mlock, including a user one.
+ (True, False, (True, False), False),
+ (True, False, (False, False), True),
+ # Both off after the policy changed the launch: it has to be undone.
+ (False, False, (True, True), True),
+ (False, False, (False, False), True),
+ ],
+ )
+ def test_matrix(self, monkeypatch, keep, no_res, state, expected):
+ assert self._required(keep, no_res, state, monkeypatch) is expected
+
+ def test_no_model_loaded_never_asks_for_a_reload(self, monkeypatch):
+ assert (
+ self._required(
+ False, True, (False, True), monkeypatch, is_loaded = False, is_active = False
+ )
+ is False
+ )
+
+ def test_a_save_during_startup_still_asks_for_a_reload(self, monkeypatch):
+ """The child is spawned and committed to its flags well before the
+ health check flips is_loaded; keying on that reported no reload while
+ the process was already coming up on the pre-save placement."""
+ assert (
+ self._required(False, True, (True, False), monkeypatch, is_loaded = False, is_active = True)
+ is True
+ )
+
+ def test_a_skipped_mlock_is_not_a_permanent_reload_prompt(self, monkeypatch):
+ import routes.inference
+ import routes.settings as rs
+ import utils.model_memory_settings as mm
+
+ backend = type(
+ "_B",
+ (),
+ {
+ "is_loaded": True,
+ "is_active": True,
+ "_memory_state": (False, False),
+ "_memory_policy_active": True,
+ "_memory_mlock_applicable": False,
+ },
+ )()
+ monkeypatch.setattr(routes.inference, "get_llama_cpp_backend", lambda: backend)
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: True)
+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: False)
+ assert rs._model_memory_reload_required() is False
+
+
+class TestManagedFlagIsNotReset:
+ """Measured against llama.cpp: ANY trailing mmap-family or load-mode flag
+ resets the whole load mode, so a user preset after the managed flag would
+ silently drop the mlock."""
+
+ @pytest.mark.parametrize("load_mode", [True, False])
+ @pytest.mark.parametrize(
+ "preset",
+ [
+ ["--no-mmap"],
+ ["--mmap"],
+ ["-no-mmap"],
+ ["-lm", "none"],
+ ["--load-mode", "mmap"],
+ ["--load-mode=none"],
+ ["--mlock"],
+ # Deprecated load-mode selectors: measured to reset the mode in BOTH
+ # polarities, so all four spellings must go.
+ ["--direct-io"],
+ ["-dio"],
+ ["--no-direct-io"],
+ ["-ndio"],
+ ],
+ )
+ def test_nothing_after_the_managed_flag_can_reset_it(self, policy, load_mode, preset):
+ managed, extras = policy(
+ True, False, preset + ["--temp", "0.7"], supports_load_mode = load_mode
+ )
+ assert managed # residency emitted something
+ # The resolved state of the full argv must still be mlock.
+ mlock, _ = resolve_effective_memory_state(managed + extras, {})
+ assert mlock is True, (managed, extras)
+ assert extras == ["--temp", "0.7"], extras
+
+ def test_affirmative_mmap_survives_when_nothing_is_managed(self, policy):
+ """--mmap is not a reservation, so no-reserve leaves it alone."""
+ _, extras = policy(False, True, ["--mmap", "--temp", "0.7"])
+ assert extras == ["--mmap", "--temp", "0.7"]
+
+
+class TestDuplicateLoadComparator:
+ """Toggling a setting changes only the launch flags, so the load intent is
+ unchanged and the already-loaded fast path would otherwise reuse the
+ process and never apply the setting."""
+
+ @pytest.mark.parametrize(
+ ("launched", "policy_active", "keep", "no_res", "satisfied"),
+ [
+ ((False, False), False, True, False, False), # turn residency on
+ ((True, False), True, False, True, False), # no-reserve on, mlocked
+ ((False, True), False, False, True, False), # no-reserve on, no-mmap
+ ((True, False), True, True, False, True), # already pinned
+ ((False, False), False, False, True, True), # already clean
+ # Both off: anything the policy did must be undone, but a launch it
+ # never touched is left alone.
+ ((True, False), True, False, False, False), # our flag still live
+ ((True, False), False, False, False, True), # user's own flag
+ ((False, False), True, False, False, False), # it suppressed theirs
+ ((False, False), False, False, False, True),
+ # DirectIO is not a RAM reservation, so no-reserve is satisfied.
+ ((False, False), False, False, True, True),
+ # A process this policy does not govern (diffusion) always matches,
+ # else every identical /load would tear it down and reload.
+ (None, False, True, False, True),
+ (None, False, False, True, True),
+ (None, True, True, True, True),
+ ],
+ )
+ def test_forces_a_reload_only_when_the_policy_changed(
+ self, monkeypatch, launched, policy_active, keep, no_res, satisfied
+ ):
+ import utils.model_memory_settings as mm
+
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: keep)
+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: no_res)
+ assert memory_state_satisfies_settings(launched, policy_active) is satisfied
+
+
+class TestCapabilityProbeFallback:
+ def test_load_mode_flag_survives_a_failed_probe(self, monkeypatch):
+ """A timed-out or broken --help probe must fall back conservatively,
+ not raise UnboundLocalError and block the load."""
+ import subprocess
+
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ LlamaCppBackend._capability_cache.clear()
+
+ def boom(*_a, **_k):
+ raise subprocess.TimeoutExpired("llama-server", 10)
+
+ monkeypatch.setattr(subprocess, "run", boom)
+ caps = LlamaCppBackend.probe_server_capabilities("/nonexistent/llama-server")
+ assert caps.get("supports_load_mode") is False
+
+ def test_an_ungoverned_process_never_asks_for_a_reload(self, monkeypatch):
+ """A diffusion GGUF has no llama-server load-mode, so nothing about it
+ can contradict the settings."""
+ import routes.inference
+ import routes.settings as rs
+ import utils.model_memory_settings as mm
+
+ backend = type(
+ "_B",
+ (),
+ {"is_loaded": True, "_memory_state": None, "_memory_policy_active": False},
+ )()
+ monkeypatch.setattr(routes.inference, "get_llama_cpp_backend", lambda: backend)
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: True)
+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: False)
+ assert rs._model_memory_reload_required() is False
+
+
+class TestCacheInvalidationRace:
+ """A read that began before a write must not refill the memo cache with the
+ value it already fetched: the new setting would appear to revert for the
+ rest of the TTL, and a load could launch flags contradicting it."""
+
+ def test_stale_fill_is_dropped(self, monkeypatch):
+ import threading
+
+ import utils.model_memory_settings as mm
+
+ mm._cache.clear()
+ store = {mm.KEEP_RESIDENT_SETTING_KEY: False}
+ gate = threading.Event()
+ reading = threading.Event()
+ slow = {}
+
+ def get_app_setting(key, fallback = None):
+ # SELECT first, then stall, so the reader holds the OLD value.
+ value = store.get(key, fallback)
+ if slow.get("ident") == threading.get_ident():
+ reading.set()
+ gate.wait(2)
+ return value
+
+ monkeypatch.setattr("storage.studio_db.get_app_setting", get_app_setting)
+ monkeypatch.setattr(
+ "storage.studio_db.upsert_app_settings", lambda updates: store.update(updates)
+ )
+
+ def reader():
+ slow["ident"] = threading.get_ident()
+ mm.get_keep_resident()
+
+ thread = threading.Thread(target = reader)
+ thread.start()
+ assert reading.wait(5), "reader never reached the DB"
+ mm.set_model_memory_settings(keep_resident = True)
+ gate.set()
+ thread.join(5)
+ assert not thread.is_alive()
+
+ assert mm.get_keep_resident() is True
+
+ def test_an_uncontended_read_still_caches(self, monkeypatch):
+ import utils.model_memory_settings as mm
+
+ mm._cache.clear()
+ calls = []
+
+ def get_app_setting(key, fallback = None):
+ calls.append(key)
+ return True
+
+ monkeypatch.setattr("storage.studio_db.get_app_setting", get_app_setting)
+ assert mm.get_keep_resident() is True
+ assert mm.get_keep_resident() is True
+ assert len(calls) == 1, "the guard must not disable caching"
+
+
+class TestHostResidencyGate:
+ """mlock pins host RAM. When the weights are fully offloaded to a discrete
+ GPU there is nothing in host RAM worth pinning, so asking for it would
+ reserve RAM for a copy that is not there."""
+
+ def test_discrete_full_offload_does_not_page_lock(self, policy):
+ managed, out = policy(
+ True,
+ False,
+ ["--temp", "0.7"],
+ supports_load_mode = True,
+ weights_in_host_memory = False,
+ )
+ assert managed == []
+ assert out == ["--temp", "0.7"]
+
+ def test_unified_memory_or_partial_offload_still_page_locks(self, policy):
+ managed, out = policy(
+ True,
+ False,
+ ["--temp", "0.7"],
+ supports_load_mode = True,
+ weights_in_host_memory = True,
+ )
+ assert managed == ["--load-mode", "mmap+mlock"]
+ assert out == ["--temp", "0.7"]
+
+ def test_the_gate_does_not_leak_into_the_legacy_flag_path(self, policy):
+ managed, _ = policy(True, False, [], supports_load_mode = False, weights_in_host_memory = False)
+ assert managed == []
+ managed, _ = policy(True, False, [], supports_load_mode = False, weights_in_host_memory = True)
+ assert managed == ["--mlock"]
+
+ def test_no_ram_reserve_still_strips_a_user_flag_off_a_discrete_gpu(self, policy):
+ # The gate only suppresses what the policy ADDS. Removal is unchanged.
+ managed, out = policy(
+ False, True, ["--mlock", "--temp", "0.7"], weights_in_host_memory = False
+ )
+ assert managed == []
+ assert out == ["--temp", "0.7"]
+
+ def test_both_off_is_still_a_pass_through_either_way(self, policy):
+ for host in (True, False):
+ extras = ["--mlock", "--no-mmap", "--temp", "0.7"]
+ managed, out = policy(False, False, extras, weights_in_host_memory = host)
+ assert managed == []
+ assert out == extras
+
+
+class TestRacingReadReturnsTheNewValue:
+ """The load path uses the returned value directly, so a read that raced a
+ write must not hand back the pre-write setting."""
+
+ def test_a_read_invalidated_mid_flight_is_retried(self, monkeypatch):
+ import threading
+
+ import utils.model_memory_settings as mm
+
+ mm._cache.clear()
+ store = {mm.KEEP_RESIDENT_SETTING_KEY: False}
+ gate = threading.Event()
+ reading = threading.Event()
+ slow = {}
+ stalled = {"done": False}
+
+ def get_app_setting(key, fallback = None):
+ value = store.get(key, fallback)
+ # Stall the first read only; the retry must see the committed write.
+ if slow.get("ident") == threading.get_ident() and not stalled["done"]:
+ stalled["done"] = True
+ reading.set()
+ gate.wait(2)
+ return value
+ return value
+
+ monkeypatch.setattr("storage.studio_db.get_app_setting", get_app_setting)
+ monkeypatch.setattr(
+ "storage.studio_db.upsert_app_settings", lambda updates: store.update(updates)
+ )
+
+ seen = {}
+
+ def reader():
+ slow["ident"] = threading.get_ident()
+ seen["value"] = mm.get_keep_resident()
+
+ thread = threading.Thread(target = reader)
+ thread.start()
+ assert reading.wait(5), "reader never reached the DB"
+ mm.set_model_memory_settings(keep_resident = True)
+ gate.set()
+ thread.join(5)
+ assert not thread.is_alive()
+
+ assert seen["value"] is True, "the racing reader served the pre-write value"
+
+ def test_a_write_storm_cannot_spin_forever(self, monkeypatch):
+ import utils.model_memory_settings as mm
+
+ mm._cache.clear()
+ reads = []
+
+ def get_app_setting(key, fallback = None):
+ reads.append(key)
+ mm._invalidate(key) # a write lands during every read
+ return True
+
+ monkeypatch.setattr("storage.studio_db.get_app_setting", get_app_setting)
+ assert mm.get_keep_resident() is True
+ assert len(reads) == mm._MAX_REREADS
+
+ def test_an_unreadable_db_falls_back_to_the_default(self, monkeypatch):
+ import utils.model_memory_settings as mm
+
+ mm._cache.clear()
+
+ def boom(key, fallback = None):
+ raise RuntimeError("database is locked")
+
+ monkeypatch.setattr("storage.studio_db.get_app_setting", boom)
+ assert mm.get_keep_resident() is mm.DEFAULT_KEEP_RESIDENT
+ assert mm.get_no_ram_reserve() is mm.DEFAULT_NO_RAM_RESERVE
+ assert mm.should_mlock() is False
+
+
+class TestMlockApplicability:
+ """A launch that deliberately skips mlock (full offload to a discrete GPU)
+ still satisfies residency. Demanding the flag would ask for a reload no
+ relaunch could satisfy, and would reject every duplicate load forever."""
+
+ def test_a_skipped_mlock_satisfies_keep_resident(self, monkeypatch):
+ import utils.model_memory_settings as mm
+
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: True)
+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: False)
+ state = resolve_effective_memory_state([], {})
+ assert state == (False, False)
+ # The regression: without the applicability flag this reads as unsatisfied.
+ assert memory_state_satisfies_settings(state, True, True) is False
+ assert memory_state_satisfies_settings(state, True, False) is True
+
+ def test_page_lockable_launches_are_unchanged(self, monkeypatch):
+ import utils.model_memory_settings as mm
+
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: True)
+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: False)
+ unpinned = resolve_effective_memory_state([], {})
+ pinned = resolve_effective_memory_state(["--load-mode", "mmap+mlock"], {})
+ assert memory_state_satisfies_settings(unpinned, True) is False
+ assert memory_state_satisfies_settings(pinned, True) is True
+
+ def test_applicability_does_not_override_no_ram_reserve(self, monkeypatch):
+ """no-reserve still wins: a pinned process must be relaunched even where
+ mlock would not have been applicable."""
+ import utils.model_memory_settings as mm
+
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: True)
+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: True)
+ state = resolve_effective_memory_state(["--mlock"], {})
+ assert memory_state_satisfies_settings(state, True, False) is False
+
+ def test_applicability_is_ignored_with_both_toggles_off(self, monkeypatch):
+ import utils.model_memory_settings as mm
+
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: False)
+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: False)
+ state = resolve_effective_memory_state([], {})
+ assert memory_state_satisfies_settings(state, False, False) is True
+ assert memory_state_satisfies_settings(state, True, False) is False
+
+ def test_an_ungoverned_process_still_always_matches(self, monkeypatch):
+ import utils.model_memory_settings as mm
+
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: True)
+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: False)
+ assert memory_state_satisfies_settings(None, True, False) is True
+
+ def test_the_default_keeps_the_old_meaning(self, monkeypatch):
+ """Callers that never pass the flag behave exactly as before."""
+ import utils.model_memory_settings as mm
+
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: True)
+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: False)
+ assert memory_state_satisfies_settings((False, False), True) is False
+ assert memory_state_satisfies_settings((True, False), True) is True
+
+
+class TestFullOffloadDetection:
+ """``fully_gpu_offloaded`` is set only by the auto branch, so the mlock gate
+ has to derive manual mode and a user -ngl for itself."""
+
+ @staticmethod
+ def _backend(n_layers, n_cpu_moe = 0):
+ from core.inference.llama_cpp import LlamaCppBackend
+ return type(
+ "_B",
+ (),
+ {
+ "n_layers": n_layers,
+ "_n_cpu_moe": n_cpu_moe,
+ "_offloads_every_layer": LlamaCppBackend._offloads_every_layer,
+ },
+ )()
+
+ def _check(
+ self,
+ n_layers,
+ mode,
+ layers,
+ extras = None,
+ n_cpu_moe = 0,
+ ):
+ backend = self._backend(n_layers, n_cpu_moe)
+ return backend._offloads_every_layer(
+ gpu_memory_mode = mode, gpu_layers = layers, extra_args = extras
+ )
+
+ def test_manual_at_the_pickers_maximum_is_a_full_offload(self):
+ # The slider's maximum is block_count + 1.
+ assert self._check(32, "manual", 33) is True
+
+ def test_manual_short_of_the_maximum_leaves_layers_on_the_host(self):
+ assert self._check(32, "manual", 32) is False
+ assert self._check(32, "manual", 31) is False
+ assert self._check(32, "manual", 0) is False
+
+ def test_manual_with_cpu_experts_is_not_a_full_offload(self):
+ assert self._check(32, "manual", 33, n_cpu_moe = 4) is False
+
+ def test_a_user_ngl_override_counts_in_auto_mode(self):
+ assert self._check(32, "auto", None, ["-ngl", "99"]) is True
+ assert self._check(32, "auto", None, ["--gpu-layers", "33"]) is True
+ assert self._check(32, "auto", None, ["-ngl", "-1"]) is True
+ assert self._check(32, "auto", None, ["-ngl", "16"]) is False
+
+ def test_a_tensor_override_keeps_weights_on_the_host(self):
+ for flag in ("-ot", "--override-tensor", "-cmoe", "--cpu-moe"):
+ assert self._check(32, "auto", None, ["-ngl", "99", flag, "x"]) is False
+
+ def test_every_unknown_answers_no(self):
+ # No block count, no extras, unparseable -ngl: all keep the old behaviour
+ # of page-locking rather than guessing a full offload.
+ assert self._check(None, "manual", 33) is False
+ assert self._check(0, "manual", 33) is False
+ assert self._check(32, "auto", None, None) is False
+ assert self._check(32, "auto", None, []) is False
+ assert self._check(32, "auto", None, ["-ngl", "abc"]) is False
+
+ def test_manual_auto_layers_falls_back_to_the_extras(self):
+ # gpu_layers < 0 means manual did not pin a count.
+ assert self._check(32, "manual", -1, ["-ngl", "99"]) is True
+ assert self._check(32, "manual", -1, []) is False
+
+ def test_the_manual_branch_really_does_not_set_fully_gpu_offloaded(self):
+ """Pins the premise. If a later change starts setting it there, this
+ test fails and the derived check can be simplified away."""
+ import ast
+ import inspect
+ import textwrap
+
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ source = textwrap.dedent(inspect.getsource(LlamaCppBackend.load_model))
+ tree = ast.parse(source)
+ manual_branches = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.If)
+ and 'gpu_memory_mode == "manual" and gpu_layers >= 0'
+ in ast.unparse(node.test).replace("'", '"')
+ ]
+ assert manual_branches, "the manual offload branch moved"
+ # Only the branch body: its orelse holds the auto branch, which is the
+ # one place that does set the flag.
+ assigned = {
+ target.id
+ for branch in manual_branches
+ for statement in branch.body
+ for node in ast.walk(statement)
+ if isinstance(node, ast.Assign)
+ for target in node.targets
+ if isinstance(target, ast.Name)
+ }
+ assert "fully_gpu_offloaded" not in assigned
+
+
+class TestNegativeDirectIoIsARamReservation:
+ """Upstream maps -ndio / --no-direct-io to mode `none`, like --no-mmap, so
+ they hold a full host buffer. Calling them non-reserving let no-reserve
+ leave one in the argv and still report the process compliant."""
+
+ @pytest.mark.parametrize("flag", ["--no-direct-io", "-ndio", "--no_direct_io"])
+ def test_the_negative_spellings_reserve_ram(self, flag):
+ assert resolve_effective_memory_state([flag], {}) == (False, True)
+
+ @pytest.mark.parametrize("flag", ["--direct-io", "-dio"])
+ def test_the_affirmative_spellings_do_not(self, flag):
+ assert resolve_effective_memory_state([flag], {}) == (False, False)
+
+ def test_it_matches_no_mmap_in_both_orderings(self):
+ for negative in ("--no-direct-io", "-ndio"):
+ assert resolve_effective_memory_state(["--mlock", negative], {}) == (False, True)
+ assert resolve_effective_memory_state([negative, "--mlock"], {}) == (True, True)
+
+ @pytest.mark.parametrize("flag", ["--no-direct-io", "-ndio"])
+ def test_no_ram_reserve_strips_them(self, policy, flag):
+ managed, out = policy(False, True, [flag, "--temp", "0.7"])
+ assert managed == []
+ assert out == ["--temp", "0.7"]
+
+ @pytest.mark.parametrize("flag", ["--direct-io", "-dio"])
+ def test_no_ram_reserve_leaves_the_affirmative_ones(self, policy, flag):
+ # DirectIO streams, so it is not a reservation and nothing has to go.
+ _, out = policy(False, True, [flag, "--temp", "0.7"])
+ assert out == [flag, "--temp", "0.7"]
+
+ def test_the_comparator_now_sees_the_reservation(self, monkeypatch):
+ import utils.model_memory_settings as mm
+
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: False)
+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: True)
+ state = resolve_effective_memory_state(["--no-direct-io"], {})
+ assert memory_state_satisfies_settings(state, True) is False
+
+
+class TestEnvVarsAssignTheWholeMode:
+ """Each var runs its flag's handler, so it assigns the whole mode and a
+ later one wins. Treating LLAMA_ARG_MMAP as a reserves_ram bit left mlock
+ standing, so residency read an unlocked child as already satisfied."""
+
+ @pytest.mark.parametrize(
+ ("env", "expected"),
+ [
+ # Measured against the shipped binary: VmLck is 0 for both of these.
+ ({"LLAMA_ARG_MLOCK": "1", "LLAMA_ARG_MMAP": "on"}, (False, False)),
+ ({"LLAMA_ARG_MLOCK": "1", "LLAMA_ARG_DIO": "0"}, (False, True)),
+ ({"LLAMA_ARG_MLOCK": "1", "LLAMA_ARG_DIO": "1"}, (False, False)),
+ ({"LLAMA_ARG_MLOCK": "1", "LLAMA_ARG_MMAP": "off"}, (False, True)),
+ # Registration order: load-mode is read last and wins outright.
+ (
+ {"LLAMA_ARG_MMAP": "off", "LLAMA_ARG_LOAD_MODE": "mmap+mlock"},
+ (True, False),
+ ),
+ # Each still works alone.
+ ({"LLAMA_ARG_MLOCK": "1"}, (True, False)),
+ ({"LLAMA_ARG_DIO": "1"}, (False, False)),
+ ({"LLAMA_ARG_DIO": "0"}, (False, True)),
+ # An unset or unparseable value assigns nothing.
+ ({"LLAMA_ARG_DIO": ""}, (False, False)),
+ ({"LLAMA_ARG_MLOCK": "1", "LLAMA_ARG_MMAP": "banana"}, (True, False)),
+ ],
+ )
+ def test_env_precedence(self, env, expected):
+ assert resolve_effective_memory_state([], env) == expected
+
+ def test_argv_still_beats_every_env_var(self):
+ env = {"LLAMA_ARG_MLOCK": "1", "LLAMA_ARG_DIO": "0"}
+ assert resolve_effective_memory_state(["--load-mode", "mmap+mlock"], env) == (True, False)
+
+ def test_residency_is_not_reported_satisfied_against_an_unlocked_child(self, monkeypatch):
+ import utils.model_memory_settings as mm
+
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: True)
+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: False)
+ state = resolve_effective_memory_state([], {"LLAMA_ARG_MLOCK": "1", "LLAMA_ARG_MMAP": "on"})
+ assert memory_state_satisfies_settings(state, False) is False
+
+
+class TestMlockActiveReflectsWhatWillActuallyBePassed:
+ """mlock_active drives the ulimit -l warning. Taking it from the toggles
+ alone tells a discrete-GPU user to raise a limit nothing consults, since
+ the gate suppresses the lock there."""
+
+ @staticmethod
+ def _response(keep, no_res, backend, monkeypatch):
+ import routes.inference
+ import routes.settings as rs
+ import utils.model_memory_settings as mm
+
+ monkeypatch.setattr(routes.inference, "get_llama_cpp_backend", lambda: backend)
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: keep)
+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: no_res)
+ # The route imports these by name at module scope, so patch them there.
+ monkeypatch.setattr(rs, "should_mlock", lambda: keep and not no_res)
+ monkeypatch.setattr(rs, "get_model_memory_settings", lambda: (keep, no_res))
+ monkeypatch.setattr(rs, "memlock_limit_bytes", lambda: 8 * 1024 * 1024)
+ return rs._model_memory_response()
+
+ @staticmethod
+ def _backend(
+ loaded,
+ mlock_applicable,
+ state = None,
+ ):
+ # A host-resident load with residency on carries the lock, so its state
+ # says so; a gated one carries nothing. Keeping the two in step matters,
+ # because the response reads the launched state rather than the flag.
+ if state is None:
+ state = (True, False) if mlock_applicable else (False, False)
+ return type(
+ "_B",
+ (),
+ {
+ "is_loaded": loaded,
+ "is_active": loaded,
+ "_memory_state": state,
+ "_memory_policy_active": False,
+ "_memory_mlock_applicable": mlock_applicable,
+ "_memory_launch_pending": False,
+ },
+ )()
+
+ def test_a_gated_load_reports_no_active_lock_and_no_limit(self, monkeypatch):
+ resp = self._response(True, False, self._backend(True, False), monkeypatch)
+ assert resp.mlock_active is False
+ assert resp.memlock_limit_bytes is None
+
+ def test_a_host_resident_load_still_reports_the_limit(self, monkeypatch):
+ resp = self._response(True, False, self._backend(True, True), monkeypatch)
+ assert resp.mlock_active is True
+ assert resp.memlock_limit_bytes == 8 * 1024 * 1024
+
+ def test_with_nothing_loaded_the_intent_is_reported(self, monkeypatch):
+ # No launch to read, so fall back to what the toggles ask for.
+ resp = self._response(True, False, self._backend(False, False), monkeypatch)
+ assert resp.mlock_active is True
+
+ def test_no_ram_reserve_still_wins(self, monkeypatch):
+ resp = self._response(True, True, self._backend(True, True), monkeypatch)
+ assert resp.mlock_active is False
+ assert resp.memlock_limit_bytes is None
+
+
+class TestHostMemoryGate:
+ """The full gate, not just the layer count: CPU-placement extras and
+ unified-memory devices both keep weights in pageable host RAM."""
+
+ @staticmethod
+ def _gate(
+ monkeypatch,
+ *,
+ apple = False,
+ amd = False,
+ vulkan_igpu = False,
+ **kwargs,
+ ):
+ import utils.hardware
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ monkeypatch.setattr(utils.hardware, "is_apple_silicon", lambda: apple)
+ monkeypatch.setattr(
+ LlamaCppBackend, "_amd_apu_wants_unified_memory", staticmethod(lambda idx = None: amd)
+ )
+ monkeypatch.setattr(
+ LlamaCppBackend,
+ "_vulkan_targets_are_igpus",
+ staticmethod(lambda binary, idx = None: vulkan_igpu),
+ )
+ backend = type(
+ "_B",
+ (),
+ {
+ "n_layers": 32,
+ "_n_cpu_moe": 0,
+ "_weights_in_host_memory": LlamaCppBackend._weights_in_host_memory,
+ "_offloads_every_layer": LlamaCppBackend._offloads_every_layer,
+ "_amd_apu_wants_unified_memory": staticmethod(lambda idx = None: amd),
+ "_vulkan_targets_are_igpus": staticmethod(lambda binary, idx = None: vulkan_igpu),
+ },
+ )()
+ params = {
+ "fully_gpu_offloaded": False,
+ "gpu_memory_mode": "auto",
+ "gpu_layers": None,
+ "extra_args": None,
+ }
+ params.update(kwargs)
+ return backend._weights_in_host_memory(**params)
+
+ def test_a_discrete_full_offload_is_not_host_resident(self, monkeypatch):
+ assert self._gate(monkeypatch, fully_gpu_offloaded = True) is False
+
+ def test_a_partial_offload_is_host_resident(self, monkeypatch):
+ assert self._gate(monkeypatch, fully_gpu_offloaded = False) is True
+
+ @pytest.mark.parametrize("flag", ["-ncmoe", "--n-cpu-moe", "-cmoe", "--cpu-moe"])
+ def test_cpu_moe_extras_survive_an_auto_full_offload(self, monkeypatch, flag):
+ """The auto branch sets fully_gpu_offloaded, but an extra that pins
+ experts on the CPU still leaves weights in RAM, so it must not be
+ short-circuited past."""
+ assert self._gate(monkeypatch, fully_gpu_offloaded = True, extra_args = [flag, "4"]) is True
+
+ def test_a_tensor_override_survives_an_auto_full_offload(self, monkeypatch):
+ assert (
+ self._gate(
+ monkeypatch,
+ fully_gpu_offloaded = True,
+ extra_args = ["--override-tensor", "blk.*=CPU"],
+ )
+ is True
+ )
+
+ @pytest.mark.parametrize("flag", ["-ngl", "--gpu-layers", "--n-gpu-layers"])
+ @pytest.mark.parametrize("count", ["0", "8"])
+ def test_a_pass_through_ngl_beats_the_auto_full_offload_prediction(
+ self, monkeypatch, flag, count
+ ):
+ """Auto keeps the user's -ngl and appends it after ours, and llama.cpp is
+ last-wins, so the prediction is void and the weights are in RAM."""
+ assert self._gate(monkeypatch, fully_gpu_offloaded = True, extra_args = [flag, count]) is True
+
+ @pytest.mark.parametrize("extras", [["--fit", "on"], ["--fit=on"], ["-fit", "1"]])
+ def test_a_pass_through_fit_on_beats_the_auto_full_offload_prediction(
+ self, monkeypatch, extras
+ ):
+ """--fit on re-enables the fitter, which may leave a prefix on the CPU."""
+ assert self._gate(monkeypatch, fully_gpu_offloaded = True, extra_args = extras) is True
+
+ @pytest.mark.parametrize("extras", [["--fit", "off"], ["-fit", "off"], ["--fit=off"]])
+ def test_a_pass_through_fit_off_leaves_the_prediction_alone(self, monkeypatch, extras):
+ """It restates what we already pass, and a disabled fitter cannot move
+ anything to the CPU, so pinning here is the redundant host copy."""
+ assert self._gate(monkeypatch, fully_gpu_offloaded = True, extra_args = extras) is False
+
+ def test_the_fit_value_is_last_wins(self, monkeypatch):
+ on_last = ["--fit", "off", "--fit", "on"]
+ off_last = ["--fit", "on", "--fit", "off"]
+ assert self._gate(monkeypatch, fully_gpu_offloaded = True, extra_args = on_last) is True
+ assert self._gate(monkeypatch, fully_gpu_offloaded = True, extra_args = off_last) is False
+
+ def test_a_pass_through_full_offload_still_skips_the_lock(self, monkeypatch):
+ """The guard must not over-fire: -ngl above the block count is a real
+ full offload, so page-locking a redundant host copy stays skipped."""
+ assert self._gate(monkeypatch, fully_gpu_offloaded = True, extra_args = ["-ngl", "33"]) is False
+
+ def test_apple_silicon_is_always_host_resident(self, monkeypatch):
+ assert self._gate(monkeypatch, fully_gpu_offloaded = True, apple = True) is True
+
+ def test_an_amd_unified_apu_is_always_host_resident(self, monkeypatch):
+ assert self._gate(monkeypatch, fully_gpu_offloaded = True, amd = True) is True
+
+ def test_a_vulkan_igpu_is_host_resident(self, monkeypatch):
+ """An iGPU's reported VRAM is shared system RAM, which the repo already
+ accounts for in the fit, so a full offload there is still pageable."""
+ assert (
+ self._gate(
+ monkeypatch,
+ fully_gpu_offloaded = True,
+ is_vulkan_backend = True,
+ vulkan_igpu = True,
+ )
+ is True
+ )
+
+ def test_a_discrete_vulkan_card_is_not(self, monkeypatch):
+ assert (
+ self._gate(
+ monkeypatch,
+ fully_gpu_offloaded = True,
+ is_vulkan_backend = True,
+ vulkan_igpu = False,
+ )
+ is False
+ )
+
+ def test_the_igpu_probe_is_not_consulted_off_vulkan(self, monkeypatch):
+ """A CUDA install must not pay for the probe subprocess."""
+ assert (
+ self._gate(
+ monkeypatch,
+ fully_gpu_offloaded = True,
+ is_vulkan_backend = False,
+ vulkan_igpu = True,
+ )
+ is False
+ )
+
+
+class TestVulkanIgpuDetection:
+ @staticmethod
+ def _probe(monkeypatch, rows):
+ from core.inference.llama_cpp import LlamaCppBackend
+ monkeypatch.setattr(
+ LlamaCppBackend, "_run_vulkan_probe", staticmethod(lambda binary = None: rows)
+ )
+ return LlamaCppBackend._vulkan_targets_are_igpus
+
+ def test_all_igpus(self, monkeypatch):
+ rows = [{"index": 0, "is_igpu": True}]
+ assert self._probe(monkeypatch, rows)("bin", None) is True
+
+ def test_a_mixed_set_still_has_host_weights(self, monkeypatch):
+ """A split puts part of the model on the iGPU, whose VRAM is system RAM,
+ so those pages are as evictable as if it were the only device."""
+ rows = [{"index": 0, "is_igpu": True}, {"index": 1, "is_igpu": False}]
+ assert self._probe(monkeypatch, rows)("bin", None) is True
+
+ def test_only_the_selected_devices_count(self, monkeypatch):
+ rows = [{"index": 0, "is_igpu": True}, {"index": 1, "is_igpu": False}]
+ assert self._probe(monkeypatch, rows)("bin", [0]) is True
+ assert self._probe(monkeypatch, rows)("bin", [1]) is False
+ assert self._probe(monkeypatch, rows)("bin", [0, 1]) is True
+
+ def test_discrete_only_stays_no(self, monkeypatch):
+ rows = [{"index": 0, "is_igpu": False}, {"index": 1, "is_igpu": False}]
+ assert self._probe(monkeypatch, rows)("bin", None) is False
+
+ def test_an_unreadable_probe_answers_no(self, monkeypatch):
+ assert self._probe(monkeypatch, [])("bin", None) is False
+
+ def test_a_raising_probe_never_fails_the_load(self, monkeypatch):
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ def boom(binary = None):
+ raise OSError("no vulkan loader")
+
+ monkeypatch.setattr(LlamaCppBackend, "_run_vulkan_probe", staticmethod(boom))
+ assert LlamaCppBackend._vulkan_targets_are_igpus("bin", None) is False
+
+
+class TestLegacyNegativeEnvAliases:
+ """Upstream rewrites LLAMA_ARG_<NAME> to LLAMA_ARG_NO_<NAME> for any option
+ with a negative form and, if that var EXISTS, forces the value falsey before
+ reading the affirmative one (common/arg.cpp get_value_from_env). Confirmed
+ against the shipped binary: NO_MMAP and NO_DIO fire their handler's
+ deprecation warning even at "0", and NO_MLOCK does nothing."""
+
+ @pytest.mark.parametrize("name", ["LLAMA_ARG_NO_MMAP", "LLAMA_ARG_NO_DIO"])
+ @pytest.mark.parametrize("value", ["1", "0", "", "false", "anything"])
+ def test_presence_alone_reserves_ram(self, name, value):
+ assert resolve_effective_memory_state([], {name: value}) == (False, True)
+
+ @pytest.mark.parametrize("name", ["LLAMA_ARG_NO_MMAP", "LLAMA_ARG_NO_DIO"])
+ def test_the_negative_beats_its_own_affirmative(self, name):
+ affirmative = name.replace("_NO_", "_")
+ assert resolve_effective_memory_state([], {name: "0", affirmative: "on"}) == (False, True)
+
+ def test_mlock_has_no_negative_form_so_the_alias_is_inert(self):
+ assert resolve_effective_memory_state([], {"LLAMA_ARG_NO_MLOCK": "1"}) == (False, False)
+ # And it cannot cancel the affirmative one.
+ assert resolve_effective_memory_state(
+ [], {"LLAMA_ARG_MLOCK": "1", "LLAMA_ARG_NO_MLOCK": "1"}
+ ) == (True, False)
+
+ def test_absence_does_not(self):
+ assert resolve_effective_memory_state([], {}) == (False, False)
+
+ @pytest.mark.parametrize("name", ["LLAMA_ARG_NO_MMAP", "LLAMA_ARG_NO_DIO"])
+ def test_it_is_scrubbed_when_a_toggle_owns_placement(self, monkeypatch, name):
+ import utils.model_memory_settings as mm
+
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: False)
+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: True)
+ env = {name: "1", "PATH": "/usr/bin"}
+ assert name in scrub_memory_env(env)
+ assert env == {"PATH": "/usr/bin"}
+
+ def test_both_off_leaves_it_alone(self, monkeypatch):
+ import utils.model_memory_settings as mm
+
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: False)
+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: False)
+ env = {"LLAMA_ARG_NO_MMAP": "1", "LLAMA_ARG_NO_DIO": "1"}
+ assert scrub_memory_env(env) == []
+ assert env == {"LLAMA_ARG_NO_MMAP": "1", "LLAMA_ARG_NO_DIO": "1"}
+
+ def test_argv_still_overrides_it(self):
+ assert resolve_effective_memory_state(["--mmap"], {"LLAMA_ARG_NO_MMAP": "1"}) == (
+ False,
+ False,
+ )
+
+
+class TestNonReservingLoadModesSurvive:
+ """No-reserve vetoes the reservation, not the loader: dio and mmap hold no
+ full host copy, so a DirectIO preset must not silently become mmap."""
+
+ @pytest.mark.parametrize("value", ["dio", "mmap"])
+ def test_a_non_reserving_mode_is_kept(self, policy, value):
+ _managed, out = policy(False, True, ["--load-mode", value, "--temp", "0.7"])
+ assert out == ["--load-mode", value, "--temp", "0.7"]
+
+ @pytest.mark.parametrize("value", ["none", "mlock", "mmap+mlock"])
+ def test_a_reserving_or_locking_mode_is_dropped(self, policy, value):
+ _managed, out = policy(False, True, ["--load-mode", value, "--temp", "0.7"])
+ assert out == ["--temp", "0.7"]
+
+ def test_the_attached_spelling_is_handled_too(self, policy):
+ _managed, out = policy(False, True, ["--load-mode=mlock", "-c", "4096"])
+ assert out == ["-c", "4096"]
+ _managed, out = policy(False, True, ["--load-mode=dio", "-c", "4096"])
+ assert out == ["--load-mode=dio", "-c", "4096"]
+
+ def test_the_short_alias_is_handled_too(self, policy):
+ _managed, out = policy(False, True, ["-lm", "mlock"])
+ assert out == []
+ _managed, out = policy(False, True, ["-lm", "dio"])
+ assert out == ["-lm", "dio"]
+
+ def test_an_unknown_value_is_left_alone(self, policy):
+ _managed, out = policy(False, True, ["--load-mode", "future-mode"])
+ assert out == ["--load-mode", "future-mode"]
+
+ def test_a_trailing_flag_does_not_crash(self, policy):
+ _managed, out = policy(False, True, ["--load-mode"])
+ assert out == ["--load-mode"]
+
+ def test_the_kept_mode_actually_satisfies_no_reserve(self, policy):
+ """The point of keeping it: the resolver must agree it reserves nothing,
+ or the reload hint would fire forever."""
+ _managed, out = policy(False, True, ["--load-mode", "dio"])
+ assert resolve_effective_memory_state(out, {}) == (False, False)
+
+ def test_keep_resident_still_strips_every_mode(self, policy):
+ """The mlock branch is unchanged: a trailing mode of ANY value resets
+ the whole thing and would drop the managed lock."""
+ managed, out = policy(True, False, ["--load-mode", "dio"], supports_load_mode = True)
+ assert managed == ["--load-mode", "mmap+mlock"]
+ assert out == []
+
+
+def _fake_backend(**attrs):
+ base = {
+ "is_loaded": False,
+ "is_active": False,
+ "_memory_state": None,
+ "_memory_policy_active": False,
+ "_memory_mlock_applicable": True,
+ "_memory_launch_pending": False,
+ }
+ base.update(attrs)
+ return type("_B", (), base)()
+
+
+def _install_backend(monkeypatch, backend, *, keep, no_res):
+ import routes.inference
+ import utils.model_memory_settings as mm
+
+ monkeypatch.setattr(routes.inference, "get_llama_cpp_backend", lambda: backend)
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: keep)
+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: no_res)
+ monkeypatch.setattr(mm, "should_mlock", lambda: keep and not no_res)
+
+
+class TestPreSpawnWindow:
+ """The placement is fixed before Popen assigns _process, so is_active alone
+ still leaves a window where a save reports no reload."""
+
+ def test_a_save_before_the_child_spawns_still_asks_for_a_reload(self, monkeypatch):
+ import routes.settings as rs
+
+ backend = _fake_backend(
+ is_active = False,
+ _memory_launch_pending = True,
+ _memory_state = (True, False),
+ _memory_policy_active = True,
+ )
+ _install_backend(monkeypatch, backend, keep = False, no_res = True)
+ assert rs._model_memory_reload_required() is True
+
+ def test_nothing_running_still_never_asks(self, monkeypatch):
+ import routes.settings as rs
+
+ backend = _fake_backend(_memory_state = (True, False), _memory_policy_active = True)
+ _install_backend(monkeypatch, backend, keep = False, no_res = True)
+ assert rs._model_memory_reload_required() is False
+
+ def test_a_pending_launch_that_matches_needs_no_reload(self, monkeypatch):
+ import routes.settings as rs
+
+ backend = _fake_backend(
+ _memory_launch_pending = True,
+ _memory_state = (True, False),
+ _memory_policy_active = True,
+ )
+ _install_backend(monkeypatch, backend, keep = True, no_res = False)
+ assert rs._model_memory_reload_required() is False
+
+
+class TestMlockActiveReporting:
+ """mlock_active drives the ulimit -l warning, so it has to describe the lock
+ that was actually taken once something is running."""
+
+ def test_with_nothing_loaded_it_reports_the_intent(self, monkeypatch):
+ import routes.settings as rs
+
+ _install_backend(monkeypatch, _fake_backend(), keep = True, no_res = False)
+ body = rs._model_memory_response()
+ assert body.mlock_active is True
+ assert body.memlock_limit_bytes == mm_settings.memlock_limit_bytes()
+
+ def test_a_diffusion_runner_reports_no_lock(self, monkeypatch):
+ """It has no load-mode, so it never received a lock flag and warning
+ about ulimit -l would be noise."""
+ import routes.settings as rs
+
+ backend = _fake_backend(is_active = True, is_loaded = True, _memory_state = None)
+ _install_backend(monkeypatch, backend, keep = True, no_res = False)
+ body = rs._model_memory_response()
+ assert body.mlock_active is False
+ assert body.memlock_limit_bytes is None
+ assert body.keep_resident is True, "the toggle itself still reads back on"
+
+ def test_a_skipped_lock_on_a_discrete_gpu_reports_no_lock(self, monkeypatch):
+ import routes.settings as rs
+
+ backend = _fake_backend(
+ is_active = True,
+ is_loaded = True,
+ _memory_state = (False, False),
+ _memory_mlock_applicable = False,
+ )
+ _install_backend(monkeypatch, backend, keep = True, no_res = False)
+ assert rs._model_memory_response().mlock_active is False
+
+ def test_a_lock_that_was_taken_reports_active(self, monkeypatch):
+ import routes.settings as rs
+
+ backend = _fake_backend(is_active = True, is_loaded = True, _memory_state = (True, False))
+ _install_backend(monkeypatch, backend, keep = True, no_res = False)
+ body = rs._model_memory_response()
+ assert body.mlock_active is True
+ assert body.memlock_limit_bytes == mm_settings.memlock_limit_bytes()
+
+ def test_a_users_own_mlock_counts_as_a_real_lock(self, monkeypatch):
+ """Keep resident on, full discrete offload so Unsloth emits nothing, but
+ the user typed --mlock: the child IS locked, so say so."""
+ import routes.settings as rs
+
+ backend = _fake_backend(
+ is_active = True,
+ is_loaded = True,
+ _memory_state = resolve_effective_memory_state(["--mlock"], {}),
+ _memory_mlock_applicable = False,
+ )
+ _install_backend(monkeypatch, backend, keep = True, no_res = False)
+ assert rs._model_memory_response().mlock_active is True
+
+ def test_no_reserve_still_vetoes_it_outright(self, monkeypatch):
+ import routes.settings as rs
+
+ backend = _fake_backend(is_active = True, is_loaded = True, _memory_state = (True, False))
+ _install_backend(monkeypatch, backend, keep = True, no_res = True)
+ assert rs._model_memory_response().mlock_active is False
+
+
+class TestFitOnRetryReArmsResidency:
+ """The --fit on fallback fires exactly when the full-offload prediction that
+ suppressed the lock turns out to be wrong, so the retry must re-apply it."""
+
+ @staticmethod
+ def _retry_argv(original, *, supports_load_mode = True):
+ """What the fallback builds: flip --fit, then append the managed flag.
+
+ Appending (rather than inserting before the extras) is measured against
+ the binary in the simulation suite: the last --load-mode wins.
+ """
+ run = list(original)
+ if "--fit" in run:
+ run[run.index("--fit") + 1] = "on"
+ run.extend(["--load-mode", "mmap+mlock"] if supports_load_mode else ["--mlock"])
+ return run
+
+ def test_the_retry_is_page_locked(self):
+ original = ["-ngl", "-1", "--fit", "off", "--temp", "0.7"]
+ retry = self._retry_argv(original)
+ assert resolve_effective_memory_state(original, {}) == (False, False)
+ assert resolve_effective_memory_state(retry, {}) == (True, False)
+ assert retry[:4] == ["-ngl", "-1", "--fit", "on"]
+
+ def test_it_wins_over_a_user_load_mode_in_the_extras(self):
+ original = ["--fit", "off", "--load-mode", "dio"]
+ assert resolve_effective_memory_state(self._retry_argv(original), {}) == (True, False)
+
+ def test_it_wins_over_a_user_no_mmap(self):
+ original = ["--fit", "off", "--no-mmap"]
+ assert resolve_effective_memory_state(self._retry_argv(original), {}) == (True, False)
+
+ def test_the_legacy_flag_path_re_arms_too(self):
+ original = ["--fit", "off"]
+ retry = self._retry_argv(original, supports_load_mode = False)
+ assert resolve_effective_memory_state(retry, {}) == (True, False)
+
+ def test_the_re_armed_launch_satisfies_residency(self, monkeypatch):
+ """Without this the retry would nag for a reload that cannot help."""
+ import utils.model_memory_settings as mm
+
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: True)
+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: False)
+ state = resolve_effective_memory_state(self._retry_argv(["--fit", "off"]), {})
+ assert memory_state_satisfies_settings(state, True, True) is True
+
+ def test_a_missing_fit_flag_does_not_crash(self):
+ assert resolve_effective_memory_state(self._retry_argv(["-ngl", "-1"]), {}) == (
+ True,
+ False,
+ )
+
+
+class TestTheRetryCanReadTheGate:
+ """The re-arm above runs inside _spawn_and_wait but assigns
+ _mem_host_resident, which is a load_model local. Without a nonlocal that
+ assignment makes it local to _spawn_and_wait, so reading it first is an
+ UnboundLocalError and the --fit on retry raises instead of retrying."""
+
+ @staticmethod
+ def _load_model_ast():
+ import ast
+ from pathlib import Path
+
+ src = Path(__file__).resolve().parent.parent / "core" / "inference" / "llama_cpp.py"
+ for node in ast.walk(ast.parse(src.read_text(encoding = "utf-8"))):
+ if isinstance(node, ast.FunctionDef) and node.name == "load_model":
+ return node
+ raise AssertionError("load_model not found")
+
+ def test_every_writer_of_the_gate_can_also_read_it(self):
+ import ast
+ outer = self._load_model_ast()
+ for inner in ast.walk(outer):
+ if not isinstance(inner, ast.FunctionDef) or inner is outer:
+ continue
+ writes = any(
+ isinstance(n, ast.Name)
+ and n.id == "_mem_host_resident"
+ and isinstance(n.ctx, ast.Store)
+ for n in ast.walk(inner)
+ )
+ if not writes:
+ continue
+ declared = any(
+ isinstance(n, ast.Nonlocal) and "_mem_host_resident" in n.names
+ for n in ast.walk(inner)
+ )
+ assert declared, (
+ f"{inner.name} assigns _mem_host_resident without a nonlocal, so "
+ f"reading it there raises UnboundLocalError"
+ )
+
+
+class TestInheritedCpuPlacement:
+ """The child inherits these, so they outlive stripping the equivalent
+ flags and keep weights in host RAM whatever the layer count says."""
+
+ @pytest.mark.parametrize(
+ "env,expected",
+ [
+ ({}, False),
+ ({"LLAMA_ARG_OVERRIDE_TENSOR": "blk.*=CPU"}, True),
+ ({"LLAMA_ARG_OVERRIDE_TENSOR": ""}, False),
+ ({"LLAMA_ARG_CPU_MOE": "1"}, True),
+ ({"LLAMA_ARG_CPU_MOE": "on"}, True),
+ ({"LLAMA_ARG_CPU_MOE": "0"}, False),
+ ({"LLAMA_ARG_N_CPU_MOE": "4"}, True),
+ ({"LLAMA_ARG_N_CPU_MOE": "0"}, False),
+ ({"LLAMA_ARG_N_CPU_MOE": "-1"}, False),
+ ({"LLAMA_ARG_N_CPU_MOE": "nonsense"}, False),
+ ],
+ )
+ def test_the_predicate(self, env, expected):
+ from core.inference.llama_cpp import _env_places_tensors_on_cpu
+ assert _env_places_tensors_on_cpu(env) is expected
+
+ def test_it_is_the_same_predicate_the_pipeline_check_uses(self):
+ """Shared, so the two cannot drift apart."""
+ import inspect
+
+ from core.inference.llama_cpp import _pipeline_parallel_disabled_by_args
+
+ source = inspect.getsource(_pipeline_parallel_disabled_by_args)
+ assert "_env_places_tensors_on_cpu" in source
+ for name in ("LLAMA_ARG_OVERRIDE_TENSOR", "LLAMA_ARG_CPU_MOE", "LLAMA_ARG_N_CPU_MOE"):
+ assert name not in source, f"{name} re-implemented instead of shared"
+
+ @pytest.mark.parametrize(
+ "env",
+ [
+ {"LLAMA_ARG_OVERRIDE_TENSOR": "blk.*=CPU"},
+ {"LLAMA_ARG_CPU_MOE": "1"},
+ {"LLAMA_ARG_N_CPU_MOE": "4"},
+ ],
+ )
+ def test_an_inherited_placement_keeps_a_full_offload_host_resident(self, monkeypatch, env):
+ assert (
+ TestHostMemoryGate._gate(
+ monkeypatch, fully_gpu_offloaded = True, extra_args = None, env = env
+ )
+ is True
+ )
+
+ def test_an_unset_environment_leaves_the_gate_alone(self, monkeypatch):
+ assert (
+ TestHostMemoryGate._gate(monkeypatch, fully_gpu_offloaded = True, extra_args = None, env = {})
+ is False
+ )
+
+
+class TestCpuMoeCountIsParsed:
+ """A CPU-MoE count places nothing at zero, which the env side already knew.
+ Presence alone would page-lock an all-GPU load for a no-op flag."""
+
+ @pytest.mark.parametrize(
+ ("extras", "expected"),
+ [
+ (None, False),
+ ([], False),
+ (["--n-cpu-moe", "0"], False),
+ (["-ncmoe", "0"], False),
+ (["--n-cpu-moe=0"], False),
+ (["--n-cpu-moe", "4"], True),
+ (["-ncmoe", "4"], True),
+ (["--n-cpu-moe=4"], True),
+ (["--n-cpu-moe", "-1"], False),
+ (["--n-cpu-moe", "nonsense"], False),
+ (["--n-cpu-moe"], False), # trailing, no value
+ # No value to parse: presence is the whole signal.
+ (["--cpu-moe"], True),
+ (["-cmoe"], True),
+ (["-ot", "blk.*=CPU"], True),
+ (["--override-tensor", "x"], True),
+ ],
+ )
+ def test_the_predicate(self, extras, expected):
+ from core.inference.llama_cpp import _args_place_tensors_on_cpu
+ assert _args_place_tensors_on_cpu(extras) is expected
+
+ def test_it_is_the_same_predicate_the_pipeline_check_uses(self):
+ import inspect
+
+ from core.inference.llama_cpp import _pipeline_parallel_disabled_by_args
+
+ import ast
+ import textwrap
+
+ tree = ast.parse(textwrap.dedent(inspect.getsource(_pipeline_parallel_disabled_by_args)))
+ fn = tree.body[0]
+ if ast.get_docstring(fn) is not None:
+ fn.body = fn.body[1:]
+ # unparse drops comments and the docstring, so only real code is left;
+ # either would otherwise name the flags without being a second copy.
+ code = ast.unparse(fn)
+ assert "_args_place_tensors_on_cpu" in code
+ for flag in ("-ncmoe", "--n-cpu-moe", "--override-tensor"):
+ assert flag not in code, f"{flag} re-implemented instead of shared"
+
+ def test_a_zero_count_no_longer_forces_a_page_lock(self, monkeypatch):
+ assert (
+ TestHostMemoryGate._gate(
+ monkeypatch, fully_gpu_offloaded = True, extra_args = ["--n-cpu-moe", "0"]
+ )
+ is False
+ )
+
+ def test_a_real_count_still_does(self, monkeypatch):
+ assert (
+ TestHostMemoryGate._gate(
+ monkeypatch, fully_gpu_offloaded = True, extra_args = ["--n-cpu-moe", "4"]
+ )
+ is True
+ )
+
+
+class TestManualModeIgnoresClearedEnv:
+ """Manual mode strips its placement vars from the child env, so the gate
+ must not pin for a setting the child is never going to see. It reads the
+ reconciled env, built with the same helper the launch uses."""
+
+ @staticmethod
+ def _child_env(parent, gpu_memory_mode):
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ env = dict(parent)
+ if gpu_memory_mode == "manual":
+ LlamaCppBackend._clear_manual_placement_env(env)
+ return env
+
+ @pytest.mark.parametrize("var", ["LLAMA_ARG_CPU_MOE", "LLAMA_ARG_N_CPU_MOE"])
+ def test_manual_mode_drops_them_so_the_gate_ignores_them(self, monkeypatch, var):
+ parent = {var: "4" if var.endswith("N_CPU_MOE") else "1"}
+ env = self._child_env(parent, "manual")
+ assert env == {}, "the launch clears these, so the gate must not see them"
+ assert (
+ TestHostMemoryGate._gate(
+ monkeypatch, fully_gpu_offloaded = True, extra_args = None, env = env
+ )
+ is False
+ )
+
+ @pytest.mark.parametrize("var", ["LLAMA_ARG_CPU_MOE", "LLAMA_ARG_N_CPU_MOE"])
+ def test_auto_mode_still_honours_them(self, monkeypatch, var):
+ parent = {var: "4" if var.endswith("N_CPU_MOE") else "1"}
+ env = self._child_env(parent, "auto")
+ assert env == parent
+ assert (
+ TestHostMemoryGate._gate(
+ monkeypatch, fully_gpu_offloaded = True, extra_args = None, env = env
+ )
+ is True
+ )
+
+ def test_override_tensor_is_not_cleared_by_manual_mode(self, monkeypatch):
+ """It is absent from _MANUAL_PLACEMENT_ENV_VARS, so it DOES reach the
+ child and must keep counting even in manual mode."""
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ assert "LLAMA_ARG_OVERRIDE_TENSOR" not in LlamaCppBackend._MANUAL_PLACEMENT_ENV_VARS
+ env = self._child_env({"LLAMA_ARG_OVERRIDE_TENSOR": "blk.*=CPU"}, "manual")
+ assert env == {"LLAMA_ARG_OVERRIDE_TENSOR": "blk.*=CPU"}
+ assert (
+ TestHostMemoryGate._gate(
+ monkeypatch, fully_gpu_offloaded = True, extra_args = None, env = env
+ )
+ is True
+ )
+
+
+class TestADefaultLaunchRecordsItsApplicability:
+ """_memory_mlock_applicable is recorded from the gate, and a later "keep
+ resident" save is compared against it. Skipping the gate when no lock was on
+ the table recorded the placeholder True, so enabling the toggle on a discrete
+ full offload demanded a reload and relaunched identical argv."""
+
+ def test_the_gate_is_not_skipped_when_should_mlock_is_false(self):
+ import ast
+
+ outer = TestTheRetryCanReadTheGate._load_model_ast()
+ parents = {}
+ for node in ast.walk(outer):
+ for child in ast.iter_child_nodes(node):
+ parents[id(child)] = node
+ calls = [
+ n
+ for n in ast.walk(outer)
+ if isinstance(n, ast.Call)
+ and isinstance(n.func, ast.Attribute)
+ and n.func.attr == "_weights_in_host_memory"
+ ]
+ assert calls, "the gate call vanished"
+ for call in calls:
+ cur = parents.get(id(call))
+ while cur is not None and cur is not outer:
+ if isinstance(cur, ast.If):
+ named = {
+ f.func.id
+ for f in ast.walk(cur.test)
+ if isinstance(f, ast.Call) and isinstance(f.func, ast.Name)
+ }
+ assert "should_mlock" not in named, (
+ "the gate is behind should_mlock again, so a default "
+ "launch records a placeholder applicability"
+ )
+ cur = parents.get(id(cur))
+
+ def test_enabling_residency_after_a_default_full_offload_needs_no_reload(self, monkeypatch):
+ import utils.model_memory_settings as mm
+
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: True)
+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: False)
+ # What the gate records for a discrete full offload.
+ assert memory_state_satisfies_settings((False, False), False, False) is True
+
+ def test_a_partial_offload_still_demands_the_reload(self, monkeypatch):
+ import utils.model_memory_settings as mm
+
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: True)
+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: False)
+ assert memory_state_satisfies_settings((False, False), False, True) is False
+
+ def test_the_bookkeeping_call_skips_the_vulkan_probe(self, monkeypatch):
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ def boom(binary = None):
+ raise AssertionError("the probe must not run for a bookkeeping call")
+
+ monkeypatch.setattr(LlamaCppBackend, "_run_vulkan_probe", staticmethod(boom))
+ assert (
+ TestHostMemoryGate._gate(
+ monkeypatch,
+ fully_gpu_offloaded = True,
+ is_vulkan_backend = True,
+ probe_vulkan = False,
+ )
+ is True
+ )
+
+ def test_skipping_the_probe_leaves_non_vulkan_alone(self, monkeypatch):
+ assert (
+ TestHostMemoryGate._gate(
+ monkeypatch,
+ fully_gpu_offloaded = True,
+ is_vulkan_backend = False,
+ probe_vulkan = False,
+ )
+ is False
+ )
+
+
+class TestPairedWritesAreInvalidatedTogether:
+ """The write commits both keys in one transaction, so a reader must never
+ observe a combination that was never stored. Invalidating key by key let a
+ load read the new keep_resident against a cached old no_ram_reserve and emit
+ --mlock for a launch the user had just told not to reserve RAM."""
+
+ def test_a_paired_write_invalidates_once_for_both_keys(self, monkeypatch):
+ """Deterministic: the timing window itself is only a few instructions, so
+ pin the contract instead of racing for it."""
+ import utils.model_memory_settings as mm
+
+ store: dict = {}
+ monkeypatch.setattr(
+ "storage.studio_db.get_app_setting", lambda key, default = None: store.get(key, default)
+ )
+ monkeypatch.setattr(
+ "storage.studio_db.upsert_app_settings", lambda updates: store.update(updates)
+ )
+ calls: list[tuple] = []
+ real = mm._invalidate
+ monkeypatch.setattr(mm, "_invalidate", lambda *keys: (calls.append(keys), real(*keys))[1])
+
+ mm.set_model_memory_settings(keep_resident = True, no_ram_reserve = True)
+
+ assert len(calls) == 1, f"the pair must be dropped in one call, got {calls}"
+ assert set(calls[0]) == {mm.KEEP_RESIDENT_SETTING_KEY, mm.NO_RAM_RESERVE_SETTING_KEY}
+
+ def test_invalidating_a_pair_bumps_both_generations(self):
+ import utils.model_memory_settings as mm
+
+ mm._generation.clear()
+ mm._invalidate(mm.KEEP_RESIDENT_SETTING_KEY, mm.NO_RAM_RESERVE_SETTING_KEY)
+ assert mm._generation[mm.KEEP_RESIDENT_SETTING_KEY] == 1
+ assert mm._generation[mm.NO_RAM_RESERVE_SETTING_KEY] == 1
+
+ def test_one_acquisition_covers_every_key(self):
+ import ast
+ from pathlib import Path
+
+ src = Path(__file__).resolve().parent.parent / "utils" / "model_memory_settings.py"
+ tree = ast.parse(src.read_text(encoding = "utf-8"))
+ setter = next(
+ n
+ for n in ast.walk(tree)
+ if isinstance(n, ast.FunctionDef) and n.name == "set_model_memory_settings"
+ )
+ for node in ast.walk(setter):
+ if isinstance(node, ast.For):
+ called = {
+ c.func.id
+ for c in ast.walk(node)
+ if isinstance(c, ast.Call) and isinstance(c.func, ast.Name)
+ }
+ assert (
+ "_invalidate" not in called
+ ), "_invalidate is back in a loop, so the pair is not atomic"
+
+
+class TestThePolicyReadsOneSnapshot:
+ """apply_model_memory_policy decided stripping and locking from separate
+ reads, so a save landing between them produced a launch for a pair that was
+ never stored: no strip for the new no-reserve, and no lock either, leaving a
+ saved --mlock in the extras."""
+
+ def test_a_save_between_the_two_reads_is_not_observable(self, monkeypatch):
+ import utils.model_memory_settings as mm
+
+ # Start at (keep_resident=True, no_ram_reserve=False).
+ store = {
+ mm.KEEP_RESIDENT_SETTING_KEY: True,
+ mm.NO_RAM_RESERVE_SETTING_KEY: False,
+ }
+ monkeypatch.setattr(
+ "storage.studio_db.get_app_setting", lambda key, default = None: store.get(key, default)
+ )
+ monkeypatch.setattr(
+ "storage.studio_db.upsert_app_settings", lambda updates: store.update(updates)
+ )
+ mm._cache.clear()
+ mm._generation.clear()
+
+ # Flip to (False, True) the moment keep_resident has been read.
+ real = mm.get_keep_resident
+ fired: list[bool] = []
+
+ def flip_after_first_read():
+ value = real()
+ if not fired:
+ fired.append(True)
+ store[mm.KEEP_RESIDENT_SETTING_KEY] = False
+ store[mm.NO_RAM_RESERVE_SETTING_KEY] = True
+ mm._invalidate(mm.KEEP_RESIDENT_SETTING_KEY, mm.NO_RAM_RESERVE_SETTING_KEY)
+ return value
+
+ monkeypatch.setattr(mm, "get_keep_resident", flip_after_first_read)
+ keep_resident, no_ram_reserve = mm.get_model_memory_settings()
+ assert fired, "the write never landed, so this proves nothing"
+ # (True, True) was never stored: the old pair or the new one, not a mix.
+ assert (keep_resident, no_ram_reserve) in {(True, False), (False, True)}
+
+ def test_the_policy_derives_both_from_one_call(self):
+ import ast
+ from pathlib import Path
+
+ src = Path(__file__).resolve().parent.parent / "core" / "inference" / "llama_server_args.py"
+ tree = ast.parse(src.read_text(encoding = "utf-8"))
+ fn = next(
+ n
+ for n in ast.walk(tree)
+ if isinstance(n, ast.FunctionDef) and n.name == "apply_model_memory_policy"
+ )
+ named = [
+ c.func.id
+ for c in ast.walk(fn)
+ if isinstance(c, ast.Call) and isinstance(c.func, ast.Name)
+ ]
+ assert named.count("get_model_memory_settings") == 1
+ for separate in ("should_mlock", "get_no_ram_reserve", "get_keep_resident"):
+ assert (
+ separate not in named
+ ), f"{separate} is read separately again, so the pair can tear"
+
+
+class TestTheGateDoesNotOverFire:
+ """Pinning where the weights are all on a discrete GPU is the redundant host
+ copy this gate exists to avoid, so the two ways it could over-fire are
+ pinned here: a zero CPU-MoE count, and the ROCm APU probe under Vulkan."""
+
+ @pytest.mark.parametrize("flag", ["--n-cpu-moe", "-ncmoe"])
+ def test_a_zero_cpu_moe_count_places_nothing(self, monkeypatch, flag):
+ """_args_place_tensors_on_cpu already treats 0 as a no-op; the offload
+ proof used flag presence, so the count flipped an all-GPU launch."""
+ assert TestHostMemoryGate._gate(monkeypatch, extra_args = ["-ngl", "-1", flag, "0"]) is False
+
+ @pytest.mark.parametrize("extras", [["-cmoe"], ["--n-cpu-moe", "4"], ["-ot", "exps=CPU"]])
+ def test_real_cpu_placement_still_counts(self, monkeypatch, extras):
+ assert TestHostMemoryGate._gate(monkeypatch, extra_args = ["-ngl", "-1", *extras]) is True
+
+ def test_the_rocm_apu_probe_is_not_consulted_under_vulkan(self, monkeypatch):
+ """gpu_indices are Vulkan ordinals there, which the ROCm helper would
+ read as physical ids and answer for a different device."""
+ assert (
+ TestHostMemoryGate._gate(
+ monkeypatch,
+ extra_args = ["-ngl", "-1"],
+ is_vulkan_backend = True,
+ amd = True,
+ vulkan_igpu = False,
+ )
+ is False
+ )
+
+ def test_the_rocm_apu_probe_still_decides_off_vulkan(self, monkeypatch):
+ assert TestHostMemoryGate._gate(monkeypatch, extra_args = ["-ngl", "-1"], amd = True) is True
+
+
+class TestResidencyDoesNotBlockReload:
+ """Residency stops UNLOADS, not reloads. A model the idle loop already freed
+ must still come back on the next request, and then stay resident."""
+
+ @pytest.fixture
+ def idle_env(self, monkeypatch):
+ """Standalone UNSLOTH_MODEL_IDLE_TTL with auto-switch off."""
+ import utils.openai_auto_switch_settings as aus
+
+ monkeypatch.setattr(aus, "_stored_idle_seconds", lambda: None)
+ monkeypatch.setattr(aus, "_env_idle_seconds", lambda: 300)
+ monkeypatch.setattr(aus, "get_openai_auto_switch_enabled", lambda: False)
+
+ def residency(on):
+ import utils.model_memory_settings as mm
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: on)
+
+ return residency
+
+ def test_the_effective_ttl_is_still_vetoed(self, idle_env):
+ import utils.openai_auto_switch_settings as aus
+
+ idle_env(False)
+ assert aus.get_auto_unload_idle_seconds() == 300
+ idle_env(True)
+ assert aus.get_auto_unload_idle_seconds() == 0, "the veto must still apply"
+
+ def test_but_idle_unload_is_still_configured(self, idle_env):
+ import utils.openai_auto_switch_settings as aus
+ idle_env(True)
+ assert aus.idle_unload_is_configured() is True
+
+ def test_an_automatic_load_may_still_run_under_residency(self, idle_env):
+ """The regression: this gated on the effective TTL, so enabling residency
+ made the next request 400 instead of reloading the freed model."""
+ import routes.inference as ri
+
+ idle_env(False)
+ assert ri._automatic_model_load_may_run() is True
+ idle_env(True)
+ assert ri._automatic_model_load_may_run() is True
+
+ def test_turning_idle_unload_off_still_disables_the_reload_path(self, monkeypatch):
+ """The converse: no TTL and no auto-switch means no automatic load, with
+ or without residency, so this is not just always-true."""
+ import routes.inference as ri
+ import utils.model_memory_settings as mm
+ import utils.openai_auto_switch_settings as aus
+
+ monkeypatch.setattr(aus, "_stored_idle_seconds", lambda: None)
+ monkeypatch.setattr(aus, "_env_idle_seconds", lambda: None)
+ monkeypatch.setattr(aus, "get_openai_auto_switch_enabled", lambda: False)
+ for resident in (False, True):
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: resident)
+ assert ri._automatic_model_load_may_run() is False
+
+ def test_a_stored_ttl_still_needs_auto_switch_on(self, monkeypatch):
+ """The configured reader keeps the same auto-switch gating as the
+ effective one, so swapping it in changes nothing but the veto."""
+ import utils.model_memory_settings as mm
+ import utils.openai_auto_switch_settings as aus
+
+ monkeypatch.setattr(aus, "_stored_idle_seconds", lambda: 300)
+ monkeypatch.setattr(aus, "_env_idle_seconds", lambda: None)
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: False)
+ monkeypatch.setattr(aus, "get_openai_auto_switch_enabled", lambda: False)
+ assert aus.idle_unload_is_configured() is False
+ assert aus.get_auto_unload_idle_seconds() == 0
+ monkeypatch.setattr(aus, "get_openai_auto_switch_enabled", lambda: True)
+ assert aus.idle_unload_is_configured() is True
+ assert aus.get_auto_unload_idle_seconds() == 300
+
+ def test_the_two_readers_agree_except_on_residency(self, monkeypatch):
+ """Pins the substitution itself across the whole input space."""
+ import utils.model_memory_settings as mm
+ import utils.openai_auto_switch_settings as aus
+
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: False)
+ for stored in (None, 0, 300):
+ for env in (None, 0, 300):
+ for switch in (False, True):
+ monkeypatch.setattr(aus, "_stored_idle_seconds", lambda s = stored: s)
+ monkeypatch.setattr(aus, "_env_idle_seconds", lambda e = env: e)
+ monkeypatch.setattr(aus, "get_openai_auto_switch_enabled", lambda v = switch: v)
+ assert aus.idle_unload_is_configured() == (
+ aus.get_auto_unload_idle_seconds() > 0
+ ), (stored, env, switch)
+
+ def test_the_idle_loop_itself_still_reads_the_vetoed_value(self):
+ """Scheduling keeps the veto; only the reload-capability checks moved."""
+ import inspect
+
+ from core.inference import llama_keepwarm
+
+ source = inspect.getsource(llama_keepwarm)
+ assert "get_auto_unload_idle_seconds" in source
+ assert "idle_unload_is_configured" not in source
+
+
+class TestACpuDevicePinIsHostResident:
+ """--device cpu/none leaves llama.cpp nowhere to offload to, so the model
+ stays in host RAM whatever the layer count predicted. Unlike a silent
+ fallback this is knowable before launch, so the gate can just read it."""
+
+ @pytest.mark.parametrize(
+ "extras",
+ [
+ ["--device", "cpu"],
+ ["--device", "none"],
+ ["-dev", "cpu"],
+ ["--device=none"],
+ ["--device", "cpu,none"],
+ ],
+ )
+ def test_a_cpu_pin_beats_the_offload_prediction(self, monkeypatch, extras):
+ assert (
+ TestHostMemoryGate._gate(monkeypatch, fully_gpu_offloaded = True, extra_args = extras)
+ is True
+ )
+
+ @pytest.mark.parametrize("extras", [["--device", "CUDA0"], ["--device", "CUDA0,cpu"]])
+ def test_a_pin_naming_a_gpu_still_skips_the_lock(self, monkeypatch, extras):
+ assert (
+ TestHostMemoryGate._gate(monkeypatch, fully_gpu_offloaded = True, extra_args = extras)
+ is False
+ )
+
+ def test_an_unreadable_pin_answers_conservatively(self, monkeypatch):
+ assert (
+ TestHostMemoryGate._gate(
+ monkeypatch, fully_gpu_offloaded = True, extra_args = ["--device", ""]
+ )
+ is True
+ )
+
+ @pytest.mark.parametrize(
+ ("value", "expected"), [("none", True), ("cpu", True), ("CUDA0", False)]
+ )
+ def test_the_inherited_env_pin_counts_too(self, monkeypatch, value, expected):
+ assert (
+ TestHostMemoryGate._gate(
+ monkeypatch, fully_gpu_offloaded = True, env = {"LLAMA_ARG_DEVICE": value}
+ )
+ is expected
+ )
+
+ def test_argv_wins_over_the_env_pin(self, monkeypatch):
+ """llama.cpp applies the env first and argv after, so a GPU pin in the
+ extras overrides an inherited LLAMA_ARG_DEVICE=none."""
+ assert (
+ TestHostMemoryGate._gate(
+ monkeypatch,
+ fully_gpu_offloaded = True,
+ extra_args = ["--device", "CUDA0"],
+ env = {"LLAMA_ARG_DEVICE": "none"},
+ )
+ is False
+ )
+
+
+class TestAGpuIdsPinOverridesADeviceFlag:
+ """gpu_ids owns placement: the launch drops the device flags from argv and
+ the env twin, so the child really is on the GPU. Classifying on the raw
+ extras would pin a redundant host copy for a --device the child never sees.
+ Built with the same helpers the launch uses, so the two cannot drift."""
+
+ @staticmethod
+ def _child(extra_args, env, gpu_ids):
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ env = dict(env or {})
+ if gpu_ids is not None:
+ extra_args = LlamaCppBackend._strip_device_extra_args(extra_args)
+ LlamaCppBackend._clear_device_placement_env(env)
+ return extra_args, env
+
+ @pytest.mark.parametrize(
+ "extras", [["--device", "cpu"], ["--device", "none"], ["-dev", "cpu"], ["--device=none"]]
+ )
+ def test_a_pin_makes_the_gate_ignore_the_device_flag(self, monkeypatch, extras):
+ extra_args, env = self._child(extras, None, gpu_ids = [0])
+ assert extra_args == [], "the launch drops these, so the gate must not see them"
+ assert (
+ TestHostMemoryGate._gate(
+ monkeypatch, fully_gpu_offloaded = True, extra_args = extra_args, env = env
+ )
+ is False
+ )
+
+ def test_a_pin_drops_the_env_twin_too(self, monkeypatch):
+ extra_args, env = self._child(None, {"LLAMA_ARG_DEVICE": "none"}, gpu_ids = [0])
+ assert env == {}
+ assert (
+ TestHostMemoryGate._gate(
+ monkeypatch, fully_gpu_offloaded = True, extra_args = extra_args, env = env
+ )
+ is False
+ )
+
+ def test_without_a_pin_the_device_flag_still_counts(self, monkeypatch):
+ extra_args, env = self._child(["--device", "cpu"], None, gpu_ids = None)
+ assert extra_args == ["--device", "cpu"]
+ assert (
+ TestHostMemoryGate._gate(
+ monkeypatch, fully_gpu_offloaded = True, extra_args = extra_args, env = env
+ )
+ is True
+ )
+
+ def test_a_pin_leaves_the_other_placement_extras_alone(self, monkeypatch):
+ """Only the device family is stripped, so -ot still forces host residency."""
+ extra_args, _env = self._child(
+ ["--device", "cpu", "-ot", r"\.ffn_.*=CPU"], None, gpu_ids = [0]
+ )
+ assert extra_args == ["-ot", r"\.ffn_.*=CPU"]
+ assert (
+ TestHostMemoryGate._gate(monkeypatch, fully_gpu_offloaded = True, extra_args = extra_args)
+ is True
+ )
+
+ def test_the_launch_really_sanitizes_before_classifying(self):
+ """Source check: the gate call must receive the stripped extras and env,
+ so this cannot regress into reading the raw ones again."""
+ import inspect
+ import re
+
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ src = inspect.getsource(LlamaCppBackend.load_model)
+ strip = src.find("_mem_extra_args = self._strip_device_extra_args(extra_args)")
+ assert strip != -1, "the launch no longer strips device flags for the gate"
+ assert re.search(r"self\._clear_device_placement_env\(_mem_env\)", src)
+ call = src.find("self._weights_in_host_memory(", strip)
+ assert call != -1 and "extra_args = _mem_extra_args" in src[call : call + 400]
+
+
+class TestFitOffRetryDropsTheLock:
+ """The mirror of TestFitOnRetryReArmsResidency. --fit off leaves -ngl at its
+ default, which llama.cpp resolves to every layer (llama-model.cpp:
+ n_gpu_layers < 0 -> n_layer_all + 1), so a lock taken for the fitted attempt
+ would reserve a full host copy of a fully offloaded model."""
+
+ @staticmethod
+ def _retry_argv(original, managed, *, drops):
+ """What the fallback builds: append --fit off, then drop the managed run."""
+ from core.inference.llama_cpp import _without_subsequence
+
+ run = [*original, "--fit", "off"]
+ return _without_subsequence(run, managed) if drops else run
+
+ def test_the_retry_is_not_page_locked(self):
+ managed = ["--load-mode", "mmap+mlock"]
+ original = [*managed, "--fit", "on", "--temp", "0.7"]
+ assert resolve_effective_memory_state(original, {}) == (True, False)
+ retry = self._retry_argv(original, managed, drops = True)
+ assert resolve_effective_memory_state(retry, {}) == (False, False)
+ assert retry == ["--fit", "on", "--temp", "0.7", "--fit", "off"]
+
+ def test_the_legacy_flag_path_drops_too(self):
+ managed = ["--mlock"]
+ original = [*managed, "--fit", "on"]
+ retry = self._retry_argv(original, managed, drops = True)
+ assert resolve_effective_memory_state(retry, {}) == (False, False)
+
+ def test_a_user_mlock_in_the_extras_survives(self):
+ """Managed flags go in before the user's, so only the first run is ours."""
+ managed = ["--mlock"]
+ original = [*managed, "--fit", "on", "--mlock"]
+ retry = self._retry_argv(original, managed, drops = True)
+ assert retry == ["--fit", "on", "--mlock", "--fit", "off"]
+ assert resolve_effective_memory_state(retry, {}) == (True, False)
+
+ def test_staying_host_resident_keeps_the_lock(self):
+ managed = ["--load-mode", "mmap+mlock"]
+ original = [*managed, "--fit", "on"]
+ retry = self._retry_argv(original, managed, drops = False)
+ assert resolve_effective_memory_state(retry, {}) == (True, False)
+
+ def test_the_dropped_launch_does_not_demand_a_reload(self, monkeypatch):
+ """mlock_applicable goes False with the lock, so a later residency save
+ is not compared against a lock this launch deliberately dropped."""
+ import utils.model_memory_settings as mm
+
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: True)
+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: False)
+ managed = ["--load-mode", "mmap+mlock"]
+ state = resolve_effective_memory_state(
+ self._retry_argv([*managed, "--fit", "on"], managed, drops = True), {}
+ )
+ assert memory_state_satisfies_settings(state, True, False) is True
+
+ def test_the_launch_really_reclassifies_the_fit_off_retry(self):
+ """Source check: the branch must re-ask the gate and clear the
+ bookkeeping, so it cannot drift back to reusing the fitted verdict."""
+ import inspect
+
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ src = inspect.getsource(LlamaCppBackend.load_model)
+ branch = src.find('run_cmd = [*run_cmd, "--fit", "off"]')
+ assert branch != -1, "the --fit off retry moved"
+ # To the end of the retry block, not a fixed width: the branch grows.
+ end = src.find("return False", branch)
+ assert end != -1
+ tail = src[branch:end]
+ for needle in (
+ "self._weights_in_host_memory(",
+ "fully_gpu_offloaded = True",
+ "_without_subsequence(run_cmd, _mem_managed)",
+ "_mem_host_resident = False",
+ "self._memory_mlock_applicable = False",
+ "resolve_effective_memory_state(run_cmd, env)",
+ ):
+ assert needle in tail, needle
+
+
+class TestFitOffRetryClearsPolicyActivity:
+ """Dropping the lock can leave the child identical to an unmanaged launch.
+ Keeping policy_active set from the first attempt then makes turning the
+ toggles off demand a reload that would relaunch the very same argv."""
+
+ @staticmethod
+ def _satisfied(monkeypatch, *, policy_active):
+ import utils.model_memory_settings as mm
+
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: False)
+ monkeypatch.setattr(mm, "get_no_ram_reserve", lambda: False)
+ # The retry child: lock dropped, so no lock and no reservation.
+ return memory_state_satisfies_settings((False, False), policy_active, False)
+
+ def test_an_untouched_child_is_left_alone(self, monkeypatch):
+ assert self._satisfied(monkeypatch, policy_active = False) is True
+
+ def test_a_still_touched_child_is_relaunched(self, monkeypatch):
+ """A scrub or a strip survives the drop, so that one must still reload."""
+ assert self._satisfied(monkeypatch, policy_active = True) is False
+
+ def test_the_launch_recomputes_activity_without_the_managed_flag(self):
+ """Source check: the retry must reuse the non-managed half of the launch
+ expression, not leave the first attempt's verdict standing."""
+ import inspect
+
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ src = inspect.getsource(LlamaCppBackend.load_model)
+ assert (
+ "self._memory_policy_active = bool(_mem_managed) or _mem_policy_touched_extras" in src
+ )
+ branch = src.find('run_cmd = [*run_cmd, "--fit", "off"]')
+ assert branch != -1
+ end = src.find("return False", branch)
+ assert end != -1
+ assert "self._memory_policy_active = _mem_policy_touched_extras" in src[branch:end]
+
+
+class TestNoDeadMemoryBookkeeping:
+ """Every _memory_* marker the launch records is read by something. A
+ write-only one silently goes stale on the retry paths, which is how the
+ fit-off retry's activity marker was missed."""
+
+ def test_the_launch_records_nothing_unread(self):
+ import ast
+ from pathlib import Path
+
+ backend = Path(__file__).resolve().parent.parent
+ target = backend / "core" / "inference" / "llama_cpp.py"
+
+ def attrs(tree, ctx):
+ return {
+ n.attr
+ for n in ast.walk(tree)
+ if isinstance(n, ast.Attribute) and isinstance(n.ctx, ctx)
+ }
+
+ written = {
+ a
+ for a in attrs(ast.parse(target.read_text(encoding = "utf-8")), ast.Store)
+ if a.startswith("_memory_") or a.endswith("_mlock_enabled")
+ }
+ assert written, "no markers found; the scan is looking in the wrong place"
+
+ read: set[str] = set()
+ for path in backend.rglob("*.py"):
+ try:
+ tree = ast.parse(path.read_text(encoding = "utf-8"))
+ except (SyntaxError, UnicodeDecodeError, OSError):
+ continue
+ read |= attrs(tree, ast.Load)
+ # routes read some of these dynamically:
+ # getattr(backend, "_memory_policy_active", False).
+ read |= {
+ n.args[1].value
+ for n in ast.walk(tree)
+ if isinstance(n, ast.Call)
+ and isinstance(n.func, ast.Name)
+ and n.func.id == "getattr"
+ and len(n.args) >= 2
+ and isinstance(n.args[1], ast.Constant)
+ and isinstance(n.args[1].value, str)
+ }
+ unread = sorted(written - read)
+ assert not unread, f"written but never read, so they go stale on retries: {unread}"
+
+
+class TestAnActiveFitterVoidsTheAllLayersVerdict:
+ """-ngl -1 IS llama.cpp's default, so common/fit.cpp does not abort on it
+ (it aborts only on a count the user really set) and the fitter is free to
+ move layers back to the CPU. A concrete count stands, so only -1 is gated."""
+
+ @staticmethod
+ def _all_on_gpu(monkeypatch, extras, *, fit_active):
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ backend = LlamaCppBackend.__new__(LlamaCppBackend)
+ monkeypatch.setattr(type(backend), "n_layers", property(lambda self: 32), raising = False)
+ backend._n_cpu_moe = 0
+ return backend._offloads_every_layer(
+ gpu_memory_mode = "auto",
+ gpu_layers = None,
+ extra_args = extras,
+ fit_active = fit_active,
+ )
+
+ def test_minus_one_under_an_active_fitter_is_not_full_offload(self, monkeypatch):
+ assert self._all_on_gpu(monkeypatch, ["-ngl", "-1"], fit_active = True) is False
+
+ def test_minus_one_with_the_fitter_off_still_is(self, monkeypatch):
+ assert self._all_on_gpu(monkeypatch, ["-ngl", "-1"], fit_active = False) is True
+
+ @pytest.mark.parametrize("count", ["33", "99"])
+ def test_a_concrete_count_stands_under_the_fitter(self, monkeypatch, count):
+ """fit.cpp aborts on a user-set n_gpu_layers, so it cannot be lowered."""
+ assert self._all_on_gpu(monkeypatch, ["-ngl", count], fit_active = True) is True
+
+ def test_a_count_at_or_below_the_blocks_is_never_full(self, monkeypatch):
+ assert self._all_on_gpu(monkeypatch, ["-ngl", "32"], fit_active = True) is False
+
+
+class TestTheEffectiveFitterState:
+ """fit_is_enabled_in answers for the extras; this answers for the child, so
+ Studio's own --fit counts and llama.cpp's ON default is respected."""
+
+ @pytest.mark.parametrize(
+ ("args", "env", "expected"),
+ [
+ ([], None, True),
+ (["--fit", "on"], None, True),
+ (["--fit", "off"], None, False),
+ (["--fit", "on", "--fit", "off"], None, False),
+ (["--fit", "off", "--fit", "on"], None, True),
+ (["--fit=off"], None, False),
+ (["-fit", "off"], None, False),
+ ([], {"LLAMA_ARG_FIT": "off"}, False),
+ ([], {"LLAMA_ARG_FIT": "on"}, True),
+ (["--fit", "off"], {"LLAMA_ARG_FIT": "on"}, False),
+ (["--fit", "on"], {"LLAMA_ARG_FIT": "off"}, True),
+ (["--fit", "banana"], None, True),
+ ],
+ )
+ def test_only_an_explicit_off_disables_it(self, args, env, expected):
+ assert _lsa.fit_is_effectively_on(args, env) is expected
+
+ def test_the_launch_asks_over_the_whole_command(self):
+ """Source check: Studio emits its own --fit into cmd, so reading the
+ extras alone would miss it."""
+ import inspect
+
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ src = inspect.getsource(LlamaCppBackend.load_model)
+ assert "fit_active = fit_is_effectively_on(" in src
+ assert "[*cmd, *(_mem_extra_args or [])], _mem_env" in src
diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.py
index a0788f1ded7..befafd25d69 100644
--- a/studio/backend/tests/test_openai_auto_switch.py
+++ b/studio/backend/tests/test_openai_auto_switch.py
@@ -107,6 +107,10 @@ class _LoadRecorder:
return None
+# The reload-capability checks in routes/inference ask whether idle unload is
+# CONFIGURED, not what the effective TTL is: Model Memory residency zeroes the
+# latter, and a model the idle loop already freed still has to come back. So a
+# stubbed TTL is paired with the configured reader wherever one is set.
def _wire(monkeypatch, *, enabled, resolves_to, backend, recorder):
monkeypatch.setattr(settings, "get_openai_auto_switch_enabled", lambda: enabled)
monkeypatch.setattr(resolver, "resolve_local_gguf", lambda _m, **_kw: resolves_to)
@@ -487,6 +491,7 @@ def test_idle_loop_does_not_unload_freshly_loaded_model(monkeypatch):
from core.inference import llama_keepwarm as kw
monkeypatch.setattr(settings, "get_auto_unload_idle_seconds", lambda: 1)
+ monkeypatch.setattr(settings, "idle_unload_is_configured", lambda: 1 > 0)
kw._inflight = 0
kw._last_active = time.monotonic() - 3600
@@ -516,6 +521,7 @@ def test_idle_loop_unloads_after_ttl_and_stashes_for_reload(monkeypatch):
from core.inference import llama_keepwarm as kw
monkeypatch.setattr(settings, "get_auto_unload_idle_seconds", lambda: 0.005)
+ monkeypatch.setattr(settings, "idle_unload_is_configured", lambda: 0.005 > 0)
kw._inflight = 0
kw._pending = 0
kw._last_active = time.monotonic() - 3600
@@ -551,6 +557,7 @@ def test_idle_loop_deletes_saved_kv_when_unload_fails(monkeypatch, tmp_path):
from core.inference import llama_keepwarm as kw
monkeypatch.setattr(settings, "get_auto_unload_idle_seconds", lambda: 0.005)
+ monkeypatch.setattr(settings, "idle_unload_is_configured", lambda: 0.005 > 0)
monkeypatch.setattr(settings, "get_auto_unload_keep_kv", lambda: True)
kw._inflight = 0
kw._pending = 0
@@ -619,6 +626,51 @@ def test_disabling_idle_unload_purges_saved_kv(monkeypatch, tmp_path):
assert kw._kv_resume is None and not saved.exists()
+def test_residency_does_not_purge_saved_kv(monkeypatch, tmp_path):
+ # Residency zeroes the effective TTL, but the user never turned idle unload
+ # off, so saving anything else must leave their saved KV alone.
+ import routes.settings as settings_route
+ from core.inference import llama_keepwarm as kw
+
+ saved = tmp_path / "resume-abc-slot0.bin"
+ saved.write_bytes(b"kv")
+ manifest = {
+ "identity": ("m", None, "m"),
+ "dir": str(tmp_path),
+ "slots": [{"id": 0, "filename": saved.name}],
+ }
+ kw._kv_resume = manifest
+ monkeypatch.setattr(
+ settings_route, "set_openai_auto_switch", lambda *a: (True, 300, True, False)
+ )
+ monkeypatch.setattr(settings_route, "get_auto_unload_idle_seconds", lambda: 0)
+ monkeypatch.setattr(settings_route, "idle_unload_is_configured", lambda: True)
+
+ payload = settings_route.OpenAIAutoSwitchPayload(enabled = True)
+ resp = settings_route.update_openai_auto_switch(payload, "tester")
+ try:
+ assert resp.idle_unload_active is False
+ assert kw._kv_resume is manifest and saved.exists()
+ finally:
+ kw._kv_resume = None
+
+
+def test_idle_unload_is_configured_ignores_the_residency_veto(monkeypatch):
+ # The reader the purge uses must report the user's setting, not the veto.
+ import utils.model_memory_settings as mm
+ import utils.openai_auto_switch_settings as settings
+
+ monkeypatch.setattr(settings, "_stored_idle_seconds", lambda: 300)
+ monkeypatch.setattr(settings, "get_openai_auto_switch_enabled", lambda: True)
+ monkeypatch.setattr(mm, "get_keep_resident", lambda: True)
+
+ assert settings.get_auto_unload_idle_seconds() == 0
+ assert settings.idle_unload_is_configured() is True
+
+ monkeypatch.setattr(settings, "_stored_idle_seconds", lambda: 0)
+ assert settings.idle_unload_is_configured() is False
+
+
def test_audio_generate_is_tracked_as_inference_path():
# Direct GGUF TTS uses the llama backend and can outlive the idle TTL, so
# the keep-warm middleware must count it as in-flight inference.
@@ -636,6 +688,7 @@ def test_idle_loop_does_not_unload_while_request_inflight(monkeypatch):
from core.inference import llama_keepwarm as kw
monkeypatch.setattr(settings, "get_auto_unload_idle_seconds", lambda: 0.01)
+ monkeypatch.setattr(settings, "idle_unload_is_configured", lambda: 0.01 > 0)
monkeypatch.setattr(kw, "_inflight", 1)
monkeypatch.setattr(kw, "_last_active", time.monotonic() - 3600)
@@ -1378,6 +1431,7 @@ def test_idle_loop_resets_timer_for_same_repo_different_variant(monkeypatch):
from core.inference import llama_keepwarm as kw
monkeypatch.setattr(settings, "get_auto_unload_idle_seconds", lambda: 0.05)
+ monkeypatch.setattr(settings, "idle_unload_is_configured", lambda: 0.05 > 0)
monkeypatch.setattr(kw, "_inflight", 0)
monkeypatch.setattr(kw, "_pending", 0)
@@ -1988,6 +2042,7 @@ def test_env_idle_standalone_reloads_freed_model_with_auto_switch_off(monkeypatc
recorder = rec,
)
monkeypatch.setattr(settings, "get_auto_unload_idle_seconds", lambda: 600) # standalone env TTL
+ monkeypatch.setattr(settings, "idle_unload_is_configured", lambda: 600 > 0)
monkeypatch.setattr(kw, "_inflight", 0)
monkeypatch.setattr(kw, "_last_unloaded_model", ("/cache/snap/A", "Q4_K_M", "org/A-GGUF"))
# A is restored, but the request named B, so it is told so rather than served A.
@@ -2010,6 +2065,7 @@ def test_no_stash_reload_when_idle_off_and_auto_switch_off(monkeypatch):
rec = _LoadRecorder(backend)
_wire(monkeypatch, enabled = False, resolves_to = None, backend = backend, recorder = rec)
monkeypatch.setattr(settings, "get_auto_unload_idle_seconds", lambda: 0)
+ monkeypatch.setattr(settings, "idle_unload_is_configured", lambda: 0 > 0)
monkeypatch.setattr(kw, "_inflight", 0)
monkeypatch.setattr(kw, "_last_unloaded_model", ("/cache/snap/A", "Q4_K_M", "org/A-GGUF"))
_run_hook("org/B-GGUF")
@@ -2332,6 +2388,7 @@ def _stash(monkeypatch, *, idle = 600):
from core.inference import llama_keepwarm as kw
monkeypatch.setattr(settings, "get_auto_unload_idle_seconds", lambda: idle)
+ monkeypatch.setattr(settings, "idle_unload_is_configured", lambda: idle > 0)
monkeypatch.setattr(kw, "_inflight", 0)
monkeypatch.setattr(kw, "_last_unloaded_model", ("/cache/snap/A", "Q4_K_M", "org/A-GGUF"))
@@ -2594,6 +2651,7 @@ def test_omitted_model_still_reloads_idle_freed_model(monkeypatch):
rec = _LoadRecorder(backend)
_wire(monkeypatch, enabled = False, resolves_to = None, backend = backend, recorder = rec)
monkeypatch.setattr(settings, "get_auto_unload_idle_seconds", lambda: 600)
+ monkeypatch.setattr(settings, "idle_unload_is_configured", lambda: 600 > 0)
monkeypatch.setattr(kw, "_inflight", 0)
monkeypatch.setattr(kw, "_last_unloaded_model", ("/cache/snap/A", "Q4_K_M", "org/A-GGUF"))
asyncio.run(
@@ -3058,6 +3116,7 @@ def test_require_vision_ignores_reload_stash(monkeypatch):
rec = _LoadRecorder(backend)
_wire(monkeypatch, enabled = False, resolves_to = None, backend = backend, recorder = rec)
monkeypatch.setattr(settings, "get_auto_unload_idle_seconds", lambda: 600)
+ monkeypatch.setattr(settings, "idle_unload_is_configured", lambda: 600 > 0)
monkeypatch.setattr(kw, "_inflight", 0)
monkeypatch.setattr(kw, "_last_unloaded_model", ("/cache/snap/A", "Q4_K_M", "org/A-GGUF"))
monkeypatch.setattr(
@@ -4737,6 +4796,7 @@ def test_idle_unload_saves_slots_before_unload_and_stashes_manifest(monkeypatch,
from core.inference import llama_keepwarm as kw
monkeypatch.setattr(settings, "get_auto_unload_idle_seconds", lambda: 0.005)
+ monkeypatch.setattr(settings, "idle_unload_is_configured", lambda: 0.005 > 0)
monkeypatch.setattr(settings, "get_auto_unload_keep_kv", lambda: True)
kw._inflight = 0
kw._pending = 0
@@ -4779,6 +4839,7 @@ def test_idle_save_failure_still_unloads_plain(monkeypatch):
from core.inference import llama_keepwarm as kw
monkeypatch.setattr(settings, "get_auto_unload_idle_seconds", lambda: 0.005)
+ monkeypatch.setattr(settings, "idle_unload_is_configured", lambda: 0.005 > 0)
monkeypatch.setattr(settings, "get_auto_unload_keep_kv", lambda: True)
kw._inflight = 0
kw._pending = 0
@@ -4811,6 +4872,7 @@ def test_keep_kv_setting_off_skips_save(monkeypatch):
from core.inference import llama_keepwarm as kw
monkeypatch.setattr(settings, "get_auto_unload_idle_seconds", lambda: 0.005)
+ monkeypatch.setattr(settings, "idle_unload_is_configured", lambda: 0.005 > 0)
monkeypatch.setattr(settings, "get_auto_unload_keep_kv", lambda: False)
kw._inflight = 0
kw._pending = 0
@@ -4841,6 +4903,7 @@ def test_keep_kv_disabled_mid_save_discards_manifest(monkeypatch, tmp_path):
keep = {"on": True}
monkeypatch.setattr(settings, "get_auto_unload_idle_seconds", lambda: 0.005)
+ monkeypatch.setattr(settings, "idle_unload_is_configured", lambda: 0.005 > 0)
monkeypatch.setattr(settings, "get_auto_unload_keep_kv", lambda: keep["on"])
kw._inflight = 0
kw._pending = 0
@@ -4882,6 +4945,7 @@ def test_idle_ttl_disabled_mid_save_skips_unload(monkeypatch, tmp_path):
ttl = {"v": 0.005}
monkeypatch.setattr(settings, "get_auto_unload_idle_seconds", lambda: ttl["v"])
+ monkeypatch.setattr(settings, "idle_unload_is_configured", lambda: ttl["v"] > 0)
monkeypatch.setattr(settings, "get_auto_unload_keep_kv", lambda: True)
kw._inflight = 0
kw._pending = 0
@@ -5091,6 +5155,7 @@ def test_stale_stash_cleanup_waits_for_lifecycle_gate(monkeypatch, tmp_path):
from core.inference import llama_keepwarm as kw
monkeypatch.setattr(settings, "get_auto_unload_idle_seconds", lambda: 3600)
+ monkeypatch.setattr(settings, "idle_unload_is_configured", lambda: 3600 > 0)
kw._inflight = 0
kw._pending = 0
kw._last_active = time.monotonic()
diff --git a/studio/backend/utils/model_memory_settings.py b/studio/backend/utils/model_memory_settings.py
new file mode 100644
index 00000000000..c0d8688416d
--- /dev/null
+++ b/studio/backend/utils/model_memory_settings.py
@@ -0,0 +1,180 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Persisted model-memory residency controls.
+
+``keep_resident`` -- weights never go back to system RAM while loaded: no idle
+auto-unload, and ``--mlock`` so the OS cannot page them out and re-fault them in.
+
+``no_ram_reserve`` -- no full host-RAM copy: keeps llama.cpp's default mmap path
+and drops ``--no-mmap`` / ``--mlock``.
+
+Both on means "live in VRAM, keep no RAM copy, never idle-unload". ``--mlock`` is
+itself a full-model RAM reservation, so ``no_ram_reserve`` wins on that flag.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from typing import Any, Optional
+
+KEEP_RESIDENT_SETTING_KEY = "model_memory_keep_resident"
+NO_RAM_RESERVE_SETTING_KEY = "model_memory_no_ram_reserve"
+
+DEFAULT_KEEP_RESIDENT = False
+DEFAULT_NO_RAM_RESERVE = False
+
+# Read on the load path and every idle poll, so memo briefly to spare SQLite.
+# Matches openai_auto_switch_settings.
+_CACHE_TTL_S = 2.0
+_cache_lock = threading.Lock()
+_cache: dict[str, tuple[float, Any]] = {}
+# Bumped on every write. A read that began before a write must not fill the
+# cache with the value it already fetched, or the new setting would appear to
+# revert for the rest of the TTL and a load could launch contradicting it.
+_generation: dict[str, int] = {}
+
+
+def _coerce_bool(value: Any) -> Optional[bool]:
+ if isinstance(value, bool):
+ return value
+ if isinstance(value, str):
+ normalized = value.strip().lower()
+ if normalized in {"1", "true", "yes", "on"}:
+ return True
+ if normalized in {"0", "false", "no", "off", ""}:
+ return False
+ return None
+
+
+# A write racing a read is rare, so a couple of retries always converges. The
+# bound only exists so a pathological write storm cannot spin here forever.
+_MAX_REREADS = 3
+
+
+def _cached_setting(key: str) -> Any:
+ for _attempt in range(_MAX_REREADS):
+ with _cache_lock:
+ hit = _cache.get(key)
+ if hit is not None and time.monotonic() - hit[0] < _CACHE_TTL_S:
+ return hit[1]
+ generation = _generation.get(key, 0)
+ try:
+ from storage.studio_db import get_app_setting
+ stored = get_app_setting(key, None)
+ except Exception:
+ # An unreadable DB must not fail a load; fall back to the default.
+ return None
+ with _cache_lock:
+ if _generation.get(key, 0) == generation:
+ _cache[key] = (time.monotonic(), stored)
+ return stored
+ # A write committed while this read was in flight, so `stored` predates
+ # it. Returning it would let a load launch with flags contradicting the
+ # setting that was just saved, so read again against the new generation.
+ return stored
+
+
+def _invalidate(*keys: str) -> None:
+ """Drop these keys in ONE acquisition. The write commits the pair in one
+ transaction, so invalidating them separately would let a load in between read
+ a new keep_resident against a cached old no_ram_reserve and emit --mlock for
+ a combination that was never stored."""
+ with _cache_lock:
+ for key in keys:
+ _cache.pop(key, None)
+ _generation[key] = _generation.get(key, 0) + 1
+
+
+def get_keep_resident() -> bool:
+ """True when the loaded model must stay in GPU memory while it is loaded."""
+ parsed = _coerce_bool(_cached_setting(KEEP_RESIDENT_SETTING_KEY))
+ return parsed if parsed is not None else DEFAULT_KEEP_RESIDENT
+
+
+def get_no_ram_reserve() -> bool:
+ """True when no full host-RAM copy of the weights may be held."""
+ parsed = _coerce_bool(_cached_setting(NO_RAM_RESERVE_SETTING_KEY))
+ return parsed if parsed is not None else DEFAULT_NO_RAM_RESERVE
+
+
+def should_mlock() -> bool:
+ """Whether to pass ``--mlock``.
+
+ mlock pins the whole model in host RAM, so it is emitted only when residency
+ is on and no-reserve is off. The two conflict, and no-reserve wins.
+ """
+ keep_resident, no_ram_reserve = get_model_memory_settings()
+ return keep_resident and not no_ram_reserve
+
+
+def _pair_generations() -> tuple[int, int]:
+ with _cache_lock:
+ return (
+ _generation.get(KEEP_RESIDENT_SETTING_KEY, 0),
+ _generation.get(NO_RAM_RESERVE_SETTING_KEY, 0),
+ )
+
+
+def get_model_memory_settings() -> tuple[bool, bool]:
+ """``(keep_resident, no_ram_reserve)`` from ONE coherent snapshot.
+
+ Read one after the other, a save landing in between returns a pair that was
+ never stored, and the launch then strips for one setting while locking for
+ the other. The write drops both keys in a single acquisition, so a bumped
+ generation on either side is enough to spot it and read again.
+ """
+ pair = (get_keep_resident(), get_no_ram_reserve())
+ for _attempt in range(_MAX_REREADS):
+ before = _pair_generations()
+ pair = (get_keep_resident(), get_no_ram_reserve())
+ if _pair_generations() == before:
+ return pair
+ return pair
+
+
+def set_model_memory_settings(
+ keep_resident: Any = None, no_ram_reserve: Any = None
+) -> tuple[bool, bool]:
+ """One-transaction write; ``None`` leaves a stored value untouched."""
+ updates: dict[str, bool] = {}
+
+ if keep_resident is not None:
+ parsed = _coerce_bool(keep_resident)
+ if parsed is None:
+ raise ValueError("Keep model in GPU memory must be true or false.")
+ updates[KEEP_RESIDENT_SETTING_KEY] = parsed
+
+ if no_ram_reserve is not None:
+ parsed = _coerce_bool(no_ram_reserve)
+ if parsed is None:
+ raise ValueError("Do not reserve system RAM must be true or false.")
+ updates[NO_RAM_RESERVE_SETTING_KEY] = parsed
+
+ if updates:
+ from storage.studio_db import upsert_app_settings
+ upsert_app_settings(updates)
+ _invalidate(*updates)
+
+ return get_keep_resident(), get_no_ram_reserve()
+
+
+def memlock_limit_bytes() -> Optional[int]:
+ """Soft RLIMIT_MEMLOCK, or None when unlimited or unavailable.
+
+ mlock cannot exceed this. Linux commonly defaults to 8 MB, where llama.cpp
+ logs "failed to mlock" and carries on, so residency would silently do
+ nothing. None on Windows (no RLIMIT_MEMLOCK) and on macOS (unlimited).
+ """
+ try:
+ import resource
+ except ImportError:
+ return None
+ try:
+ soft, _hard = resource.getrlimit(resource.RLIMIT_MEMLOCK)
+ except (AttributeError, ValueError, OSError):
+ return None
+ if soft < 0 or soft == resource.RLIM_INFINITY:
+ return None
+ return int(soft)
diff --git a/studio/backend/utils/openai_auto_switch_settings.py b/studio/backend/utils/openai_auto_switch_settings.py
index da38b797fb9..8f55ca86146 100644
--- a/studio/backend/utils/openai_auto_switch_settings.py
+++ b/studio/backend/utils/openai_auto_switch_settings.py
@@ -170,6 +170,14 @@ def get_stored_auto_unload_idle_seconds() -> int:
def get_auto_unload_idle_seconds() -> int:
"""Effective idle TTL the idle loop runs on (0 = never unload)."""
+ # Model Memory residency vetoes the TTL. Effective reader only, so the stored
+ # reader keeps the number the user typed and it returns when they turn it off.
+ try:
+ from utils.model_memory_settings import get_keep_resident
+ if get_keep_resident():
+ return 0
+ except Exception:
+ pass
stored = _stored_idle_seconds()
if stored is not None:
# An explicit UI/API value stays gated on auto-switch: off reports 0 so the
@@ -182,6 +190,19 @@ def get_auto_unload_idle_seconds() -> int:
return env if env is not None else 0
+def idle_unload_is_configured() -> bool:
+ """The user's idle-unload setting, ignoring the residency veto.
+
+ Residency zeroes the effective TTL without them turning idle unload off, so
+ anything deciding whether to DISCARD saved state reads this, not the gated one.
+ """
+ stored = _stored_idle_seconds()
+ if stored is not None:
+ return _apply_idle_floor(stored) > 0 and get_openai_auto_switch_enabled()
+ env = _env_idle_seconds()
+ return env is not None and env > 0
+
+
def get_auto_unload_keep_kv() -> bool:
"""Whether the idle unload persists slot KV to disk for restore on reload."""
parsed = _coerce_bool(_cached_setting(AUTO_UNLOAD_KEEP_KV_SETTING_KEY, None))
diff --git a/studio/frontend/src/features/settings/api/model-memory.ts b/studio/frontend/src/features/settings/api/model-memory.ts
new file mode 100644
index 00000000000..8784cba88a8
--- /dev/null
+++ b/studio/frontend/src/features/settings/api/model-memory.ts
@@ -0,0 +1,123 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { authFetch } from "@/features/auth";
+import { readFastApiError } from "@/lib/format-fastapi-error";
+import { invalidateOpenAIAutoSwitchSettings } from "./openai-auto-switch";
+
+const MODEL_MEMORY_EVENT = "unsloth-model-memory-change";
+
+export type ModelMemorySettings = {
+ keepResident: boolean;
+ noRamReserve: boolean;
+ defaultKeepResident: boolean;
+ defaultNoRamReserve: boolean;
+ /** Whether --mlock applies; false when noRamReserve vetoes it. */
+ mlockActive: boolean;
+ /** A model is loaded whose --mlock state differs from the saved one. */
+ reloadRequired: boolean;
+ /** Soft RLIMIT_MEMLOCK when finite; null means unlimited or N/A. */
+ memlockLimitBytes: number | null;
+};
+
+type ApiModelMemorySettings = {
+ // biome-ignore lint/style/useNamingConvention: API schema
+ keep_resident: boolean;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ no_ram_reserve: boolean;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ default_keep_resident: boolean;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ default_no_ram_reserve: boolean;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ mlock_active: boolean;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ reload_required: boolean;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ memlock_limit_bytes: number | null;
+};
+
+let inFlightModelMemory: Promise<ModelMemorySettings> | null = null;
+
+export function subscribeModelMemorySettings(
+ listener: (settings: ModelMemorySettings) => void,
+) {
+ const handleChange = (event: Event) => {
+ listener((event as CustomEvent<ModelMemorySettings>).detail);
+ };
+ window.addEventListener(MODEL_MEMORY_EVENT, handleChange);
+ return () => window.removeEventListener(MODEL_MEMORY_EVENT, handleChange);
+}
+
+function fromApi(settings: ApiModelMemorySettings): ModelMemorySettings {
+ return {
+ keepResident: settings.keep_resident,
+ noRamReserve: settings.no_ram_reserve,
+ defaultKeepResident: settings.default_keep_resident,
+ defaultNoRamReserve: settings.default_no_ram_reserve,
+ mlockActive: settings.mlock_active,
+ reloadRequired: settings.reload_required,
+ memlockLimitBytes: settings.memlock_limit_bytes,
+ };
+}
+
+// No read-through cache on purpose: the response carries runtime state
+// (reloadRequired, memlockLimitBytes) that goes stale as soon as a model is
+// loaded or swapped. This only fans the latest value out to subscribers.
+function publishModelMemory(settings: ModelMemorySettings) {
+ window.dispatchEvent(
+ new CustomEvent(MODEL_MEMORY_EVENT, { detail: settings }),
+ );
+ return settings;
+}
+
+async function fetchModelMemorySettings(): Promise<ModelMemorySettings> {
+ const res = await authFetch("/api/settings/model-memory");
+ if (!res.ok) {
+ throw new Error(
+ await readFastApiError(res, "Failed to load model memory settings"),
+ );
+ }
+ return fromApi(await res.json());
+}
+
+/**
+ * Always refetches: `reloadRequired` and `memlockLimitBytes` describe the
+ * currently loaded process, so a cached copy goes stale as soon as a model is
+ * loaded or swapped. Concurrent calls still share one request.
+ */
+export async function loadModelMemorySettings() {
+ inFlightModelMemory ??= fetchModelMemorySettings()
+ .then(publishModelMemory)
+ .finally(() => {
+ inFlightModelMemory = null;
+ });
+ return inFlightModelMemory;
+}
+
+/** Partial update: omitted fields keep their stored value. */
+export async function updateModelMemorySettings(
+ patch: Partial<Pick<ModelMemorySettings, "keepResident" | "noRamReserve">>,
+): Promise<ModelMemorySettings> {
+ const body: Record<string, boolean> = {};
+ if (patch.keepResident !== undefined) {
+ body.keep_resident = patch.keepResident;
+ }
+ if (patch.noRamReserve !== undefined) {
+ body.no_ram_reserve = patch.noRamReserve;
+ }
+ const res = await authFetch("/api/settings/model-memory", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ if (!res.ok) {
+ throw new Error(
+ await readFastApiError(res, "Failed to update model memory settings"),
+ );
+ }
+ // Residency vetoes the idle-unload TTL, so the auto-switch endpoint's
+ // idleUnloadActive changed too and its own cache is now stale.
+ invalidateOpenAIAutoSwitchSettings();
+ return publishModelMemory(fromApi(await res.json()));
+}
diff --git a/studio/frontend/src/features/settings/api/openai-auto-switch.ts b/studio/frontend/src/features/settings/api/openai-auto-switch.ts
index a7e93aa68d2..3a5e4c3a6ef 100644
--- a/studio/frontend/src/features/settings/api/openai-auto-switch.ts
+++ b/studio/frontend/src/features/settings/api/openai-auto-switch.ts
@@ -33,6 +33,10 @@ type ApiOpenAIAutoSwitchSettings = {
let cachedSettings: OpenAIAutoSwitchSettings | null = null;
let inFlightSettings: Promise<OpenAIAutoSwitchSettings> | null = null;
+// The generation inFlightSettings was issued at. A caller arriving after an
+// invalidation must not adopt a request issued before it: that reply describes
+// the pre-write world, and the hub poll puts it straight into idleUnloadArmed.
+let inFlightGeneration = -1;
function fromApi(
settings: ApiOpenAIAutoSwitchSettings,
@@ -57,21 +61,63 @@ async function fetchOpenAIAutoSwitchSettings(): Promise<OpenAIAutoSwitchSettings
return fromApi(await res.json());
}
-function cacheSettings(settings: OpenAIAutoSwitchSettings) {
- cachedSettings = settings;
+// Bumped on every invalidation. A response that was already in flight when the
+// cache was cleared must not refill it, or the pre-toggle value would be served
+// indefinitely.
+let cacheGeneration = 0;
+
+function cacheSettings(settings: OpenAIAutoSwitchSettings, generation: number) {
+ if (generation === cacheGeneration) {
+ cachedSettings = settings;
+ }
return settings;
}
+/**
+ * Drop the cached response. `idleUnloadActive` depends on the Model Memory
+ * residency setting, which is saved through a different endpoint, so that
+ * endpoint invalidates this cache rather than letting it go stale.
+ */
+export function invalidateOpenAIAutoSwitchSettings() {
+ cachedSettings = null;
+ cacheGeneration += 1;
+}
+
+// An invalidation racing a read is rare, so a couple of retries always
+// converges. The bound only exists so a write storm cannot spin here.
+const MAX_REREADS = 3;
+
+function startRead(generation: number) {
+ // cacheGeneration only increases, so a later read always claims the slot under
+ // a different generation and this clear cannot drop its request.
+ const read = fetchOpenAIAutoSwitchSettings().finally(() => {
+ if (inFlightGeneration === generation) {
+ inFlightSettings = null;
+ }
+ });
+ inFlightSettings = read;
+ inFlightGeneration = generation;
+ return read;
+}
+
export async function loadOpenAIAutoSwitchSettings() {
- if (cachedSettings) {
- return cachedSettings;
+ let settings: OpenAIAutoSwitchSettings | null = null;
+ for (let attempt = 0; attempt < MAX_REREADS; attempt += 1) {
+ if (cachedSettings) {
+ return cachedSettings;
+ }
+ const generation = cacheGeneration;
+ settings = await (inFlightSettings && inFlightGeneration === generation
+ ? inFlightSettings
+ : startRead(generation));
+ if (generation === cacheGeneration) {
+ return cacheSettings(settings, generation);
+ }
+ // The request was already in flight when the cache was dropped, so this
+ // response predates the write. Callers put it straight into idleUnloadArmed,
+ // so refetch against the new generation rather than returning it.
}
- inFlightSettings ??= fetchOpenAIAutoSwitchSettings()
- .then(cacheSettings)
- .finally(() => {
- inFlightSettings = null;
- });
- return inFlightSettings;
+ return settings as OpenAIAutoSwitchSettings;
}
export async function updateOpenAIAutoSwitchSettings(
@@ -80,6 +126,10 @@ export async function updateOpenAIAutoSwitchSettings(
autoUnloadKeepKv?: boolean,
autoDownloadModel?: boolean,
): Promise<OpenAIAutoSwitchSettings> {
+ // Read BEFORE the request: idleUnloadActive depends on the Model Memory
+ // setting, so a residency write landing mid-flight makes this response stale
+ // even though it is our own write's reply.
+ const generation = cacheGeneration;
const res = await authFetch("/api/settings/openai-auto-switch", {
method: "PUT",
headers: { "Content-Type": "application/json" },
@@ -108,5 +158,12 @@ export async function updateOpenAIAutoSwitchSettings(
),
);
}
- return cacheSettings(fromApi(await res.json()));
+ const settings = fromApi(await res.json());
+ if (generation !== cacheGeneration) {
+ // A Model Memory write committed while this PUT was in flight, so this
+ // reply predates it. Caching it would pin a stale idleUnloadActive, which
+ // the Hub reads to decide whether an eviction was a real unload.
+ return loadOpenAIAutoSwitchSettings();
+ }
+ return cacheSettings(settings, generation);
}
diff --git a/studio/frontend/src/features/settings/components/model-memory-section.tsx b/studio/frontend/src/features/settings/components/model-memory-section.tsx
new file mode 100644
index 00000000000..31e10f717ca
--- /dev/null
+++ b/studio/frontend/src/features/settings/components/model-memory-section.tsx
@@ -0,0 +1,129 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { Switch } from "@/components/ui/switch";
+import { formatBytes } from "@/features/hub/lib/format";
+import { useT } from "@/i18n";
+import { useEffect, useState } from "react";
+import {
+ type ModelMemorySettings,
+ loadModelMemorySettings,
+ updateModelMemorySettings,
+} from "../api/model-memory";
+import { SettingsRow } from "./settings-row";
+import { SettingsSection } from "./settings-section";
+
+export function ModelMemorySection() {
+ const t = useT();
+ const [settings, setSettings] = useState<ModelMemorySettings | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [isSaving, setIsSaving] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ void loadModelMemorySettings()
+ .then((loaded) => {
+ if (cancelled) return;
+ setSettings(loaded);
+ setError(null);
+ })
+ .catch((loadError) => {
+ if (cancelled) return;
+ setError(
+ loadError instanceof Error
+ ? loadError.message
+ : t("settings.resources.modelMemory.loadError"),
+ );
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [t]);
+
+ const persist = async (
+ patch: Partial<Pick<ModelMemorySettings, "keepResident" | "noRamReserve">>,
+ ) => {
+ setIsSaving(true);
+ setError(null);
+ try {
+ setSettings(await updateModelMemorySettings(patch));
+ } catch (saveError) {
+ setError(
+ saveError instanceof Error
+ ? saveError.message
+ : t("settings.resources.modelMemory.saveError"),
+ );
+ } finally {
+ setIsSaving(false);
+ }
+ };
+
+ // Both on suppresses --mlock. Say so, rather than looking like a no-op.
+ // Keyed on the toggles, not mlockActive: that now also reads false when the
+ // running model simply had nothing in host RAM to lock, which is a different
+ // reason than the one this line gives.
+ const mlockVetoed =
+ settings?.keepResident === true && settings.noRamReserve === true;
+ // A finite locked-memory cap means llama.cpp logs "failed to mlock" and
+ // carries on, so residency would look enabled but do nothing.
+ const memlockCap =
+ settings?.mlockActive === true && settings.memlockLimitBytes !== null
+ ? settings.memlockLimitBytes
+ : null;
+
+ return (
+ <SettingsSection title={t("settings.resources.modelMemory.title")}>
+ <SettingsRow
+ label={t("settings.resources.modelMemory.keepResident")}
+ description={t(
+ "settings.resources.modelMemory.keepResidentDescription",
+ )}
+ hint={t("settings.resources.modelMemory.keepResidentHint")}
+ >
+ <Switch
+ aria-label={t("settings.resources.modelMemory.keepResident")}
+ checked={settings?.keepResident ?? false}
+ disabled={!settings || isSaving}
+ onCheckedChange={(keepResident) => void persist({ keepResident })}
+ />
+ </SettingsRow>
+ <SettingsRow
+ label={t("settings.resources.modelMemory.noRamReserve")}
+ description={t(
+ "settings.resources.modelMemory.noRamReserveDescription",
+ )}
+ hint={t("settings.resources.modelMemory.noRamReserveHint")}
+ >
+ <Switch
+ aria-label={t("settings.resources.modelMemory.noRamReserve")}
+ checked={settings?.noRamReserve ?? false}
+ disabled={!settings || isSaving}
+ onCheckedChange={(noRamReserve) => void persist({ noRamReserve })}
+ />
+ </SettingsRow>
+ {error ? (
+ <p className="pb-3 text-xs text-destructive">{error}</p>
+ ) : (
+ <>
+ {mlockVetoed ? (
+ <p className="pb-1 text-xs text-muted-foreground">
+ {t("settings.resources.modelMemory.mlockVetoed")}
+ </p>
+ ) : null}
+ {memlockCap !== null ? (
+ <p className="pb-1 text-xs text-amber-600 dark:text-amber-400">
+ {t("settings.resources.modelMemory.memlockCapped", {
+ limit: formatBytes(memlockCap),
+ })}
+ </p>
+ ) : null}
+ {settings?.reloadRequired ? (
+ <p className="pb-3 text-xs text-muted-foreground">
+ {t("settings.resources.modelMemory.reloadRequired")}
+ </p>
+ ) : null}
+ </>
+ )}
+ </SettingsSection>
+ );
+}
diff --git a/studio/frontend/src/features/settings/components/settings-row.tsx b/studio/frontend/src/features/settings/components/settings-row.tsx
index f50286350ad..827b51f8f58 100644
--- a/studio/frontend/src/features/settings/components/settings-row.tsx
+++ b/studio/frontend/src/features/settings/components/settings-row.tsx
@@ -1,12 +1,20 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
+import { InformationCircleIcon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
import type { ReactNode } from "react";
export function SettingsRow({
label,
description,
+ hint,
icon,
children,
destructive,
@@ -15,6 +23,11 @@ export function SettingsRow({
}: {
label: string;
description?: ReactNode;
+ /**
+ * Long-form explanation, shown on hover behind an info icon so `description`
+ * can stay to one line. Plain text: it doubles as the trigger's aria-label.
+ */
+ hint?: string;
icon?: ReactNode;
children?: ReactNode;
destructive?: boolean;
@@ -48,7 +61,37 @@ export function SettingsRow({
</span>
) : null}
<div className="flex min-w-0 flex-col gap-0.5">
- <span className="text-sm font-medium text-foreground">{label}</span>
+ {/* Flex only when hinted, so every other row's label renders exactly
+ as before. */}
+ <span
+ className={cn(
+ "text-sm font-medium text-foreground",
+ hint && "flex items-center gap-1.5",
+ )}
+ >
+ {label}
+ {hint ? (
+ <Tooltip>
+ <TooltipTrigger asChild={true}>
+ {/* Focusable and labelled, so keyboard users reach the
+ text too. Matches the secure-HTTPS hint. */}
+ <button
+ type="button"
+ aria-label={hint}
+ className="flex shrink-0 items-center rounded text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ >
+ <HugeiconsIcon
+ icon={InformationCircleIcon}
+ className="size-3.5"
+ />
+ </button>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-[300px] text-ui-11 leading-snug">
+ {hint}
+ </TooltipContent>
+ </Tooltip>
+ ) : null}
+ </span>
{description ? (
<span className="text-xs text-muted-foreground leading-snug">
{description}
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index 115a98558e1..27db153920a 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -76,6 +76,9 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
"settings.resources.liveMonitor.vram",
"settings.resources.liveMonitor.disk",
"settings.resources.gpu.title",
+ "settings.resources.modelMemory.title",
+ "settings.resources.modelMemory.keepResident",
+ "settings.resources.modelMemory.noRamReserve",
"settings.resources.storage.title",
"settings.resources.storage.modelsFolder",
"settings.resources.storage.futureDownloads",
@@ -187,4 +190,12 @@ export const SETTINGS_SEARCH_KEYWORDS: Partial<
> = {
"settings.resources.storage.modelsFolder":
"settings.resources.storage.modelsFolderKeywords",
+ // mlock, vram, ulimit and pin are in none of these labels, so search
+ // missed the rows the feature is named after.
+ "settings.resources.modelMemory.title":
+ "settings.resources.modelMemory.modelMemoryKeywords",
+ "settings.resources.modelMemory.keepResident":
+ "settings.resources.modelMemory.modelMemoryKeywords",
+ "settings.resources.modelMemory.noRamReserve":
+ "settings.resources.modelMemory.modelMemoryKeywords",
};
diff --git a/studio/frontend/src/features/settings/tabs/resources-tab.tsx b/studio/frontend/src/features/settings/tabs/resources-tab.tsx
index ddefdadec46..a64ab241513 100644
--- a/studio/frontend/src/features/settings/tabs/resources-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/resources-tab.tsx
@@ -26,6 +26,7 @@ import {
loadHuggingFaceCacheSettings,
updateHuggingFaceCacheSettings,
} from "../api/hugging-face-cache";
+import { ModelMemorySection } from "../components/model-memory-section";
import { SettingsRow } from "../components/settings-row";
import { SettingsSection } from "../components/settings-section";
import { useMonitorOverlayStore } from "../stores/monitor-overlay-store";
@@ -567,6 +568,8 @@ export function ResourcesTab() {
)}
</SettingsSection>
+ <ModelMemorySection />
+
<SettingsSection title={t("settings.resources.storage.title")}>
<InfoRow
label={t("settings.resources.storage.systemDisk")}
@@ -581,6 +584,7 @@ export function ResourcesTab() {
<SettingsRow
label={t("settings.resources.storage.modelsFolder")}
description={t("settings.resources.storage.modelsFolderDescription")}
+ hint={t("settings.resources.storage.modelsFolderHint")}
className="max-[840px]:flex-col max-[840px]:items-stretch max-[840px]:gap-2"
>
<div className="grid w-[392px] min-w-0 grid-cols-[minmax(0,1fr)_auto] gap-x-2 gap-y-1.5 max-[840px]:w-full">
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 82a8c763847..5b991aa135f 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -709,6 +709,23 @@ export const ar = {
free: "{value} متاح",
total: "{value} إجمالي",
},
+ modelMemory: {
+ title: "ذاكرة النموذج",
+ keepResident: "إبقاء النموذج في ذاكرة كرت الرسوميات",
+ keepResidentDescription: "يبقى في ذاكرة كرت الرسوميات بين الرسائل.",
+ keepResidentHint: "لا تُعاد الأوزان إلى ذاكرة النظام ما دام النموذج محمَّلاً. يعطّل التفريغ التلقائي عند الخمول، وإذا كانت الأوزان موجودة فعلاً في ذاكرة المضيف (ذاكرة موحّدة أو تفريغ جزئي إلى المعالج الرسومي) فإنه يمرّر ‎--mlock‎ أيضاً حتى لا يُخرجها النظام من الذاكرة ويعيد رفعها عند رسالتك التالية.",
+ noRamReserve: "عدم حجز ذاكرة النظام للنموذج",
+ noRamReserveDescription: "لا يحتفظ بنسخة كاملة في ذاكرة النظام.",
+ noRamReserveHint: "ينقل الأوزان إلى ذاكرة كرت الرسوميات بدل الاحتفاظ بنسخة كاملة في ذاكرة النظام. يُبقي تحميل llama.cpp المعتمد على تعيين الذاكرة ويحذف ‎--no-mmap‎ و‎--mlock‎.",
+ mlockVetoed: "يبقى ‎--mlock‎ معطَّلاً: تثبيت النموذج سيحجز ذاكرة تكفي حجمه كاملاً. ولا يزال التفريغ التلقائي عند الخمول معطَّلاً.",
+ memlockCapped: "يحدّ هذا النظام الذاكرة المقفلة عند {limit}. لن يُثبَّت نموذج أكبر بالكامل؛ ارفع الحد باستخدام ulimit -l.",
+ reloadRequired: "أعد تحميل النموذج لتطبيق خيارات الذاكرة الجديدة.",
+ loadError: "تعذّر تحميل إعدادات ذاكرة النموذج",
+ saveError: "تعذّر حفظ إعدادات ذاكرة النموذج",
+ // Not rendered: extra terms the settings search matches these rows on.
+ modelMemoryKeywords:
+ "mlock memlock ulimit vram gpu ذاكرة رام مقيم تثبيت قفل إبقاء محمل تفريغ خامل mmap no-mmap load-mode تبديل ترحيل",
+ },
storage: {
title: "التخزين",
systemDisk: "قرص النظام",
@@ -717,8 +734,8 @@ export const ar = {
modelsFolder: "مجلد النماذج",
modelsFolderKeywords:
"النماذج مجلد دليل مسار موقع تنزيلات التنزيل ذاكرة التخزين المؤقت تخزين قرص محرك نقل تغيير models folder path hugging face",
- modelsFolderDescription:
- "المكان الذي تُخزَّن فيه النماذج المُنزَّلة. غيّره لإبقاء النماذج خارج قرص النظام.",
+ modelsFolderDescription: "مكان تخزين النماذج التي جرى تنزيلها.",
+ modelsFolderHint: "مكان تخزين النماذج التي جرى تنزيلها. غيّره لإبقاء النماذج بعيدًا عن قرص النظام. ينطبق على التنزيلات الجديدة فقط، أما النماذج الموجودة لديك فتبقى في مكانها.",
openAction: "فتح",
copyAction: "نسخ المسار",
copied: "تم نسخ المسار",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index fb4dfd758ce..70905e0bb8d 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -733,14 +733,31 @@ export const de = {
free: "{value} frei",
total: "{value} gesamt",
},
+ modelMemory: {
+ title: "Modellspeicher",
+ keepResident: "Modell im GPU-Speicher behalten",
+ keepResidentDescription: "Zwischen Prompts im VRAM bleiben.",
+ keepResidentHint: "Die Gewichte werden nicht an den System-RAM zurückgegeben, solange das Modell geladen bleibt. Deaktiviert das automatische Entladen im Leerlauf und übergibt zusätzlich --mlock, wenn die Gewichte tatsächlich im Host-RAM liegen (Unified Memory oder teilweises GPU-Offload), damit das Betriebssystem sie nicht auslagert und beim nächsten Prompt neu hochlädt.",
+ noRamReserve: "Keinen System-RAM für das Modell reservieren",
+ noRamReserveDescription: "Keine vollständige Kopie im RAM behalten.",
+ noRamReserveHint: "Die Gewichte werden in den VRAM gestreamt, statt eine vollständige Kopie im RAM zu halten. Behält das speicherabgebildete Laden von llama.cpp bei und entfernt --no-mmap und --mlock.",
+ mlockVetoed: "--mlock bleibt aus: das Fixieren des Modells würde RAM für das gesamte Modell reservieren. Das automatische Entladen im Leerlauf bleibt deaktiviert.",
+ memlockCapped: "Dieses System begrenzt gesperrten Speicher auf {limit}. Ein größeres Modell wird nicht vollständig fixiert; erhöhen Sie das Limit mit ulimit -l.",
+ reloadRequired: "Modell neu laden, um die neuen Speicheroptionen anzuwenden.",
+ loadError: "Modellspeicher-Einstellungen konnten nicht geladen werden",
+ saveError: "Modellspeicher-Einstellungen konnten nicht gespeichert werden",
+ // Not rendered: extra terms the settings search matches these rows on.
+ modelMemoryKeywords:
+ "mlock memlock ulimit vram gpu speicher arbeitsspeicher ram resident anheften fixieren sperren geladen halten entladen leerlauf mmap no-mmap load-mode auslagern",
+ },
storage: {
title: "Speicher",
systemDisk: "Systemfestplatte",
diskUsage: "{used} belegt / {total}",
diskFree: "{free} frei",
modelsFolder: "Modell-Ordner",
- modelsFolderDescription:
- "Wo heruntergeladene Modelle gespeichert werden. Ändern Sie ihn, um Modelle nicht auf dem Systemlaufwerk abzulegen.",
+ modelsFolderDescription: "Wo heruntergeladene Modelle gespeichert werden.",
+ modelsFolderHint: "Wo heruntergeladene Modelle gespeichert werden. Ändern Sie den Pfad, um Modelle von Ihrem Systemlaufwerk fernzuhalten. Gilt nur für neue Downloads. Bereits vorhandene Modelle bleiben, wo sie sind.",
modelsFolderKeywords:
"Modelle Ordner Verzeichnis Pfad Speicherort Download Downloads Cache Speicher Festplatte Laufwerk verschieben ändern hugging face",
futureDownloads: "Nur neue Downloads",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index c7b7d037ac8..1e9042c4332 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -702,14 +702,31 @@ export const en = {
free: "{value} free",
total: "{value} total",
},
+ modelMemory: {
+ title: "Model memory",
+ keepResident: "Keep model in GPU memory",
+ keepResidentDescription: "Stay in VRAM between prompts.",
+ keepResidentHint: "Don't hand the weights back to system RAM while the model stays loaded. Turns off idle auto-unload, and when the weights do sit in host RAM (unified memory, or a partial GPU offload) it also passes --mlock so the OS can't page them out and re-upload them on your next prompt.",
+ noRamReserve: "Don't reserve system RAM for the model",
+ noRamReserveDescription: "Keep no full copy in RAM.",
+ noRamReserveHint: "Stream the weights into VRAM instead of keeping a full copy in RAM. Keeps llama.cpp's memory-mapped loading and drops --no-mmap and --mlock.",
+ mlockVetoed: "--mlock stays off: pinning the model in place would reserve RAM for all of it. Idle auto-unload is still disabled.",
+ memlockCapped: "This system caps locked memory at {limit}. A larger model will not be fully pinned; raise the limit with ulimit -l.",
+ reloadRequired: "Reload the model to apply the new memory flags.",
+ loadError: "Failed to load model memory settings",
+ saveError: "Failed to save model memory settings",
+ // Not rendered: extra terms the settings search matches these rows on.
+ modelMemoryKeywords:
+ "mlock memlock ulimit vram gpu memory ram resident residency pin pinned page lock locked keep loaded unload idle mmap no-mmap load-mode swap paging",
+ },
storage: {
title: "Storage",
systemDisk: "System disk",
diskUsage: "{used} used / {total}",
diskFree: "{free} free",
modelsFolder: "Models folder",
- modelsFolderDescription:
- "Where downloaded models are stored. Change it to keep models off your system drive.",
+ modelsFolderDescription: "Where downloaded models are stored.",
+ modelsFolderHint: "Where downloaded models are stored. Change it to keep models off your system drive. Applies to new downloads only. Models you already have stay where they are.",
// Not rendered: extra terms the settings search matches this row on.
modelsFolderKeywords:
"models folder directory path location download downloads cache storage disk drive move relocate hugging face",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index cdf6b689163..aafff3ddd82 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -728,6 +728,23 @@ export const es = {
free: "Libre: {value}",
total: "{value} en total",
},
+ modelMemory: {
+ title: "Memoria del modelo",
+ keepResident: "Mantener el modelo en la memoria de la GPU",
+ keepResidentDescription: "Permanece en la VRAM entre mensajes.",
+ keepResidentHint: "No devuelve los pesos a la RAM del sistema mientras el modelo siga cargado. Desactiva la descarga automática por inactividad y, cuando los pesos sí residen en la RAM del host (memoria unificada o descarga parcial a la GPU), también pasa --mlock para que el sistema operativo no los pagine ni los vuelva a subir en tu siguiente mensaje.",
+ noRamReserve: "No reservar RAM del sistema para el modelo",
+ noRamReserveDescription: "No mantiene una copia completa en la RAM.",
+ noRamReserveHint: "Transfiere los pesos a la VRAM en lugar de mantener una copia completa en la RAM. Conserva la carga mapeada en memoria de llama.cpp y elimina --no-mmap y --mlock.",
+ mlockVetoed: "--mlock permanece desactivado: fijar el modelo reservaría RAM para todo él. La descarga automática por inactividad sigue desactivada.",
+ memlockCapped: "Este sistema limita la memoria bloqueada a {limit}. Un modelo mayor no quedará fijado por completo; aumenta el límite con ulimit -l.",
+ reloadRequired: "Vuelve a cargar el modelo para aplicar las nuevas opciones de memoria.",
+ loadError: "No se pudieron cargar los ajustes de memoria del modelo",
+ saveError: "No se pudieron guardar los ajustes de memoria del modelo",
+ // Not rendered: extra terms the settings search matches these rows on.
+ modelMemoryKeywords:
+ "mlock memlock ulimit vram gpu memoria ram residente fijar anclar bloquear mantener cargado descargar inactivo mmap no-mmap load-mode paginacion intercambio",
+ },
storage: {
title: "Almacenamiento",
systemDisk: "Disco del sistema",
@@ -736,8 +753,8 @@ export const es = {
modelsFolder: "Carpeta de modelos",
modelsFolderKeywords:
"modelos carpeta directorio ruta ubicacion ubicación descargas descarga cache caché almacenamiento disco unidad mover cambiar models folder path hugging face",
- modelsFolderDescription:
- "Dónde se almacenan los modelos descargados. Cambia la ubicación para guardar los modelos fuera de la unidad del sistema.",
+ modelsFolderDescription: "Dónde se guardan los modelos descargados.",
+ modelsFolderHint: "Dónde se guardan los modelos descargados. Cámbialo para mantener los modelos fuera de tu unidad del sistema. Solo se aplica a las descargas nuevas: los modelos que ya tienes se quedan donde están.",
openAction: "Abrir",
copyAction: "Copiar ruta",
copied: "Ruta copiada",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 81c168774c9..3e460ce9fea 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -732,6 +732,23 @@ export const fr = {
free: "Disponible : {value}",
total: "{value} au total",
},
+ modelMemory: {
+ title: "Mémoire du modèle",
+ keepResident: "Conserver le modèle dans la mémoire du GPU",
+ keepResidentDescription: "Reste en VRAM entre les messages.",
+ keepResidentHint: "Ne rend pas les poids à la RAM système tant que le modèle reste chargé. Désactive le déchargement automatique en veille et, lorsque les poids résident réellement en RAM hôte (mémoire unifiée ou déchargement GPU partiel), passe aussi --mlock afin que le système ne les décharge pas pour les retransférer au prochain message.",
+ noRamReserve: "Ne pas réserver de RAM système pour le modèle",
+ noRamReserveDescription: "Ne garde aucune copie complète en RAM.",
+ noRamReserveHint: "Transfère les poids vers la VRAM au lieu d'en garder une copie complète en RAM. Conserve le chargement mappé en mémoire de llama.cpp et supprime --no-mmap et --mlock.",
+ mlockVetoed: "--mlock reste désactivé : épingler le modèle réserverait de la RAM pour l'intégralité de celui-ci. Le déchargement automatique en veille reste désactivé.",
+ memlockCapped: "Ce système limite la mémoire verrouillée à {limit}. Un modèle plus grand ne sera pas entièrement épinglé ; augmentez la limite avec ulimit -l.",
+ reloadRequired: "Rechargez le modèle pour appliquer les nouvelles options de mémoire.",
+ loadError: "Impossible de charger les paramètres de mémoire du modèle",
+ saveError: "Impossible d'enregistrer les paramètres de mémoire du modèle",
+ // Not rendered: extra terms the settings search matches these rows on.
+ modelMemoryKeywords:
+ "mlock memlock ulimit vram gpu memoire ram resident epingler verrouiller garder charge decharger inactif mmap no-mmap load-mode pagination echange",
+ },
storage: {
title: "Stockage",
systemDisk: "Disque système",
@@ -740,8 +757,8 @@ export const fr = {
modelsFolder: "Dossier des modèles",
modelsFolderKeywords:
"modeles modèles dossier repertoire répertoire chemin emplacement telechargements téléchargements cache stockage disque lecteur deplacer déplacer changer models folder path hugging face",
- modelsFolderDescription:
- "Emplacement où sont stockés les modèles téléchargés. Modifiez-le pour ne pas stocker les modèles sur votre disque système.",
+ modelsFolderDescription: "Où sont stockés les modèles téléchargés.",
+ modelsFolderHint: "Où sont stockés les modèles téléchargés. Modifiez-le pour garder les modèles hors de votre disque système. S'applique uniquement aux nouveaux téléchargements. Les modèles que vous avez déjà restent où ils sont.",
openAction: "Ouvrir",
copyAction: "Copier le chemin",
copied: "Chemin copié",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 427c8afe0eb..0d28ced3177 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -712,6 +712,23 @@ export const hi = {
free: "{value} खाली",
total: "{value} कुल",
},
+ modelMemory: {
+ title: "मॉडल मेमोरी",
+ keepResident: "मॉडल को GPU मेमोरी में रखें",
+ keepResidentDescription: "प्रॉम्प्ट के बीच VRAM में बना रहता है।",
+ keepResidentHint: "जब तक मॉडल लोड रहता है, वेट्स सिस्टम RAM को वापस नहीं दिए जाते। निष्क्रिय होने पर स्वतः अनलोड बंद कर देता है, और जब वेट्स वास्तव में होस्ट RAM में रहते हैं (यूनिफाइड मेमोरी, या आंशिक GPU ऑफ़लोड) तब --mlock भी भेजता है, ताकि OS उन्हें पेज आउट करके आपके अगले प्रॉम्प्ट पर दोबारा अपलोड न करे।",
+ noRamReserve: "मॉडल के लिए सिस्टम RAM आरक्षित न करें",
+ noRamReserveDescription: "RAM में पूरी प्रति नहीं रखता।",
+ noRamReserveHint: "RAM में पूरी प्रति रखने के बजाय वेट्स को VRAM में भेजता है। llama.cpp की मेमोरी-मैप्ड लोडिंग बनाए रखता है और --no-mmap तथा --mlock हटा देता है।",
+ mlockVetoed: "--mlock बंद ही रहता है: मॉडल को पिन करने से उसकी पूरी मात्रा के लिए RAM आरक्षित हो जाएगी। निष्क्रिय होने पर स्वतः अनलोड अब भी अक्षम है।",
+ memlockCapped: "यह सिस्टम लॉक की गई मेमोरी को {limit} तक सीमित करता है। इससे बड़ा मॉडल पूरी तरह पिन नहीं होगा; ulimit -l से सीमा बढ़ाएँ।",
+ reloadRequired: "नई मेमोरी सेटिंग्स लागू करने के लिए मॉडल दोबारा लोड करें।",
+ loadError: "मॉडल मेमोरी सेटिंग्स लोड नहीं हो सकीं",
+ saveError: "मॉडल मेमोरी सेटिंग्स सहेजी नहीं जा सकीं",
+ // Not rendered: extra terms the settings search matches these rows on.
+ modelMemoryKeywords:
+ "mlock memlock ulimit vram gpu मेमोरी रैम स्थायी पिन लॉक बनाए रखें लोड अनलोड निष्क्रिय mmap no-mmap load-mode स्वैप पेजिंग",
+ },
storage: {
title: "स्टोरेज",
systemDisk: "सिस्टम डिस्क",
@@ -720,8 +737,8 @@ export const hi = {
modelsFolder: "मॉडल फ़ोल्डर",
modelsFolderKeywords:
"मॉडल फ़ोल्डर फोल्डर निर्देशिका पथ स्थान डाउनलोड कैश संग्रहण डिस्क ड्राइव स्थानांतरित बदलें models folder path hugging face",
- modelsFolderDescription:
- "डाउनलोड किए गए मॉडल यहाँ संग्रहीत होते हैं। मॉडल को सिस्टम ड्राइव से अलग रखने के लिए यह स्थान बदलें।",
+ modelsFolderDescription: "डाउनलोड किए गए मॉडल कहाँ संग्रहीत होते हैं।",
+ modelsFolderHint: "डाउनलोड किए गए मॉडल कहाँ संग्रहीत होते हैं। मॉडल को अपनी सिस्टम ड्राइव से दूर रखने के लिए इसे बदलें। यह केवल नए डाउनलोड पर लागू होता है। आपके पास पहले से मौजूद मॉडल वहीं रहते हैं।",
openAction: "खोलें",
copyAction: "पथ कॉपी करें",
copied: "पथ कॉपी किया गया",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 9049790f71e..d0eb6001fb2 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -701,14 +701,31 @@ export const it = {
free: "Disponibili: {value}",
total: "Totale: {value}",
},
+ modelMemory: {
+ title: "Memoria del modello",
+ keepResident: "Mantieni il modello nella memoria della GPU",
+ keepResidentDescription: "Resta nella VRAM tra un prompt e l'altro.",
+ keepResidentHint: "Non restituisce i pesi alla RAM di sistema finché il modello resta caricato. Disattiva lo scaricamento automatico in inattività e, quando i pesi risiedono davvero nella RAM host (memoria unificata o offload parziale sulla GPU), passa anche --mlock, così il sistema operativo non li pagina per ricaricarli al prompt successivo.",
+ noRamReserve: "Non riservare RAM di sistema per il modello",
+ noRamReserveDescription: "Non tiene una copia completa in RAM.",
+ noRamReserveHint: "Trasferisce i pesi nella VRAM invece di tenerne una copia completa in RAM. Mantiene il caricamento mappato in memoria di llama.cpp e rimuove --no-mmap e --mlock.",
+ mlockVetoed: "--mlock resta disattivato: bloccare il modello riserverebbe RAM per l'intero modello. Lo scaricamento automatico in inattività resta disattivato.",
+ memlockCapped: "Questo sistema limita la memoria bloccata a {limit}. Un modello più grande non verrà bloccato del tutto; aumenta il limite con ulimit -l.",
+ reloadRequired: "Ricarica il modello per applicare le nuove opzioni di memoria.",
+ loadError: "Impossibile caricare le impostazioni di memoria del modello",
+ saveError: "Impossibile salvare le impostazioni di memoria del modello",
+ // Not rendered: extra terms the settings search matches these rows on.
+ modelMemoryKeywords:
+ "mlock memlock ulimit vram gpu memoria ram residente bloccare fissare mantenere caricato scaricare inattivo mmap no-mmap load-mode paginazione swap",
+ },
storage: {
title: "Archiviazione",
systemDisk: "Disco di sistema",
diskUsage: "In uso: {used} / Totale: {total}",
diskFree: "Disponibili: {free}",
modelsFolder: "Cartella dei modelli",
- modelsFolderDescription:
- "Dove vengono salvati i modelli scaricati. Cambiala per tenere i modelli fuori dal disco di sistema.",
+ modelsFolderDescription: "Dove vengono salvati i modelli scaricati.",
+ modelsFolderHint: "Dove vengono salvati i modelli scaricati. Cambialo per tenere i modelli fuori dall'unità di sistema. Vale solo per i nuovi download: i modelli che hai già restano dove sono.",
// Non visualizzato: termini extra su cui la ricerca delle impostazioni trova questa riga.
modelsFolderKeywords:
"cartella modelli directory percorso posizione download scaricati cache archiviazione disco unità spostare sposta hugging face models folder path storage",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index a58e305682c..f1f146c07e0 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -692,6 +692,23 @@ export const ja = {
free: "{value} 空き",
total: "{value} 合計",
},
+ modelMemory: {
+ title: "モデルメモリ",
+ keepResident: "モデルを GPU メモリに保持",
+ keepResidentDescription: "プロンプト間も VRAM に常駐します。",
+ keepResidentHint: "モデルがロードされている間、重みをシステム RAM に戻しません。アイドル時の自動アンロードを無効にし、重みが実際にホスト RAM 上にある場合(ユニファイドメモリ、または GPU への部分オフロード)は --mlock も渡すため、OS が重みをページアウトして次のプロンプトで再アップロードすることがなくなります。",
+ noRamReserve: "モデル用にシステム RAM を確保しない",
+ noRamReserveDescription: "RAM に完全なコピーを保持しません。",
+ noRamReserveHint: "RAM に完全なコピーを保持せず、重みを VRAM へ転送します。llama.cpp のメモリマップ読み込みを維持し、--no-mmap と --mlock を除去します。",
+ mlockVetoed: "--mlock は無効のままです。モデルを固定するとモデル全体分の RAM を確保することになります。アイドル時の自動アンロードは引き続き無効です。",
+ memlockCapped: "このシステムはロック可能なメモリを {limit} に制限しています。これより大きいモデルは完全には固定されません。ulimit -l で上限を引き上げてください。",
+ reloadRequired: "新しいメモリ設定を適用するにはモデルを再読み込みしてください。",
+ loadError: "モデルメモリ設定の読み込みに失敗しました",
+ saveError: "モデルメモリ設定の保存に失敗しました",
+ // Not rendered: extra terms the settings search matches these rows on.
+ modelMemoryKeywords:
+ "mlock memlock ulimit vram gpu メモリ ram 常駐 固定 ロック 保持 ロード済み アンロード アイドル mmap no-mmap load-mode スワップ ページング",
+ },
storage: {
title: "ストレージ",
systemDisk: "システムディスク",
@@ -700,8 +717,8 @@ export const ja = {
modelsFolder: "モデルフォルダ",
modelsFolderKeywords:
"モデル フォルダ ディレクトリ パス 保存先 場所 ダウンロード キャッシュ ストレージ ディスク ドライブ 移動 変更 models folder path hugging face",
- modelsFolderDescription:
- "ダウンロードしたモデルの保存先です。変更すると、システムドライブ以外にモデルを保存できます。",
+ modelsFolderDescription: "ダウンロードしたモデルの保存場所です。",
+ modelsFolderHint: "ダウンロードしたモデルの保存場所です。システムドライブを圧迫しないよう変更できます。新規ダウンロードにのみ適用され、既存のモデルはそのままの場所に残ります。",
openAction: "開く",
copyAction: "パスをコピー",
copied: "パスをコピーしました",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 5b694902ac9..3c696d88593 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -706,6 +706,23 @@ export const ko = {
free: "{value} 여유",
total: "총 {value}",
},
+ modelMemory: {
+ title: "모델 메모리",
+ keepResident: "모델을 GPU 메모리에 유지",
+ keepResidentDescription: "프롬프트 사이에도 VRAM에 상주합니다.",
+ keepResidentHint: "모델이 로드되어 있는 동안 가중치를 시스템 RAM으로 되돌리지 않습니다. 유휴 시 자동 언로드를 끄고, 가중치가 실제로 호스트 RAM에 있는 경우(통합 메모리 또는 부분 GPU 오프로드)에는 --mlock도 전달하여 운영체제가 가중치를 페이지 아웃했다가 다음 프롬프트에서 다시 업로드하지 않도록 합니다.",
+ noRamReserve: "모델을 위해 시스템 RAM을 예약하지 않음",
+ noRamReserveDescription: "RAM에 전체 사본을 두지 않습니다.",
+ noRamReserveHint: "RAM에 전체 사본을 두지 않고 가중치를 VRAM으로 전송합니다. llama.cpp의 메모리 매핑 로딩을 유지하고 --no-mmap과 --mlock을 제거합니다.",
+ mlockVetoed: "--mlock은 꺼진 상태로 유지됩니다. 모델을 고정하면 모델 전체 크기만큼 RAM을 예약하게 됩니다. 유휴 시 자동 언로드는 계속 비활성화됩니다.",
+ memlockCapped: "이 시스템은 잠금 메모리를 {limit}로 제한합니다. 더 큰 모델은 완전히 고정되지 않습니다. ulimit -l로 한도를 늘리세요.",
+ reloadRequired: "새 메모리 옵션을 적용하려면 모델을 다시 로드하세요.",
+ loadError: "모델 메모리 설정을 불러오지 못했습니다",
+ saveError: "모델 메모리 설정을 저장하지 못했습니다",
+ // Not rendered: extra terms the settings search matches these rows on.
+ modelMemoryKeywords:
+ "mlock memlock ulimit vram gpu 메모리 ram 상주 고정 잠금 유지 로드됨 언로드 유휴 mmap no-mmap load-mode 스왑 페이징",
+ },
storage: {
title: "저장소",
systemDisk: "시스템 디스크",
@@ -714,8 +731,8 @@ export const ko = {
modelsFolder: "모델 폴더",
modelsFolderKeywords:
"모델 폴더 디렉터리 디렉토리 경로 위치 저장 다운로드 캐시 저장소 디스크 드라이브 이동 변경 models folder path hugging face",
- modelsFolderDescription:
- "다운로드한 모델이 저장되는 위치입니다. 시스템 드라이브에 모델을 저장하지 않으려면 위치를 변경하세요.",
+ modelsFolderDescription: "다운로드한 모델이 저장되는 위치입니다.",
+ modelsFolderHint: "다운로드한 모델이 저장되는 위치입니다. 시스템 드라이브를 차지하지 않도록 변경하세요. 새 다운로드에만 적용되며, 이미 받은 모델은 원래 위치에 그대로 남습니다.",
openAction: "열기",
copyAction: "경로 복사",
copied: "경로가 복사되었습니다",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index cdf7f0d3536..e13569e0e38 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -716,6 +716,23 @@ export const ptBR = {
free: "{value} livres",
total: "{value} total",
},
+ modelMemory: {
+ title: "Memória do modelo",
+ keepResident: "Manter o modelo na memória da GPU",
+ keepResidentDescription: "Permanece na VRAM entre os prompts.",
+ keepResidentHint: "Não devolve os pesos à RAM do sistema enquanto o modelo continuar carregado. Desativa a descarga automática por inatividade e, quando os pesos de fato ficam na RAM do host (memória unificada ou offload parcial para a GPU), também passa --mlock, para que o sistema operacional não os pagine e os reenvie no próximo prompt.",
+ noRamReserve: "Não reservar RAM do sistema para o modelo",
+ noRamReserveDescription: "Não mantém uma cópia completa na RAM.",
+ noRamReserveHint: "Transfere os pesos para a VRAM em vez de manter uma cópia completa na RAM. Mantém o carregamento mapeado em memória do llama.cpp e remove --no-mmap e --mlock.",
+ mlockVetoed: "--mlock continua desativado: fixar o modelo reservaria RAM para todo ele. A descarga automática por inatividade continua desativada.",
+ memlockCapped: "Este sistema limita a memória bloqueada a {limit}. Um modelo maior não será totalmente fixado; aumente o limite com ulimit -l.",
+ reloadRequired: "Recarregue o modelo para aplicar as novas opções de memória.",
+ loadError: "Falha ao carregar as configurações de memória do modelo",
+ saveError: "Falha ao salvar as configurações de memória do modelo",
+ // Not rendered: extra terms the settings search matches these rows on.
+ modelMemoryKeywords:
+ "mlock memlock ulimit vram gpu memoria ram residente fixar travar manter carregado descarregar ocioso mmap no-mmap load-mode paginacao swap",
+ },
storage: {
title: "Armazenamento",
systemDisk: "Disco do sistema",
@@ -724,8 +741,8 @@ export const ptBR = {
modelsFolder: "Pasta de modelos",
modelsFolderKeywords:
"modelos pasta diretorio diretório caminho local localizacao localização downloads baixar cache armazenamento disco unidade mover alterar models folder path hugging face",
- modelsFolderDescription:
- "Onde os modelos baixados são armazenados. Altere o local para manter os modelos fora da unidade do sistema.",
+ modelsFolderDescription: "Onde os modelos baixados são armazenados.",
+ modelsFolderHint: "Onde os modelos baixados são armazenados. Altere para manter os modelos fora da sua unidade de sistema. Vale apenas para novos downloads. Os modelos que você já tem permanecem onde estão.",
openAction: "Abrir",
copyAction: "Copiar caminho",
copied: "Caminho copiado",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 496b42f2e70..5477d6f468d 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -713,6 +713,23 @@ export const ru = {
free: "{value} свободно",
total: "{value} всего",
},
+ modelMemory: {
+ title: "Память модели",
+ keepResident: "Держать модель в памяти GPU",
+ keepResidentDescription: "Остаётся в видеопамяти между запросами.",
+ keepResidentHint: "Веса не возвращаются в системную ОЗУ, пока модель загружена. Отключает автовыгрузку по простою, а если веса действительно находятся в ОЗУ хоста (единая память или частичная выгрузка на GPU), дополнительно передаёт --mlock, чтобы ОС не вытесняла их и не загружала заново при следующем запросе.",
+ noRamReserve: "Не резервировать системную ОЗУ под модель",
+ noRamReserveDescription: "Не хранит полную копию в ОЗУ.",
+ noRamReserveHint: "Веса передаются в видеопамять вместо хранения полной копии в ОЗУ. Сохраняет загрузку через отображение файла в память в llama.cpp и убирает --no-mmap и --mlock.",
+ mlockVetoed: "--mlock остаётся выключенным: закрепление модели зарезервировало бы ОЗУ под неё целиком. Автовыгрузка по простою по-прежнему отключена.",
+ memlockCapped: "Система ограничивает блокируемую память значением {limit}. Модель большего размера не будет закреплена полностью; увеличьте лимит через ulimit -l.",
+ reloadRequired: "Перезагрузите модель, чтобы применить новые параметры памяти.",
+ loadError: "Не удалось загрузить настройки памяти модели",
+ saveError: "Не удалось сохранить настройки памяти модели",
+ // Not rendered: extra terms the settings search matches these rows on.
+ modelMemoryKeywords:
+ "mlock memlock ulimit vram gpu память озу резидентный закрепить блокировать держать загружен выгрузка простой mmap no-mmap load-mode подкачка",
+ },
storage: {
title: "Хранилище",
systemDisk: "Системный диск",
@@ -721,8 +738,8 @@ export const ru = {
modelsFolder: "Папка моделей",
modelsFolderKeywords:
"модели папка каталог путь расположение загрузки кэш хранилище диск перенести изменить models folder path hugging face",
- modelsFolderDescription:
- "Здесь хранятся скачанные модели. Измените папку, чтобы хранить модели не на системном диске.",
+ modelsFolderDescription: "Где хранятся загруженные модели.",
+ modelsFolderHint: "Где хранятся загруженные модели. Измените путь, чтобы модели не занимали системный диск. Применяется только к новым загрузкам. Уже имеющиеся модели останутся на прежнем месте.",
openAction: "Открыть",
copyAction: "Копировать путь",
copied: "Путь скопирован",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 8c6dd4bd0dd..0f23f790f04 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -688,6 +688,23 @@ export const zhCN = {
free: "{value} 可用",
total: "共 {value}",
},
+ modelMemory: {
+ title: "模型内存",
+ keepResident: "将模型保留在显存中",
+ keepResidentDescription: "在两次提问之间保持驻留显存。",
+ keepResidentHint: "模型保持加载期间,不把权重交还给系统内存。关闭空闲自动卸载;当权重确实位于主机内存中时(统一内存,或部分卸载到 GPU),还会传入 --mlock,使操作系统无法将其换出、并在你下次提问时重新上传。",
+ noRamReserve: "不为模型预留系统内存",
+ noRamReserveDescription: "不在内存中保留完整副本。",
+ noRamReserveHint: "将权重传输到显存,而不在内存中保留完整副本。保持 llama.cpp 的内存映射加载方式,并移除 --no-mmap 和 --mlock。",
+ mlockVetoed: "--mlock 保持关闭:锁定模型会为其全部内容预留内存。空闲自动卸载仍处于禁用状态。",
+ memlockCapped: "本系统将锁定内存限制为 {limit}。更大的模型无法被完全锁定;请使用 ulimit -l 提高上限。",
+ reloadRequired: "重新加载模型以应用新的内存选项。",
+ loadError: "加载模型内存设置失败",
+ saveError: "保存模型内存设置失败",
+ // Not rendered: extra terms the settings search matches these rows on.
+ modelMemoryKeywords:
+ "mlock memlock ulimit vram gpu 内存 显存 常驻 固定 锁定 保持 已加载 卸载 空闲 mmap no-mmap load-mode 交换 分页",
+ },
storage: {
title: "存储",
systemDisk: "系统磁盘",
@@ -696,8 +713,8 @@ export const zhCN = {
modelsFolder: "模型文件夹",
modelsFolderKeywords:
"模型 文件夹 目录 路径 位置 下载 缓存 存储 磁盘 驱动器 移动 更改 models folder path hugging face",
- modelsFolderDescription:
- "已下载模型的存储位置。更改此位置可避免将模型存放在系统磁盘上。",
+ modelsFolderDescription: "下载的模型的存放位置。",
+ modelsFolderHint: "下载的模型的存放位置。可更改以避免占用系统盘。仅对新的下载生效。已有的模型仍保留在原位置。",
openAction: "打开",
copyAction: "复制路径",
copied: "路径已复制",
diff --git a/studio/frontend/tests/helpers/auth-stub.mjs b/studio/frontend/tests/helpers/auth-stub.mjs
new file mode 100644
index 00000000000..e45b9b78449
--- /dev/null
+++ b/studio/frontend/tests/helpers/auth-stub.mjs
@@ -0,0 +1,11 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Stands in for src/features/auth/index.ts. The real barrel re-exports
+// login-page.tsx, and node --experimental-strip-types cannot parse JSX, so a
+// settings API unit test would pull in the whole React tree. Same cut as
+// export-api-stub.mjs. Forwards to globalThis.fetch, which the test replaces.
+
+export async function authFetch(input, init) {
+ return globalThis.fetch(input, init);
+}
diff --git a/studio/frontend/tests/helpers/settings-api-resolver.mjs b/studio/frontend/tests/helpers/settings-api-resolver.mjs
new file mode 100644
index 00000000000..56b97f44e8e
--- /dev/null
+++ b/studio/frontend/tests/helpers/settings-api-resolver.mjs
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// bundler-resolver's two rules, plus one redirect: features/auth -> a stub.
+// See auth-stub.mjs for why the redirect is needed.
+import { existsSync } from "node:fs";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const SRC = fileURLToPath(new URL("../../src/", import.meta.url));
+const STUB = new URL("./auth-stub.mjs", import.meta.url).href;
+
+function firstExisting(base) {
+ for (const candidate of [`${base}.ts`, `${base}/index.ts`, base]) {
+ if (existsSync(candidate)) return pathToFileURL(candidate).href;
+ }
+ return null;
+}
+
+export function resolve(specifier, context, next) {
+ if (specifier === "@/features/auth" || /(^|\/)features\/auth$/.test(specifier)) {
+ return next(STUB, context);
+ }
+ if (specifier.startsWith("@/")) {
+ const resolved = firstExisting(SRC + specifier.slice(2));
+ return next(resolved ?? specifier, context);
+ }
+ if (specifier.startsWith(".") && context.parentURL?.startsWith("file:")) {
+ const resolved = firstExisting(fileURLToPath(new URL(specifier, context.parentURL)));
+ if (resolved) return next(resolved, context);
+ }
+ return next(specifier, context);
+}
diff --git a/studio/frontend/tests/model-memory-cache.test.ts b/studio/frontend/tests/model-memory-cache.test.ts
new file mode 100644
index 00000000000..1e55de9c6d7
--- /dev/null
+++ b/studio/frontend/tests/model-memory-cache.test.ts
@@ -0,0 +1,214 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The response carries runtime state that goes stale as soon as a model is
+// loaded, so the module coalesces concurrent reads but never caches. Saving it
+// must also drop the auto-switch cache, whose idle TTL residency vetoes.
+
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+import { installLocalStorageFake } from "./helpers/kit.ts";
+
+// The settings API modules reach authFetch through the auth barrel, which
+// re-exports login-page.tsx. See helpers/auth-stub.mjs.
+register("./helpers/settings-api-resolver.mjs", import.meta.url);
+installLocalStorageFake();
+
+type Listener = (event: Event) => void;
+const listeners = new Map<string, Set<Listener>>();
+Object.assign(globalThis.window as object, {
+ addEventListener: (type: string, fn: Listener) => {
+ if (!listeners.has(type)) listeners.set(type, new Set());
+ listeners.get(type)?.add(fn);
+ },
+ removeEventListener: (type: string, fn: Listener) => {
+ listeners.get(type)?.delete(fn);
+ },
+ dispatchEvent: (event: Event) => {
+ for (const fn of listeners.get(event.type) ?? []) fn(event);
+ return true;
+ },
+});
+
+const API = {
+ keep_resident: false,
+ no_ram_reserve: false,
+ default_keep_resident: false,
+ default_no_ram_reserve: false,
+ mlock_active: false,
+ reload_required: false,
+ memlock_limit_bytes: null as number | null,
+};
+
+let calls: string[] = [];
+let nextBody: Record<string, unknown> = { ...API };
+let release: (() => void) | null = null;
+
+globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(
+ typeof input === "string" ? input : (input as Request).url,
+ );
+ calls.push(`${init?.method ?? "GET"} ${url}`);
+ const body = { ...nextBody };
+ if (release) {
+ await new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ }
+ return new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+}) as typeof fetch;
+
+const {
+ loadModelMemorySettings,
+ subscribeModelMemorySettings,
+ updateModelMemorySettings,
+} = await import("../src/features/settings/api/model-memory.ts");
+const autoSwitch = await import(
+ "../src/features/settings/api/openai-auto-switch.ts"
+);
+
+test("concurrent reads share one request", async () => {
+ calls = [];
+ const [a, b, c] = await Promise.all([
+ loadModelMemorySettings(),
+ loadModelMemorySettings(),
+ loadModelMemorySettings(),
+ ]);
+ assert.equal(calls.length, 1, "three callers, one GET");
+ assert.deepEqual(a, b);
+ assert.deepEqual(b, c);
+});
+
+test("a later read is NOT served from a cache", async () => {
+ calls = [];
+ await loadModelMemorySettings();
+ nextBody = { ...API, reload_required: true };
+ const second = await loadModelMemorySettings();
+ assert.equal(
+ calls.length,
+ 2,
+ "runtime state must be refetched, never cached",
+ );
+ assert.equal(second.reloadRequired, true);
+ nextBody = { ...API };
+});
+
+test("a failed read does not wedge the in-flight slot", async () => {
+ calls = [];
+ const original = globalThis.fetch;
+ globalThis.fetch = (async () => {
+ throw new Error("offline");
+ }) as typeof fetch;
+ await assert.rejects(loadModelMemorySettings());
+ globalThis.fetch = original;
+ // The next caller must get a fresh request rather than the rejected promise.
+ const after = await loadModelMemorySettings();
+ assert.equal(after.keepResident, false);
+});
+
+test("only the fields actually set are sent, so the switches save independently", async () => {
+ calls = [];
+ const bodies: string[] = [];
+ const original = globalThis.fetch;
+ globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {
+ bodies.push(String(init?.body ?? ""));
+ return new Response(JSON.stringify(API), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ }) as typeof fetch;
+ await updateModelMemorySettings({ keepResident: true });
+ globalThis.fetch = original;
+ assert.deepEqual(JSON.parse(bodies[0] ?? "{}"), { keep_resident: true });
+});
+
+test("subscribers receive every published value", async () => {
+ const seen: boolean[] = [];
+ const stop = subscribeModelMemorySettings((s) => seen.push(s.keepResident));
+ nextBody = { ...API, keep_resident: true };
+ await loadModelMemorySettings();
+ stop();
+ nextBody = { ...API };
+ await loadModelMemorySettings();
+ assert.deepEqual(
+ seen,
+ [true],
+ "one while subscribed, none after unsubscribe",
+ );
+});
+
+test("saving model memory drops the auto-switch cache", async () => {
+ // idle_unload_active is vetoed by residency, so the other endpoint's cached
+ // copy is wrong the moment this one is written. hub-page reads it on every
+ // status poll, so a stale value survives for the life of the page.
+ const first = await autoSwitch.loadOpenAIAutoSwitchSettings();
+ assert.ok(first);
+ calls = [];
+ await autoSwitch.loadOpenAIAutoSwitchSettings();
+ assert.equal(calls.length, 0, "auto-switch does cache");
+
+ await updateModelMemorySettings({ keepResident: true });
+ calls = [];
+ await autoSwitch.loadOpenAIAutoSwitchSettings();
+ assert.equal(calls.length, 1, "the write must have invalidated it");
+});
+
+test("a read invalidated in flight returns the post-write value, not the stale one", async () => {
+ // hub-page puts this straight into idleUnloadArmed, so handing back a
+ // response that predates the write is as bad as caching it.
+ autoSwitch.invalidateOpenAIAutoSwitchSettings();
+ nextBody = { ...API, idle_unload_active: true };
+ release = () => {};
+ const pending = autoSwitch.loadOpenAIAutoSwitchSettings();
+
+ // Land the invalidation, and the new value, while that response is in flight.
+ autoSwitch.invalidateOpenAIAutoSwitchSettings();
+ nextBody = { ...API, idle_unload_active: false };
+ const resume = release;
+ release = null;
+ resume?.();
+
+ const settings = await pending;
+ assert.equal(
+ settings.idleUnloadActive,
+ false,
+ "the read must have been retried against the new generation",
+ );
+
+ // And the retry's value is the one that got cached.
+ calls = [];
+ const again = await autoSwitch.loadOpenAIAutoSwitchSettings();
+ assert.equal(calls.length, 0);
+ assert.equal(again.idleUnloadActive, false);
+});
+
+test("a caller arriving after the invalidation does not adopt the pre-write read", async () => {
+ // The retry above covers the caller that started before the write. One that
+ // arrives after it must not share that same GET either: the reply predates the
+ // write, and the hub poll puts it straight into idleUnloadArmed, where
+ // "disarmed" clears the user's selected checkpoint.
+ autoSwitch.invalidateOpenAIAutoSwitchSettings();
+ nextBody = { ...API, idle_unload_active: true };
+ release = () => {};
+ const before = autoSwitch.loadOpenAIAutoSwitchSettings();
+ const resume = release;
+ release = null;
+
+ autoSwitch.invalidateOpenAIAutoSwitchSettings();
+ nextBody = { ...API, idle_unload_active: false };
+ const after = autoSwitch.loadOpenAIAutoSwitchSettings();
+ resume?.();
+
+ assert.equal(
+ (await after).idleUnloadActive,
+ false,
+ "the post-write caller must read the post-write value",
+ );
+ assert.equal((await before).idleUnloadActive, false);
+ nextBody = { ...API };
+});
diff --git a/studio/frontend/tests/settings-search.test.ts b/studio/frontend/tests/settings-search.test.ts
index f562eb88803..5b4164e657c 100644
--- a/studio/frontend/tests/settings-search.test.ts
+++ b/studio/frontend/tests/settings-search.test.ts
@@ -4,7 +4,11 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { createSettingsSearchIndex } from "../src/features/settings/settings-search.ts";
+import {
+ SETTINGS_SEARCH_KEYWORDS,
+ createSettingsSearchIndex,
+} from "../src/features/settings/settings-search.ts";
+import { en } from "../src/i18n/locales/en.ts";
const UPDATE_ENTRY = "settings.about.updates";
@@ -22,6 +26,33 @@ test("browser update searches keep routing to About", () => {
assert.ok(index.about.includes(UPDATE_ENTRY));
});
+// The words a user types for this feature are not substrings of any of its
+// labels, so without keywords the rows it is named after were unfindable.
+test("model memory rows are reachable by the terms the feature is about", () => {
+ const index = createSettingsSearchIndex(false);
+ const rows = [
+ "settings.resources.modelMemory.title",
+ "settings.resources.modelMemory.keepResident",
+ "settings.resources.modelMemory.noRamReserve",
+ ] as const;
+
+ for (const row of rows) {
+ assert.ok(index.resources.includes(row), `${row} is indexed under Resources`);
+ assert.equal(
+ SETTINGS_SEARCH_KEYWORDS[row],
+ "settings.resources.modelMemory.modelMemoryKeywords",
+ `${row} has synonyms`,
+ );
+ }
+
+ for (const term of ["mlock", "vram", "ulimit", "memlock", "pin"]) {
+ assert.ok(
+ en.settings.resources.modelMemory.modelMemoryKeywords.includes(term),
+ `search matches "${term}"`,
+ );
+ }
+});
+
const STARTUP_ENTRIES = [
"settings.general.startup.sectionTitle",
"settings.general.startup.launchAtLogin",