Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(model-cache): offload other architectures and keep the work reserve driver-free (#9655)
Alexander Eichhorn0fe26a92123f
diff --git a/docs/src/content/docs/configuration/Optimization/low-vram-mode.mdx b/docs/src/content/docs/configuration/Optimization/low-vram-mode.mdxindex e3d9204387..0626eb3107 100644--- a/docs/src/content/docs/configuration/Optimization/low-vram-mode.mdx+++ b/docs/src/content/docs/configuration/Optimization/low-vram-mode.mdx@@ -168,6 +168,23 @@ Invoke has the option of keeping a RAM copy of all model weights, even when theykeep_ram_copy_of_weights: false```+### Switching between model architectures++When a generation uses main models of another architecture than the previous one on the same GPU (say, FLUX.1 after SDXL), Invoke first moves every model the new generation does not use from VRAM to RAM. Models both generations use, such as a shared VAE or text encoder, stay in VRAM. Moving models back from RAM costs a few seconds per switch, more with `keep_ram_copy_of_weights: false`, so if you alternate between architectures that would fit in VRAM together, you can turn this off:++```yaml+# Keep other architectures' models in VRAM until a load needs the room.+offload_on_architecture_switch: false+```++### Clearing VRAM after every generation++If a generation runs fine the first time but runs out of memory when you repeat it, or slows down sharply because Windows moves part of it into shared GPU memory, you can have Invoke move the models it holds in VRAM to RAM after every queue item (every image of a batch) and hand the freed memory back to the GPU driver. The models stay cached in RAM, so each queue item then costs a few seconds for reloading them, not a full load from disk, and with `keep_ram_copy_of_weights: false` also the time to copy them back to RAM. On a machine with several GPUs, handing the memory back briefly holds up a generation running on another GPU. On CPU, Apple Silicon and integrated GPUs, whose VRAM is system memory, the setting changes nothing:++```yaml+clear_vram_after_session: true+```+### Tiled VAE decode and encodeWithout tiling, the memory a VAE needs grows with the square of the image size. For FLUX.1, an untiled 3072² encode peaks at about 18.8 GiB on an RTX 4090, and a tiled one at 0.8 GiB, while tiled memory stays roughly flat as the image grows. Tiling costs some speed on smaller images.diff --git a/docs/src/generated/settings.json b/docs/src/generated/settings.jsonindex 58f45af193..4ffefdca7e 100644--- a/docs/src/generated/settings.json+++ b/docs/src/generated/settings.json@@ -526,6 +526,28 @@"type": "<class 'bool'>","validation": {}},+ {+ "category": "CACHE",+ "default": true,+ "description": "When a session uses main models of another architecture than the previous one on the same GPU, move every model it does not use from VRAM to RAM before it runs. Models both sessions use stay. Switching back reloads the moved models from RAM, which costs a few seconds per switch when both architectures would have fit in VRAM together; turn this off if you alternate between such models.",+ "env_var": "INVOKEAI_OFFLOAD_ON_ARCHITECTURE_SWITCH",+ "literal_values": [],+ "name": "offload_on_architecture_switch",+ "required": false,+ "type": "<class 'bool'>",+ "validation": {}+ },+ {+ "category": "CACHE",+ "default": false,+ "description": "After every queue item (each image of a batch), move the models held in VRAM to RAM and return the freed memory to the GPU driver. The models stay cached in RAM; the next item reloads them from there, which costs a few seconds (more with keep_ram_copy_of_weights off). Changes nothing where VRAM is system memory (CPU, MPS, integrated GPUs). Turn this on if a generation that runs fine the first time runs out of memory, or slows down sharply because the GPU spills into shared memory, when it is repeated.",+ "env_var": "INVOKEAI_CLEAR_VRAM_AFTER_SESSION",+ "literal_values": [],+ "name": "clear_vram_after_session",+ "required": false,+ "type": "<class 'bool'>",+ "validation": {}+ },{"category": "CACHE","default": false,diff --git a/invokeai/app/services/config/config_default.py b/invokeai/app/services/config/config_default.pyindex b8af990093..99786c1f9c 100644--- a/invokeai/app/services/config/config_default.py+++ b/invokeai/app/services/config/config_default.py@@ -112,6 +112,8 @@ class InvokeAIAppConfig(BaseSettings):device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.+ offload_on_architecture_switch: When a session uses main models of another architecture than the previous one on the same GPU, move every model it does not use from VRAM to RAM before it runs. Models both sessions use stay. Switching back reloads the moved models from RAM, which costs a few seconds per switch when both architectures would have fit in VRAM together; turn this off if you alternate between such models.+ clear_vram_after_session: After every queue item (each image of a batch), move the models held in VRAM to RAM and return the freed memory to the GPU driver. The models stay cached in RAM; the next item reloads them from there, which costs a few seconds (more with keep_ram_copy_of_weights off). Changes nothing where VRAM is system memory (CPU, MPS, integrated GPUs). Turn this on if a generation that runs fine the first time runs out of memory, or slows down sharply because the GPU spills into shared memory, when it is repeated.fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU, or a ROCm GPU that passes an fp8 matmul probe; falls back automatically otherwise). Speeds up denoising and keeps the transformer at fp8 size - FP8 Storage alone also keeps it at that size, without the speedup - but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.@@ -229,6 +231,8 @@ class InvokeAIAppConfig(BaseSettings):device_working_mem_gb: float = Field(default=3, description="The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.")enable_partial_loading: bool = Field(default=True, description="Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.")keep_ram_copy_of_weights: bool = Field(default=True, description="Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.")+ offload_on_architecture_switch: bool = Field(default=True, description="When a session uses main models of another architecture than the previous one on the same GPU, move every model it does not use from VRAM to RAM before it runs. Models both sessions use stay. Switching back reloads the moved models from RAM, which costs a few seconds per switch when both architectures would have fit in VRAM together; turn this off if you alternate between such models.")+ clear_vram_after_session: bool = Field(default=False, description="After every queue item (each image of a batch), move the models held in VRAM to RAM and return the freed memory to the GPU driver. The models stay cached in RAM; the next item reloads them from there, which costs a few seconds (more with keep_ram_copy_of_weights off). Changes nothing where VRAM is system memory (CPU, MPS, integrated GPUs). Turn this on if a generation that runs fine the first time runs out of memory, or slows down sharply because the GPU spills into shared memory, when it is repeated.")fp8_compute: bool = Field(default=False, description="Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU, or a ROCm GPU that passes an fp8 matmul probe; falls back automatically otherwise). Speeds up denoising and keeps the transformer at fp8 size - FP8 Storage alone also keeps it at that size, without the speedup - but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).")fp8_compute_full_precision_hints: bool = Field(default=True, description="Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.")# Deprecated CACHE configsdiff --git a/invokeai/app/services/session_processor/architecture_switch.py b/invokeai/app/services/session_processor/architecture_switch.pynew file mode 100644index 0000000000..eaae175849--- /dev/null+++ b/invokeai/app/services/session_processor/architecture_switch.py@@ -0,0 +1,77 @@+"""Clear VRAM of the previous architecture's models when a worker's sessions switch architecture.++The model cache otherwise leaves every model where it is until a reservation needs its VRAM, and a reservation+evicts only as much as the next node estimates, so after a run of different architectures the card stays nearly full+of models the current one will not use. Measured on an RTX 4090 after SDXL, FLUX.1, FLUX.2 Klein, Z-Image and Krea-2:+with the offload, warm runs were 1-2 s faster (Krea-2 14.1 -> 12.1 s) and the GPU peak was 14-19 GB instead of+19-23 GB. When two architectures that fit in VRAM together alternate, each switch costs a reload from RAM instead+(SDXL 5.8 -> 7.4 s, Z-Image 7.8 -> 10.9 s), which the `offload_on_architecture_switch` setting turns off.++A session's architecture is the set of bases of the main models its graph names. When it differs from the previous+session's on the same worker, every cached model the new graph does not name moves from VRAM to RAM. Models the new+session names stay, so an encoder or VAE that two architectures share (Qwen3 4B for Z-Image and FLUX.2 Klein, the+FLUX.1 autoencoder for Z-Image) is not reloaded.+"""++from typing import Any, Iterator, Optional++from pydantic import BaseModel++from invokeai.app.invocations.model import ModelIdentifierField+from invokeai.app.services.shared.graph_validation import Graph+from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType+from invokeai.backend.util.logging import InvokeAILogger++GB = 2**30+++def models_named_by(graph: Graph) -> list[ModelIdentifierField]:+ """Every model a graph's node inputs name, at any depth (a LoRA field, a loader's model field, ...)."""+ return [model for node in graph.nodes.values() for model in _models_in(node)]+++def _models_in(value: Any) -> Iterator[ModelIdentifierField]:+ if isinstance(value, ModelIdentifierField):+ yield value+ elif isinstance(value, BaseModel):+ for name in type(value).model_fields:+ yield from _models_in(getattr(value, name, None))+ elif isinstance(value, (list, tuple, set)):+ for item in value:+ yield from _models_in(item)+ elif isinstance(value, dict):+ for item in value.values():+ yield from _models_in(item)+++class ArchitectureSwitchOffload:+ """One worker's view of which architecture it last ran, and the offload when that changes."""++ def __init__(self) -> None:+ self._last_bases: Optional[frozenset[BaseModelType]] = None++ def before_session(self, graph: Graph, cache: ModelCache) -> int:+ """Offload what `graph` does not name if its architecture differs from the last session's. Returns bytes freed.++ A session that names no main model (an upscale, a utility workflow) decides nothing and leaves the last+ architecture as it was. The first session after startup has nothing to compare with.+ """+ models = models_named_by(graph)+ bases = frozenset(model.base for model in models if model.type is ModelType.Main)+ if not bases:+ return 0+ previous, self._last_bases = self._last_bases, bases+ if previous is None or bases == previous:+ return 0+ freed = cache.offload_models_from_vram_except({model.key for model in models})+ if freed > 0:+ InvokeAILogger.get_logger(__name__).info(+ f"Switched from {_names(previous)} to {_names(bases)} models on {cache.execution_device}: moved "+ f"{freed / GB:.1f} GB of models this session does not use from VRAM to RAM."+ )+ return freed+++def _names(bases: frozenset[BaseModelType]) -> str:+ return "/".join(sorted(base.value for base in bases))diff --git a/invokeai/app/services/session_processor/session_processor_default.py b/invokeai/app/services/session_processor/session_processor_default.pyindex 05a045882b..3dfe6cffd0 100644--- a/invokeai/app/services/session_processor/session_processor_default.py+++ b/invokeai/app/services/session_processor/session_processor_default.py@@ -21,6 +21,7 @@ from invokeai.app.services.events.events_common import ()from invokeai.app.services.invocation_stats.invocation_stats_common import GESStatsNotFoundErrorfrom invokeai.app.services.invoker import Invoker+from invokeai.app.services.session_processor.architecture_switch import ArchitectureSwitchOffloadfrom invokeai.app.services.session_processor.session_processor_base import (InvocationServices,OnAfterRunNode,@@ -162,6 +163,8 @@ class DefaultSessionRunner(SessionRunnerBase):self._on_after_run_session_callbacks = on_after_run_session_callbacks or []self.workflow_call_coordinator = WorkflowCallCoordinator(self)self.workflow_call_queue_lifecycle = WorkflowCallQueueLifecycle(self)+ # Per runner, hence per worker and device: each worker remembers the architecture it last ran.+ self._architecture_switch = ArchitectureSwitchOffload()def start(self, services: InvocationServices, cancel_event: ThreadEvent, profiler: Optional[Profiler] = None):self._services = services@@ -480,9 +483,25 @@ class DefaultSessionRunner(SessionRunnerBase):if self._profiler is not None:self._profiler.start(profile_id=queue_item.session_id)+ self._offload_other_architectures(queue_item)+for callback in self._on_before_run_session_callbacks:callback(queue_item=queue_item)+ def _offload_other_architectures(self, queue_item: SessionQueueItem) -> None:+ """Clear this worker's VRAM of models the session does not name when it switches architecture.++ Best effort: a failure costs at most the VRAM the offload would have freed, never the session.+ """+ model_manager = getattr(self._services, "model_manager", None)+ load = model_manager.load if model_manager is not None else None+ if load is None or not self._services.configuration.offload_on_architecture_switch:+ return+ try:+ self._architecture_switch.before_session(queue_item.session.graph, load.ram_cache)+ except Exception:+ self._services.logger.warning("Could not clear VRAM for an architecture switch", exc_info=True)+def _on_after_run_session(self, queue_item: SessionQueueItem) -> None:"""Called after a session is run.@@ -943,11 +962,20 @@ class DefaultSessionProcessor(SessionProcessorBase):released its own working memory along the way, so it only flushes a release a peerdeferred onto it — a flag test when nothing is pending.+ With `clear_vram_after_session`, every unlocked model on this worker's device also moves to+ RAM first (it stays cached there), and the release is forced past a busy peer: deferred, it+ would leave the freed memory with the allocator while this worker's next session budgets its+ first load, which then loads at minimum residency. Once per session, and the user opted in.+Both are best effort: the session's outcome is already recorded, and a free on a sickdevice context must not fail the worker."""try:- if worker.cancel_event.is_set():+ services = self._invoker.services+ if services.configuration.clear_vram_after_session and services.model_manager.load is not None:+ services.model_manager.load.ram_cache.offload_models_from_vram_except(())+ TorchDevice.empty_cache(force=True)+ elif worker.cancel_event.is_set():TorchDevice.empty_cache()else:TorchDevice.flush_deferred_empty_cache()diff --git a/invokeai/backend/model_manager/load/model_cache/model_cache.py b/invokeai/backend/model_manager/load/model_cache/model_cache.pyindex c64bc9fe69..5b13fb5980 100644--- a/invokeai/backend/model_manager/load/model_cache/model_cache.py+++ b/invokeai/backend/model_manager/load/model_cache/model_cache.py@@ -2,6 +2,7 @@ import gcimport loggingimport osimport queue+import sysimport threadingimport timeimport weakref@@ -9,7 +10,7 @@ from contextlib import contextmanagerfrom dataclasses import dataclassfrom functools import wrapsfrom logging import Logger-from typing import Any, Callable, Dict, Generator, List, NamedTuple, Optional, Protocol+from typing import Any, Callable, Collection, Dict, Generator, List, NamedTuple, Optional, Protocolimport psutilimport torch@@ -501,6 +502,11 @@ class CacheModelsClearedCallback(Protocol):) -> None: ...+# Below this, torch's releasable cache cannot matter to the driver's share of a working-memory reserve (kernel modules+# and library workspaces run to hundreds of MB), and releasing it would cost a device synchronization per lock.+_MIN_RELEASABLE_FOR_RESERVE = 256 * MB++def _has_dedicated_vram(device: torch.device) -> bool:"""Whether a device has its own VRAM rather than sharing system memory with the CPU.@@ -2135,8 +2141,7 @@ class ModelCache:# The reservation _get_vram_available actually applied: callers passing None (the# majority) get the configured default, and smaller values are clamped up to it —# printing the raw argument would report 0MB for the very number being diagnosed.- working_mem_bytes_default = int(self._execution_device_working_mem_gb * GB)- effective_working_mem = max(working_mem_bytes or working_mem_bytes_default, working_mem_bytes_default)+ effective_working_mem = self._working_mem_reserve(working_mem_bytes)self._logger.warning(f"VRAM budget for '{cache_entry.key}' is short by {-vram_available / MB:.0f}MB even after "f"offloading (working memory reservation: {effective_working_mem / MB:.0f}MB); the model will "@@ -2189,8 +2194,55 @@ class ModelCache:self._logger.debug(f"After loading: {self._get_vram_state_str(model_cur_vram_bytes, model_total_bytes, vram_available)}")+ self._release_allocator_blocks_for_reserve(working_mem_bytes)return True+ def _working_mem_reserve(self, working_mem_bytes: Optional[int]) -> int:+ """The working memory a lock keeps free: the request, but never less than `device_working_mem_gb`."""+ default = int(self._execution_device_working_mem_gb * GB)+ return max(working_mem_bytes or default, default)++ def _release_allocator_blocks_for_reserve(self, working_mem_bytes: Optional[int]) -> None:+ """Return torch's unused blocks to the driver when the working-memory reserve is not free there.++ `_get_vram_available` counts the blocks torch's caching allocator holds but does not use as available, and+ to torch's own allocations they are. The driver cannot hand them out, though, and part of a node's working+ memory is the driver's: cuDNN loads a convolution engine's kernel module into VRAM the first time it runs+ it. On Windows such an allocation is not refused when it does not fit; the driver keeps retrying while the+ GPU shows 100% load. Measured on an RTX 4090 with torch 2.13: a 1024px FLUX.1 VAE decode (2.4 GiB peak)+ with 2.0 GiB driver-free and 3.0 GiB cached by torch had not finished after 100 s; after `empty_cache()`+ (5.0 GiB driver-free) it took 0.36 s. In a server the same state left decodes running for 25+ minutes.++ Only blocks `empty_cache()` can actually return count, and only a holding that could matter: a partial load+ fills the budget to within a megabyte, so the reserve is short by construction after one, and releasing+ slivers would cost a device synchronization on every lock.++ On Windows the release is forced past a busy peer's deferral, which would otherwise leave the reserve short+ exactly on multi-GPU machines; the peer then stalls for the rest of its step, which beats a hang. Elsewhere an+ allocation that does not fit fails instead of hanging, so the deferral (and the convoy it avoids, see+ `TorchDevice.empty_cache`) stays.+ """+ if self._execution_device.type != "cuda":+ return+ reserve = self._working_mem_reserve(working_mem_bytes)+ driver_free, _ = TorchDevice.cuda_mem_get_info(self._execution_device)+ if driver_free >= reserve:+ return+ if _expandable_segments_enabled():+ # Freed pages inside a segment are not counted as reclaimable there, but empty_cache() unmaps them.+ releasable = torch.cuda.memory_reserved(self._execution_device) - torch.cuda.memory_allocated(+ self._execution_device+ )+ else:+ releasable = self._get_reclaimable_allocator_bytes()+ if releasable < _MIN_RELEASABLE_FOR_RESERVE:+ return+ TorchDevice.empty_cache(force=sys.platform == "win32")+ self._logger.debug(+ f"Returned {releasable / MB:.0f}MB of the allocator's unused blocks to the driver: {driver_free / MB:.0f}MB "+ f"driver-free was short of the {reserve / MB:.0f}MB working-memory reserve."+ )+def _move_model_to_vram(self, cache_entry: CacheRecord, vram_available: int, max_move_bytes: Optional[int] = None) -> tuple[int, bool]:@@ -2290,8 +2342,7 @@ class ModelCache:`honor_cap=False` measures the device instead of `max_vram_cache_size_gb`: see`_get_physical_vram_available`."""- working_mem_bytes_default = int(self._execution_device_working_mem_gb * GB)- working_mem_bytes = max(working_mem_bytes or working_mem_bytes_default, working_mem_bytes_default)+ working_mem_bytes = self._working_mem_reserve(working_mem_bytes)# An explicit cache cap limits model residency, but operation-specific working# memory still must remain free for activations and temporary tensors.@@ -3076,9 +3127,28 @@ class ModelCache:Returns the number of VRAM bytes freed."""prefix = f"{model_key}:"+ return self._offload_entries_from_vram(lambda key: key == model_key or key.startswith(prefix))++ @synchronized+ def offload_models_from_vram_except(self, keep_model_keys: Collection[str]) -> int:+ """Move every model whose key is not in `keep_model_keys` from VRAM to RAM, keeping it cached.++ `keep_model_keys` are plain model keys; a kept model keeps its submodels too. As with+ `offload_model_from_vram`, the entries stay resident in RAM, so a later use re-streams weights instead of+ rebuilding from disk, and locked (in-use) entries are skipped.++ Returns the number of VRAM bytes freed.+ """+ if not _has_dedicated_vram(self._execution_device):+ # CPU, MPS, integrated GPUs: their "VRAM" is system RAM, so moving models out frees nothing.+ return 0+ keep = set(keep_model_keys)+ return self._offload_entries_from_vram(lambda key: key.split(":", 1)[0] not in keep)++ def _offload_entries_from_vram(self, select: Callable[[str], bool]) -> int:bytes_freed = 0for key, entry in list(self._cached_models.items()):- if (key == model_key or key.startswith(prefix)) and not entry.is_locked:+ if select(key) and not entry.is_locked and entry.cached_model.cur_vram_bytes() > 0:bytes_freed += self._move_model_to_ram(entry, entry.cached_model.total_bytes())if bytes_freed > 0:gc.collect()diff --git a/invokeai/backend/util/devices.py b/invokeai/backend/util/devices.pyindex 84c6208594..644a390d4b 100644--- a/invokeai/backend/util/devices.py+++ b/invokeai/backend/util/devices.py@@ -345,9 +345,15 @@ class TorchDevice:return device@classmethod- def empty_cache(cls) -> bool:+ def empty_cache(cls, force: bool = False) -> bool:"""Clear the GPU device cache — unless another generation device is mid-session. Says whether it ran.+ `force` runs it regardless, for callers whose alternative is worse than stalling a busy peer for the rest of+ its current step: a model about to run without the driver-free working memory it needs, which on Windows+ hangs instead of failing (see `ModelCache._release_allocator_blocks_for_reserve`), and the opt-in+ `clear_vram_after_session` release, whose next session would otherwise budget its first load against memory+ the allocator still holds.+``torch.cuda.empty_cache()`` is process-global: it takes EVERY device'scaching-allocator mutex and cudaFree/hipFrees their cached blocks, and a free on adevice with a long kernel in flight blocks until that kernel completes with the mutex@@ -373,7 +379,7 @@ class TorchDevice:quiet moment. Without that, VRAM freed on one GPU stayed resident until the peer'swhole render finished and something else happened to call empty_cache."""- if cls._another_generation_device_busy():+ if not force and cls._another_generation_device_busy():cls._empty_cache_deferred.set()InvokeAILogger.get_logger(cls.__name__).debug("Deferring empty_cache: another generation device is mid-session."@@ -385,7 +391,9 @@ class TorchDevice:if torch.backends.mps.is_available():torch.mps.empty_cache()if torch.cuda.is_available():- torch.cuda.empty_cache()+ # A forced call must get past `install_peer_aware_empty_cache`'s wrapper, which would defer it again.+ cuda_empty_cache = torch.cuda.empty_cache+ (getattr(cuda_empty_cache, "__wrapped__", cuda_empty_cache) if force else cuda_empty_cache)()if _xpu_is_available():torch.xpu.empty_cache()return Truediff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex 6a3c8162b4..3d7eb1e1d7 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -58151,6 +58151,18 @@"description": "Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.","default": true},+ "offload_on_architecture_switch": {+ "type": "boolean",+ "title": "Offload On Architecture Switch",+ "description": "When a session uses main models of another architecture than the previous one on the same GPU, move every model it does not use from VRAM to RAM before it runs. Models both sessions use stay. Switching back reloads the moved models from RAM, which costs a few seconds per switch when both architectures would have fit in VRAM together; turn this off if you alternate between such models.",+ "default": true+ },+ "clear_vram_after_session": {+ "type": "boolean",+ "title": "Clear Vram After Session",+ "description": "After every queue item (each image of a batch), move the models held in VRAM to RAM and return the freed memory to the GPU driver. The models stay cached in RAM; the next item reloads them from there, which costs a few seconds (more with keep_ram_copy_of_weights off). Changes nothing where VRAM is system memory (CPU, MPS, integrated GPUs). Turn this on if a generation that runs fine the first time runs out of memory, or slows down sharply because the GPU spills into shared memory, when it is repeated.",+ "default": false+ },"fp8_compute": {"type": "boolean","title": "Fp8 Compute",@@ -58588,7 +58600,7 @@"additionalProperties": false,"type": "object","title": "InvokeAIAppConfig",- "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n db_synchronous: SQLite durability setting. `full`, the default and what InvokeAI has always used, flushes every commit to disk. `normal` acknowledges commits without waiting for that flush - measured at roughly 12x shorter commits on an SSD - and cannot corrupt the database under WAL, which is why it is refused, with a warning, when WAL is unavailable for the database file. What `normal` gives up is the most recent transactions on a power loss or OS crash: a just-written image record or queue status, not the image file itself.<br>Valid values: `full`, `normal`\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU, or a ROCm GPU that passes an fp8 matmul probe; falls back automatically otherwise). Speeds up denoising and keeps the transformer at fp8 size - FP8 Storage alone also keeps it at that size, without the speedup - but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).\n fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally. Unset on a ROCm build of PyTorch on Windows, \"expandable_segments:True\" is used.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `xpu`, `cuda:N`, `xpu:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n noise_dtype: The dtype seeded noise is drawn in for SD1.5/SDXL, SD3, FLUX.1, FLUX.2, CogView4 and the Z-Image seed variance enhancer. `float32` draws the same noise on every platform. `float16` is the half-precision draw of earlier versions: on macOS it keeps the images your seeds gave before this update; on Windows and Linux both values give (nearly) the same images, and images made before the update cannot be reproduced there.<br>Valid values: `float32`, `float16`\n wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.\n pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.\n attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`\n attention_slice_size: Slice size, valid when attention_type==\"sliced\".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, Z-Image and Qwen-Image VAE nodes, the Anima encode and the Krea-2 style reference; other model families ignore it.\n auto_tiled_decode: Decode large images in tiles when an untiled decode's estimated working memory would take most of the GPU's memory (FLUX.1, Z-Image, Qwen-Image, Krea-2 and Wan decodes). Turn off to decode untiled unless tiling is requested; the FLUX.1 and Z-Image decodes then still retry tiled after running out of memory. Anima keeps tiling a decode too large for its GPU either way, because tiling is what makes that case fast there.\n pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n allow_private_download_urls: Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.\n download_proxy: Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n image_index_enabled: Maintain a semantic embedding index of gallery images and videos, used by the image map and semantic search features.\n image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images and video thumbnails. Changing the model discards embeddings computed by the previous model.\n image_index_device: Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.\n image_index_batch_size: Number of gallery items embedded per batch by the image index worker.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set.\n http_compression_level: Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses."+ "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n db_synchronous: SQLite durability setting. `full`, the default and what InvokeAI has always used, flushes every commit to disk. `normal` acknowledges commits without waiting for that flush - measured at roughly 12x shorter commits on an SSD - and cannot corrupt the database under WAL, which is why it is refused, with a warning, when WAL is unavailable for the database file. What `normal` gives up is the most recent transactions on a power loss or OS crash: a just-written image record or queue status, not the image file itself.<br>Valid values: `full`, `normal`\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n offload_on_architecture_switch: When a session uses main models of another architecture than the previous one on the same GPU, move every model it does not use from VRAM to RAM before it runs. Models both sessions use stay. Switching back reloads the moved models from RAM, which costs a few seconds per switch when both architectures would have fit in VRAM together; turn this off if you alternate between such models.\n clear_vram_after_session: After every queue item (each image of a batch), move the models held in VRAM to RAM and return the freed memory to the GPU driver. The models stay cached in RAM; the next item reloads them from there, which costs a few seconds (more with keep_ram_copy_of_weights off). Changes nothing where VRAM is system memory (CPU, MPS, integrated GPUs). Turn this on if a generation that runs fine the first time runs out of memory, or slows down sharply because the GPU spills into shared memory, when it is repeated.\n fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU, or a ROCm GPU that passes an fp8 matmul probe; falls back automatically otherwise). Speeds up denoising and keeps the transformer at fp8 size - FP8 Storage alone also keeps it at that size, without the speedup - but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).\n fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally. Unset on a ROCm build of PyTorch on Windows, \"expandable_segments:True\" is used.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `xpu`, `cuda:N`, `xpu:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n noise_dtype: The dtype seeded noise is drawn in for SD1.5/SDXL, SD3, FLUX.1, FLUX.2, CogView4 and the Z-Image seed variance enhancer. `float32` draws the same noise on every platform. `float16` is the half-precision draw of earlier versions: on macOS it keeps the images your seeds gave before this update; on Windows and Linux both values give (nearly) the same images, and images made before the update cannot be reproduced there.<br>Valid values: `float32`, `float16`\n wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.\n pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.\n attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`\n attention_slice_size: Slice size, valid when attention_type==\"sliced\".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty). A tiled decode is not pixel-identical to a single-pass one: a VAE decoder normalises and attends over the whole image, so the difference is spread across it rather than confined to the tile seams. Also tiles the encode. Read by the SD1.5/SDXL, FLUX.1, Z-Image and Qwen-Image VAE nodes, the Anima encode and the Krea-2 style reference; other model families ignore it.\n auto_tiled_decode: Decode large images in tiles when an untiled decode's estimated working memory would take most of the GPU's memory (FLUX.1, Z-Image, Qwen-Image, Krea-2 and Wan decodes). Turn off to decode untiled unless tiling is requested; the FLUX.1 and Z-Image decodes then still retry tiled after running out of memory. Anima keeps tiling a decode too large for its GPU either way, because tiling is what makes that case fast there.\n pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n allow_private_download_urls: Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.\n download_proxy: Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n image_index_enabled: Maintain a semantic embedding index of gallery images and videos, used by the image map and semantic search features.\n image_index_model: Name of the installed CLIP Vision or SigLIP model used to embed gallery images and video thumbnails. Changing the model discards embeddings computed by the previous model.\n image_index_device: Set to `cpu` to compute image embeddings on the CPU with a service-local copy of the model - avoids VRAM use and lets indexing run during generations. Any other value is ignored: embeddings otherwise run on the model cache's device, pausing while generations are in progress.\n image_index_batch_size: Number of gallery items embedded per batch by the image index worker.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set.\n http_compression_level: Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses."},"InvokeAIAppConfigWithSetFields": {"properties": {diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex fddf71a271..91ea055de2 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -22224,6 +22224,8 @@ export type components = {* device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.* enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.* keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.+ * offload_on_architecture_switch: When a session uses main models of another architecture than the previous one on the same GPU, move every model it does not use from VRAM to RAM before it runs. Models both sessions use stay. Switching back reloads the moved models from RAM, which costs a few seconds per switch when both architectures would have fit in VRAM together; turn this off if you alternate between such models.+ * clear_vram_after_session: After every queue item (each image of a batch), move the models held in VRAM to RAM and return the freed memory to the GPU driver. The models stay cached in RAM; the next item reloads them from there, which costs a few seconds (more with keep_ram_copy_of_weights off). Changes nothing where VRAM is system memory (CPU, MPS, integrated GPUs). Turn this on if a generation that runs fine the first time runs out of memory, or slows down sharply because the GPU spills into shared memory, when it is repeated.* fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU, or a ROCm GPU that passes an fp8 matmul probe; falls back automatically otherwise). Speeds up denoising and keeps the transformer at fp8 size - FP8 Storage alone also keeps it at that size, without the speedup - but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).* fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.* ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.@@ -22572,6 +22574,18 @@ export type components = {* @default true*/keep_ram_copy_of_weights?: boolean;+ /**+ * Offload On Architecture Switch+ * @description When a session uses main models of another architecture than the previous one on the same GPU, move every model it does not use from VRAM to RAM before it runs. Models both sessions use stay. Switching back reloads the moved models from RAM, which costs a few seconds per switch when both architectures would have fit in VRAM together; turn this off if you alternate between such models.+ * @default true+ */+ offload_on_architecture_switch?: boolean;+ /**+ * Clear Vram After Session+ * @description After every queue item (each image of a batch), move the models held in VRAM to RAM and return the freed memory to the GPU driver. The models stay cached in RAM; the next item reloads them from there, which costs a few seconds (more with keep_ram_copy_of_weights off). Changes nothing where VRAM is system memory (CPU, MPS, integrated GPUs). Turn this on if a generation that runs fine the first time runs out of memory, or slows down sharply because the GPU spills into shared memory, when it is repeated.+ * @default false+ */+ clear_vram_after_session?: boolean;/*** Fp8 Compute* @description Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU, or a ROCm GPU that passes an fp8 matmul probe; falls back automatically otherwise). Speeds up denoising and keeps the transformer at fp8 size - FP8 Storage alone also keeps it at that size, without the speedup - but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).diff --git a/tests/app/services/session_processor/test_architecture_switch.py b/tests/app/services/session_processor/test_architecture_switch.pynew file mode 100644index 0000000000..8d6707d785--- /dev/null+++ b/tests/app/services/session_processor/test_architecture_switch.py@@ -0,0 +1,179 @@+"""Clearing a worker's VRAM when its sessions switch architecture, and only then."""++from types import SimpleNamespace++import pytest++from invokeai.app.invocations.model import (+ LoRACollectionLoader,+ LoRAField,+ LoRALoaderInvocation,+ MainModelLoaderInvocation,+ ModelIdentifierField,+ VAELoaderInvocation,+)+from invokeai.app.invocations.primitives import IntegerInvocation+from invokeai.app.services.session_processor.architecture_switch import ArchitectureSwitchOffload, models_named_by+from invokeai.app.services.session_processor.session_processor_default import (+ DefaultSessionProcessor,+ DefaultSessionRunner,+)+from invokeai.app.services.shared.graph_validation import Graph+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType+++def _model(key: str, base: BaseModelType, type: ModelType) -> ModelIdentifierField:+ return ModelIdentifierField(key=key, hash=f"blake3:{key}", name=key, base=base, type=type)+++SD1 = _model("sd1-main", BaseModelType.StableDiffusion1, ModelType.Main)+SD1_LORA = _model("sd1-lora", BaseModelType.StableDiffusion1, ModelType.LoRA)+SD2 = _model("sd2-main", BaseModelType.StableDiffusion2, ModelType.Main)+SHARED_VAE = _model("shared-vae", BaseModelType.StableDiffusion1, ModelType.VAE)+++def _graph(main: ModelIdentifierField | None, *extra: ModelIdentifierField) -> Graph:+ nodes: dict = {"seed": IntegerInvocation(id="seed", value=1)}+ if main is not None:+ nodes["main"] = MainModelLoaderInvocation(id="main", model=main)+ for model in extra:+ if model.type is ModelType.LoRA:+ nodes[model.key] = LoRALoaderInvocation(id=model.key, lora=model)+ else:+ nodes[model.key] = VAELoaderInvocation(id=model.key, vae_model=model)+ return Graph(nodes=nodes)+++class _Cache:+ execution_device = "cuda:0"++ def __init__(self) -> None:+ self.kept: list[set[str]] = []++ def offload_models_from_vram_except(self, keep_model_keys) -> int:+ self.kept.append(set(keep_model_keys))+ return 3 * 2**30+++def test_every_model_a_graph_names_is_found_including_loras() -> None:+ graph = _graph(SD1, SD1_LORA, SHARED_VAE)+ assert {model.key for model in models_named_by(graph)} == {"sd1-main", "sd1-lora", "shared-vae"}+++def test_models_nested_in_node_inputs_are_found() -> None:+ """A LoRA collection names its models inside a list of `LoRAField`s."""+ graph = Graph(nodes={"loras": LoRACollectionLoader(id="loras", loras=[LoRAField(lora=SD1_LORA, weight=0.5)])})+ assert [model.key for model in models_named_by(graph)] == ["sd1-lora"]+++def test_a_switch_keeps_what_the_new_session_names_and_moves_the_rest() -> None:+ offload, cache = ArchitectureSwitchOffload(), _Cache()+ offload.before_session(_graph(SD1, SHARED_VAE), cache) # type: ignore[arg-type]++ freed = offload.before_session(_graph(SD2, SHARED_VAE), cache) # type: ignore[arg-type]++ assert cache.kept == [{"sd2-main", "shared-vae"}]+ assert freed == 3 * 2**30+++def test_the_same_architecture_moves_nothing() -> None:+ offload, cache = ArchitectureSwitchOffload(), _Cache()+ offload.before_session(_graph(SD1), cache) # type: ignore[arg-type]+ offload.before_session(_graph(SD1, SD1_LORA), cache) # type: ignore[arg-type]+ assert cache.kept == []+++def test_the_first_session_has_nothing_to_compare_with() -> None:+ offload, cache = ArchitectureSwitchOffload(), _Cache()+ offload.before_session(_graph(SD2), cache) # type: ignore[arg-type]+ assert cache.kept == []+++ ("third", "expected"),+ [(_graph(SD1), []), (_graph(SD2), [{"sd2-main"}])],+ ids=["same-architecture-after", "switch-after"],+)+def test_a_session_without_a_main_model_leaves_the_architecture_as_it_was(third: Graph, expected: list) -> None:+ """An upscale between two sessions neither makes the second one look like a switch nor hides one."""+ offload, cache = ArchitectureSwitchOffload(), _Cache()+ for graph in (_graph(SD1), _graph(None), third):+ offload.before_session(graph, cache) # type: ignore[arg-type]+ assert cache.kept == expected+++# --- the session runner --------------------------------------------------------------------------------------+++class _Logger:+ def __init__(self) -> None:+ self.warnings: list[str] = []++ def warning(self, message: str, **kwargs) -> None:+ self.warnings.append(message)++ def debug(self, message: str, **kwargs) -> None:+ pass+++def _runner(load, enabled: bool = True) -> tuple[DefaultSessionRunner, _Logger]:+ runner = DefaultSessionRunner()+ logger = _Logger()+ runner._services = SimpleNamespace( # type: ignore[assignment]+ model_manager=SimpleNamespace(load=load),+ logger=logger,+ configuration=SimpleNamespace(offload_on_architecture_switch=enabled),+ )+ runner._profiler = None+ return runner, logger+++def _queue_item(graph: Graph) -> SimpleNamespace:+ return SimpleNamespace(item_id=1, session_id="s", session=SimpleNamespace(graph=graph))+++def test_the_runner_offloads_through_its_devices_cache_before_a_switched_session() -> None:+ cache = _Cache()+ runner, logger = _runner(SimpleNamespace(ram_cache=cache))++ runner._on_before_run_session(_queue_item(_graph(SD1))) # type: ignore[arg-type]+ runner._on_before_run_session(_queue_item(_graph(SD2))) # type: ignore[arg-type]++ assert cache.kept == [{"sd2-main"}]+ assert logger.warnings == []+++def test_a_failed_offload_is_logged_and_the_session_runs() -> None:+ class _Broken:+ def offload_models_from_vram_except(self, keep_model_keys) -> int:+ raise RuntimeError("CUDA error: an illegal memory access was encountered")++ runner, logger = _runner(SimpleNamespace(ram_cache=_Broken()))+ runner._on_before_run_session(_queue_item(_graph(SD1))) # type: ignore[arg-type]+ runner._on_before_run_session(_queue_item(_graph(SD2))) # type: ignore[arg-type]++ assert len(logger.warnings) == 1+++def test_the_setting_turns_it_off() -> None:+ cache = _Cache()+ runner, _ = _runner(SimpleNamespace(ram_cache=cache), enabled=False)++ runner._on_before_run_session(_queue_item(_graph(SD1))) # type: ignore[arg-type]+ runner._on_before_run_session(_queue_item(_graph(SD2))) # type: ignore[arg-type]++ assert cache.kept == []+++def test_each_worker_judges_only_its_own_sessions() -> None:+ """Two GPUs running different architectures side by side: neither worker is switching."""+ first, _ = _runner(SimpleNamespace(ram_cache=_Cache()))+ second = DefaultSessionProcessor()._clone_session_runner(first)+ second._services = first._services # type: ignore[attr-defined]+ second._profiler = None # type: ignore[attr-defined]+ caches = {first: _Cache(), second: _Cache()}+ for _ in range(3):+ for runner, main in ((first, SD1), (second, SD2)):+ runner._services.model_manager.load.ram_cache = caches[runner] # type: ignore[attr-defined]+ runner._on_before_run_session(_queue_item(_graph(main))) # type: ignore[arg-type]+ assert caches[first].kept == [] and caches[second].kept == []diff --git a/tests/app/services/session_processor/test_for_loop_processor.py b/tests/app/services/session_processor/test_for_loop_processor.pyindex 9db343c1ae..f64a0f0579 100644--- a/tests/app/services/session_processor/test_for_loop_processor.py+++ b/tests/app/services/session_processor/test_for_loop_processor.py@@ -257,6 +257,7 @@ def _build_processor(multiuser=False,node_cache_size=0,offload_text_encoders_to_idle_gpus=False,+ clear_vram_after_session=False,)services = SimpleNamespace(configuration=config,diff --git a/tests/app/services/session_processor/test_lent_device_scheduling.py b/tests/app/services/session_processor/test_lent_device_scheduling.pyindex 3762007965..d9eb2cf206 100644--- a/tests/app/services/session_processor/test_lent_device_scheduling.py+++ b/tests/app/services/session_processor/test_lent_device_scheduling.py@@ -62,7 +62,7 @@ def _start_worker(device: torch.device) -> tuple[threading.Thread, Event, list[ssession_queue=_Queue(),logger=MagicMock(),image_moves=None,- configuration=SimpleNamespace(multiuser=False),+ configuration=SimpleNamespace(multiuser=False, clear_vram_after_session=False),))processor._polling_interval = 5 # long enough that only the release listener can wake it in timediff --git a/tests/app/services/session_processor/test_privilege_revocation.py b/tests/app/services/session_processor/test_privilege_revocation.pyindex 72c0a6ca93..12afd472bd 100644--- a/tests/app/services/session_processor/test_privilege_revocation.py+++ b/tests/app/services/session_processor/test_privilege_revocation.py@@ -30,7 +30,7 @@ from invokeai.app.services.session_queue.session_queue_common import SessionQueudef _services(multiuser: bool = True, users_by_id: dict | None = None) -> SimpleNamespace:users_by_id = users_by_id or {}return SimpleNamespace(- configuration=SimpleNamespace(multiuser=multiuser),+ configuration=SimpleNamespace(multiuser=multiuser, clear_vram_after_session=False),users=SimpleNamespace(get=lambda user_id: users_by_id.get(user_id)),session_queue=MagicMock(),logger=MagicMock(),diff --git a/tests/app/services/session_processor/test_release_vram_after_session.py b/tests/app/services/session_processor/test_release_vram_after_session.pyindex 796a0f24d8..a95792acd6 100644--- a/tests/app/services/session_processor/test_release_vram_after_session.py+++ b/tests/app/services/session_processor/test_release_vram_after_session.py@@ -5,6 +5,10 @@ one only flushes a release a peer deferred onto it; neither may fail the worker.import threadingfrom types import SimpleNamespace+import torch++from invokeai.app.services.config.config_default import InvokeAIAppConfig+from invokeai.app.services.model_load.model_load_default import ModelLoadServicefrom invokeai.app.services.session_processor.session_processor_default import DefaultSessionProcessorfrom invokeai.backend.util.devices import TorchDevice@@ -17,10 +21,26 @@ class _Logger:self.warnings.append(message)-def _processor() -> tuple[DefaultSessionProcessor, _Logger]:+class _Cache:+ def __init__(self) -> None:+ self.offloaded: list[tuple[str, ...]] = []++ def offload_models_from_vram_except(self, keep_model_keys) -> int:+ self.offloaded.append(tuple(keep_model_keys))+ return 0+++def _processor(+ clear_vram_after_session: bool = False, cache: "_Cache | None" = None+) -> tuple[DefaultSessionProcessor, _Logger]:logger = _Logger()processor = DefaultSessionProcessor()- processor._invoker = SimpleNamespace(services=SimpleNamespace(logger=logger)) # type: ignore[attr-defined]+ services = SimpleNamespace(+ logger=logger,+ configuration=SimpleNamespace(clear_vram_after_session=clear_vram_after_session),+ model_manager=SimpleNamespace(load=SimpleNamespace(ram_cache=cache or _Cache())),+ )+ processor._invoker = SimpleNamespace(services=services) # type: ignore[attr-defined]return processor, logger@@ -66,3 +86,50 @@ def test_release_failure_is_logged_not_raised(monkeypatch) -> None:assert len(logger.warnings) == 1assert "cuda:0" in logger.warnings[0]+++def test_clear_vram_after_session_moves_every_model_to_ram_and_releases_the_memory(monkeypatch) -> None:+ """The setting for a session that runs fine once and runs out of memory the second time: every unlocked model+ leaves VRAM (staying cached in RAM) and the allocator hands its blocks back, even after a completed session."""+ calls: list[tuple[str, bool]] = []+ monkeypatch.setattr(+ TorchDevice, "empty_cache", classmethod(lambda cls, force=False: calls.append(("empty", force)))+ )+ monkeypatch.setattr(+ TorchDevice, "flush_deferred_empty_cache", classmethod(lambda cls: calls.append(("flush", False)))+ )+ cache = _Cache()+ processor, logger = _processor(clear_vram_after_session=True, cache=cache)++ processor._release_vram_after_session(_worker(canceled=False)) # type: ignore[arg-type]++ assert cache.offloaded == [()]+ # Forced: deferred behind a busy peer, the next session would budget against memory the allocator still holds.+ assert calls == [("empty", True)]+ assert logger.warnings == []+++def test_clear_vram_after_session_leaves_other_gpus_caches_alone(monkeypatch) -> None:+ """Multi-GPU: a worker clears its own device's cache only -- a peer may be mid-session on its own."""+ monkeypatch.setattr(TorchDevice, "empty_cache", classmethod(lambda cls, force=False: True))+ caches = {"cuda:0": _Cache(), "cuda:1": _Cache()}+ for device, cache in caches.items():+ cache.execution_device = torch.device(device) # type: ignore[attr-defined]+ load = ModelLoadService(app_config=InvokeAIAppConfig(), ram_cache=caches["cuda:0"], ram_caches=caches) # type: ignore[arg-type]+ processor, logger = _processor(clear_vram_after_session=True)+ processor._invoker.services.model_manager.load = load # type: ignore[attr-defined]++ def worker() -> None:+ TorchDevice.set_session_device("cuda:1")+ try:+ processor._release_vram_after_session(_worker(canceled=False)) # type: ignore[arg-type]+ finally:+ TorchDevice.clear_session_device()++ thread = threading.Thread(target=worker)+ thread.start()+ thread.join()++ assert caches["cuda:1"].offloaded == [()]+ assert caches["cuda:0"].offloaded == []+ assert logger.warnings == []diff --git a/tests/app/services/session_processor/test_session_processor_cancel_guard.py b/tests/app/services/session_processor/test_session_processor_cancel_guard.pyindex dbed63f0ee..c5dd7fc0e6 100644--- a/tests/app/services/session_processor/test_session_processor_cancel_guard.py+++ b/tests/app/services/session_processor/test_session_processor_cancel_guard.py@@ -111,7 +111,7 @@ def _run_guard_scenario(statuses: list[str], set_cancel_event: bool, set_stop_onimage_moves=None,# Single-user mode: the post-dequeue owner check short-circuits, keeping this# test focused on the cancellation guard.- configuration=SimpleNamespace(multiuser=False),+ configuration=SimpleNamespace(multiuser=False, clear_vram_after_session=False),))processor._polling_interval = 0.001@@ -249,7 +249,7 @@ def test_cuda_device_pin_is_deferred_until_first_claim_and_runs_once():image_moves=None,# Single-user mode: the post-dequeue owner check short-circuits, keeping this# test focused on device pinning.- configuration=SimpleNamespace(multiuser=False),+ configuration=SimpleNamespace(multiuser=False, clear_vram_after_session=False),))processor._polling_interval = 0diff --git a/tests/backend/model_manager/load/model_cache/test_model_cache_offload_from_vram.py b/tests/backend/model_manager/load/model_cache/test_model_cache_offload_from_vram.pynew file mode 100644index 0000000000..084f6a616b--- /dev/null+++ b/tests/backend/model_manager/load/model_cache/test_model_cache_offload_from_vram.py@@ -0,0 +1,120 @@+"""`ModelCache.offload_models_from_vram_except`: what an architecture switch moves out of VRAM, and what it keeps.++The entries stay cached (in RAM); locked entries and every submodel of a kept model stay where they are.+"""++import logging+from unittest.mock import MagicMock, patch++import pytest+import torch++from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache++MB = 2**20+MODULE = "invokeai.backend.model_manager.load.model_cache.model_cache"+++def cache():+ logger = MagicMock()+ logger.getEffectiveLevel.return_value = logging.INFO+ cache = ModelCache(+ execution_device_working_mem_gb=1.0,+ enable_partial_loading=False,+ keep_ram_copy_of_weights=True,+ execution_device="cpu",+ storage_device="cpu",+ logger=logger,+ )+ yield cache+ cache.shutdown()+++def moved(cache: ModelCache):+ """Record which entries the cache moves to RAM. A CPU cache stands in for a GPU one: it reports its entries as+ resident and its device as having dedicated VRAM, but nothing really moves."""+ keys: list[str] = []++ def move(cache_entry, vram_bytes_to_free, keep_required_weights_in_vram=None):+ keys.append(cache_entry.key)+ return cache_entry.cached_model.total_bytes()++ with (+ patch.object(cache, "_move_model_to_ram", side_effect=move),+ patch(f"{MODULE}._has_dedicated_vram", return_value=True),+ patch(f"{MODULE}.TorchDevice.empty_cache") as empty_cache,+ ):+ yield keys, empty_cache+++def _put(cache: ModelCache, key: str, mb: int, in_vram: bool = True) -> None:+ cache.put(key, torch.nn.Linear(mb * MB // 4, 1, bias=False))+ cached_model = cache._cached_models[key].cached_model+ vram = cached_model.total_bytes() if in_vram else 0+ cached_model.cur_vram_bytes = lambda: vram # type: ignore[method-assign]+++def test_models_the_session_does_not_name_move_to_ram_and_stay_cached(cache: ModelCache, moved):+ keys, empty_cache = moved+ _put(cache, "flux:transformer", 8)+ _put(cache, "flux:vae", 1)+ _put(cache, "qwen3:text_encoder", 4) # shared with the next session+ _put(cache, "zimage:transformer", 2)+ _put(cache, r"D:\models\upscaler.safetensors", 1) # loaded by path, names no model key++ freed = cache.offload_models_from_vram_except({"zimage", "qwen3"})++ assert sorted(keys) == sorted(["flux:transformer", "flux:vae", r"D:\models\upscaler.safetensors"])+ assert freed == 10 * MB+ assert len(cache._cached_models) == 5+ empty_cache.assert_called_once()+++def test_locked_entries_stay(cache: ModelCache, moved):+ keys, _ = moved+ _put(cache, "flux:transformer", 8)+ _put(cache, "borrowed:text_encoder", 4)+ cache._cached_models["borrowed:text_encoder"].lock()++ cache.offload_models_from_vram_except(set())++ assert keys == ["flux:transformer"]+++def test_entries_already_in_ram_are_not_moved_again(cache: ModelCache, moved):+ keys, empty_cache = moved+ _put(cache, "flux:transformer", 8, in_vram=False)++ assert cache.offload_models_from_vram_except(set()) == 0+ assert keys == []+ empty_cache.assert_not_called()+++def test_nothing_to_move_spends_no_empty_cache(cache: ModelCache, moved):+ keys, empty_cache = moved+ _put(cache, "zimage:transformer", 2)++ assert cache.offload_models_from_vram_except({"zimage"}) == 0+ assert keys == []+ empty_cache.assert_not_called()+++def test_offload_model_from_vram_still_moves_one_model_with_its_submodels(cache: ModelCache, moved):+ keys, _ = moved+ _put(cache, "flux", 1)+ _put(cache, "flux:vae", 1)+ _put(cache, "fluxier:vae", 1) # shares the prefix text, not the key++ cache.offload_model_from_vram("flux")++ assert sorted(keys) == ["flux", "flux:vae"]+++def test_a_device_whose_vram_is_system_ram_moves_nothing(cache: ModelCache):+ """CPU, MPS and integrated GPUs: moving a model "to RAM" would copy it within the same memory."""+ cache.put("flux:transformer", torch.nn.Linear(MB // 4, 1, bias=False))+ with patch.object(cache, "_move_model_to_ram") as move:+ assert cache.offload_models_from_vram_except(set()) == 0+ move.assert_not_called()diff --git a/tests/backend/model_manager/load/model_cache/test_model_cache_vram_accounting.py b/tests/backend/model_manager/load/model_cache/test_model_cache_vram_accounting.pyindex b7f3023b8c..f79c7ab239 100644--- a/tests/backend/model_manager/load/model_cache/test_model_cache_vram_accounting.py+++ b/tests/backend/model_manager/load/model_cache/test_model_cache_vram_accounting.py@@ -9,11 +9,13 @@ to 0% VRAM residency while the allocator happily reused the "missing" memory for"""import logging+import sysfrom unittest.mock import MagicMockimport pytestimport torch+from invokeai.backend.model_manager.load.model_cache import model_cache as model_cache_modulefrom invokeai.backend.model_manager.load.model_cache.model_cache import ModelCachefrom invokeai.backend.util.devices import TorchDevice@@ -258,3 +260,118 @@ def test_offloading_under_expandable_segments_stops_once_enough_is_free(monkeypa# 2 GB needed + 1 GB working memory: one 4 GB model is enough.assert cache._offload_unlocked_models(2 * GB) == 4 * GBassert cache._move_model_to_ram.call_count == 1+++class TestReserveRelease:+ """When a lock hands torch's cached blocks back to the driver (`_release_allocator_blocks_for_reserve`).++ The reserve a lock budgets must be free for the driver too: cuDNN loads a convolution engine's kernel module into+ driver memory on first use, and on Windows a driver allocation that does not fit is retried indefinitely instead of+ failing. The driver's and torch's figures are faked, so this runs without a GPU.+ """++ @pytest.fixture(autouse=True)+ def _windows(self, monkeypatch):+ monkeypatch.setattr(sys, "platform", "win32")++ @staticmethod+ def _cache(device: str) -> ModelCache:+ """A cache with the 0.1 GB default reserve, built for the CPU: a CUDA cache reads the card's properties."""+ cache = ModelCache(+ execution_device_working_mem_gb=0.1,+ enable_partial_loading=True,+ keep_ram_copy_of_weights=True,+ execution_device="cpu",+ storage_device="cpu",+ logger=MagicMock(),+ shared_cpu_weights=None,+ )+ cache._execution_device = torch.device(device)+ return cache++ def _release(self, monkeypatch, *, driver_free_mb: int, releasable_mb: int, working_mb, device="cuda") -> list:+ cache = self._cache(device)+ calls: list = []+ monkeypatch.setattr(+ TorchDevice, "cuda_mem_get_info", classmethod(lambda cls, d: (driver_free_mb * MB, 24 * GB))+ )+ monkeypatch.setattr(cache, "_get_reclaimable_allocator_bytes", lambda: releasable_mb * MB)+ monkeypatch.setattr(model_cache_module, "_expandable_segments_enabled", lambda: False)+ monkeypatch.setattr(TorchDevice, "empty_cache", classmethod(lambda cls, force=False: calls.append(force)))+ cache._release_allocator_blocks_for_reserve(None if working_mb is None else working_mb * MB)+ return calls++ def test_a_short_reserve_with_releasable_blocks_is_released_past_a_busy_peer(self, monkeypatch):+ assert self._release(monkeypatch, driver_free_mb=2048, releasable_mb=3072, working_mb=4096) == [True]++ def test_a_reserve_that_is_driver_free_costs_nothing(self, monkeypatch):+ assert self._release(monkeypatch, driver_free_mb=4096, releasable_mb=3072, working_mb=4096) == []++ def test_slivers_left_by_a_partial_load_are_not_worth_a_sync(self, monkeypatch):+ assert self._release(monkeypatch, driver_free_mb=2048, releasable_mb=64, working_mb=4096) == []++ @pytest.mark.parametrize(("driver_free_mb", "expected"), [(80, [True]), (120, [])])+ def test_no_request_means_the_default_reserve(self, monkeypatch, driver_free_mb, expected):+ assert (+ self._release(monkeypatch, driver_free_mb=driver_free_mb, releasable_mb=1024, working_mb=None) == expected+ )++ @pytest.mark.parametrize("device", ["xpu", "mps"])+ def test_other_devices_are_left_alone(self, monkeypatch, device):+ assert self._release(monkeypatch, driver_free_mb=0, releasable_mb=4096, working_mb=4096, device=device) == []++ def test_off_windows_the_release_waits_for_a_busy_peer(self, monkeypatch):+ """Where a driver allocation that does not fit fails instead of hanging, a forced release would only bring+ back the cross-GPU empty_cache convoy."""+ monkeypatch.setattr(sys, "platform", "linux")+ assert self._release(monkeypatch, driver_free_mb=2048, releasable_mb=3072, working_mb=4096) == [False]++ def test_under_expandable_segments_the_unused_reserved_pages_count(self, monkeypatch):+ """The allocator's reclaimable figure is 0 there, but empty_cache() unmaps freed pages inside segments+ (the default on ROCm under Windows)."""+ cache = self._cache("cuda")+ calls: list = []+ monkeypatch.setattr(TorchDevice, "cuda_mem_get_info", classmethod(lambda cls, d: (2 * GB, 24 * GB)))+ monkeypatch.setattr(model_cache_module, "_expandable_segments_enabled", lambda: True)+ monkeypatch.setattr(cache, "_get_reclaimable_allocator_bytes", lambda: 0)+ monkeypatch.setattr(torch.cuda, "memory_reserved", lambda device=None: 9 * GB)+ monkeypatch.setattr(torch.cuda, "memory_allocated", lambda device=None: 6 * GB)+ monkeypatch.setattr(TorchDevice, "empty_cache", classmethod(lambda cls, force=False: calls.append(force)))++ cache._release_allocator_blocks_for_reserve(4 * GB)++ assert calls == [True]+++@requires_cuda+def test_lock_hands_cached_blocks_back_when_the_reserve_is_not_driver_free():+ """On a real card: torch holds most of the free memory in cached blocks, then a lock asks for a reserve that only+ those blocks can cover; afterwards torch holds nothing worth releasing. Needs a quiet GPU (it fills the card to+ within 1 GiB), hence `slow`.+ """+ torch.cuda.empty_cache()+ device = torch.device("cuda:0")+ # Slack in segments that other live tensors keep, which no release can return.+ baseline_unused = torch.cuda.memory_reserved(device) - torch.cuda.memory_allocated(device)+ free, _total = torch.cuda.mem_get_info(device)+ if free < 4 * GB:+ pytest.skip("needs at least 4 GiB of free VRAM")+ cache = _make_cache()+ cache.put("A", BigModule(64))+ record = cache.get("A")+ chunk = 256 * MB+ blocks = [torch.empty(chunk, dtype=torch.uint8, device=device) for _ in range(int((free - GB) // chunk))]+ del blocks+ driver_free = torch.cuda.mem_get_info(device)[0]+ held_unused = torch.cuda.memory_reserved(device) - torch.cuda.memory_allocated(device)++ cache.lock(record, driver_free + held_unused // 2)+ try:+ # Process-local, so another program on the card cannot decide the outcome. Read from the allocator itself: the+ # cache's reclaimable figure is 0 under expandable segments whether or not anything was released.+ unused = torch.cuda.memory_reserved(device) - torch.cuda.memory_allocated(device)+ assert unused - baseline_unused < 256 * MB+ finally:+ cache.unlock(record)+ torch.cuda.empty_cache()diff --git a/tests/backend/util/test_devices.py b/tests/backend/util/test_devices.pyindex 1f01eb2df6..a1ca9b078a 100644--- a/tests/backend/util/test_devices.py+++ b/tests/backend/util/test_devices.py@@ -912,3 +912,25 @@ def test_disable_conv_benchmark_empty_cache_flips_torch_flag():assert getter() is Falsefinally:setter(original)+++def test_a_forced_empty_cache_runs_past_a_busy_peer_and_its_wrapper(monkeypatch):+ """The peer-aware wrapper on torch.cuda.empty_cache would defer a forced call again; it must reach torch."""+ calls: list[str] = []++ def original() -> None:+ calls.append("torch")++ def wrapper() -> None:+ calls.append("deferred")++ wrapper.__wrapped__ = original # type: ignore[attr-defined]+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(torch.cuda, "empty_cache", wrapper)+ monkeypatch.setattr(torch.backends.mps, "is_available", lambda: False)+ monkeypatch.setattr(TorchDevice, "_another_generation_device_busy", classmethod(lambda cls: True))++ assert TorchDevice.empty_cache() is False+ assert calls == []+ assert TorchDevice.empty_cache(force=True) is True+ assert calls == ["torch"]