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): add opt-in async weight streaming for partially loaded models (#10265)
Alexander Eichhorncd9567ca216c
diff --git a/docs/src/content/docs/configuration/Optimization/async-weight-streaming.mdx b/docs/src/content/docs/configuration/Optimization/async-weight-streaming.mdxnew file mode 100644index 0000000000..e8bd94e6d4--- /dev/null+++ b/docs/src/content/docs/configuration/Optimization/async-weight-streaming.mdx@@ -0,0 +1,108 @@+---+title: Async Weight Streaming+description: Copy the layers of a partially loaded model from RAM to the GPU while the previous layers compute, with identical images.+lastUpdated: 2026-11-14+sidebar:+ order: 8+---++import BenchmarkChart from '@components/memory/BenchmarkChart.astro';+import BenchmarkRow from '@components/memory/BenchmarkRow.astro';++When a model does not fit in VRAM, [Low-VRAM mode](/configuration/optimization/low-vram-mode/) keeps part of its layers+in RAM and copies each of them to the GPU every time a step needs it. By default each of those copies blocks: the GPU+finishes its queued work, the layer is copied, then the computation continues. The GPU waits for every copy, and the+copy waits for the GPU.++`async_weight_streaming` is a global setting that overlaps the two. The layers in RAM are page-locked, so the GPU can+read them directly, and each copy runs on a separate stream while the GPU is still computing the layers before it.+A step then takes closer to the time of a fully loaded model.++It only changes anything while a model is **partially loaded**. The log line for a model load shows how much of it is in+VRAM, for example `VRAM: 12000.00MB (50.0%)`; at 100% nothing is copied per step, and the setting has no effect.++Images are **bit-identical** to the default path: the same weights reach the same computations, only earlier.++Measured end to end with the VRAM cache capped at 8 GB (`max_cache_vram_gb: 8`), so the transformer loads only partly,+and a RAM cache large enough to keep the text encoder and the transformer between images (`max_cache_ram_gb: 40`, see+[below](#requirements)): 1024², 8 steps, the median of warm runs from interleaved pairs, pixel-identical images. The+gain depends on how much of the model streams, on the GPU's PCIe link and on how fast the system copies from ordinary+RAM; a model fully in VRAM sees no change. The process's peak VRAM with the setting stayed within 50 MB of the peak+without it in these runs.++<BenchmarkChart title="Time per image on an RTX 4090 (PCIe 4.0 x16, Windows), BF16, transformer partly in VRAM" setting="async_weight_streaming">+ <BenchmarkRow label="ERNIE-Image Turbo, about 18% in VRAM" before={20.3} after={8.7} />+ <BenchmarkRow label="Z-Image Turbo, about 24% in VRAM" before={15.1} after={6.7} />+</BenchmarkChart>++<BenchmarkChart title="Time per image on an RTX PRO 6000 Blackwell (Linux), BF16, transformer partly in VRAM" setting="async_weight_streaming">+ <BenchmarkRow label="ERNIE-Image Turbo, about 31% in VRAM" before={6.05} after={3.71} />+ <BenchmarkRow label="Z-Image Turbo, about 40% in VRAM" before={4.56} after={3.09} />+</BenchmarkChart>++<BenchmarkChart title="Time per image on an RX 9060 XT (PCIe 4.0 x4, Windows, ROCm 10), transformer partly in VRAM" setting="async_weight_streaming">+ <BenchmarkRow label="Krea-2 Turbo, scaled FP8, about 38% in VRAM" before={61.9} after={33.7} />+</BenchmarkChart>++## Requirements++- **An NVIDIA GPU, or an AMD GPU with ROCm.** On Apple silicon and the CPU, models load whole, so there is nothing to+ stream. Intel GPUs keep the blocking copy, and the log says so once: `async_weight_streaming is enabled, but not used+ on <device>: it needs an NVIDIA or AMD (ROCm) GPU.`+- **`keep_ram_copy_of_weights: true`**, the default. Without the RAM copy, the layers in RAM are new allocations after+ every unload and are not page-locked, so they keep the blocking copy. The log says so once.+- **`enable_partial_loading: true`**, the default.+- **Room in the RAM cache for the models of one generation.** The first time a model's layers are locked costs time+ (see [Memory](#memory)); they then stay locked while the model is in the RAM cache. When the RAM cache cannot hold,+ say, the text encoder and the transformer at once, Invoke loads them again for every image, and every image pays for+ the first lock again. On Linux with an 8 GB RAM cache, ERNIE-Image Turbo took 9.4 seconds per image with the setting+ instead of 8.5 without it. The startup log shows the size (`Calculated model RAM cache size`); without+ `max_cache_ram_gb`, it is at most your VRAM, or `max_cache_vram_gb` when that is set. Raise+ [`max_cache_ram_gb`](/configuration/optimization/memory-options/) so the models you use together fit. When a model+ with locked layers leaves the RAM cache, the log says so once.++Layers whose weights use a special tensor format, such as GGUF and SDNQ, keep the blocking copy, so the setting does+not speed up those models; it keeps VRAM free only for their few plain layers. Full-precision, FP8 and int8 layers+stream.++## Turning it on++Set it in your [`invokeai.yaml`](/configuration/invokeai-yaml/) and restart InvokeAI:++```yaml+async_weight_streaming: true+```++The first layer that streams logs, once per GPU:++```+async_weight_streaming: weights in RAM stream to cuda:0 asynchronously.+```++## Memory++- **VRAM.** Copies that the GPU has not reached yet take up to about 384MB of VRAM. Invoke keeps that much free for a+ model it loads partially with this setting on (less for a model with fewer layers to stream), so slightly less of+ the model stays in VRAM. A model that fits in VRAM is loaded whole as before. When the model is released, Invoke+ hands that memory back to the driver; on a system with several GPUs this waits while another GPU is mid-generation,+ so the memory stays reserved a little longer there.+ Nodes that hold a second model within a VRAM limit (Wan 2.2's experts, Ideogram 4's second branch) count that+ memory inside the limit: what they move to RAM streams from then on, so the resident weights stay that much under+ it, also when the model was loaded partially to begin with. Nothing is kept free when the limit on locked RAM (see+ below) leaves nothing to stream: such a model then keeps the blocking copy until its next load.+- **RAM.** Page-locking makes no second copy: the existing RAM copy of the layers is locked in place. It does change+ what that memory is. Weights that are still mapped from their file (see Loading below) are page cache, which the+ system can reclaim; once locked, the driver has made a private copy of the pages. That copy stays private after+ the layer is unlocked (it can then be swapped out, but it is no longer reclaimable page cache) until its model+ leaves the RAM cache. A layer stays locked+ while its model is in the RAM cache, also while a later load keeps it in VRAM and between generations, so models+ that take turns in VRAM lock their layers only once. Locked memory cannot be moved to the page file or swap, so at+ most 40% of your physical RAM is locked. When a model needs more than that, Invoke unlocks layers that no running+ model streams right now, the longest unused first, and only as many as it needs; the layers that still do not fit+ keep the blocking copy. A model removed from the RAM cache is unlocked.+- **Loading.** Most models are read from their files lazily. Locking a layer the first time reads it, and the driver+ makes a private copy of the file's pages as it locks them: about 0.3 seconds per GiB on Linux and 0.5 seconds per+ GiB on Windows when the file is already in the system's file cache, up to about 2.5 seconds per GiB when it is read+ from an NVMe SSD. Only the reading is a cost the first step would pay anyway. Other models keep loading meanwhile.+ Locking a layer again after another model reclaimed it is much cheaper: about 0.03 seconds per GiB was measured for+ memory already in RAM.diff --git a/docs/src/content/docs/configuration/Optimization/low-vram-mode.mdx b/docs/src/content/docs/configuration/Optimization/low-vram-mode.mdxindex 8c4925490a..afecee4f96 100644--- a/docs/src/content/docs/configuration/Optimization/low-vram-mode.mdx+++ b/docs/src/content/docs/configuration/Optimization/low-vram-mode.mdx@@ -1,7 +1,7 @@---title: Low-VRAM modedescription: How Invoke runs models larger than your GPU's memory, the invokeai.yaml settings that tune it, and what to do when you still run out of memory.-lastUpdated: 2026-10-26+lastUpdated: 2026-11-14sidebar:order: 2---@@ -84,6 +84,7 @@ none of them.| `max_cache_vram_gb` | unset: measured | You want Invoke to use less VRAM than it could. | Invoke stops measuring the GPU, so VRAM other programs use is not seen. || `max_cache_ram_gb` | unset: half your RAM minus 2 GB, within limits | You want more inactive models kept in RAM, or Invoke to use less RAM. | More: faster reloads, more RAM in use. || `keep_ram_copy_of_weights` | `true` | RAM is consistently tight. | Off: lower average RAM use, slower model switching and LoRA patching. |+| [`async_weight_streaming`](/configuration/optimization/async-weight-streaming/) | `false` | A model runs partially loaded on an NVIDIA or AMD (ROCm) GPU. | On: faster steps, identical images; about 384MB of VRAM kept free for copies, so slightly less of the model in VRAM, and the streamed layers' RAM is page-locked. Needs room in the RAM cache for the models of one generation. || `offload_on_architecture_switch` | `true` | You alternate between model architectures that fit in VRAM together. | Off: other architectures' models stay in VRAM until a load needs the room. || `clear_vram_after_session` | `false` | A generation that runs fine once runs out of memory, or slows down sharply, when repeated. | A few seconds per queue item to reload models from RAM. || `pytorch_cuda_alloc_conf` | unset | You want to tune peak reserved VRAM, for example with `backend:cudaMallocAsync`. | The best value depends on the GPU, driver and CUDA version: test it. |@@ -98,8 +99,10 @@ The details of each:<summary><span>`enable_partial_loading`: partial model loading</span></summary>Invoke streams a model's layers between RAM and VRAM as they are needed. When a step needs layers that are not in-VRAM and there is no room for them, inactive layers are moved to RAM. To load every model whole instead, for example-on a GPU with plenty of VRAM where that is faster:+VRAM and there is no room for them, inactive layers are moved to RAM. Each layer in RAM is copied to the GPU for every+step, and the GPU waits for the copy; on NVIDIA and AMD (ROCm) GPUs,+[Async Weight Streaming](/configuration/optimization/async-weight-streaming/) overlaps those copies with the+computation. To load every model whole instead, for example on a GPU with plenty of VRAM where that is faster:```yamlenable_partial_loading: false@@ -170,6 +173,23 @@ keep_ram_copy_of_weights: false</details>+<details>+<summary><span>`async_weight_streaming`: copy streamed layers while the GPU computes</span></summary>++Off by default. With a model partially loaded on an NVIDIA or AMD (ROCm) GPU, Invoke page-locks the layers in RAM and+copies each one to the GPU while the layers before it compute, instead of stopping the GPU for every copy. Images stay+bit-identical. Up to about 384MB of VRAM is kept free for the copies in flight, so slightly less of the model stays+in VRAM; it needs `keep_ram_copy_of_weights: true`, and GGUF and SDNQ layers keep the blocking copy. Locking the+layers the first time costs time, so it pays off when the models of one generation stay in the RAM cache: raise+`max_cache_ram_gb` if they do not fit. Details in+[Async Weight Streaming](/configuration/optimization/async-weight-streaming/).++```yaml+async_weight_streaming: true+```++</details>+<details><summary><span>`offload_on_architecture_switch`: switching between model architectures</span></summary>diff --git a/docs/src/content/docs/configuration/Optimization/memory-options.mdx b/docs/src/content/docs/configuration/Optimization/memory-options.mdxindex dc0c2c8e8c..00f04c0de1 100644--- a/docs/src/content/docs/configuration/Optimization/memory-options.mdx+++ b/docs/src/content/docs/configuration/Optimization/memory-options.mdx@@ -1,7 +1,7 @@---title: Which memory option do I need?description: Pick your GPU, VRAM and model format to see which of Invoke's memory options apply, and compare GGUF, int8, nvfp4, SDNQ, NF4 and FP8 in one table.-lastUpdated: 2026-10-26+lastUpdated: 2026-11-13sidebar:label: Which option do I need?order: 1@@ -35,7 +35,9 @@ around it; close games and other GPU programs while generating, and read the</MemoryOption><MemoryOption id="low-vram-mode" title="Low-VRAM mode is already on">On NVIDIA, AMD and Intel GPUs, Invoke streams the layers of a model too large for your VRAM from RAM as they are needed.-Nothing to turn on; [Low-VRAM mode](/configuration/optimization/low-vram-mode/) lists the settings that tune it.+Nothing to turn on; [Low-VRAM mode](/configuration/optimization/low-vram-mode/) lists the settings that tune it. On an+NVIDIA or AMD (ROCm) GPU, [Async Weight Streaming](/configuration/optimization/async-weight-streaming/) makes the streamed steps+faster, with identical images.</MemoryOption><MemoryOption id="fp8-storage" title="Turn on FP8 Storage for full-precision models that don't fit">On NVIDIA, AMD and Intel GPUs (not Apple silicon or the CPU), with a full-precision model: a per-model setting in thediff --git a/docs/src/generated/settings.json b/docs/src/generated/settings.jsonindex 70037347a4..a881c2d3bb 100644--- a/docs/src/generated/settings.json+++ b/docs/src/generated/settings.json@@ -647,6 +647,17 @@"type": "<class 'bool'>","validation": {}},+ {+ "category": "CACHE",+ "default": false,+ "description": "When a model is only partially loaded into VRAM, copy the weights it streams from RAM to the GPU asynchronously from page-locked RAM on a separate stream, overlapping with the computation, instead of one blocking copy per layer. Speeds up partially loaded models; images stay identical. Requires an NVIDIA or AMD (ROCm) GPU and keep_ram_copy_of_weights; falls back to the blocking copy automatically otherwise (Apple and Intel GPUs, the CPU, and GGUF or other specially quantized weights, which gain nothing from it). Copies in flight take up to about 384MB of VRAM; the model cache keeps that much free for them, so slightly less of such a model stays in VRAM. The RAM copy of the streamed weights is page-locked and stays locked while the model is in the cache, so models taking turns in VRAM lock it once (not swappable; at most 40% of physical RAM, where the weights of models not running are unlocked first); weights loaded from a file mapping are read into RAM when they are first locked. Has no effect on models that fit fully in VRAM.",+ "env_var": "INVOKEAI_ASYNC_WEIGHT_STREAMING",+ "literal_values": [],+ "name": "async_weight_streaming",+ "required": false,+ "type": "<class 'bool'>",+ "validation": {}+ },{"category": "CACHE","default": null,diff --git a/invokeai/app/invocations/ideogram4/ideogram4_denoise.py b/invokeai/app/invocations/ideogram4/ideogram4_denoise.pyindex f9fa58827d..6ab862fc66 100644--- a/invokeai/app/invocations/ideogram4/ideogram4_denoise.py+++ b/invokeai/app/invocations/ideogram4/ideogram4_denoise.py@@ -589,13 +589,13 @@ class Ideogram4DenoiseInvocation(BaseInvocation, WithMetadata):load can slip into a paced lock's gap. Without this the guarantee would be approximate; withit the reservation saves the transfer and this only ever trims what is left over.- `keep_required_weights_in_vram` leaves behind the tensors a streamed forward cannot fetch- per layer, such as quantization scales.+ `hold_resident_bytes` leaves behind the tensors a streamed forward cannot fetch per layer,+ such as quantization scales, and keeps the VRAM that streaming the rest in needs (see+ `async_weight_streaming`) within `target`."""- excess = second_branch.resident_weight_bytes - target- if excess <= 0:+ freed = second_branch.hold_resident_bytes(target)+ if freed <= 0:return- freed = second_branch.unload_from_vram(excess, keep_required_weights_in_vram=True)# The cache moves the weights to RAM but does not return the blocks to the driver, so# without this the bytes stay in torch's reserve -- invisible to the display, which is who# the room was made for.diff --git a/invokeai/app/invocations/wan/wan_denoise.py b/invokeai/app/invocations/wan/wan_denoise.pyindex 28fd7e005d..897c9770d5 100644--- a/invokeai/app/invocations/wan/wan_denoise.py+++ b/invokeai/app/invocations/wan/wan_denoise.py@@ -294,9 +294,7 @@ class _ExpertSwapper:)self._warned_partial_loading_unavailable = Trueelse:- vram_bytes_to_free = max(0, info.resident_weight_bytes - self._max_resident_model_bytes)- if vram_bytes_to_free > 0:- info.unload_from_vram(vram_bytes_to_free, keep_required_weights_in_vram=True)+ if info.hold_resident_bytes(self._max_resident_model_bytes) > 0:TorchDevice.empty_cache()# Apply LoRA patches for this expert. Quantized transformers (GGUF, or an int8 checkpoint whose Linearsdiff --git a/invokeai/app/services/config/config_default.py b/invokeai/app/services/config/config_default.pyindex 4ab24a91d1..ec52316e7a 100644--- a/invokeai/app/services/config/config_default.py+++ b/invokeai/app/services/config/config_default.py@@ -126,6 +126,7 @@ class InvokeAIAppConfig(BaseSettings):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.int8_compute: Run the matmuls of ComfyUI int8 builds quantized with convrot ('int8_tensorwise' with 'convrot') on the int8 tensor cores instead of dequantizing their weights on every forward (requires an NVIDIA GPU with compute capability 8.0 or newer and Triton; falls back automatically otherwise, including on AMD, Apple and Intel GPUs and the CPU). Speeds up denoising with these builds, but quantizes activations per token as well, so images will differ from the dequantized path at the same seed. The kernels are tuned once per layer shape and token-count bucket: about 35 seconds for the first image after enabling it, about 1-5 seconds for a later size in a new token-count bucket, cached on disk across restarts.+ async_weight_streaming: When a model is only partially loaded into VRAM, copy the weights it streams from RAM to the GPU asynchronously from page-locked RAM on a separate stream, overlapping with the computation, instead of one blocking copy per layer. Speeds up partially loaded models; images stay identical. Requires an NVIDIA or AMD (ROCm) GPU and keep_ram_copy_of_weights; falls back to the blocking copy automatically otherwise (Apple and Intel GPUs, the CPU, and GGUF or other specially quantized weights, which gain nothing from it). Copies in flight take up to about 384MB of VRAM; the model cache keeps that much free for them, so slightly less of such a model stays in VRAM. The RAM copy of the streamed weights is page-locked and stays locked while the model is in the cache, so models taking turns in VRAM lock it once (not swappable; at most 40% of physical RAM, where the weights of models not running are unlocked first); weights loaded from a file mapping are read into RAM when they are first locked. Has no effect on models that fit fully in VRAM.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.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.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.@@ -257,6 +258,7 @@ class InvokeAIAppConfig(BaseSettings):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.")int8_compute: bool = Field(default=False, description="Run the matmuls of ComfyUI int8 builds quantized with convrot ('int8_tensorwise' with 'convrot') on the int8 tensor cores instead of dequantizing their weights on every forward (requires an NVIDIA GPU with compute capability 8.0 or newer and Triton; falls back automatically otherwise, including on AMD, Apple and Intel GPUs and the CPU). Speeds up denoising with these builds, but quantizes activations per token as well, so images will differ from the dequantized path at the same seed. The kernels are tuned once per layer shape and token-count bucket: about 35 seconds for the first image after enabling it, about 1-5 seconds for a later size in a new token-count bucket, cached on disk across restarts.")+ async_weight_streaming: bool = Field(default=False, description="When a model is only partially loaded into VRAM, copy the weights it streams from RAM to the GPU asynchronously from page-locked RAM on a separate stream, overlapping with the computation, instead of one blocking copy per layer. Speeds up partially loaded models; images stay identical. Requires an NVIDIA or AMD (ROCm) GPU and keep_ram_copy_of_weights; falls back to the blocking copy automatically otherwise (Apple and Intel GPUs, the CPU, and GGUF or other specially quantized weights, which gain nothing from it). Copies in flight take up to about 384MB of VRAM; the model cache keeps that much free for them, so slightly less of such a model stays in VRAM. The RAM copy of the streamed weights is page-locked and stays locked while the model is in the cache, so models taking turns in VRAM lock it once (not swappable; at most 40% of physical RAM, where the weights of models not running are unlocked first); weights loaded from a file mapping are read into RAM when they are first locked. Has no effect on models that fit fully in VRAM.")# Deprecated CACHE configsram: Optional[float] = Field(default=None, gt=0, description="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.")vram: Optional[float] = Field(default=None, ge=0, description="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.")diff --git a/invokeai/backend/model_manager/load/load_base.py b/invokeai/backend/model_manager/load/load_base.pyindex c0a4de5828..2f2fd963a5 100644--- a/invokeai/backend/model_manager/load/load_base.py+++ b/invokeai/backend/model_manager/load/load_base.py@@ -24,6 +24,7 @@ from invokeai.backend.model_manager.load.model_cache.model_cache import (FirstUseClaim,ModelCache,)+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast import weight_streamingfrom invokeai.backend.model_manager.taxonomy import AnyModel, SubModelTypefrom invokeai.backend.util.logging import InvokeAILoggerfrom invokeai.backend.working_memory import probe@@ -212,6 +213,10 @@ class LoadedModelWithoutConfig:locked = Trueself._end_first_use_window()self.repair_required_tensors_on_device()+ cached_model = self._cache_record.cached_model+ if isinstance(cached_model, CachedModelWithPartialLoad):+ # Outside the global load lock and the cache's lock, see `pin_streamed_weights`.+ cached_model.pin_streamed_weights()except BaseException:if locked:self._cache.unlock(self._cache_record)@@ -226,6 +231,9 @@ class LoadedModelWithoutConfig:self._cache.unlock(self._cache_record)if probe.armed:probe.unlocked(self._cache, self._cache_record)+ cached_model = self._cache_record.cached_model+ if isinstance(cached_model, CachedModelWithPartialLoad):+ weight_streaming.release_side_pool(cached_model.compute_device)def __enter__(self) -> AnyModel:self._lock_on_device(None)@@ -351,11 +359,30 @@ class LoadedModelWithoutConfig:Full-load-only entries ignore the requested byte count and unload all weights."""with MODEL_LOAD_LOCK.read_lock():- return self._cache.unload_model_from_vram(+ freed = self._cache.unload_model_from_vram(self._cache_record,vram_bytes_to_free,keep_required_weights_in_vram=keep_required_weights_in_vram,)+ self._pin_streamed_weights_of_a_trimmed_lock(freed)+ return freed++ def hold_resident_bytes(self, max_resident_bytes: int) -> int:+ """Trim the locked model to at most ``max_resident_bytes`` of resident weights, leaving room within that for the+ copies in flight when what it moved to RAM streams (`async_weight_streaming`). Returns the bytes moved. For a+ node that holds a second model of the same size at the same time: prefer this to sizing an `unload_from_vram`+ request from `resident_weight_bytes`, which does not know that reserve."""+ with MODEL_LOAD_LOCK.read_lock():+ freed = self._cache.hold_model_residency(self._cache_record, max_resident_bytes)+ self._pin_streamed_weights_of_a_trimmed_lock(freed)+ return freed++ def _pin_streamed_weights_of_a_trimmed_lock(self, freed: int) -> None:+ cached_model = self._cache_record.cached_model+ if freed and self._cache_record.is_locked and isinstance(cached_model, CachedModelWithPartialLoad):+ # A node that makes room within its lock (a second expert or branch) runs on: what this moved to RAM+ # streams from now on. Outside the locks, as in `_lock_on_device`.+ cached_model.pin_streamed_weights()class LoadedModel(LoadedModelWithoutConfig):diff --git a/invokeai/backend/model_manager/load/model_cache/cached_model/cached_model_with_partial_load.py b/invokeai/backend/model_manager/load/model_cache/cached_model/cached_model_with_partial_load.pyindex a6814c4f13..53ed67d1ae 100644--- a/invokeai/backend/model_manager/load/model_cache/cached_model/cached_model_with_partial_load.py+++ b/invokeai/backend/model_manager/load/model_cache/cached_model/cached_model_with_partial_load.py@@ -1,3 +1,4 @@+import threadingimport weakreffrom contextlib import contextmanagerfrom typing import Iterator@@ -11,6 +12,7 @@ from invokeai.backend.model_manager.load.model_cache.tensor_aliases import (analyze_state_dict,move_shared,)+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast import weight_streamingfrom invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_module_mixin import (CustomModuleMixin,)@@ -42,6 +44,27 @@ class CachedModelWithPartialLoad:# Assigned for real at the end of __init__; initialized here so the acquire-failure path# below can call release_shared_weights(), which reads it, before that assignment runs.self._cpu_state_dict: dict[str, torch.Tensor] | None = None+ # The page-locked CPU weights this model streams with `async_weight_streaming`; created on the first load that+ # leaves streaming weights in RAM. `release_pinned_weights()` releases them on eviction, the finalizer if the+ # wrapper is dropped without one.+ self._pin_holder: weight_streaming.PinHolder | None = None+ self._pin_release_finalizer: weakref.finalize | None = None+ # Set on eviction. An evicted record can still finish a lock that was under way; it must not pin again, as+ # nothing would release that before the wrapper is collected.+ self._pinning_retired = False+ # Whether weights moved since the pins were last brought up to date (`pin_streamed_weights`).+ self._pins_stale = True+ # Serializes `pin_streamed_weights`: two threads locking this model at once (a session and the image index+ # worker) would otherwise both create a holder, or one would return while the other's update still runs.+ # Releases do not take it: eviction must not wait behind a slow first pin.+ self._pin_lock = threading.Lock()+ # The cache locks of this wrapper (`begin_streaming_lock`), the storages they locked in the registry (None+ # while the feature is not in use for them), and whether the lock planned VRAM for streaming copies.+ self._streaming_locks = 0+ self._locked_keys: frozenset | None = None+ self._ram_storages: list[torch.UntypedStorage] | None = None+ self._ram_keys: frozenset | None = None+ self._registration_planned = Truemodel_state_dict = model.state_dict()# A CPU read-only copy of the model's state dict. Used for faster model unloads from VRAM, and to speed up LoRA@@ -76,6 +99,13 @@ class CachedModelWithPartialLoad:model_state_dict)self._state_dict_keys_by_module_prefix = self._group_state_dict_keys_by_module_prefix(model_state_dict)+ # What `cast_to_device` could stream asynchronously at most; bounds the VRAM reserve of a streaming lock.+ self._streamable_bytes = sum(+ self._state_dict_bytes[key]+ for key, tensor in model_state_dict.items()+ if key not in self._keys_in_modules_that_do_not_support_autocast+ and weight_streaming.is_streamable_tensor(tensor)+ )# In multi-GPU mode, share a single canonical CPU copy of the weights across the per-device# caches instead of keeping one copy per device (see SharedCpuWeightsStore). If another@@ -211,6 +241,7 @@ class CachedModelWithPartialLoad:yieldexcept BaseException:self._cur_vram_bytes = None+ self._pins_stale = Trueself._set_autocast_enabled_in_all_modules(True)raise@@ -249,6 +280,148 @@ class CachedModelWithPartialLoad:self._shared_store = Noneself._shared_key = None+ def release_pinned_weights(self) -> bool:+ """Release this model's page-locked CPU weights (see `pin_streamed_weights`); whether it had any. Called on+ eviction; idempotent. Storages another holder (a wrapper on another GPU sharing these weights) still uses stay+ pinned."""+ # Set first: a `pin_streamed_weights` running concurrently checks it again after registering and undoes that.+ self._pinning_retired = True+ if self._pin_release_finalizer is not None:+ self._pin_release_finalizer.detach()+ self._pin_release_finalizer = None+ holder, self._pin_holder = self._pin_holder, None+ return holder is not None and weight_streaming.PINNED_STORAGES.release(holder)++ def _streams_weights(self) -> bool:+ return not self._pinning_retired and weight_streaming.can_stream_weights_to(+ self._compute_device, has_ram_copy=self._cpu_state_dict is not None+ )++ def _streamable_ram_storages(self) -> list[torch.UntypedStorage]:+ """The storages of the RAM copy the custom modules could stream: all that can ever be registered for this model.+ Fixed for the wrapper's life, so listed once."""+ if self._ram_storages is None:+ ram_copy = self._cpu_state_dict+ assert ram_copy is not None # Callers check `has_ram_copy`.+ self._ram_storages = [+ tensor.untyped_storage()+ for key, tensor in ram_copy.items()+ if key not in self._keys_in_modules_that_do_not_support_autocast+ and weight_streaming.is_streamable_tensor(tensor)+ ]+ return self._ram_storages++ def begin_streaming_lock(self) -> None:+ """Called by the cache as it takes a lock on this model, under its lock and before anything moves.++ While the lock lasts, the storages of the RAM copy are not unregistered (see `PinnedStorageRegistry`): the+ cache's partial loads, the repair of required weights, the synchronous fallback copies and the unpatching of+ LoRAs all copy from them on this thread's own streams, and the registry cannot see those copies. Another+ thread that is unregistering one of them makes this wait for it. Also withdraws the plan for streaming copies+ (`weight_streaming_reserve_bytes`) until this lock plans it again.+ """+ if self._streaming_locks == 0:+ self._registration_planned = False+ if weight_streaming.can_stream_weights_to(self._compute_device, self._cpu_state_dict is not None):+ if self._ram_keys is None:+ self._ram_keys = weight_streaming.storage_keys(self._streamable_ram_storages())+ weight_streaming.PINNED_STORAGES.lock(self._ram_keys)+ self._locked_keys = self._ram_keys+ self._streaming_locks += 1++ def end_streaming_lock(self) -> None:+ """Called by the cache as a lock on this model ends, whether or not it settled."""+ self._streaming_locks -= 1+ if self._streaming_locks == 0 and self._locked_keys is not None:+ keys, self._locked_keys = self._locked_keys, None+ registry = weight_streaming.PINNED_STORAGES+ registry.unlock(keys)+ # Unregisters what an eviction left pending behind this lock. A thread holding the registration lock drains+ # when it releases it.+ registry.drain_deferred()++ def weight_streaming_reserve_bytes(self) -> int:+ """VRAM a lock that leaves streamed weights in RAM needs beyond the model's resident weights and the working+ memory: the copies in flight, at most `weight_streaming.STREAM_BUDGET_BYTES`. The layer being computed needs+ no reserve, the synchronous path holds it as well.++ The answer is the plan: when it is 0 (nothing streams, or the pinned-RAM cap leaves no room), this lock+ registers nothing new, so no streaming starts that nobody reserved VRAM for.+ """+ self._registration_planned = False+ if self._streamable_bytes == 0 or not self._streams_weights():+ return 0+ registry = weight_streaming.PINNED_STORAGES+ if not registry.can_register(self._compute_device):+ return 0+ if not registry.has_room_for_any(self._streamable_ram_storages()):+ return 0+ self._registration_planned = True+ return min(weight_streaming.STREAM_BUDGET_BYTES, self._streamable_bytes)++ def pin_streamed_weights(self) -> None:+ """Page-lock the CPU-resident weights the custom modules stream, so `cast_to_device` copies them+ asynchronously (`async_weight_streaming`), and mark them as streamed by this lock. What earlier locks pinned+ stays pinned (see `PinnedStorageRegistry`): models that take turns in VRAM pay for registration once.++ Called by the holder of a settled lock, outside the global load lock and the cache's lock: page-locking+ weights that are still only mapped from their file reads them into RAM (about 2.5 s/GiB measured), which+ must not stall other models' construction or this device's cache. The lock keeps the residency fixed.++ Only with a RAM copy: its tensors are the ones the parameters point to while offloaded, and they stay put+ across loads and unloads. Without one, offloaded weights are fresh allocations on every unload.+ """+ with self._pin_lock:+ self._pin_streamed_weights_locked()++ def mark_streamed_weights_idle(self) -> None:+ """Called by the cache when the model's last lock ends: its pins stay, but another model's registration may+ reclaim them under the pinned-RAM cap."""+ holder = self._pin_holder+ if holder is not None:+ weight_streaming.PINNED_STORAGES.idle(holder)++ def _pin_streamed_weights_locked(self) -> None:+ registry = weight_streaming.PINNED_STORAGES+ if not self._streams_weights():+ # Also covers the setting being switched off while pins are held.+ holder = self._pin_holder+ if holder is not None:+ registry.release(holder)+ self._pins_stale = True+ return+ holder = self._pin_holder+ if not self._pins_stale and holder is not None and registry.activate(holder):+ return # Nothing moved since the last lock, and all it streams is still pinned.+ if holder is None:+ holder = weight_streaming.PinHolder(self._compute_device)+ # Like the shared-weights finalizer: must not reference `self`, and only enqueues (GC context).+ finalizer = weakref.finalize(self, registry.release_deferred, holder)+ finalizer.atexit = False+ self._pin_holder, self._pin_release_finalizer = holder, finalizer+ self._pins_stale = False+ ram_copy = self._cpu_state_dict+ assert ram_copy is not None # `_streams_weights` requires it.+ # Only storages of the RAM copy: they live as long as this wrapper, so the registry holding them keeps nothing+ # alive that would otherwise be freed (a holder may have cast weights in place, see `restore_counted_dtypes`).+ streamed = [+ tensor.untyped_storage()+ for key, tensor in self._model.state_dict().items()+ if tensor.device.type == "cpu"+ and key not in self._keys_in_modules_that_do_not_support_autocast+ and weight_streaming.is_streamable_tensor(tensor)+ and key in ram_copy+ and ram_copy[key].untyped_storage().data_ptr() == tensor.untyped_storage().data_ptr()+ ]+ try:+ registry.update(holder, streamed, register_new=self._registration_planned)+ except BaseException:+ self._pins_stale = True+ raise+ if self._pinning_retired:+ # Evicted while registering: `release_pinned_weights` may have released before this update.+ registry.release(holder)+def total_bytes(self) -> int:"""Get the total size (in bytes) of all the weights in the model."""return self._total_bytes@@ -298,6 +471,8 @@ class CachedModelWithPartialLoad:self._move_non_persistent_buffers_to_device(self._compute_device)if keys_to_repair:self._cur_vram_bytes = None+ if keys_to_repair:+ self._pins_stale = Truereturn repaired_required_tensorsdef restore_counted_dtypes(self) -> None:@@ -494,6 +669,9 @@ class CachedModelWithPartialLoad:# in the vram_bytes_loaded tracking.self._move_non_persistent_buffers_to_device(self._compute_device)+ if keys_to_load:+ self._pins_stale = True+return vram_bytes_loaded, truncated@torch.no_grad()@@ -544,4 +722,7 @@ class CachedModelWithPartialLoad:# We may have gone from a fully-loaded model to a partially-loaded model, so we need to reapply the custom# layers.self._set_autocast_enabled_in_all_modules(True)++ if keys_to_offload:+ self._pins_stale = Truereturn vram_bytes_freeddiff --git a/invokeai/backend/model_manager/load/model_cache/model_cache.py b/invokeai/backend/model_manager/load/model_cache/model_cache.pyindex 03ffb3d54e..981261ada4 100644--- a/invokeai/backend/model_manager/load/model_cache/model_cache.py+++ b/invokeai/backend/model_manager/load/model_cache/model_cache.py@@ -627,6 +627,8 @@ class ModelCache:self._last_activity_time: Optional[float] = Noneself._timeout_timer: Optional[threading.Timer] = Noneself._shutdown_event = threading.Event()+ # Whether `_delete_cache_entry` has said once that a model left with page-locked weights.+ self._pinned_eviction_logged = Falseself._deferred_work_queue: queue.SimpleQueue[object] = queue.SimpleQueue()self._deferred_work_thread: Optional[threading.Thread] = Noneself._deferred_work_finalizer: Optional[weakref.finalize] = None@@ -1865,7 +1867,14 @@ class ModelCache:return self._locks_helddef _pin(self, cache_entry: CacheRecord) -> None:- """Lock `cache_entry` and count the lock in `locks_held`. Caller holds the lock."""+ """Lock `cache_entry` and count the lock in `locks_held`. Caller holds the lock.++ A model with a RAM copy first locks its weights' storages in the registry of page-locked memory, which may wait+ for one that another thread is unregistering. That thread needs none of this cache's locks.+ """+ cached_model = cache_entry.cached_model+ if isinstance(cached_model, CachedModelWithPartialLoad):+ cached_model.begin_streaming_lock()cache_entry.lock()self._locks_held += 1@@ -1873,17 +1882,21 @@ class ModelCache:"""Release a lock `_pin` took. Caller holds the lock. The record refuses an unlock it has no lock for beforeeither count changes, so a double unlock leaves `locks_held` right.- The last release, an unlock or a failed `lock`/`continue_lock` alike, returns weights a holder cast in place to- their counted dtypes (see `_restore_counted_dtypes`). A record that is detached or stale is skipped: it leaves- the cache, and a restore would only allocate on the device outside any reservation.+ The last release, an unlock or a failed `lock`/`continue_lock` alike, marks the weights the model streamed as+ idle: they stay page-locked, but another model may reclaim them (`PinnedStorageRegistry`). It also returns+ weights a holder cast in place to their counted dtypes (see `_restore_counted_dtypes`), except on a record that+ is detached or stale: it leaves the cache, and a restore would only allocate on the device outside any+ reservation."""cache_entry.unlock()self._locks_held -= 1- if (- not cache_entry.is_locked- and not cache_entry.is_stale- and self._cached_models.get(cache_entry.key) is cache_entry- ):+ if isinstance(cache_entry.cached_model, CachedModelWithPartialLoad):+ cache_entry.cached_model.end_streaming_lock()+ if cache_entry.is_locked:+ return+ if isinstance(cache_entry.cached_model, CachedModelWithPartialLoad):+ cache_entry.cached_model.mark_streamed_weights_idle()+ if not cache_entry.is_stale and self._cached_models.get(cache_entry.key) is cache_entry:self._restore_counted_dtypes(cache_entry)@synchronized@@ -2144,11 +2157,19 @@ class ModelCache:f"After unloading: {self._get_vram_state_str(model_cur_vram_bytes, model_total_bytes, vram_available)}")+ # A model that will run partially loaded with async weight streaming holds copies in flight on top of its+ # resident weights and the working memory. Plan for them by loading that much less of it; a model that fits+ # streams nothing and needs no reserve. Other models are already offloaded at this point (it did not fit).+ streaming_reserve = 0+ if model_vram_needed > vram_available + MB and isinstance(cache_entry.cached_model, CachedModelWithPartialLoad):+ streaming_reserve = cache_entry.cached_model.weight_streaming_reserve_bytes()+ vram_available -= streaming_reserve+if vram_available < 0:# There is insufficient VRAM available. As a last resort, try to unload the model being locked from VRAM,# as it may still be loaded from a previous use.vram_bytes_freed_from_own_model = self._move_model_to_ram(cache_entry, -vram_available)- vram_available = self._get_vram_available(working_mem_bytes)+ vram_available = self._get_vram_available(working_mem_bytes) - streaming_reserveself._logger.debug(f"Unloaded {vram_bytes_freed_from_own_model / MB:.2f}MB from the model being locked ({cache_entry.key}).")@@ -2168,7 +2189,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.- effective_working_mem = self._working_mem_reserve(working_mem_bytes)+ effective_working_mem = self._working_mem_reserve(working_mem_bytes) + streaming_reserveself._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 "@@ -2196,7 +2217,7 @@ class ModelCache:return Falsemodel_cur_vram_bytes = cache_entry.cached_model.cur_vram_bytes()- vram_available = self._get_vram_available(working_mem_bytes)+ vram_available = self._get_vram_available(working_mem_bytes) - streaming_reserveloaded_percent = model_cur_vram_bytes / model_total_bytes if model_total_bytes > 0 else 0# Use the model's actual compute_device for logging, not the cache's defaultmodel_device = cache_entry.cached_model.compute_device@@ -2224,7 +2245,9 @@ 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)+ self._release_allocator_blocks_for_reserve(+ self._working_mem_reserve(working_mem_bytes) + streaming_reserve if streaming_reserve else working_mem_bytes+ )return Truedef _working_mem_reserve(self, working_mem_bytes: Optional[int]) -> int:@@ -2367,6 +2390,26 @@ class ModelCache:keep_required_weights_in_vram=keep_required_weights_in_vram,)+ @synchronized+ def hold_model_residency(self, cache_entry: CacheRecord, max_resident_bytes: int) -> int:+ """Trim a locked model that keeps running to at most ``max_resident_bytes`` of resident weights, counting what+ it streams in: returns the bytes moved to RAM.++ A model that streams from RAM (`async_weight_streaming`) holds up to `weight_streaming_reserve_bytes()` of+ copies in flight on top of its resident weights, which the caller's limit has to leave room for, whether the+ lock settled above the limit or already under it by the reserve its own load planned. The reserve is asked for+ here, which also plans the streaming that follows (a lock that planned none registers nothing new). A model+ that stays fully resident streams nothing.+ """+ cached_model = cache_entry.cached_model+ resident = cached_model.cur_vram_bytes()+ if isinstance(cached_model, CachedModelWithPartialLoad) and max_resident_bytes < cached_model.total_bytes():+ resident += cached_model.weight_streaming_reserve_bytes()+ excess = resident - max_resident_bytes+ if excess <= 0:+ return 0+ return self._move_model_to_ram(cache_entry, excess, keep_required_weights_in_vram=True)+def _get_vram_available(self, working_mem_bytes: Optional[int], honor_cap: bool = True) -> int:"""Calculate the amount of additional VRAM available for the cache to use (takes into account the workingmemory).@@ -3043,6 +3086,19 @@ class ModelCache:# released via the store above). Captured before release_shared_weights() flips the flag.if self._ram_budget is not None and not uses_shared:self._ram_budget.remove_non_shared(total_bytes, cache=self)+ # Last, after the bookkeeping above: it waits for the device. It does not raise, but a hang or+ # an interrupt there must not leave the record half removed.+ if isinstance(cache_entry.cached_model, CachedModelWithPartialLoad):+ had_pins = cache_entry.cached_model.release_pinned_weights()+ if had_pins and not self._pinned_eviction_logged and not self._shutdown_event.is_set():+ # Its next load page-locks the weights again, which can cost more than streaming saves when it+ # happens between the images of one generation (measured on Linux with an 8 GB RAM cache).+ self._pinned_eviction_logged = True+ self._logger.info(+ f"async_weight_streaming: {cache_entry.key} left the RAM cache with page-locked weights; loading "+ "it again locks them again. If that happens between images, raise max_cache_ram_gb so the models "+ "of one generation fit."+ )def _notify_models_cleared(self,diff --git a/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/cast_to_device.py b/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/cast_to_device.pyindex 7a50a19953..dc19bdaaba 100644--- a/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/cast_to_device.py+++ b/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/cast_to_device.py@@ -2,6 +2,8 @@ from typing import TypeVarimport torch+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.weight_streaming import stream_to_device+T = TypeVar("T", torch.Tensor, None, torch.Tensor | None)@@ -11,5 +13,9 @@ def cast_to_device(t: T, to_device: torch.device) -> T:return tif t.device.type != to_device.type:+ if t.device.type == "cpu" and to_device.type == "cuda":+ streamed = stream_to_device(t, to_device)+ if streamed is not None:+ return streamedreturn t.to(to_device)return tdiff --git a/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/weight_streaming.py b/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/weight_streaming.pynew file mode 100644index 0000000000..e4a4d2b7b4--- /dev/null+++ b/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/weight_streaming.py@@ -0,0 +1,1004 @@+"""Async weight streaming for partially loaded models, opt-in via ``async_weight_streaming``.++A partially loaded model keeps part of its weights in RAM, and the custom modules copy each of them to the compute+device on every forward (`cast_to_device`). Without this feature that copy is a synchronous ``t.to(device)`` from+pageable memory: the CPU waits for the GPU to drain before every copy, and the GPU idles while the copy runs. With it,+the copy runs on a side stream from page-locked RAM and overlaps with the compute stream. Outputs are bit-identical:+the same bytes arrive before the same kernels read them.++Two parts:++- `PinnedStorageRegistry` page-locks CPU storages in place (``cudaHostRegister``, no second copy), shared by holders.+ `CachedModelWithPartialLoad` keeps the RAM-copy weights its streaming modules stream registered.+- `stream_to_device` issues the asynchronous copy of a registered tensor, or of a small one through a pinned staging+ buffer. Everything else returns None, and the caller copies synchronously as before.++Runs on CUDA devices: NVIDIA, and AMD through ROCm, where the HIP runtime provides the same calls+(measured on an RX 9060 XT with ROCm 10: registration works, outputs bit-identical).+"""++import ctypes+import fnmatch+import logging+import mmap+import os+import queue+import threading+from collections import deque+from contextlib import contextmanager+from dataclasses import dataclass, field, replace+from typing import Iterable, Iterator++import psutil+import torch++from invokeai.backend.util.devices import TorchDevice+from invokeai.backend.util.logging import InvokeAILogger++logger = InvokeAILogger.get_logger(__name__)++# Bytes of streamed weights the compute stream has not reached yet. The CPU runs ahead of the GPU; without a bound it+# issues every copy of a forward at once and holds all streamed weights in VRAM at the same time (measured: +1.9 GiB+# for 1.69 GiB streamed), which defeats partial loading. Both paths hold the tensor being consumed; this one also holds+# up to the budget of copies in flight, and the model cache reserves that much VRAM (or the model's streamable bytes,+# if fewer) for a lock that leaves streamed weights in RAM (`CachedModelWithPartialLoad.weight_streaming_reserve_bytes`).+#+# The copies are allocated on the side stream, so their freed blocks are cached for it: the compute stream cannot take+# them directly. The allocator frees them on an out-of-memory retry and `empty_cache()` returns them, so the cache's+# reclaimable-VRAM credit (`ModelCache._get_reclaimable_allocator_bytes`) is right to count them, at the cost of a+# synchronization when it is drawn on. Between locks they hold about the reserve the next streaming lock plans for.+STREAM_BUDGET_BYTES = 384 * 2**20+# Tensors up to this size that are not registered (registration failed, or the pinned-RAM cap is reached) are copied+# into a pinned staging buffer first. A single synchronous copy among the asynchronous ones would stall the CPU until+# the GPU has drained, losing the overlap; for small tensors the extra CPU copy is cheap. Only while something is+# wanted on the device at all: where every large weight copies synchronously anyway, staging the small ones gains+# nothing.+STAGE_MAX_BYTES = 2**20+# Page-locked RAM cannot be swapped out. ComfyUI caps it at 40 % of physical RAM on Windows; storages past the cap stay+# pageable and stream synchronously.+PINNED_RAM_CAP_BYTES = int(0.4 * psutil.virtual_memory().total)++_CUDA_HOST_REGISTER_PORTABLE = 1 # Registered memory is pinned for every GPU, so shared weights serve all devices.+_PAGE_SIZE = mmap.PAGESIZE++# Opt-in like fp8/int8 compute. Tests override it process-wide without a configured app.+_override: bool | None = None+++def set_async_weight_streaming_enabled(enabled: bool | None) -> None:+ """Override the configured setting process-wide. Pass ``None`` to revert to the config value."""+ global _override+ _override = enabled+++def is_async_weight_streaming_enabled() -> bool:+ if _override is not None:+ return _override+ try:+ from invokeai.app.services.config.config_default import get_config++ return bool(get_config().async_weight_streaming)+ except Exception:+ # Backend code may run outside a configured app (scripts, tests). Default to the synchronous path.+ return False+++_logged: set[str] = set()+_logged_lock = threading.Lock()+++def _log_once(key: str, level: int, message: str) -> None:+ with _logged_lock:+ if key in _logged:+ return+ _logged.add(key)+ logger.log(level, message)+++def is_streamable_tensor(t: torch.Tensor) -> bool:+ """Plain tensors only. Subclasses (GGMLTensor, SDNQTensor, bitsandbytes parameters) define their own transfers, and+ some have no storage of their own to page-lock."""+ return type(t) is torch.Tensor or type(t) is torch.nn.Parameter+++def can_stream_weights_to(device: torch.device, has_ram_copy: bool) -> bool:+ """Whether the CPU-resident weights of a model computing on ``device`` stream asynchronously.++ When the feature is on but cannot work for the model, the log says why, once.+ """+ if not is_async_weight_streaming_enabled():+ return False+ if device.type != "cuda":+ _log_once(+ f"device:{device}",+ logging.INFO,+ f"async_weight_streaming is enabled, but not used on {device}: it needs an NVIDIA or AMD (ROCm) GPU. "+ "Weights in RAM are copied there synchronously.",+ )+ return False+ if not has_ram_copy:+ _log_once(+ "ram_copy",+ logging.INFO,+ "async_weight_streaming is enabled, but not used: it needs keep_ram_copy_of_weights: true. Weights in RAM "+ "are copied synchronously.",+ )+ return False+ return True+++class _Runtime:+ """``cudaHostRegister``, ``cudaHostUnregister`` and ``cudaGetLastError`` (the ``hip`` equivalents on ROCm) of one+ runtime library, called through ctypes.++ Registration needs a way to clear the error a refused call leaves: the runtime keeps it as the thread's last+ error, and torch raised it from the next allocation that reached cudaMalloc, unrelated to the registration+ (measured on an RTX 4090 and an RX 9060 XT; a kernel launch did not clear it). ``torch.cuda.cudart()`` has no+ cudaGetLastError. Taking all three calls from the same library puts every error the registry causes into the error+ state it clears, whichever runtime instance torch itself uses, so no refused call can stay pending for torch.+ """++ def __init__(self, library: ctypes.CDLL, prefix: str) -> None:+ self._register = getattr(library, f"{prefix}HostRegister")+ self._register.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_uint]+ self._register.restype = ctypes.c_int+ self._unregister = getattr(library, f"{prefix}HostUnregister")+ self._unregister.argtypes = [ctypes.c_void_p]+ self._unregister.restype = ctypes.c_int+ self._get_last_error = getattr(library, f"{prefix}GetLastError")+ self._get_last_error.argtypes = []+ self._get_last_error.restype = ctypes.c_int++ def register(self, ptr: int, nbytes: int) -> int:+ """Page-lock [ptr, ptr + nbytes) for every GPU. Returns the error code; a refusal is cleared at once."""+ error = self._register(ptr, nbytes, _CUDA_HOST_REGISTER_PORTABLE)+ if error != 0:+ self._get_last_error()+ return error++ def unregister(self, ptr: int) -> int:+ error = self._unregister(ptr)+ if error != 0:+ self._get_last_error()+ return error+++def _find_runtime() -> _Runtime | None:+ """The runtime library torch uses, among those mapped into the process; None if there is none.++ Another wheel can bring a private copy of the runtime. Registering through it would use that copy's current device+ (0 by default), possibly creating a context on a GPU this worker does not use. So torch's own copy comes first: in+ torch's lib directory (Windows, ROCm wheels) or in the ``nvidia`` runtime wheel torch depends on (Linux), with the+ soname of torch's CUDA major version. The self-test then checks that torch sees the registrations.+ """+ hip = torch.version.hip is not None+ patterns = ("amdhip64*.dll", "libamdhip64.so*") if hip else ("cudart64_*.dll", "libcudart.so*")+ torch_lib = os.path.normcase(os.path.join(os.path.dirname(torch.__file__), "lib"))+ soname = None if hip or torch.version.cuda is None else f"libcudart.so.{torch.version.cuda.split('.')[0]}"+ try:+ paths = {m.path for m in psutil.Process().memory_maps()}+ except Exception:+ return None+ matching = [p for p in paths if any(fnmatch.fnmatch(os.path.basename(p).lower(), pat) for pat in patterns)]++ def preference(path: str) -> tuple[bool, bool, str]:+ directory = os.path.normcase(os.path.dirname(path))+ torchs = directory == torch_lib or f"{os.sep}nvidia{os.sep}" in directory+ return (not torchs, soname is not None and os.path.basename(path) != soname, path)++ matching.sort(key=preference)+ for path in matching:+ try:+ return _Runtime(ctypes.CDLL(path), "hip" if hip else "cuda")+ except (OSError, AttributeError):+ continue+ return None+++# Chosen by the self-test (`_registration_self_test`); every registration goes through it.+_runtime: _Runtime | None = None+# Self-test buffers that could not be unregistered; never freed (see `_registration_self_test`).+_self_test_stranded: list[torch.Tensor] = []+++def _fault_in(storage: torch.UntypedStorage) -> None:+ """Read a byte of every page of ``storage``, so the file behind it is read before the registration lock is taken.++ Weights from safetensors' ``load_file`` stay mapped from the file until first read, and registering them reads+ them in. Measured for a 3.89 GiB file in the page cache on an RTX 4090: 1.96 s to register without this, 0.59 s+ for this plus 1.43 s to register. The rest is the driver making the copy-on-write pages private as it locks them,+ which only a write would do earlier; the weights may be read-only, so `update` takes the lock per storage instead.+ """+ data = torch.empty(0, dtype=torch.uint8).set_(storage)+ data[::_PAGE_SIZE].sum()+ data[-1:].sum()+++_StorageKey = tuple[int, int]+++def _registration_self_test(device: torch.device | None = None) -> str | None:+ """Check what the registry relies on, once per process on a scratch buffer; None if it holds, else why not.++ Runs on ``device``, the compute device of the model that asks, with that device current: the runtime's calls act on+ the current device, which is GPU 0 on a thread that never chose one, and the self-test must not create a context+ on a GPU the process does not use, nor wait for its queued work. Without ``device``, the thread's current one.++ Storages are registered byte-exact, not page-rounded: safetensors' ``load_file`` returns tensors back to back+ inside one file mapping, so neighbours share pages. A copy that starts inside a registration and runs past its end+ fails ("invalid argument"), so a page-rounded registration would break the copies of the neighbour that starts in+ its last page, and two page-rounded registrations could not hold neighbours at all. Measured on Windows with an+ RTX 4090 (CUDA 13) and an RX 9060 XT (ROCm 10): registrations end at their exact byte, two may share a page, and+ memory past the end in the same page copies as pageable. A driver that rounds to pages keeps the synchronous copy+ instead of failing copies; its refusal is cleared by `_Runtime`.+ """+ if device is None:+ return _self_test_on_current_device(torch.device("cuda"))+ with torch.cuda.device(device):+ return _self_test_on_current_device(device)+++def _self_test_on_current_device(device: torch.device) -> str | None:+ global _runtime+ runtime = _find_runtime()+ if runtime is None:+ # Nothing has been called that could fail.+ return "the GPU runtime library was not found"+ page = _PAGE_SIZE+ buffer = (torch.arange(8 * page, dtype=torch.int32) % 251).to(torch.uint8)+ origin = buffer.data_ptr()+ first = (origin // page + 1) * page+ boundary, last = first + page + 100, first + 3 * page++ def view(lo: int, hi: int) -> torch.Tensor:+ return buffer[lo - origin : hi - origin]++ def copies_intact(t: torch.Tensor) -> bool:+ return torch.equal(t.to(device, non_blocking=True).cpu(), t)++ exact_ranges = "this driver does not page-lock memory by exact ranges, so neighbouring weights could not be copied"+ # Torch must see what the runtime registers: a copy of the runtime that torch does not use (ROCm has no+ # driver/runtime split) would leave every copy pageable. `is_pinned` asks about a tensor's storage, so this+ # registers one storage whole.+ whole = torch.empty(2 * page, dtype=torch.uint8)+ # Every address registered and not yet unregistered: the `finally` unregisters what is left.+ registered: list[int] = []++ def unregister_last() -> bool:+ if runtime.unregister(registered[-1]) != 0:+ return False+ registered.pop()+ return True++ try:+ if runtime.register(whole.data_ptr(), whole.nbytes) != 0:+ return "page-locking a test buffer failed"+ registered.append(whole.data_ptr())+ visible = whole.is_pinned()+ if not unregister_last():+ return "unpinning a test buffer failed"+ if not visible:+ return "the GPU runtime library found is not the one torch uses"+ for lo, hi in ((first, boundary), (boundary, last)):+ if runtime.register(lo, hi - lo) != 0:+ return exact_ranges+ registered.append(lo)+ if not all(copies_intact(t) for t in (view(first + 50, boundary), view(boundary, last))):+ return exact_ranges+ if not unregister_last():+ return exact_ranges+ # Now pageable, starting in the last page of a registration.+ if not copies_intact(view(boundary, last)):+ return exact_ranges+ # A driver that cannot unregister would strand every model's weights it pinned.+ if not unregister_last():+ return "unpinning a test buffer failed"+ _runtime = runtime+ return None+ except RuntimeError as error:+ return f"its self-test failed ({error})"+ finally:+ # A registration that outlived its buffer would cover whatever the allocator puts there next, and copies from+ # that would fail. Buffers that cannot be unregistered are kept for the process lifetime instead.+ if [lo for lo in registered if runtime.unregister(lo) != 0]:+ _self_test_stranded.extend((buffer, whole))+++class PinHolder:+ """The storages one holder (a cached model wrapper) holds, and which of them its model streams in its current+ lock. Mutated only under the registration lock.++ ``device`` is where the model computes: registration and the first self-test run there, and only copies to it may+ stream what the holder wants (see `PinnedStorageRegistry.lookup`)."""++ __slots__ = ("keys", "wanted", "active", "device")++ def __init__(self, device: torch.device) -> None:+ self.device = TorchDevice.normalize(device)+ self.keys: set[_StorageKey] = set()+ # What the model streams in its current lock (or streamed in its last one); counts only while `active`.+ self.wanted: set[_StorageKey] = set()+ self.active = False+++@dataclass(eq=False)+class _StorageEntry:+ key: _StorageKey+ # Held so the memory cannot be freed while registered; freeing registered memory is undefined behaviour.+ storage: torch.UntypedStorage+ # False when the storage was already page-locked (torch's pinned allocator): it is never unregistered here.+ registered_here: bool+ holders: set[PinHolder] = field(default_factory=set)+ # Active holders that stream it in their current lock, per compute device of the holders: copies to a device+ # stream the storage only if a holder computing there wants it. Mutated under the lookup lock, which `lookup` reads+ # it under.+ wanted_on: dict[torch.device, int] = field(default_factory=dict)++ @property+ def wanted_by(self) -> int:+ """Active holders that stream it. At 0 a storage registered here is reclaimable."""+ return sum(self.wanted_on.values())+++def _storage_key(storage: torch.UntypedStorage) -> _StorageKey:+ return storage.data_ptr(), storage.nbytes()+++def storage_keys(storages: Iterable[torch.UntypedStorage]) -> frozenset[_StorageKey]:+ """What `PinnedStorageRegistry.lock` takes: the keys of the storages (empty ones are never registered)."""+ return frozenset(_storage_key(s) for s in storages if s.nbytes() > 0)+++class PinnedStorageRegistry:+ """Process-wide in-place page-locking of CPU storages, shared by holders.++ Storages are keyed by address and size, so tied weights and the canonical CPU tensors several per-device wrappers+ share (`SharedCpuWeightsStore`) are registered once and held once per holder. Each storage is registered by its+ exact byte range (see `_registration_self_test`), so every copy from it lies inside its registration.++ A holder keeps what it registered across loads and unloads, so models that take turns in VRAM do not pay for+ registration on every lock: about 0.03 s/GiB for memory already private, measured on Windows (RTX 4090) and Linux+ (RTX PRO 6000), and 0.3 to 0.4 s/GiB the first time for weights still mapped from their file, whose pages the+ driver makes private. `update` marks what a+ lock streams, `idle` marks the end of the model's last lock. A storage that no active holder streams is+ reclaimable: when a registration would pass `PINNED_RAM_CAP_BYTES`, reclaimable storages are unregistered, the+ longest unused first, and only as many as that registration needs.++ Three locks. The lookup lock only guards which storages are registered and which devices want them; the streamer+ holds it from its check to the enqueued copy. The registration lock serializes the slow driver calls. The small+ lock of `_unregistering` and `_locked` (a condition) guards the exclusion between locks and unregistration, below,+ and is never held across a driver call.++ Unregistration removes the entries under the lookup lock first, so no copy can start from them, then waits for the+ streamers' side streams and unregisters. Copies that the registry does not see are different: a partial load's+ `.to(device)`, the repair of required weights, the synchronous fallback of `cast_to_device` and the unpatching of a+ LoRA all copy from a RAM-copy storage on the caller's own stream, and unregistering during such a DMA is undefined.+ So a cached model locks the storages of its whole RAM copy (`lock`) from the start of its cache lock to the end of+ it, even before it holds a registration of its own (another device's wrapper may have registered the shared+ weights). A storage that is locked is not unregistered: reclaiming skips it, and a release leaves it registered,+ pending, until the last unlock. A lock that finds a storage being unregistered waits for that to finish: the copies+ that follow are then plain pageable ones. The waiter holds its cache lock, and the unregistering thread needs no+ cache lock, so the wait cannot deadlock.+ """++ def __init__(self) -> None:+ self._registration_lock = threading.Lock()+ self._lookup_lock = threading.Lock()+ # Posted releases (True) and idle marks (False). A finalizer runs in GC context, possibly on a thread that holds+ # one of the locks, so it only enqueues (as SharedCpuWeightsStore.release_deferred does); an idle mark comes+ # from under the cache's lock, which must not wait for a registration. Every registry call applies the queue+ # first, in order, and so does the streamer between them (`drain_deferred`).+ self._deferred: queue.SimpleQueue[tuple[PinHolder, bool]] = queue.SimpleQueue()+ self._entries: dict[_StorageKey, _StorageEntry] = {}+ # Reclaimable entries (registered here, `wanted_by == 0`), the longest unused first, and their bytes.+ self._reclaimable: dict[_StorageKey, None] = {}+ self._reclaimable_bytes = 0+ # Per compute device, the entries some active holder there wants. Mutated under the lookup lock, read without.+ self._wanted_entries_on: dict[torch.device, int] = {}+ self._pinned_bytes = 0+ # Decided by the first registration (`_registration_self_test`).+ self._driver_ok: bool | None = None+ # Storages whose unregistration failed, kept alive for the process lifetime rather than freed while possibly+ # still registered. The cap keeps counting them.+ self._stranded: list[_StorageEntry] = []+ self._cond = threading.Condition()+ # Storages locks hold (count), and storages being unregistered right now. Guarded by `_cond`.+ self._locked: dict[_StorageKey, int] = {}+ self._unregistering: set[_StorageKey] = set()+ # Entries that were dropped while locked, still registered and counted, unregistered once unlocked. A storage+ # registered again meanwhile takes its entry back. Mutated under the registration lock.+ self._pending: dict[_StorageKey, _StorageEntry] = {}+ # Set when an `unlock` freed a pending key: the only thing that makes retrying `_pending` worth a lock.+ self._pending_freed = False++ @contextmanager+ def _registering(self) -> Iterator[None]:+ """The registration lock. A non-blocking drain that lost the lock to this hold (`drain_deferred`) is made up+ for after it: what it would have applied is still posted, and no one else is obliged to retry."""+ try:+ with self._registration_lock:+ yield+ finally:+ self.drain_deferred()++ def _has_work_to_drain(self) -> bool:+ return not self._deferred.empty() or self._pending_freed++ def update(self, holder: PinHolder, storages: Iterable[torch.UntypedStorage], register_new: bool = True) -> None:+ """Mark ``holder`` active and streaming exactly ``storages``, and register those it does not hold yet, as far+ as they fit under the cap. What it holds beyond them stays registered, reclaimable. Never raises a driver+ error. Registration and the first call's self-test run on ``holder.device``.+ ``register_new=False``: the lock did not plan the VRAM for the copies that would follow, so the holder+ registers and joins nothing new; it streams only what it holds already."""+ candidates = {_storage_key(s): s for s in storages if s.nbytes() > 0}+ missing: dict[_StorageKey, torch.UntypedStorage] = {}+ with self._registering():+ self._drain_deferred_locked()+ self._set_wanted_locked(holder, set(candidates), active=True)+ # Joining a storage another holder registered costs nothing, but it starts streaming from it: not in a+ # lock that planned no VRAM for copies in flight (another device may have registered it since).+ for key in candidates.keys() - holder.keys if register_new else ():+ if key in self._entries:+ self._join_locked(holder, key)+ # The rest is registered below only as far as it can fit, so what the cap refuses is not read in on every+ # lock.+ room = PINNED_RAM_CAP_BYTES - self._pinned_bytes + self._reclaimable_bytes+ for key, storage in candidates.items():+ if key in holder.keys or not register_new:+ continue+ if storage.is_pinned(): # Torch's pinned allocator: joining costs no room.+ missing[key] = storage+ elif key[1] <= room:+ room -= key[1]+ missing[key] = storage+ else:+ self._log_cap()+ if self._driver_ok is False:+ return # The self-test failed: nothing registers.+ for storage in missing.values():+ _fault_in(storage)+ # One storage per lock hold: a release (another device's offload or eviction, under its cache lock) waits+ # for at most one registration and the reclaim it needs, not for a whole model's.+ for key, storage in missing.items():+ with self._registering():+ if key in holder.keys or not holder.active or key not in holder.wanted:+ continue # Released or marked idle meanwhile.+ try:+ if key not in self._entries and not self._register_locked(key, storage, holder.device):+ continue+ self._join_locked(holder, key)+ except BaseException:+ # An interrupt between tracking the registration and the join would leave an entry no holder+ # holds, which nothing reclaims. Best effort, like the rest of the interrupt handling here: Python+ # delivers it between any two statements.+ entry = self._entries.get(key)+ if entry is not None and not entry.holders:+ self._drop_locked([entry])+ raise++ def activate(self, holder: PinHolder) -> bool:+ """Mark ``holder`` active again, streaming what it streamed in its last `update`, for a lock that moved+ nothing. False if some of that is not registered (reclaimed, or refused at the cap): `update` it then."""+ with self._registering():+ self._drain_deferred_locked()+ self._set_wanted_locked(holder, holder.wanted, active=True)+ return holder.wanted <= holder.keys++ def idle(self, holder: PinHolder) -> None:+ """Mark the end of the last lock of ``holder``'s model: what it holds stays registered but becomes reclaimable.+ Takes no lock; the next registry call applies it, before it looks for room."""+ self._deferred.put((holder, False))++ def release(self, holder: PinHolder) -> bool:+ """Release everything ``holder`` holds; whether it held anything. Best effort: never raises on a failing+ device."""+ with self._registering():+ self._drain_deferred_locked()+ held = bool(holder.keys)+ self._release_holder_locked(holder)+ return held++ def release_deferred(self, holder: PinHolder) -> None:+ """Post a release without taking a lock. The only entry point that is safe from GC context."""+ self._deferred.put((holder, True))++ def drain_deferred(self) -> None:+ """Apply posted releases and idle marks, and unregister pending entries an `unlock` freed, unless another+ thread holds the registration lock right now: it drains after its hold (`_registering`). Lock-free while+ nothing is posted, so a streamed copy pays for it only when there is something to apply."""+ # Looped: a thread that loses the acquire relies on the holder to drain after its release, and the holder's+ # own drain may have cleared the flag before that thread's unlock set it again.+ while self._has_work_to_drain() and self._registration_lock.acquire(blocking=False):+ try:+ self._drain_deferred_locked()+ finally:+ self._registration_lock.release()++ def is_registered(self, storage: torch.UntypedStorage) -> bool:+ return _storage_key(storage) in self._entries++ def holds_registrations(self) -> bool:+ return bool(self._entries)++ def is_wanted_on(self, storage: torch.UntypedStorage, device: torch.device) -> bool:+ """Whether an active holder computing on ``device`` wants ``storage``. Lock-free, so only a hint: `lookup`+ decides. A stale answer costs a synchronous copy or a lookup that says no."""+ entry = self._entries.get(_storage_key(storage))+ return entry is not None and entry.wanted_on.get(device, 0) > 0++ def wants_anything_on(self, device: torch.device) -> bool:+ """Whether an active holder computing on ``device`` wants any storage. Lock-free, like `is_wanted_on`."""+ return self._wanted_entries_on.get(device, 0) > 0++ def can_register(self, device: torch.device | None = None) -> bool:+ """Whether this driver passed the self-test (run on the first call, on ``device``). Needs a CUDA device."""+ if self._driver_ok is None:+ with self._registering():+ self._decide_driver_locked(device)+ return bool(self._driver_ok)++ def has_room_for_any(self, storages: Iterable[torch.UntypedStorage]) -> bool:+ """Whether any of ``storages`` is registered or could be: the model that streams them has something to stream.+ Advisory and lock-free: the caller holds the cache's lock, which must not wait behind a registration. The+ caller plans its VRAM by the answer and tells `update` (``register_new``), so a change after it does not+ start streaming that nobody reserved room for."""+ room = PINNED_RAM_CAP_BYTES - self._pinned_bytes + self._reclaimable_bytes+ for storage in storages:+ # Cheapest first: `is_pinned` asks the driver, which costs milliseconds over a whole model.+ if storage.nbytes() <= room or _storage_key(storage) in self._entries or storage.is_pinned():+ return True+ return False++ def lock(self, keys: frozenset[_StorageKey]) -> None:+ """Keep ``keys`` from being unregistered until `unlock`: a cached model's cache lock copies from them on its own+ streams (see the class docstring). Waits while any is being unregistered, so those copies never race an+ unregistration. Registering a locked key meanwhile is allowed: the copies are then pageable or pinned, and+ either works. (Best effort under an interrupt: `_register_locked` unregisters a range it may have registered+ without regard to locks.)"""+ with self._cond:+ while not self._unregistering.isdisjoint(keys):+ self._cond.wait()+ for key in keys:+ self._locked[key] = self._locked.get(key, 0) + 1++ def unlock(self, keys: frozenset[_StorageKey]) -> None:+ """Release a `lock`. A storage whose release was deferred is unregistered by the next drain+ (`drain_deferred`), which this makes due."""+ with self._cond:+ for key in keys:+ count = self._locked[key] - 1+ if count:+ self._locked[key] = count+ else:+ del self._locked[key]+ if key in self._pending:+ self._pending_freed = True++ @contextmanager+ def lookup(self, storage: torch.UntypedStorage, device: torch.device) -> Iterator[bool]:+ """Whether a copy of ``storage`` to ``device`` may stream: it is registered and an active holder computing on+ ``device`` wants it. A holder whose lock planned no VRAM for copies in flight never wants what another+ device's holder registered. Held stable for the block: a copy enqueued inside cannot race its+ unregistration."""+ with self._lookup_lock:+ entry = self._entries.get(_storage_key(storage))+ yield entry is not None and entry.wanted_on.get(device, 0) > 0++ def _drain_deferred_locked(self) -> None:+ while True:+ try:+ holder, release = self._deferred.get_nowait()+ except queue.Empty:+ self._unregister_pending_locked()+ return+ if release:+ self._release_holder_locked(holder)+ else:+ self._set_wanted_locked(holder, holder.wanted, active=False)++ def _unregister_pending_locked(self) -> None:+ # Cleared before looking: an unlock that frees a key after this sets it again.+ self._pending_freed = False+ if self._pending:+ self._unregister_locked(list(self._pending.values()))++ def _release_holder_locked(self, holder: PinHolder) -> None:+ self._set_wanted_locked(holder, set(), active=False)+ unheld: list[_StorageEntry] = []+ for key in holder.keys:+ entry = self._entries[key]+ entry.holders.discard(holder)+ if not entry.holders:+ unheld.append(entry)+ holder.keys.clear()+ self._drop_locked(unheld)++ def _join_locked(self, holder: PinHolder, key: _StorageKey) -> None:+ entry = self._entries[key]+ # The holder's side first: an interrupt in between leaves an entry without the holder, which a release drops,+ # not one that no release can reach.+ holder.keys.add(key)+ entry.holders.add(holder)+ if holder.active and key in holder.wanted:+ self._want_locked(entry, holder)++ def _set_wanted_locked(self, holder: PinHolder, wanted: set[_StorageKey], active: bool) -> None:+ before = holder.wanted & holder.keys if holder.active else set()+ holder.wanted, holder.active = wanted, active+ after = wanted & holder.keys if active else set()+ for key in after - before:+ self._want_locked(self._entries[key], holder)+ for key in before - after:+ self._unwant_locked(self._entries[key], holder)++ def _want_locked(self, entry: _StorageEntry, holder: PinHolder) -> None:+ with self._lookup_lock:+ wanted_here = entry.wanted_on.get(holder.device, 0) + 1+ entry.wanted_on[holder.device] = wanted_here+ if wanted_here == 1:+ self._wanted_entries_on[holder.device] = self._wanted_entries_on.get(holder.device, 0) + 1+ if entry.wanted_by == 1 and entry.key in self._reclaimable:+ del self._reclaimable[entry.key]+ self._reclaimable_bytes -= entry.key[1]++ def _unwant_locked(self, entry: _StorageEntry, holder: PinHolder) -> None:+ # Tolerant of a want that an interrupt cut short: this runs from `release`, which never raises.+ with self._lookup_lock:+ wanted_here = entry.wanted_on.get(holder.device, 0) - 1+ if wanted_here > 0:+ entry.wanted_on[holder.device] = wanted_here+ elif entry.wanted_on.pop(holder.device, None) is not None:+ self._wanted_entries_on[holder.device] = max(0, self._wanted_entries_on.get(holder.device, 0) - 1)+ if entry.wanted_by == 0 and entry.registered_here and entry.key not in self._reclaimable:+ self._reclaimable[entry.key] = None+ self._reclaimable_bytes += entry.key[1]++ def _make_room_locked(self, nbytes: int) -> bool:+ """Unregister reclaimable storages, the longest unused first, until ``nbytes`` more fit under the cap; nothing+ if even all of them would not make enough room."""+ shortfall = self._pinned_bytes + nbytes - PINNED_RAM_CAP_BYTES+ if shortfall <= 0:+ return True+ # Storages a cache lock holds are not reclaimed, however long they have been unused.+ with self._cond:+ candidates = [key for key in self._reclaimable if key not in self._locked]+ if shortfall > sum(key[1] for key in candidates):+ return False+ victims: list[_StorageEntry] = []+ for key in candidates:+ victims.append(self._entries[key])+ shortfall -= key[1]+ if shortfall <= 0:+ break+ for entry in victims:+ for holder in entry.holders:+ holder.keys.discard(entry.key)+ entry.holders.clear()+ self._drop_locked(victims)+ # A storage that could not be unregistered stays counted (stranded).+ return self._pinned_bytes + nbytes <= PINNED_RAM_CAP_BYTES++ def _log_cap(self) -> None:+ _log_once(+ "cap",+ logging.INFO,+ f"async_weight_streaming: the pinned-RAM cap of {PINNED_RAM_CAP_BYTES / 2**30:.1f} GiB is reached; "+ "further weights in RAM are copied synchronously.",+ )++ def _decide_driver_locked(self, device: torch.device | None) -> None:+ if self._driver_ok is not None:+ return+ reason = _registration_self_test(device)+ self._driver_ok = reason is None+ if reason is not None:+ _log_once(+ "driver",+ logging.WARNING,+ f"async_weight_streaming: {reason}; weights in RAM are copied synchronously.",+ )++ def _register_locked(self, key: _StorageKey, storage: torch.UntypedStorage, device: torch.device) -> bool:+ """Register ``storage`` and track it in `_entries`; whether it is tracked now."""+ self._decide_driver_locked(device)+ if not self._driver_ok:+ return False+ pending = self._pending.pop(key, None)+ if pending is not None: # Dropped while a lock held it, so still registered.+ with self._lookup_lock:+ self._entries[key] = pending+ return True+ if storage.is_pinned():+ with self._lookup_lock:+ self._entries[key] = _StorageEntry(key, storage, registered_here=False)+ return True+ ptr, nbytes = key+ if not self._make_room_locked(nbytes):+ self._log_cap()+ return False+ assert _runtime is not None # The self-test passed.+ entry = _StorageEntry(key, storage, registered_here=True)+ # Counted before the call: an interrupt that arrives once the range is page-locked must find it counted.+ self._pinned_bytes += nbytes+ try:+ with torch.cuda.device(device):+ error = _runtime.register(ptr, nbytes)+ except BaseException:+ # The call may or may not have registered the range before the interrupt. Unregistering one that is not+ # registered is refused, which is harmless; nothing has copied from it yet, so no copy needs waiting for.+ try:+ _runtime.unregister(ptr)+ finally:+ self._pinned_bytes -= nbytes+ raise+ if error != 0:+ self._pinned_bytes -= nbytes+ _log_once(+ f"register:{error}",+ logging.WARNING,+ f"async_weight_streaming: page-locking {nbytes / 2**20:.1f} MiB of weights failed (CUDA error "+ f"{error}); weights that cannot be page-locked are copied synchronously.",+ )+ return False+ try:+ with self._lookup_lock:+ self._entries[key] = entry+ except BaseException:+ # The range is page-locked: an interrupt here must not leave it untracked and counted forever.+ with self._lookup_lock:+ self._entries.pop(key, None)+ self._unregister_locked([entry])+ raise+ return True++ def _drop_locked(self, entries: list[_StorageEntry]) -> None:+ """Remove entries no holder holds any more, and unregister those registered here."""+ if not entries:+ return+ unregister = [entry for entry in entries if entry.registered_here]+ try:+ with self._lookup_lock:+ for entry in entries:+ del self._entries[entry.key]+ for entry in entries:+ if entry.key in self._reclaimable:+ del self._reclaimable[entry.key]+ self._reclaimable_bytes -= entry.key[1]+ except BaseException:+ # Best effort: what left `_entries` and would be forgotten is kept registered for the process lifetime.+ self._stranded.extend(entry for entry in unregister if entry.key not in self._entries)+ raise+ if unregister:+ self._unregister_locked(unregister)++ def _unregister_locked(self, entries: list[_StorageEntry]) -> None:+ """Unregister ``entries``, which are out of `_entries`, except those a cache lock still holds: they stay+ registered, pending, until the lock ends.++ Best effort: eviction runs this, also from paths that must not raise (a dying worker's last frame). What cannot+ be unregistered is stranded. An interrupt here strands what is left as well before it propagates: dropping+ them would free memory that may still be registered.+ """+ now: list[_StorageEntry] = []+ remaining: list[_StorageEntry] | None = None+ try:+ with self._cond:+ for entry in entries:+ if entry.key in self._locked:+ self._pending[entry.key] = entry+ else:+ self._pending.pop(entry.key, None)+ self._unregistering.add(entry.key)+ now.append(entry)+ if not now:+ return+ remaining = list(now)+ try:+ # Copies the streamers issued before the entries were removed may still be reading them. Everything+ # else that copies from these storages holds a lock on them, which kept them out of `now`.+ _synchronize_issued_copies()+ except Exception as error:+ _log_once("sync", logging.WARNING, f"async_weight_streaming: waiting for copies failed ({error}).")+ self._stranded.extend(remaining)+ return+ assert _runtime is not None # Only storages registered here are unregistered.+ while remaining:+ entry = remaining[-1]+ try:+ error = _runtime.unregister(entry.key[0])+ except Exception:+ error = -1+ remaining.pop()+ if error != 0:+ _log_once(+ f"unregister:{error}", logging.WARNING, f"async_weight_streaming: unpinning failed ({error})."+ )+ self._stranded.append(entry)+ continue+ self._pinned_bytes -= entry.key[1]+ except BaseException:+ # An interrupt before `remaining` exists leaves entries that are out of `_entries` and in neither list.+ self._stranded.extend(+ [e for e in entries if self._pending.get(e.key) is not e] if remaining is None else remaining+ )+ raise+ finally:+ # Covers the moment keys enter `_unregistering`: a key left there would make every later `lock` wait.+ with self._cond:+ self._unregistering.difference_update(entry.key for entry in entries)+ self._cond.notify_all()+++# Process-global: shared CPU weights of several devices are one set of storages.+PINNED_STORAGES = PinnedStorageRegistry()+++@dataclass+class StreamingStats:+ """Counters of one device's streamer. Which path a copy took has no other observable: the output is identical."""++ streamed_tensors: int = 0+ staged_tensors: int = 0+ bounded_waits: int = 0+ max_inflight_bytes: int = 0+++class _DeviceStreamer:+ """Issues asynchronous weight copies to one CUDA device and bounds how many bytes are in flight."""++ def __init__(self, device: torch.device) -> None:+ self.device = device+ self._side = torch.cuda.Stream(device)+ self._lock = threading.Lock()+ # Events recorded on the compute stream after each copy, oldest first, with the bytes they release.+ self._inflight: deque[tuple[torch.cuda.Event, int]] = deque()+ self._inflight_bytes = 0+ self._announced = False+ self._used = False # Copies allocated since the last `release_side_pool`.+ self.stats = StreamingStats()++ def synchronize_copies(self) -> None:+ self._side.synchronize()++ def take_used(self) -> bool:+ with self._lock:+ used, self._used = self._used, False+ return used++ def copy(self, t: torch.Tensor) -> torch.Tensor | None:+ PINNED_STORAGES.drain_deferred()+ storage = t.untyped_storage()+ nbytes = t.nbytes+ if not PINNED_STORAGES.is_wanted_on(storage, self.device) and (+ nbytes > STAGE_MAX_BYTES or not PINNED_STORAGES.wants_anything_on(self.device)+ ):+ return None+ with self._lock:+ self._wait_for_room(nbytes)+ compute = torch.cuda.current_stream(self.device)+ with torch.cuda.stream(self._side):+ # Allocated before the lookup lock, which covers only the check and the enqueue.+ dst = torch.empty(t.shape, dtype=t.dtype, device=self.device)+ self._used = True+ with PINNED_STORAGES.lookup(storage, self.device) as registered:+ if registered:+ dst.copy_(t, non_blocking=True)+ if registered:+ self.stats.streamed_tensors += 1+ if not self._announced:+ self._announced = True+ logger.info(f"async_weight_streaming: weights in RAM stream to {self.device} asynchronously.")+ else:+ if nbytes > STAGE_MAX_BYTES:+ return None+ try:+ staged = torch.empty(t.shape, dtype=t.dtype, pin_memory=True)+ except RuntimeError as error:+ _log_once("stage", logging.WARNING, f"async_weight_streaming: staging failed ({error}).")+ return None+ staged.copy_(t)+ # The staging block returns to torch's pinned pool once the copy reading it has finished.+ dst.copy_(staged, non_blocking=True)+ self.stats.staged_tensors += 1+ # Flush the queued work to the GPU now. On Windows (WDDM), the driver batches submissions; a later host+ # wait on an event whose work is still unsubmitted serialized copy and compute (measured on an RTX 4090+ # with HAGS: 125 ms instead of 68 ms for overlapped copy + GEMM). A query forces the submission: 70 ms.+ # ROCm on an RX 9060 XT did not need it; it is harmless there.+ self._side.query()+ compute.wait_stream(self._side)+ # The allocator hands this block out again only after the compute stream has consumed it, however long+ # the returned tensor lives. A fixed ring of buffers would be overwritten silently in that case.+ dst.record_stream(compute)+ event = torch.cuda.Event()+ event.record(compute)+ compute.query() # Flush, as above.+ self._inflight.append((event, nbytes))+ self._inflight_bytes += nbytes+ self.stats.max_inflight_bytes = max(self.stats.max_inflight_bytes, self._inflight_bytes)+ return dst++ def _wait_for_room(self, nbytes: int) -> None:+ inflight = self._inflight+ while inflight and inflight[0][0].query():+ self._inflight_bytes -= inflight.popleft()[1]+ # A tensor larger than the budget proceeds once nothing else is in flight.+ while inflight and self._inflight_bytes + nbytes > STREAM_BUDGET_BYTES:+ event, done_bytes = inflight.popleft()+ event.synchronize()+ self._inflight_bytes -= done_bytes+ self.stats.bounded_waits += 1+++# One streamer per device, created on first use.+_streamers: dict[torch.device, _DeviceStreamer] = {}+_streamers_lock = threading.Lock()+++def _synchronize_issued_copies() -> None:+ for streamer in list(_streamers.values()):+ streamer.synchronize_copies()+++def _streamer_for(device: torch.device) -> _DeviceStreamer:+ if device.index is None:+ device = torch.device("cuda", torch.cuda.current_device())+ streamer = _streamers.get(device)+ if streamer is None:+ with _streamers_lock:+ streamer = _streamers.get(device)+ if streamer is None:+ streamer = _DeviceStreamer(device)+ _streamers[device] = streamer+ return streamer+++def release_side_pool(device: torch.device) -> None:+ """Return the blocks the side stream's copies left cached, when a lock that streamed to ``device`` has ended.++ Freed copies stay cached for the side stream, and the compute stream cannot reuse them: measured end to end+ (Z-Image and ERNIE-Image on an RTX 4090 at max_cache_vram_gb 8), the process peak rose by 846 MiB in the VAE decode+ after a streamed denoise. ``empty_cache`` releases the unused blocks of every stream, so it runs only after a lock+ that allocated copies, and through `TorchDevice.empty_cache`, which defers while another GPU is mid-session.+ """+ if device.type != "cuda":+ return+ if device.index is None:+ device = torch.device("cuda", torch.cuda.current_device())+ streamer = _streamers.get(device)+ if streamer is None or not streamer.take_used():+ return+ try:+ # Freed copies become free blocks once their copy and the compute stream's reads are done; empty_cache waits+ # for the latter itself.+ streamer.synchronize_copies()+ TorchDevice.empty_cache()+ except Exception as error:+ # Runs as a lock ends; the memory is advisory, the unlock is not.+ _log_once("release", logging.WARNING, f"async_weight_streaming: returning streamed copies failed ({error}).")+++def _is_capturing(device: torch.device) -> bool:+ if device.index == torch.cuda.current_device():+ return torch.cuda.is_current_stream_capturing()+ with torch.cuda.device(device):+ return torch.cuda.is_current_stream_capturing()+++def stream_to_device(t: torch.Tensor, device: torch.device) -> torch.Tensor | None:+ """Copy CPU tensor ``t`` to CUDA ``device`` asynchronously, or return None for the caller's synchronous copy."""+ if not is_async_weight_streaming_enabled() or not is_streamable_tensor(t):+ return None+ if not t.is_contiguous() or (t.requires_grad and torch.is_grad_enabled()):+ return None+ streamer = _streamer_for(device)+ if _is_capturing(streamer.device):+ return None+ return streamer.copy(t)+++def streaming_stats(device: torch.device) -> StreamingStats | None:+ """A snapshot of the counters of ``device``'s streamer, or None if nothing streamed to it yet."""+ if device.index is None:+ device = torch.device("cuda", torch.cuda.current_device())+ streamer = _streamers.get(device)+ return replace(streamer.stats) if streamer is not None else Nonediff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex 02d1c601bb..53c0939366 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -66349,6 +66349,12 @@"description": "Run the matmuls of ComfyUI int8 builds quantized with convrot ('int8_tensorwise' with 'convrot') on the int8 tensor cores instead of dequantizing their weights on every forward (requires an NVIDIA GPU with compute capability 8.0 or newer and Triton; falls back automatically otherwise, including on AMD, Apple and Intel GPUs and the CPU). Speeds up denoising with these builds, but quantizes activations per token as well, so images will differ from the dequantized path at the same seed. The kernels are tuned once per layer shape and token-count bucket: about 35 seconds for the first image after enabling it, about 1-5 seconds for a later size in a new token-count bucket, cached on disk across restarts.","default": false},+ "async_weight_streaming": {+ "type": "boolean",+ "title": "Async Weight Streaming",+ "description": "When a model is only partially loaded into VRAM, copy the weights it streams from RAM to the GPU asynchronously from page-locked RAM on a separate stream, overlapping with the computation, instead of one blocking copy per layer. Speeds up partially loaded models; images stay identical. Requires an NVIDIA or AMD (ROCm) GPU and keep_ram_copy_of_weights; falls back to the blocking copy automatically otherwise (Apple and Intel GPUs, the CPU, and GGUF or other specially quantized weights, which gain nothing from it). Copies in flight take up to about 384MB of VRAM; the model cache keeps that much free for them, so slightly less of such a model stays in VRAM. The RAM copy of the streamed weights is page-locked and stays locked while the model is in the cache, so models taking turns in VRAM lock it once (not swappable; at most 40% of physical RAM, where the weights of models not running are unlocked first); weights loaded from a file mapping are read into RAM when they are first locked. Has no effect on models that fit fully in VRAM.",+ "default": false+ },"ram": {"anyOf": [{@@ -66818,7 +66824,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 show_donation_link: Show the Donate to InvokeAI link in the frontend menus.\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_url: URL of a MySQL 8.4+ or MariaDB 10.11+ database to use instead of the SQLite database in `db_dir`, e.g. `mariadb+pymysql://invokeai:[email protected]/invokeai`. Needs the `mysql` extra. One InvokeAI process uses a database at a time. Read at startup only.\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 prompt_files_dir: Path to the directory holding prompt list files readable by the Prompts from File node. The node cannot read outside this directory.\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 reserve_vram_gb: The amount of VRAM (in GB) to subtract from the model cache's available memory budget. Defaults to 0.\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 int8_compute: Run the matmuls of ComfyUI int8 builds quantized with convrot ('int8_tensorwise' with 'convrot') on the int8 tensor cores instead of dequantizing their weights on every forward (requires an NVIDIA GPU with compute capability 8.0 or newer and Triton; falls back automatically otherwise, including on AMD, Apple and Intel GPUs and the CPU). Speeds up denoising with these builds, but quantizes activations per token as well, so images will differ from the dequantized path at the same seed. The kernels are tuned once per layer shape and token-count bucket: about 35 seconds for the first image after enabling it, about 1-5 seconds for a later size in a new token-count bucket, cached on disk across restarts.\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 rocm_aotriton_experimental: Use AOTriton's fused (flash and memory-efficient) attention kernels on AMD GPUs that PyTorch marks experimental for them, such as the RX 7600/7700/7800 series, Ryzen AI 300/Max and the RX 9060 series, by setting TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL. Without them, attention on those GPUs runs on the slower math kernel, which also needs far more memory. `auto` turns them on only with a ROCm 10 build of PyTorch, and only when every GPU used for generation is one they were measured correct on (so far gfx1200, the RX 9060 series); `on` and `off` decide for any build and GPU. A TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL value already set in the environment takes precedence. Has no effect on other GPUs.<br>Valid values: `auto`, `on`, `off`\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 tiny_autoencoder_previews: Render denoising previews with an installed Tiny AutoEncoder instead of the linear latent projection. Install the matching Tiny AutoEncoder starter model; families without one keep linear previews. A preview costs a few tens of ms and up to about 1.1 GB of transient VRAM on an RTX 4090 (image decoders 0.15-0.65 GB, Wan video windows up to 1.1 GB); a TAE that does not fit in VRAM next to the running model can instead run on the CPU (its `Decode previews on CPU` setting in the model manager): previews are capped at 512 px there and a frame takes about 0.3-0.4 s (TAESDXL, TAEF2), 0.8-1.1 s (TAEW2.1, one frame) or 1.0-1.9 s (Wan two-frame window) on a Ryzen 9 7900 with 8 threads in float32, so previews update less often.\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 attention_backend: Attention kernel for the attention inside diffusion models. `auto` uses PyTorch's exact SDPA kernels ranked flash, cuDNN, memory-efficient, math, taking the first one the GPU and build support for each call; it never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA. `cudnn`, `flash`, `efficient` and `math` rank that PyTorch kernel first for all attention on CUDA and ROCm GPUs, ahead of the `auto` order. That is never exclusive: a call the kernel cannot serve runs on the next kernel, and the log reports that once per node type and reason (not for the PiD decoder, whose attention is ranked the same but not reported). `math` materializes the full attention score matrix, so it is slow and needs much more memory, which the working-memory estimates of most model families do not reserve, so generations can run out of memory; it is meant for debugging. Images can differ slightly between kernels.<br>Valid values: `auto`, `sage`, `cudnn`, `flash`, `efficient`, `math`\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, FLUX.2, Z-Image, Qwen-Image and Qwen-Image-2.1 VAE nodes, the Anima encode, the Z-Image control 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, FLUX.2, Z-Image, Qwen-Image, Qwen-Image-2.1, Krea-2 and Wan decodes, and Qwen-Image-2.1 encodes). Turn off to decode untiled unless tiling is requested; the FLUX.1, FLUX.2 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 (the default). Requires user authentication and authorization; the first visitor creates the administrator account. Set to false for single-user mode, which uses a default system account with administrator privileges and no sign-in: anyone who can reach the server then has full control of it. Single-user mode is deprecated.\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_atlascloud_api_key: API key for Atlas Cloud image generation.\n external_atlascloud_base_url: Base URL override for Atlas Cloud 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 show_donation_link: Show the Donate to InvokeAI link in the frontend menus.\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_url: URL of a MySQL 8.4+ or MariaDB 10.11+ database to use instead of the SQLite database in `db_dir`, e.g. `mariadb+pymysql://invokeai:[email protected]/invokeai`. Needs the `mysql` extra. One InvokeAI process uses a database at a time. Read at startup only.\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 prompt_files_dir: Path to the directory holding prompt list files readable by the Prompts from File node. The node cannot read outside this directory.\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 reserve_vram_gb: The amount of VRAM (in GB) to subtract from the model cache's available memory budget. Defaults to 0.\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 int8_compute: Run the matmuls of ComfyUI int8 builds quantized with convrot ('int8_tensorwise' with 'convrot') on the int8 tensor cores instead of dequantizing their weights on every forward (requires an NVIDIA GPU with compute capability 8.0 or newer and Triton; falls back automatically otherwise, including on AMD, Apple and Intel GPUs and the CPU). Speeds up denoising with these builds, but quantizes activations per token as well, so images will differ from the dequantized path at the same seed. The kernels are tuned once per layer shape and token-count bucket: about 35 seconds for the first image after enabling it, about 1-5 seconds for a later size in a new token-count bucket, cached on disk across restarts.\n async_weight_streaming: When a model is only partially loaded into VRAM, copy the weights it streams from RAM to the GPU asynchronously from page-locked RAM on a separate stream, overlapping with the computation, instead of one blocking copy per layer. Speeds up partially loaded models; images stay identical. Requires an NVIDIA or AMD (ROCm) GPU and keep_ram_copy_of_weights; falls back to the blocking copy automatically otherwise (Apple and Intel GPUs, the CPU, and GGUF or other specially quantized weights, which gain nothing from it). Copies in flight take up to about 384MB of VRAM; the model cache keeps that much free for them, so slightly less of such a model stays in VRAM. The RAM copy of the streamed weights is page-locked and stays locked while the model is in the cache, so models taking turns in VRAM lock it once (not swappable; at most 40% of physical RAM, where the weights of models not running are unlocked first); weights loaded from a file mapping are read into RAM when they are first locked. Has no effect on models that fit fully in VRAM.\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 rocm_aotriton_experimental: Use AOTriton's fused (flash and memory-efficient) attention kernels on AMD GPUs that PyTorch marks experimental for them, such as the RX 7600/7700/7800 series, Ryzen AI 300/Max and the RX 9060 series, by setting TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL. Without them, attention on those GPUs runs on the slower math kernel, which also needs far more memory. `auto` turns them on only with a ROCm 10 build of PyTorch, and only when every GPU used for generation is one they were measured correct on (so far gfx1200, the RX 9060 series); `on` and `off` decide for any build and GPU. A TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL value already set in the environment takes precedence. Has no effect on other GPUs.<br>Valid values: `auto`, `on`, `off`\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 tiny_autoencoder_previews: Render denoising previews with an installed Tiny AutoEncoder instead of the linear latent projection. Install the matching Tiny AutoEncoder starter model; families without one keep linear previews. A preview costs a few tens of ms and up to about 1.1 GB of transient VRAM on an RTX 4090 (image decoders 0.15-0.65 GB, Wan video windows up to 1.1 GB); a TAE that does not fit in VRAM next to the running model can instead run on the CPU (its `Decode previews on CPU` setting in the model manager): previews are capped at 512 px there and a frame takes about 0.3-0.4 s (TAESDXL, TAEF2), 0.8-1.1 s (TAEW2.1, one frame) or 1.0-1.9 s (Wan two-frame window) on a Ryzen 9 7900 with 8 threads in float32, so previews update less often.\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 attention_backend: Attention kernel for the attention inside diffusion models. `auto` uses PyTorch's exact SDPA kernels ranked flash, cuDNN, memory-efficient, math, taking the first one the GPU and build support for each call; it never selects a quantized one. `sage` uses SageAttention 2 for the models listed in the SageAttention docs: faster, most at high resolutions and for video, but quantized, so images differ slightly from `auto` at the same seed. SageAttention is installed separately and needs an NVIDIA GPU with compute capability 8.0 or newer; masked attention, text encoders and VAEs keep PyTorch SDPA. `cudnn`, `flash`, `efficient` and `math` rank that PyTorch kernel first for all attention on CUDA and ROCm GPUs, ahead of the `auto` order. That is never exclusive: a call the kernel cannot serve runs on the next kernel, and the log reports that once per node type and reason (not for the PiD decoder, whose attention is ranked the same but not reported). `math` materializes the full attention score matrix, so it is slow and needs much more memory, which the working-memory estimates of most model families do not reserve, so generations can run out of memory; it is meant for debugging. Images can differ slightly between kernels.<br>Valid values: `auto`, `sage`, `cudnn`, `flash`, `efficient`, `math`\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, FLUX.2, Z-Image, Qwen-Image and Qwen-Image-2.1 VAE nodes, the Anima encode, the Z-Image control 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, FLUX.2, Z-Image, Qwen-Image, Qwen-Image-2.1, Krea-2 and Wan decodes, and Qwen-Image-2.1 encodes). Turn off to decode untiled unless tiling is requested; the FLUX.1, FLUX.2 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 (the default). Requires user authentication and authorization; the first visitor creates the administrator account. Set to false for single-user mode, which uses a default system account with administrator privileges and no sign-in: anyone who can reach the server then has full control of it. Single-user mode is deprecated.\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_atlascloud_api_key: API key for Atlas Cloud image generation.\n external_atlascloud_base_url: Base URL override for Atlas Cloud 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 4b962627dd..09562edb27 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -25278,6 +25278,7 @@ export type components = {* 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.* int8_compute: Run the matmuls of ComfyUI int8 builds quantized with convrot ('int8_tensorwise' with 'convrot') on the int8 tensor cores instead of dequantizing their weights on every forward (requires an NVIDIA GPU with compute capability 8.0 or newer and Triton; falls back automatically otherwise, including on AMD, Apple and Intel GPUs and the CPU). Speeds up denoising with these builds, but quantizes activations per token as well, so images will differ from the dequantized path at the same seed. The kernels are tuned once per layer shape and token-count bucket: about 35 seconds for the first image after enabling it, about 1-5 seconds for a later size in a new token-count bucket, cached on disk across restarts.+ * async_weight_streaming: When a model is only partially loaded into VRAM, copy the weights it streams from RAM to the GPU asynchronously from page-locked RAM on a separate stream, overlapping with the computation, instead of one blocking copy per layer. Speeds up partially loaded models; images stay identical. Requires an NVIDIA or AMD (ROCm) GPU and keep_ram_copy_of_weights; falls back to the blocking copy automatically otherwise (Apple and Intel GPUs, the CPU, and GGUF or other specially quantized weights, which gain nothing from it). Copies in flight take up to about 384MB of VRAM; the model cache keeps that much free for them, so slightly less of such a model stays in VRAM. The RAM copy of the streamed weights is page-locked and stays locked while the model is in the cache, so models taking turns in VRAM lock it once (not swappable; at most 40% of physical RAM, where the weights of models not running are unlocked first); weights loaded from a file mapping are read into RAM when they are first locked. Has no effect on models that fit fully in VRAM.* 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.* 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.* 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.@@ -25695,6 +25696,12 @@ export type components = {* @default false*/int8_compute?: boolean;+ /**+ * Async Weight Streaming+ * @description When a model is only partially loaded into VRAM, copy the weights it streams from RAM to the GPU asynchronously from page-locked RAM on a separate stream, overlapping with the computation, instead of one blocking copy per layer. Speeds up partially loaded models; images stay identical. Requires an NVIDIA or AMD (ROCm) GPU and keep_ram_copy_of_weights; falls back to the blocking copy automatically otherwise (Apple and Intel GPUs, the CPU, and GGUF or other specially quantized weights, which gain nothing from it). Copies in flight take up to about 384MB of VRAM; the model cache keeps that much free for them, so slightly less of such a model stays in VRAM. The RAM copy of the streamed weights is page-locked and stays locked while the model is in the cache, so models taking turns in VRAM lock it once (not swappable; at most 40% of physical RAM, where the weights of models not running are unlocked first); weights loaded from a file mapping are read into RAM when they are first locked. Has no effect on models that fit fully in VRAM.+ * @default false+ */+ async_weight_streaming?: boolean;/*** Ram* @description 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.diff --git a/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.json b/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.jsonindex 8843037aa6..d644c3ee21 100644--- a/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.json+++ b/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.json@@ -77,6 +77,7 @@{"s":"configuration/multi-user-mode/admin-guide","t":"Multi-User Administrator Guide","d":"Set up the first administrator, manage accounts, and keep a shared InvokeAI server safe.","c":3,"h":[["roles","Roles"],["set-up-multi-user-mode","Set up multi-user mode"],["verify-local-only-access","Verify local-only access"],["single-user-mode","Single-user mode"],["upgrading-from-single-user-mode","Upgrading from single-user mode"],["if-you-have-already-upgraded","If you have already upgraded"],["what-happens-to-existing-data","What happens to existing data"],["upgrading-from-v6","Upgrading from v6"],["manage-users","Manage users"],["deleting-a-user","Deleting a user"],["the-shared-queue","The shared queue"],["security","Security"],["passwords","Passwords"],["sessions","Sessions"],["signing-key","Signing key"],["model-downloads","Model downloads"],["node-filesystem-access","Node filesystem access"],["https-and-internet-access","HTTPS and internet access"],["backups","Backups"],["troubleshooting","Troubleshooting"],["not-supported","Not supported"],["more","More"]]},{"s":"configuration/multi-user-mode/api-guide","t":"Multi-User API Guide","d":"How to authenticate and interact with the InvokeAI API in multi-user mode.","c":3,"h":[["overview","Overview"],["single-user-vs-multi-user-mode","Single-User vs Multi-User Mode"],["authentication-multi-user-mode-only","Authentication (Multi-User Mode Only)"],["authentication-flow","Authentication Flow"],["login-endpoint","Login Endpoint"],["using-the-token","Using the Token"],["token-expiration","Token Expiration"],["logout-endpoint","Logout Endpoint"],["code-examples","Code Examples"],["python","Python"],["javascripttypescript","JavaScript/TypeScript"],["curl","cURL"],["api-endpoint-changes","API Endpoint Changes"],["authentication-required","Authentication Required"],["user-scoped-resources","User-Scoped Resources"],["administrator-endpoints","Administrator Endpoints"],["error-responses","Error Responses"],["multiuser-api-endpoints","Multiuser API Endpoints"],["authentication-endpoints","Authentication Endpoints"],["user-management-endpoints-admin-only","User Management Endpoints (Admin Only)"],["board-endpoints","Board Endpoints"],["project-endpoints","Project Endpoints"],["best-practices","Best Practices"],["token-storage","Token Storage"],["error-handling","Error Handling"],["rate-limiting","Rate Limiting"],["connection-management","Connection Management"],["migration-guide","Migration Guide"],["updating-existing-code","Updating Existing Code"],["backward-compatibility","Backward Compatibility"],["programmatic-graph-execution","Programmatic Graph Execution"],["openapiswagger-documentation","OpenAPI/Swagger Documentation"],["security-considerations","Security Considerations"],["https","HTTPS"],["token-security","Token Security"],["input-validation","Input Validation"],["troubleshooting","Troubleshooting"],["common-issues","Common Issues"],["additional-resources","Additional Resources"]]},{"s":"configuration/multi-user-mode/user-guide","t":"Multi-User Guide","d":"Sign in to a shared InvokeAI server, share boards and workflows, and work alongside other users.","c":3,"h":[["signing-in","Signing in"],["your-account","Your account"],["what-you-can-do","What you can do"],["working-with-your-content-in-multi-user-mode","Working with Your Content in Multi-User Mode"],["image-boards","Image Boards"],["workflows","Workflows"],["the-generation-queue","The Generation Queue"],["switching-between-single-user-and-multi-user-mode","Switching Between Single-User and Multi-User Mode"],["troubleshooting","Troubleshooting"]]},+{"s":"configuration/optimization/async-weight-streaming","t":"Async Weight Streaming","d":"Copy the layers of a partially loaded model from RAM to the GPU while the previous layers compute, with identical images.","c":3,"h":[["requirements","Requirements"],["turning-it-on","Turning it on"],["memory","Memory"]]},{"s":"configuration/optimization/fp8-compute","t":"FP8 Compute","d":"Run checkpoints published in FP8 on the FP8 tensor cores of RTX 40-series and newer GPUs, and what it means for repeatable images.","c":3,"h":[["requirements","Requirements"],["turning-it-on","Turning it on"],["when-the-model-asks-for-full-precision","When the model asks for full precision"]]},{"s":"configuration/optimization/fp8-storage","t":"FP8 Storage","d":"Halve a full-precision model's VRAM by keeping its weights in FP8 on the GPU, per model, from the Model Manager.","c":3,"h":[["what-it-applies-to","What it applies to"],["by-file-format","By file format"],["by-model","By model"],["by-gpu","By GPU"],["turning-it-on","Turning it on"],["when-installing","When installing"],["checkpoints-that-are-already-fp8","Checkpoints that are already FP8"],["quality","Quality"],["troubleshooting","Troubleshooting"],["reporting-an-issue","Reporting an issue"]]},{"s":"configuration/optimization/int8-compute","t":"int8 Compute","d":"Run ComfyUI int8 builds on the int8 tensor cores of RTX 30-series and newer NVIDIA GPUs, up to twice as fast.","c":3,"h":[["requirements","Requirements"],["turning-it-on","Turning it on"],["what-stays-on-the-default-path","What stays on the default path"]]},diff --git a/tests/app/invocations/test_ideogram4_denoise_branches.py b/tests/app/invocations/test_ideogram4_denoise_branches.pyindex 54a32449c6..f767ca2212 100644--- a/tests/app/invocations/test_ideogram4_denoise_branches.py+++ b/tests/app/invocations/test_ideogram4_denoise_branches.py@@ -107,9 +107,13 @@ class _LoadedModel:finally:self._released.append(self._key)- def unload_from_vram(self, vram_bytes_to_free: int, keep_required_weights_in_vram: bool = False) -> int:- self.unloaded.append((vram_bytes_to_free, keep_required_weights_in_vram))- return vram_bytes_to_free+ def hold_resident_bytes(self, max_resident_bytes: int) -> int:+ # The cache's trim: required weights stay behind. Its reserve for streaming is the cache's to test.+ excess = self.resident_weight_bytes - max_resident_bytes+ if excess <= 0:+ return 0+ self.unloaded.append((excess, True))+ return excessdef _context(diff --git a/tests/app/invocations/test_wan_denoise.py b/tests/app/invocations/test_wan_denoise.pyindex ebd2e1972a..8d56852440 100644--- a/tests/app/invocations/test_wan_denoise.py+++ b/tests/app/invocations/test_wan_denoise.py@@ -38,6 +38,7 @@ from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (ConditioningFieldData,WanConditioningInfo,)+from invokeai.backend.util.devices import TorchDeviceclass _ZeroTransformer(nn.Module):@@ -284,7 +285,11 @@ class TestWanDenoiseShapes:assert _get_wan_transformer_working_mem_bytes(torch.device("cpu"), enabled=True) is Noneassert _get_wan_transformer_working_mem_bytes(torch.device("cuda"), enabled=False) is None- def test_expert_swapper_passes_aggressive_working_memory_to_model_cache(self) -> None:+ def test_expert_swapper_passes_aggressive_working_memory_to_model_cache(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ emptied: list[bool] = []+ monkeypatch.setattr(TorchDevice, "empty_cache", lambda *args, **kwargs: emptied.append(True))transformer = _ZeroTransformer()loaded = MagicMock()loaded.supports_partial_loading = True@@ -292,6 +297,7 @@ class TestWanDenoiseShapes:# here or the swapper's arithmetic compares against a mock.loaded.resident_weight_bytes = 5 * 2**30loaded.weight_bytes = 14 * 2**30+ loaded.hold_resident_bytes.return_value = 3 * 2**30device_context = MagicMock()device_context.__enter__.return_value = (None, transformer)loaded.model_on_device.return_value = device_context@@ -313,7 +319,9 @@ class TestWanDenoiseShapes:swapper.close()loaded.model_on_device.assert_called_once_with(working_mem_bytes=working_mem_bytes)- loaded.unload_from_vram.assert_called_once_with(3 * 2**30, keep_required_weights_in_vram=True)+ loaded.hold_resident_bytes.assert_called_once_with(2 * 2**30)+ # One flush when the swapper closes, one more for the weights the trim moved to RAM.+ assert len(emptied) == 2@pytest.mark.parametrize("packed", [True, False], ids=["gguf", "dense"])def test_expert_swapper_reserves_a_gguf_experts_dequant_transient(self, packed: bool) -> None:@@ -331,6 +339,7 @@ class TestWanDenoiseShapes:loaded.model = torch.nn.Sequential(linear)loaded.supports_partial_loading = Trueloaded.resident_weight_bytes = 0+ loaded.hold_resident_bytes.return_value = 0loaded.weight_bytes = 0device_context = MagicMock()device_context.__enter__.return_value = (None, transformer)@@ -359,11 +368,16 @@ class TestWanDenoiseShapes:# Zero, which the cache reads as its default working memory.assert kwargs["working_mem_bytes"] == 0- def test_expert_swapper_does_not_trim_when_residency_is_already_targeted(self) -> None:+ def test_expert_swapper_does_not_trim_when_residency_is_already_targeted(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ emptied: list[bool] = []+ monkeypatch.setattr(TorchDevice, "empty_cache", lambda *args, **kwargs: emptied.append(True))transformer = _ZeroTransformer()loaded = MagicMock()loaded.supports_partial_loading = Trueloaded.resident_weight_bytes = 2 * 2**30+ loaded.hold_resident_bytes.return_value = 0 # Nothing above the limit: the cache moves nothing.device_context = MagicMock()device_context.__enter__.return_value = (None, transformer)loaded.model_on_device.return_value = device_context@@ -385,7 +399,8 @@ class TestWanDenoiseShapes:swapper.close()loaded.model_on_device.assert_called_once_with(working_mem_bytes=working_mem_bytes)- loaded.unload_from_vram.assert_not_called()+ loaded.hold_resident_bytes.assert_called_once_with(2 * 2**30)+ assert len(emptied) == 1, "nothing moved to RAM: only the flush of closing the swapper"def test_expert_swapper_skips_residency_trim_without_partial_loading(self) -> None:transformer = _ZeroTransformer()@@ -414,7 +429,7 @@ class TestWanDenoiseShapes:# Not the aggressive budget: without partial loading the expert asks only for its own (here zero)# dequantization transient, which the cache reads as its default working memory.loaded.model_on_device.assert_called_once_with(working_mem_bytes=0)- loaded.unload_from_vram.assert_not_called()+ loaded.hold_resident_bytes.assert_not_called()context.logger.warning.assert_called_once()def test_cfg_doubles_transformer_calls(self, fake_model_root) -> None:diff --git a/tests/backend/model_manager/load/model_cache/cached_model/test_async_weight_streaming.py b/tests/backend/model_manager/load/model_cache/cached_model/test_async_weight_streaming.pynew file mode 100644index 0000000000..744983047c--- /dev/null+++ b/tests/backend/model_manager/load/model_cache/cached_model/test_async_weight_streaming.py@@ -0,0 +1,1074 @@+"""Async weight streaming (`async_weight_streaming`) of partially loaded models.++Forwards run on the GPU only (bf16, or fp32 for the GGUF layer). Bit-identity against the synchronous path is the+correctness gate: a copy that is read before it lands, or a block reused too early, shows up as different output, not+as an error. Which path a copy took has no other observable than the streamer's counters.+"""++import logging+import mmap+import os+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import MagicMock++import gguf+import numpy as np+import pytest+import torch+from safetensors.torch import load_file, save_file++from invokeai.app.services.config import config_default+from invokeai.backend.model_manager.load.load_base import LoadedModelWithoutConfig+from invokeai.backend.model_manager.load.model_cache.cached_model.cached_model_with_partial_load import (+ CachedModelWithPartialLoad,+)+from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache+from invokeai.backend.model_manager.load.model_cache.shared_cpu_weights import SharedCpuWeightsStore+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast import weight_streaming+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (+ apply_custom_layers_to_model,+)+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.weight_streaming import (+ set_async_weight_streaming_enabled,+ stream_to_device,+ streaming_stats,+)+from tests.backend.quantization.gguf.test_ggml_tensor import quantize_tensor++requires_cuda = pytest.mark.skipif(not torch.cuda.is_available(), reason="Requires CUDA.")++DEVICE = torch.device("cuda")+DIM, HIDDEN = 512, 2048 # bf16 weights of 2 MiB: above the staging limit, so they stream only when registered.+_LOGGER = weight_streaming.logger.name+++class _Mlp(torch.nn.Module):+ def __init__(self, blocks: int = 6):+ super().__init__()+ # A root buffer sits in no autocast module: the cache keeps it on the device, and repairs it there.+ self.register_buffer("scale", torch.ones(DIM))+ layers: list[torch.nn.Module] = []+ for _ in range(blocks):+ layers += [torch.nn.Linear(DIM, HIDDEN), torch.nn.GELU(), torch.nn.Linear(HIDDEN, DIM)]+ self.layers = torch.nn.Sequential(*layers)++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ return self.layers(x) * self.scale+++def _build_model() -> _Mlp:+ torch.manual_seed(0)+ model = _Mlp().to(torch.bfloat16)+ apply_custom_layers_to_model(model)+ return model+++def _input(dim: int = DIM, dtype: torch.dtype = torch.bfloat16) -> torch.Tensor:+ generator = torch.Generator(device=DEVICE).manual_seed(1)+ return torch.randn(64, dim, device=DEVICE, dtype=dtype, generator=generator)+++def _settle(cached: CachedModelWithPartialLoad, vram_bytes: int) -> None:+ """What a lock does: load, then pin outside the cache's locks (`LoadedModelWithoutConfig._lock_on_device`)."""+ cached.partial_load_to_vram(vram_bytes)+ cached.pin_streamed_weights()+++def _half_loaded(model: torch.nn.Module, **kwargs) -> CachedModelWithPartialLoad:+ cached = CachedModelWithPartialLoad(model=model, compute_device=DEVICE, keep_ram_copy=True, **kwargs)+ _settle(cached, cached.total_bytes() // 2)+ assert 0 < cached.cur_vram_bytes() < cached.total_bytes()+ return cached++[email protected]_grad()+def _forward(model: torch.nn.Module, *, streaming: bool, x: torch.Tensor | None = None) -> torch.Tensor:+ set_async_weight_streaming_enabled(streaming)+ try:+ out = model(_input() if x is None else x)+ torch.cuda.synchronize()+ return out+ finally:+ set_async_weight_streaming_enabled(True)+++def _cpu_storages(model: torch.nn.Module) -> list[torch.UntypedStorage]:+ return [p.untyped_storage() for p in model.parameters() if p.device.type == "cpu"]+++def _stats() -> weight_streaming.StreamingStats:+ stats = streaming_stats(DEVICE)+ return stats if stats is not None else weight_streaming.StreamingStats()+++def _messages(caplog: pytest.LogCaptureFixture, text: str) -> list[str]:+ return [r.getMessage() for r in caplog.records if r.name == _LOGGER and text in r.getMessage()]+++def _mock_logger() -> MagicMock:+ logger = MagicMock()+ logger.getEffectiveLevel.return_value = logging.INFO+ return logger+++def _cache_with_room_for_half_of(model: torch.nn.Module) -> ModelCache:+ """A cache on cuda:0 whose VRAM cap leaves room for half of ``model``. The cache counts every allocation on the+ device as in use, so the cap sits above what is allocated already."""+ total_bytes = sum(p.nbytes for p in model.parameters()) + sum(b.nbytes for b in model.buffers())+ return ModelCache(+ execution_device_working_mem_gb=0.0,+ enable_partial_loading=True,+ keep_ram_copy_of_weights=True,+ max_vram_cache_size_gb=(torch.cuda.memory_allocated(DEVICE) + total_bytes / 2) / 2**30,+ execution_device="cuda:0",+ storage_device="cpu",+ logger=_mock_logger(),+ shared_cpu_weights=None,+ )+++class _Streaming:+ def __init__(self, registry: weight_streaming.PinnedStorageRegistry, holders: list[weight_streaming.PinHolder]):+ self.registry = registry+ self.holders = holders++ def holds_anything(self) -> bool:+ self.registry.drain_deferred()+ return any(holder.keys for holder in self.holders)+++def streaming(monkeypatch: pytest.MonkeyPatch):+ """Feature on, with a fresh registry, streamers and log-once state. Every holder is recorded, so teardown can+ check that nothing stays pinned and release what a failing test left, keeping later tests independent."""+ registry = weight_streaming.PinnedStorageRegistry()+ holders: list[weight_streaming.PinHolder] = []++ class RecordingHolder(weight_streaming.PinHolder):+ __slots__ = ()++ def __init__(self, device: torch.device) -> None:+ super().__init__(device)+ holders.append(self)++ monkeypatch.setattr(weight_streaming, "PINNED_STORAGES", registry)+ monkeypatch.setattr(weight_streaming, "PinHolder", RecordingHolder)+ monkeypatch.setattr(weight_streaming, "_streamers", {})+ monkeypatch.setattr(weight_streaming, "_logged", set())+ monkeypatch.setattr(weight_streaming, "_runtime", None)+ set_async_weight_streaming_enabled(True)+ state = _Streaming(registry, holders)+ yield state+ set_async_weight_streaming_enabled(None)+ if torch.cuda.is_available():+ torch.cuda.synchronize()+ leaked = state.holds_anything()+ for holder in holders:+ registry.release(holder)+ assert not leaked, "a test left storages registered"+ assert not registry.holds_registrations(), "a storage stayed registered after every holder released it"+ # Counters a later registration decides by; a leak here would refuse or over-reclaim.+ assert registry._pinned_bytes == 0 and registry._reclaimable_bytes == 0 and not registry._reclaimable+++def test_a_device_without_streaming_pins_nothing_and_says_so_once(streaming, caplog: pytest.LogCaptureFixture):+ """Runs without a GPU: the meta device stands in for MPS, XPU and the CPU."""+ caplog.set_level(logging.INFO, logger=_LOGGER)+ model = _build_model()+ cached = CachedModelWithPartialLoad(model=model, compute_device=torch.device("meta"), keep_ram_copy=True)++ _settle(cached, cached.total_bytes() // 2)+ _settle(cached, cached.total_bytes())++ assert not streaming.holders+ assert cached.weight_streaming_reserve_bytes() == 0+ assert len(_messages(caplog, "not used on meta")) == 1+++@requires_cuda+def test_off_by_default_pins_and_streams_nothing(streaming, monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setattr(config_default, "get_config", lambda: config_default.InvokeAIAppConfig())+ set_async_weight_streaming_enabled(None)+ model = _build_model()++ cached = _half_loaded(model)+ with torch.no_grad():+ model(_input())++ assert not streaming.holders+ assert cached.weight_streaming_reserve_bytes() == 0+ assert streaming_stats(DEVICE) is None+++@requires_cuda+def test_streamed_forward_is_bit_identical_to_the_synchronous_path(streaming, caplog: pytest.LogCaptureFixture):+ caplog.set_level(logging.INFO, logger=_LOGGER)+ model = _build_model()+ cached = _half_loaded(model)+ assert all(s.is_pinned() for s in _cpu_storages(model))++ reference = _forward(model, streaming=False)+ streamed = _forward(model, streaming=True)+ streamed_again = _forward(model, streaming=True)++ assert _stats().streamed_tensors > 0+ assert torch.equal(streamed, reference)+ assert torch.equal(streamed_again, reference)+ assert len(_messages(caplog, "stream to cuda:")) == 1+ cached.release_pinned_weights()+++@requires_cuda+def test_bytes_in_flight_stay_within_the_budget_while_the_gpu_lags(streaming, monkeypatch: pytest.MonkeyPatch):+ budget = 3 * 2**20+ monkeypatch.setattr(weight_streaming, "STREAM_BUDGET_BYTES", budget)+ model = _build_model()+ cached = _half_loaded(model)+ largest = max(p.nbytes for p in model.parameters() if p.device.type == "cpu")+ reference = _forward(model, streaming=False)++ with torch.no_grad():+ # Hold the compute stream back so the CPU runs ahead: without the bound every copy would be issued at once.+ torch.cuda._sleep(20_000_000)+ streamed = model(_input())+ torch.cuda.synchronize()++ stats = _stats()+ assert stats.bounded_waits > 0+ assert stats.max_inflight_bytes <= budget + largest+ assert torch.equal(streamed, reference)+ cached.release_pinned_weights()+++def _counting_registrations(monkeypatch: pytest.MonkeyPatch) -> list[int]:+ """Runs the self-test, then records the size of every registration the driver gets."""+ assert weight_streaming.PINNED_STORAGES.can_register()+ runtime = weight_streaming._runtime+ assert runtime is not None+ sizes: list[int] = []+ register = runtime.register++ def counting(ptr: int, nbytes: int) -> int:+ sizes.append(nbytes)+ return register(ptr, nbytes)++ monkeypatch.setattr(runtime, "register", counting)+ return sizes+++@requires_cuda+def test_pins_outlast_unloads_and_are_released_with_the_model(streaming):+ model = _build_model()+ cached = _half_loaded(model)+ offloaded = _cpu_storages(model)+ # A second lock, which brings back only the root buffer, keeps the same pins: one release still unpins everything.+ cached.partial_unload_from_vram(1) # The root buffer, which the next load brings back first.+ _settle(cached, model.scale.nbytes)+ assert [s.data_ptr() for s in _cpu_storages(model)] == [s.data_ptr() for s in offloaded]+ assert all(s.is_pinned() for s in offloaded)++ cached.full_unload_from_vram()+ assert all(s.is_pinned() for s in offloaded), "a model moved to RAM keeps its pins for its next lock"+ cached.full_load_to_vram()+ cached.pin_streamed_weights()+ assert all(s.is_pinned() for s in offloaded), "and so does a fully resident one, for its next unload"++ cached.partial_unload_from_vram(cached.total_bytes() // 2)+ _settle(cached, 0)+ assert streaming.holds_anything()+ set_async_weight_streaming_enabled(False)+ _settle(cached, 0)+ assert not streaming.holds_anything(), "switching the setting off releases the pins on the next lock"+ set_async_weight_streaming_enabled(True)++ _settle(cached, 0)+ assert streaming.holds_anything(), "switching it back on pins again"+ cached.release_pinned_weights()+ assert not any(s.is_pinned() for s in _cpu_storages(model))++ cached.partial_unload_from_vram(1) # Stale pins, so the next lock reaches the retired check.+ holders = len(streaming.holders)+ _settle(cached, model.scale.nbytes)+ assert not streaming.holds_anything(), "a released model must not pin again"+ assert len(streaming.holders) == holders, "nor register anything only to release it"+++@requires_cuda+def test_repairing_required_weights_pins_what_an_unload_left_in_ram(streaming):+ model = _build_model()+ cached = _half_loaded(model)+ assert model.layers[0].weight.device.type == "cuda"++ # The root buffer comes first in the state dict, so this offloads it and the first weight.+ cached.partial_unload_from_vram(model.scale.nbytes + 1)+ weight = model.layers[0].weight+ assert model.scale.device.type == "cpu" and weight.device.type == "cpu"+ assert not streaming.registry.is_registered(weight.untyped_storage())++ assert cached.repair_required_tensors_on_compute_device() == 1+ cached.pin_streamed_weights()++ assert streaming.registry.is_registered(weight.untyped_storage())+ cached.release_pinned_weights()+++@requires_cuda+def test_a_dropped_wrapper_releases_its_pins(streaming):+ model = _build_model()+ cached = _half_loaded(model)+ offloaded = _cpu_storages(model)++ del cached++ assert not streaming.holds_anything()+ assert not any(s.is_pinned() for s in offloaded)+++@requires_cuda+def test_eviction_from_the_model_cache_releases_the_pins(streaming):+ model = _build_model()+ cache = _cache_with_room_for_half_of(model)+ try:+ cache.put("m", model)+ record = cache.get("m")+ for _ in range(2):+ with LoadedModelWithoutConfig(record, cache):+ pass+ cached = record.cached_model+ assert isinstance(cached, CachedModelWithPartialLoad)+ assert 0 < cached.cur_vram_bytes() < cached.total_bytes()+ offloaded = _cpu_storages(model)+ assert all(s.is_pinned() for s in offloaded)++ assert cache.drop_model("m") == 1++ assert not streaming.holds_anything()+ assert not any(s.is_pinned() for s in offloaded)+ # Its next load locks the weights again: said once, so a RAM cache too small for a generation shows.+ logged = cache._logger.logger # The mock behind the cache's prefixing adapter.+ hints = [c for c in logged.method_calls if "max_cache_ram_gb" in str(c)]+ assert len(hints) == 1+ finally:+ cache.shutdown()+++@requires_cuda+def test_a_streaming_lock_reserves_vram_for_the_copies_in_flight(streaming, monkeypatch: pytest.MonkeyPatch):+ budget = 4 * 2**20+ monkeypatch.setattr(weight_streaming, "STREAM_BUDGET_BYTES", budget)++ def resident_bytes(enabled: bool) -> int:+ set_async_weight_streaming_enabled(enabled)+ model = _build_model()+ cache = _cache_with_room_for_half_of(model)+ try:+ cache.put("m", model)+ record = cache.get("m")+ cache.lock(record, None)+ resident = record.cached_model.cur_vram_bytes()+ cache.unlock(record)+ cache.drop_model("m")+ return resident+ finally:+ cache.shutdown()++ without_streaming = resident_bytes(False)+ with_streaming = resident_bytes(True)++ # Loading picks whole tensors, so the difference may miss the budget by the small ones (biases).+ assert without_streaming - with_streaming >= budget - 2**16+++@requires_cuda+def test_a_tiny_pinned_ram_cap_streams_through_the_fallbacks_identically(streaming, monkeypatch: pytest.MonkeyPatch):+ # Room for one bias: the weights copy synchronously, the other biases through staging buffers.+ monkeypatch.setattr(weight_streaming, "PINNED_RAM_CAP_BYTES", HIDDEN * 2)+ model = _build_model()+ cached = _half_loaded(model)+ reference = _forward(model, streaming=False)++ streamed = _forward(model, streaming=True)++ stats = _stats()+ assert stats.streamed_tensors > 0+ assert stats.staged_tensors > 0, "small tensors past the cap stage through pinned buffers"+ assert torch.equal(streamed, reference)+ cached.release_pinned_weights()+++@requires_cuda+def test_wrappers_sharing_cpu_weights_hold_one_registration_each(streaming):+ """The multi-GPU shape: two cached wrappers (one per device) aliasing the same canonical CPU tensors."""+ store = SharedCpuWeightsStore()+ model_a, model_b = _build_model(), _build_model()+ cached_a = _half_loaded(model_a, shared_store=store, cache_key="k")+ cached_b = _half_loaded(model_b, shared_store=store, cache_key="k")+ shared = _cpu_storages(model_b)+ assert {s.data_ptr() for s in shared} <= {s.data_ptr() for s in _cpu_storages(model_a)}+ reference = _forward(model_b, streaming=False)++ cached_a.release_pinned_weights()+ cached_a.release_shared_weights()++ assert all(s.is_pinned() for s in shared)+ assert torch.equal(_forward(model_b, streaming=True), reference)+ assert _stats().streamed_tensors > 0++ cached_b.release_pinned_weights()+ cached_b.release_shared_weights()+ assert not any(s.is_pinned() for s in shared)+++def _pack_back_to_back(model: torch.nn.Module, tmp_path: Path) -> None:+ """Every tensor its own storage, laid end to end from an address that is not page-aligned."""+ state_dict = model.state_dict()+ offset = 2680+ buffer = np.empty(offset + sum(t.nbytes for t in state_dict.values()), dtype=np.uint8)+ packed = {}+ for key, tensor in state_dict.items():+ view = buffer[offset : offset + tensor.nbytes]+ view[:] = tensor.contiguous().view(torch.uint8).reshape(-1).numpy()+ packed[key] = torch.from_numpy(view).view(tensor.dtype).reshape(tensor.shape)+ offset += tensor.nbytes+ model.load_state_dict(packed, assign=True)+++def _load_from_safetensors(model: torch.nn.Module, tmp_path: Path) -> None:+ """``load_file`` returns the tensors back to back inside one mapping of the file, as model loaders keep them."""+ path = tmp_path / "model.safetensors"+ save_file({k: v.contiguous() for k, v in model.state_dict().items()}, str(path))+ model.load_state_dict(load_file(str(path)), assign=True)+++@requires_cuda[email protected]("layout", [_pack_back_to_back, _load_from_safetensors], ids=["adjacent", "safetensors"])+def test_storages_sharing_pages_all_stream(streaming, layout, tmp_path: Path, caplog: pytest.LogCaptureFixture):+ caplog.set_level(logging.INFO, logger=_LOGGER)+ model = _build_model()+ layout(model, tmp_path)+ cached = _half_loaded(model)+ offloaded = _cpu_storages(model)+ reference = _forward(model, streaming=False)++ streamed = _forward(model, streaming=True)++ stats = _stats()+ assert stats.streamed_tensors == len(offloaded)+ assert stats.staged_tensors == 0+ assert torch.equal(streamed, reference)+ assert not [r for r in caplog.records if r.name == _LOGGER and r.levelno >= logging.WARNING]+ cached.release_pinned_weights()+ assert not any(s.is_pinned() for s in offloaded)+++class _TensorSubclass(torch.Tensor):+ pass+++@requires_cuda+def test_ineligible_tensors_fall_back_to_the_synchronous_copy(streaming):+ weight = torch.randn(HIDDEN, DIM)+ holder = weight_streaming.PinHolder(DEVICE)+ streaming.registry.update(holder, [weight.untyped_storage()])+ assert weight.is_pinned()++ assert stream_to_device(weight.t(), DEVICE) is None, "non-contiguous"+ assert stream_to_device(weight.as_subclass(_TensorSubclass), DEVICE) is None, "subclass"+ assert stream_to_device(torch.nn.Parameter(weight), DEVICE) is None, "requires grad with grad enabled"+ set_async_weight_streaming_enabled(False)+ assert stream_to_device(weight, DEVICE) is None, "feature off"+ set_async_weight_streaming_enabled(True)++ streamed = stream_to_device(weight, DEVICE)+ assert streamed is not None+ assert torch.equal(streamed.cpu(), weight)++ graph = torch.cuda.CUDAGraph()+ counter = torch.zeros(1, device=DEVICE)+ with torch.cuda.graph(graph):+ captured = stream_to_device(weight, DEVICE)+ counter.add_(1)+ assert captured is None, "a copy cannot be enqueued into a graph capture"++ streaming.registry.release(holder)+ assert not weight.is_pinned()+++@requires_cuda+def test_a_gguf_layer_loads_and_runs_with_streaming_on(streaming):+ """GGMLTensor has no storage of its own to page-lock; its layer keeps its own transfer."""+ torch.manual_seed(0)+ ggml_layer = torch.nn.Linear(256, 64)+ ggml_layer.weight = torch.nn.Parameter(quantize_tensor(ggml_layer.weight, gguf.GGMLQuantizationType.Q8_0))+ ggml_layer.bias = torch.nn.Parameter(quantize_tensor(ggml_layer.bias, gguf.GGMLQuantizationType.Q8_0))+ model = torch.nn.Sequential(torch.nn.Linear(64, 256), ggml_layer)+ apply_custom_layers_to_model(model)+ cached = CachedModelWithPartialLoad(model=model, compute_device=DEVICE, keep_ram_copy=True)++ _settle(cached, 0)+ x = _input(64, torch.float32)+ reference = _forward(model, streaming=False, x=x)+ streamed = _forward(model, streaming=True, x=x)++ assert torch.equal(streamed, reference)+ assert _stats().streamed_tensors > 0, "the plain layer still streams"+ plain = model[0]+ assert cached.weight_streaming_reserve_bytes() == plain.weight.nbytes + plain.bias.nbytes+ cached.release_pinned_weights()+++@requires_cuda+def test_without_a_ram_copy_nothing_is_pinned_and_the_log_says_why(streaming, caplog: pytest.LogCaptureFixture):+ caplog.set_level(logging.INFO, logger=_LOGGER)+ model = _build_model()+ cached = CachedModelWithPartialLoad(model=model, compute_device=DEVICE, keep_ram_copy=False)++ _settle(cached, cached.total_bytes() // 2)+ _settle(cached, cached.total_bytes() // 2)+ reference = _forward(model, streaming=False)+ streamed = _forward(model, streaming=True)++ assert not streaming.holders+ assert cached.weight_streaming_reserve_bytes() == 0+ assert torch.equal(streamed, reference)+ stats = _stats()+ assert stats.streamed_tensors == 0 and stats.staged_tensors == 0, "staging alone buys nothing"+ assert len(_messages(caplog, "keep_ram_copy_of_weights")) == 1+ assert not _messages(caplog, "stream to")+++@requires_cuda+def test_a_storage_the_driver_refuses_stays_pageable_and_still_copies(streaming, caplog: pytest.LogCaptureFixture):+ caplog.set_level(logging.INFO, logger=_LOGGER)+ page = mmap.PAGESIZE+ buffer = (torch.arange(64 * page, dtype=torch.int32) % 251).to(torch.uint8)+ storage = buffer.untyped_storage()+ # Register an aligned range inside the storage behind the registry's back, so registering the storage fails.+ inner = (storage.data_ptr() // page + 8) * page+ cudart = torch.cuda.cudart()+ assert int(cudart.cudaHostRegister(inner, 8 * page, 1)) == 0+ other = torch.randn(HIDDEN, DIM)+ holder = weight_streaming.PinHolder(DEVICE)+ try:+ streaming.registry.update(holder, [storage, other.untyped_storage()])++ assert not streaming.registry.is_registered(storage)+ assert streaming.registry.is_registered(other.untyped_storage())+ assert len(_messages(caplog, "page-locking")) == 1+ # The failure's pending error would surface in the next allocation that reaches the driver.+ torch.cuda.empty_cache()+ torch.empty(48 * 2**20, dtype=torch.uint8, device=DEVICE).fill_(1)+ copied = stream_to_device(buffer, DEVICE)+ assert copied is not None and torch.equal(copied.cpu(), buffer)+ assert _stats().staged_tensors == 1+ finally:+ streaming.registry.release(holder)+ torch.cuda.synchronize()+ assert int(cudart.cudaHostUnregister(inner)) == 0+++@requires_cuda+def test_a_driver_that_rounds_registrations_to_pages_keeps_the_synchronous_copy(+ streaming, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture+):+ caplog.set_level(logging.INFO, logger=_LOGGER)+ monkeypatch.setattr(+ weight_streaming,+ "_registration_self_test",+ lambda device=None: "this driver does not page-lock memory by exact ranges, so neighbours could not be copied",+ )+ model = _build_model()+ cached = _half_loaded(model)+ reference = _forward(model, streaming=False)++ streamed = _forward(model, streaming=True)++ assert not streaming.holds_anything()+ assert cached.weight_streaming_reserve_bytes() == 0+ assert _stats().streamed_tensors == 0+ assert torch.equal(streamed, reference)+ assert len(_messages(caplog, "exact ranges")) == 1+ cached.release_pinned_weights()+++@requires_cuda+def test_an_eviction_during_the_first_pin_leaves_nothing_registered(streaming, monkeypatch: pytest.MonkeyPatch):+ model = _build_model()+ cached = CachedModelWithPartialLoad(model=model, compute_device=DEVICE, keep_ram_copy=True)+ cached.partial_load_to_vram(cached.total_bytes() // 2)+ # The lock plans the streaming VRAM, so this pin would register (without the eviction).+ assert cached.weight_streaming_reserve_bytes() > 0+ update = streaming.registry.update++ def evicted_while_registering(holder, storages, **kwargs):+ # The cache evicts the record (another thread, under its own lock) before this update registers.+ cached.release_pinned_weights()+ update(holder, storages, **kwargs)++ monkeypatch.setattr(streaming.registry, "update", evicted_while_registering)+ cached.pin_streamed_weights()++ assert not streaming.holds_anything()+ assert not any(s.is_pinned() for s in _cpu_storages(model))+++@requires_cuda+def test_weights_an_unload_left_in_ram_stream_after_the_next_lock(streaming):+ model = _build_model()+ cached = _half_loaded(model)+ cached.partial_unload_from_vram(DIM * HIDDEN * 2, keep_required_weights_in_vram=True)+ offloaded = _cpu_storages(model)+ assert not all(streaming.registry.is_registered(s) for s in offloaded), "an unload does not pin"++ _settle(cached, 0) # A lock that moves nothing.++ assert all(streaming.registry.is_registered(s) for s in offloaded)+ _forward(model, streaming=True)+ assert _stats().streamed_tensors == len(offloaded)+ cached.release_pinned_weights()+++@requires_cuda+def test_models_taking_turns_in_vram_register_their_weights_once(streaming, monkeypatch: pytest.MonkeyPatch):+ """A text encoder and a transformer that do not fit together evict each other on every generation."""+ sizes = _counting_registrations(monkeypatch)+ turns = [+ (model, CachedModelWithPartialLoad(model=model, compute_device=DEVICE, keep_ram_copy=True))+ for model in (_build_model(), _build_model())+ ]+ streamed: list[torch.UntypedStorage] = []+ first_pins = 0++ for turn in range(3):+ for model, cached in turns:+ for _, other in turns:+ other.full_unload_from_vram()+ _settle(cached, cached.total_bytes() // 2)+ _forward(model, streaming=True)+ cached.mark_streamed_weights_idle() # What the cache does when the lock ends.+ if turn == 0:+ streamed += _cpu_storages(model)+ if turn == 0:+ first_pins = len(sizes)++ assert first_pins > 0 and len(sizes) == first_pins+ assert all(s.is_pinned() for s in streamed)+ for _, cached in turns:+ cached.release_pinned_weights()+++@requires_cuda+def test_an_idle_model_gives_a_streaming_one_only_the_room_it_lacks(streaming, monkeypatch: pytest.MonkeyPatch):+ sizes = _counting_registrations(monkeypatch)+ idle_model, busy_model = _build_model(), _build_model()+ cache = _cache_with_room_for_half_of(idle_model)+ try:+ cache.put("idle", idle_model)+ record = cache.get("idle")+ # The streaming reserve takes the half the cap leaves, so only the root buffer stays resident.+ with LoadedModelWithoutConfig(record, cache):+ resident = record.cached_model.cur_vram_bytes()+ # The end of that lock marked its weights idle.+ idle_streamed = _cpu_storages(idle_model)+ idle_bytes = sum(s.nbytes() for s in idle_streamed)+ largest = max(s.nbytes() for s in idle_streamed)+ assert all(s.is_pinned() for s in idle_streamed)+ busy = CachedModelWithPartialLoad(model=busy_model, compute_device=DEVICE, keep_ram_copy=True)+ busy.partial_load_to_vram(busy.total_bytes() // 2)+ busy_streamed = _cpu_storages(busy_model)+ busy_bytes = sum(s.nbytes() for s in busy_streamed)+ monkeypatch.setattr(weight_streaming, "PINNED_RAM_CAP_BYTES", idle_bytes + busy_bytes // 2)++ busy.pin_streamed_weights()++ assert all(s.is_pinned() for s in busy_streamed), "the streaming model gets the room it lacks"+ kept = sum(s.nbytes() for s in idle_streamed if s.is_pinned())+ assert idle_bytes - busy_bytes // 2 - largest <= kept <= idle_bytes - busy_bytes // 2, "and only that much"++ busy.mark_streamed_weights_idle()+ busy.full_unload_from_vram() # Gives the cache back the VRAM it saw.+ registered_before = sum(sizes)+ with LoadedModelWithoutConfig(record, cache):+ assert record.cached_model.cur_vram_bytes() == resident+ assert all(s.is_pinned() for s in idle_streamed), "its next lock pins again"+ assert sum(sizes) - registered_before == idle_bytes - kept, "paying only for what it gave"+ busy.release_pinned_weights()+ cache.drop_model("idle")+ finally:+ cache.shutdown()+++@requires_cuda+def test_only_the_last_unlock_makes_the_pins_reclaimable(streaming, monkeypatch: pytest.MonkeyPatch):+ """Two overlapping locks of one record, as a session and the image index worker take them (nested here: the lock+ count does not depend on which thread holds it)."""+ model = _build_model()+ cache = _cache_with_room_for_half_of(model)+ other = weight_streaming.PinHolder(DEVICE)+ taker = torch.empty(2 * 2**20, dtype=torch.uint8)+ try:+ cache.put("m", model)+ record = cache.get("m")+ with LoadedModelWithoutConfig(record, cache):+ streamed = _cpu_storages(model)+ monkeypatch.setattr(+ weight_streaming, "PINNED_RAM_CAP_BYTES", sum(s.nbytes() for s in streamed) + taker.nbytes // 2+ )+ with LoadedModelWithoutConfig(record, cache):+ pass+ streaming.registry.update(other, [taker.untyped_storage()])+ assert all(s.is_pinned() for s in streamed) and not taker.is_pinned(), "the model is still locked"++ streaming.registry.update(other, [taker.untyped_storage()])++ assert taker.is_pinned(), "after the last unlock its pins make room"+ streaming.registry.release(other)+ cache.drop_model("m")+ finally:+ cache.shutdown()+++@requires_cuda+def test_shared_weights_one_device_still_streams_stay_pinned_when_the_other_goes_idle(+ streaming, monkeypatch: pytest.MonkeyPatch+):+ store = SharedCpuWeightsStore()+ model_a, model_b = _build_model(), _build_model()+ cached_a = _half_loaded(model_a, shared_store=store, cache_key="k")+ cached_b = _half_loaded(model_b, shared_store=store, cache_key="k")+ shared = _cpu_storages(model_b)+ assert {s.data_ptr() for s in shared} == {s.data_ptr() for s in _cpu_storages(model_a)}+ other = weight_streaming.PinHolder(DEVICE)+ taker = torch.empty(2 * 2**20, dtype=torch.uint8)+ monkeypatch.setattr(weight_streaming, "PINNED_RAM_CAP_BYTES", sum(s.nbytes() for s in shared) + taker.nbytes // 2)++ cached_a.mark_streamed_weights_idle()+ streaming.registry.update(other, [taker.untyped_storage()])++ assert all(s.is_pinned() for s in shared) and not taker.is_pinned()+ streaming.registry.release(other)+ for cached in (cached_a, cached_b):+ cached.release_pinned_weights()+ cached.release_shared_weights()+++@requires_cuda+def test_weights_a_lock_moves_to_ram_stream_for_the_rest_of_it(streaming, monkeypatch: pytest.MonkeyPatch):+ """A node that makes room within its lock, as Wan's second expert and Ideogram 4's second branch do."""+ monkeypatch.setattr(weight_streaming, "STREAM_BUDGET_BYTES", 2 * 2**20) # Leaves weights resident.+ model = _build_model()+ cache = _cache_with_room_for_half_of(model)+ try:+ cache.put("m", model)+ loaded = LoadedModelWithoutConfig(cache.get("m"), cache)+ with loaded:+ resident = sum(p.nbytes for p in model.parameters() if p.device.type == "cuda")+ assert resident > 0++ loaded.unload_from_vram(resident, keep_required_weights_in_vram=True)++ assert all(p.device.type == "cpu" for p in model.parameters())+ assert all(s.is_pinned() for s in _cpu_storages(model))+ reference = _forward(model, streaming=False)+ assert torch.equal(_forward(model, streaming=True), reference)+ assert _stats().streamed_tensors == len(_cpu_storages(model)), "the rest of the lock streams them"+ cache.drop_model("m")+ finally:+ cache.shutdown()+++def _unpinned_half_loaded_mlp() -> tuple[torch.nn.Module, CachedModelWithPartialLoad]:+ model = _build_model()+ cached = CachedModelWithPartialLoad(model=model, compute_device=DEVICE, keep_ram_copy=True)+ cached.partial_load_to_vram(cached.total_bytes() // 2)+ assert 0 < cached.cur_vram_bytes() < cached.total_bytes()+ return model, cached+++@requires_cuda+def test_registered_weights_no_active_holder_wants_copy_synchronously_and_stage_nothing(streaming):+ """The copy path asks whether a holder computing on the device wants the storage, not whether it is registered:+ an idle holder keeps its pins, and neither streams nor opens the staging gate for the small weights."""+ model, _ = _unpinned_half_loaded_mlp()+ storages = _cpu_storages(model)+ holder = weight_streaming.PinHolder(DEVICE)+ streaming.registry.update(holder, storages)+ streaming.registry.idle(holder)+ streaming.registry.drain_deferred()+ assert all(s.is_pinned() for s in storages)+ reference = _forward(model, streaming=False)++ assert torch.equal(_forward(model, streaming=True), reference)++ stats = _stats()+ assert stats.streamed_tensors == 0 and stats.staged_tensors == 0+ assert streaming.registry.activate(holder)+ assert torch.equal(_forward(model, streaming=True), reference)+ assert _stats().streamed_tensors == len(storages)+ streaming.registry.release(holder)++[email protected](torch.cuda.device_count() < 2, reason="Requires two CUDA devices.")+def test_weights_another_device_registered_stay_synchronous_until_a_holder_here_joins(streaming):+ """Multi-GPU: the holder on cuda:1 registered the shared weights; a lock on cuda:0 that planned no VRAM for+ copies in flight (`register_new=False`) must not stream them."""+ model, _ = _unpinned_half_loaded_mlp()+ storages = _cpu_storages(model)+ reference = _forward(model, streaming=False)+ other_device = weight_streaming.PinHolder(torch.device("cuda", 1))+ streaming.registry.update(other_device, storages)+ here = weight_streaming.PinHolder(DEVICE)+ streaming.registry.update(here, storages, register_new=False)+ assert all(s.is_pinned() for s in storages)++ assert torch.equal(_forward(model, streaming=True), reference)++ stats = _stats()+ assert stats.streamed_tensors == 0 and stats.staged_tensors == 0+ streaming.registry.update(here, storages)+ assert torch.equal(_forward(model, streaming=True), reference)+ assert _stats().streamed_tensors == len(storages)+ streaming.registry.release(here)+ streaming.registry.release(other_device)+++@requires_cuda+def test_a_model_locked_again_keeps_its_pins_when_another_reaches_the_cap(streaming, monkeypatch: pytest.MonkeyPatch):+ running, other = _build_model(), _build_model()+ cached_running = _half_loaded(running)+ cached_running.mark_streamed_weights_idle()+ _settle(cached_running, 0) # Its next lock, which moves nothing.+ streamed = _cpu_storages(running)+ streamed_bytes = sum(s.nbytes() for s in streamed)+ monkeypatch.setattr(weight_streaming, "PINNED_RAM_CAP_BYTES", streamed_bytes + streamed_bytes // 2)++ cached_other = _half_loaded(other)++ assert all(s.is_pinned() for s in streamed)+ assert not all(s.is_pinned() for s in _cpu_storages(other)), "what does not fit copies synchronously"+ cached_running.release_pinned_weights()+ cached_other.release_pinned_weights()+++@requires_cuda+def test_a_model_reuses_the_room_of_its_own_pins_that_moved_to_vram(streaming, monkeypatch: pytest.MonkeyPatch):+ model = _build_model()+ cached = CachedModelWithPartialLoad(model=model, compute_device=DEVICE, keep_ram_copy=True)+ cached.partial_load_to_vram(cached.total_bytes() // 2)+ first = _cpu_storages(model)+ monkeypatch.setattr(weight_streaming, "PINNED_RAM_CAP_BYTES", sum(s.nbytes() for s in first) * 2 // 3)+ cached.pin_streamed_weights()+ assert not all(s.is_pinned() for s in first), "the cap leaves part of it pageable"++ _settle(cached, cached.total_bytes() // 4) # More of it in VRAM: a shorter tail streams.++ tail = _cpu_storages(model)+ assert sum(s.nbytes() for s in tail) <= weight_streaming.PINNED_RAM_CAP_BYTES, "the tail fits by itself"+ assert all(s.is_pinned() for s in tail), "the pins now in VRAM made room for it"+ cached.release_pinned_weights()+++@requires_cuda+def test_only_weights_of_the_ram_copy_are_pinned(streaming):+ model = _build_model()+ cached = _half_loaded(model)+ layer = model.layers[-1]+ assert layer.weight.device.type == "cpu" and layer.weight.is_pinned()+ # A holder casting a layer in place, as the SD VAE nodes upcast the VAE.+ layer.weight.data = layer.weight.data.float()+ cast = layer.weight.untyped_storage()+ cached.partial_unload_from_vram(1) # The root buffer: the next lock pins again.++ _settle(cached, model.scale.nbytes)++ assert not streaming.registry.is_registered(cast)+ assert all(streaming.registry.is_registered(s) for s in _cpu_storages(model) if s.data_ptr() != cast.data_ptr())+ cached.restore_counted_dtypes()+ cached.release_pinned_weights()+++@requires_cuda+def test_a_lock_that_moves_nothing_pins_again_what_was_reclaimed(streaming, monkeypatch: pytest.MonkeyPatch):+ """A lock that moves nothing must still pin again what another model reclaimed since the last one."""+ torch.manual_seed(0)+ model = torch.nn.Sequential(torch.nn.Linear(64, 256), torch.nn.Linear(256, 64))+ apply_custom_layers_to_model(model)+ cached = CachedModelWithPartialLoad(model=model, compute_device=DEVICE, keep_ram_copy=True)+ _settle(cached, 0)+ storages = _cpu_storages(model)+ assert cached.cur_vram_bytes() == 0 and all(s.is_pinned() for s in storages)+ cached.mark_streamed_weights_idle()+ monkeypatch.setattr(weight_streaming, "PINNED_RAM_CAP_BYTES", 256 * 2**10)+ other = weight_streaming.PinHolder(DEVICE)+ taker = torch.empty(200 * 2**10, dtype=torch.uint8)+ streaming.registry.update(other, [taker.untyped_storage()])+ assert taker.is_pinned() and not all(s.is_pinned() for s in storages)+ streaming.registry.idle(other)++ _settle(cached, 0)+ _forward(model, streaming=True, x=torch.randn(4, 64, device=DEVICE))++ assert all(s.is_pinned() for s in storages)+ assert _stats().streamed_tensors == len(storages)+ streaming.registry.release(other)+ cached.release_pinned_weights()+++class _PageRoundingRuntime:+ """Refuses the second registration of the self-test's neighbouring pair, as a driver that rounds registrations to+ pages would: by really registering over the range it still holds, so the refusal is a real error of the real+ runtime. Tracks what it holds, so the test can check that the self-test leaves nothing registered."""++ def __init__(self, real) -> None:+ self._real = real+ self.held: set[int] = set()++ def register(self, ptr: int, nbytes: int) -> int:+ if self.held:+ return self._real.register(next(iter(self.held)), nbytes)+ error = self._real.register(ptr, nbytes)+ if error == 0:+ self.held.add(ptr)+ return error++ def unregister(self, ptr: int) -> int:+ self.held.discard(ptr)+ return self._real.unregister(ptr)+++@requires_cuda[email protected]("failure", ["page-rounding driver", "no runtime library found"])+def test_a_failing_self_test_leaves_no_error_for_the_next_allocation(+ streaming, monkeypatch: pytest.MonkeyPatch, failure: str+):+ """The self-test runs inside a model load; an error it left would fail that load's next allocation, and a+ registration it left would outlive its buffer and break copies from whatever the allocator puts there next."""+ runtime = None+ if failure == "page-rounding driver":+ runtime = _PageRoundingRuntime(weight_streaming._find_runtime())+ monkeypatch.setattr(weight_streaming, "_find_runtime", lambda: runtime)+ else:+ monkeypatch.setattr(weight_streaming, "_find_runtime", lambda: None)+ # Free room inside a live segment, as during a model load: allocations served from it never reach cudaMalloc, so+ # they cannot absorb a pending error. The first allocation below comes from there; the second needs a new segment,+ # and cudaMalloc is where a pending error would surface.+ torch.cuda.empty_cache()+ segment = torch.empty(160 * 2**20, dtype=torch.uint8, device=DEVICE)+ del segment+ live = torch.empty(16 * 2**20, dtype=torch.uint8, device=DEVICE)++ assert weight_streaming._registration_self_test() is not None+ assert weight_streaming._runtime is None+ assert runtime is None or not runtime.held++ torch.empty(64 * 2**20, dtype=torch.uint8, device=DEVICE).fill_(1)+ torch.empty(256 * 2**20, dtype=torch.uint8, device=DEVICE).fill_(1)+ del live+++@requires_cuda+def test_the_end_of_a_streaming_lock_returns_the_copies_cached_for_the_side_stream(streaming):+ model = _build_model()+ cache = _cache_with_room_for_half_of(model)+ try:+ cache.put("m", model)+ loaded = LoadedModelWithoutConfig(cache.get("m"), cache)+ with loaded:+ _forward(model, streaming=True)+ assert _stats().streamed_tensors > 0+ torch.cuda.synchronize()+ cached_while_locked = torch.cuda.memory_reserved(DEVICE) - torch.cuda.memory_allocated(DEVICE)+ cached_after = torch.cuda.memory_reserved(DEVICE) - torch.cuda.memory_allocated(DEVICE)+ cache.drop_model("m")+ finally:+ cache.shutdown()++ # Blocks in segments that still hold live tensors stay; the copies' blocks go.+ assert cached_after < cached_while_locked+++class _InvisibleRuntime:+ """A runtime copy torch does not use: its registrations succeed, but torch does not see the memory as pinned."""++ def register(self, ptr: int, nbytes: int) -> int:+ return 0++ def unregister(self, ptr: int) -> int:+ return 0+++class _StuckRuntime:+ """Registrations it reports cannot be undone. Registers nothing for real, so no memory stays page-locked."""++ def register(self, ptr: int, nbytes: int) -> int:+ return 0++ def unregister(self, ptr: int) -> int:+ return 1+++def test_a_self_test_buffer_that_cannot_be_unpinned_is_never_freed(monkeypatch: pytest.MonkeyPatch):+ stranded: list[torch.Tensor] = []+ monkeypatch.setattr(weight_streaming, "_self_test_stranded", stranded)+ monkeypatch.setattr(weight_streaming, "_find_runtime", _StuckRuntime)+ monkeypatch.setattr(weight_streaming, "_runtime", None)++ assert weight_streaming._registration_self_test() == "unpinning a test buffer failed"++ # The whole-storage buffer is the one left registered.+ assert any(t.nbytes == 2 * weight_streaming._PAGE_SIZE for t in stranded)+++class _LastUnpinFailsRuntime:+ """Unregisters for real, but reports the self-test's last unregistration, on its success path, as failed."""++ def __init__(self, real) -> None:+ self._real = real+ self._unregistered = 0++ def register(self, ptr: int, nbytes: int) -> int:+ return self._real.register(ptr, nbytes)++ def unregister(self, ptr: int) -> int:+ self._unregistered += 1+ error = self._real.unregister(ptr)+ return 1 if self._unregistered == 3 else error+++@requires_cuda+def test_a_self_test_whose_last_unpin_fails_does_not_pass(streaming, monkeypatch: pytest.MonkeyPatch):+ runtime = _LastUnpinFailsRuntime(weight_streaming._find_runtime())+ monkeypatch.setattr(weight_streaming, "_find_runtime", lambda: runtime)+ monkeypatch.setattr(weight_streaming, "_self_test_stranded", [])++ assert weight_streaming._registration_self_test() == "unpinning a test buffer failed"+ assert weight_streaming._runtime is None+++@requires_cuda+def test_a_runtime_whose_registrations_torch_cannot_see_disables_registration(+ streaming, monkeypatch: pytest.MonkeyPatch+):+ monkeypatch.setattr(weight_streaming, "_find_runtime", _InvisibleRuntime)++ reason = weight_streaming._registration_self_test()++ assert reason is not None and "not the one torch uses" in reason+ assert weight_streaming._runtime is None+++def test_the_runtime_torch_links_is_preferred_over_another_wheels_copy(monkeypatch: pytest.MonkeyPatch):+ """Linux layout: torch's runtime sits in the ``nvidia`` wheel, another package may bring its own copy."""+ site = os.path.join(os.sep, "venv", "site-packages")+ other = os.path.join(site, "aaa_other", "lib", "libcudart.so.12")+ torchs = os.path.join(site, "nvidia", "cu13", "lib", "libcudart.so.13")+ maps = [SimpleNamespace(path=other), SimpleNamespace(path=torchs)]+ monkeypatch.setattr(weight_streaming.psutil, "Process", lambda: SimpleNamespace(memory_maps=lambda: maps))+ monkeypatch.setattr(torch.version, "hip", None)+ monkeypatch.setattr(torch.version, "cuda", "13.0")+ opened: list[str] = []+ monkeypatch.setattr(weight_streaming.ctypes, "CDLL", lambda path: opened.append(path) or MagicMock())++ assert weight_streaming._find_runtime() is not None+ assert opened == [torchs]diff --git a/tests/backend/model_manager/load/model_cache/conftest.py b/tests/backend/model_manager/load/model_cache/conftest.pyindex c4240fb922..3b7f1ebf6e 100644--- a/tests/backend/model_manager/load/model_cache/conftest.py+++ b/tests/backend/model_manager/load/model_cache/conftest.py@@ -1,4 +1,7 @@+from contextlib import nullcontext+import pytest+import torch@pytest.fixture(autouse=True)@@ -10,3 +13,38 @@ def _no_windows_video_memory_budget(monkeypatch: pytest.MonkeyPatch) -> None:making the expected figures depend on the machine running the suite. Tests of the cap patch it back in."""monkeypatch.setattr("invokeai.backend.util.devices.video_memory_budget", lambda device: None)+++class FakeRuntime:+ """A page-locking runtime that registers nothing for real. `log` records every call, in order."""++ def __init__(self) -> None:+ self.log: list[tuple[str, int]] = []+ self.registered: set[int] = set()++ def register(self, ptr: int, nbytes: int) -> int:+ self.log.append(("register", ptr))+ self.registered.add(ptr)+ return 0++ def unregister(self, ptr: int) -> int:+ self.log.append(("unregister", ptr))+ self.registered.discard(ptr)+ return 0+++def fake_streaming(monkeypatch: pytest.MonkeyPatch):+ """A fresh registry on a `FakeRuntime`, with streaming possible on whatever device: `(registry, runtime)`."""+ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast import weight_streaming++ registry = weight_streaming.PinnedStorageRegistry()+ runtime = FakeRuntime()+ monkeypatch.setattr(weight_streaming, "PINNED_STORAGES", registry)+ monkeypatch.setattr(weight_streaming, "_runtime", runtime)+ monkeypatch.setattr(weight_streaming, "_registration_self_test", lambda device=None: None)+ monkeypatch.setattr(weight_streaming, "can_stream_weights_to", lambda device, has_ram_copy: has_ram_copy)+ monkeypatch.setattr(weight_streaming, "_streamers", {})+ # Registration selects the model's device, which does not exist here.+ monkeypatch.setattr(torch.cuda, "device", lambda device: nullcontext())+ return registry, runtimediff --git a/tests/backend/model_manager/load/model_cache/test_model_cache_weight_streaming_reserve.py b/tests/backend/model_manager/load/model_cache/test_model_cache_weight_streaming_reserve.pynew file mode 100644index 0000000000..92892a34aa--- /dev/null+++ b/tests/backend/model_manager/load/model_cache/test_model_cache_weight_streaming_reserve.py@@ -0,0 +1,424 @@+"""The cache's VRAM bookkeeping for `async_weight_streaming`, on the CPU.++A streaming lock keeps `weight_streaming_reserve_bytes()` free for the copies in flight. The reserve arithmetic lives in+`ModelCache._load_locked_model` and `hold_model_residency`, so these tests give the cache a fake GPU's free memory and a+runtime that registers nothing for real. The registry itself is tested in `test_pinned_storage_registry.py`, the+streaming on a GPU in `cached_model/test_async_weight_streaming.py`.+"""++import logging+import threading+from unittest.mock import MagicMock++import pytest+import torch++from invokeai.backend.model_manager.load.model_cache.cached_model.cached_model_with_partial_load import (+ CachedModelWithPartialLoad,+)+from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast import weight_streaming+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (+ apply_custom_layers_to_model,+)++MB = 2**20+RESERVE = 5 * MB+WEIGHT_MB = 8 # Per layer, in fp32.+LAYERS = 4+++class _Layers(torch.nn.Module):+ def __init__(self) -> None:+ super().__init__()+ self.layers = torch.nn.ModuleList(torch.nn.Linear(WEIGHT_MB * MB // 4, 1, bias=False) for _ in range(LAYERS))+++def _model() -> _Layers:+ model = _Layers()+ apply_custom_layers_to_model(model)+ return model+++class _FakeVram:+ """The device's free memory as the cache sees it. Moving weights to RAM grows it by what was asked."""++ def __init__(self, available: int) -> None:+ self.available = available+ self.loads: list[int] = [] # The budget of every move to VRAM.+ self.unloads: list[int] = [] # The bytes every move to RAM was asked for.++ def attach(self, cache: ModelCache) -> None:+ cache._get_vram_available = lambda working_mem_bytes=None, honor_cap=True: self.available # type: ignore+ cache._offload_unlocked_models = lambda *args, **kwargs: 0 # type: ignore+ cache._move_model_to_vram = self._move_to_vram # type: ignore+ cache._move_model_to_ram = self._move_to_ram # type: ignore+ cache._release_allocator_blocks_for_reserve = lambda working_mem_bytes: None # type: ignore++ def _move_to_vram(self, cache_entry, vram_available, max_move_bytes=None):+ self.loads.append(vram_available)+ return 0, False++ def _move_to_ram(self, cache_entry, vram_bytes_to_free, keep_required_weights_in_vram=None):+ self.unloads.append(vram_bytes_to_free)+ self.available += vram_bytes_to_free+ return vram_bytes_to_free+++def cache():+ logger = MagicMock()+ logger.getEffectiveLevel.return_value = logging.INFO+ cache = ModelCache(+ execution_device_working_mem_gb=0.0,+ enable_partial_loading=True,+ keep_ram_copy_of_weights=True,+ execution_device="cpu",+ storage_device="cpu",+ logger=logger,+ )+ cache._execution_device = torch.device("cuda") # Policy only: every device touch is replaced below.+ yield cache+ cache._execution_device = torch.device("cpu")+ cache.shutdown()+++def reserve(monkeypatch: pytest.MonkeyPatch) -> int:+ """Streaming is possible and wants `RESERVE` for a model that streams."""+ monkeypatch.setattr(CachedModelWithPartialLoad, "weight_streaming_reserve_bytes", lambda self: RESERVE)+ return RESERVE+++def _record(cache: ModelCache):+ cache.put("m", _model())+ record = cache.get("m")+ assert isinstance(record.cached_model, CachedModelWithPartialLoad)+ # On the CPU nothing is on the "cuda" compute device: the model needs all of its bytes.+ assert record.cached_model.cur_vram_bytes() == 0+ return record+++def test_a_model_that_does_not_fit_loads_the_reserve_less(cache: ModelCache, reserve: int):+ record = _record(cache)+ total = record.cached_model.total_bytes()+ vram = _FakeVram(total // 2)+ vram.attach(cache)++ cache._load_locked_model(record)++ assert vram.loads == [total // 2 - reserve + MB]+ assert vram.unloads == []+++def test_a_model_that_fits_fully_loads_without_the_reserve(cache: ModelCache, reserve: int):+ record = _record(cache)+ total = record.cached_model.total_bytes()+ vram = _FakeVram(total + 2 * MB)+ vram.attach(cache)++ cache._load_locked_model(record)++ # It streams nothing, so nothing is kept free for copies: a fully loaded model is much faster.+ assert vram.loads == [total + 2 * MB + MB]+++def test_the_reserve_stays_out_of_the_budget_after_the_own_model_is_unloaded(cache: ModelCache, reserve: int):+ record = _record(cache)+ short = 3 * MB+ vram = _FakeVram(reserve - short) # The reserve alone leaves the budget `short` below zero.+ vram.attach(cache)++ cache._load_locked_model(record)++ # The model's own weights are trimmed by what is missing. Of the memory that frees, the reserve stays free, so the+ # budget that follows is empty; without the reserve in it, the model would load `reserve` more.+ assert vram.unloads == [short]+ assert vram.loads == [MB]+++def _held(cache: ModelCache, monkeypatch: pytest.MonkeyPatch, resident: int):+ record = _record(cache)+ monkeypatch.setattr(record.cached_model, "cur_vram_bytes", lambda: resident)+ vram = _FakeVram(0)+ vram.attach(cache)+ record.lock()+ return record, vram+++ ("resident_after_lock", "moved"),+ [+ # Fully resident: the copies' reserve comes on top of what is above the limit.+ (32 * MB, 32 * MB + RESERVE - 20 * MB),+ # The lock settled above the limit, but under it by less than the reserve it kept free: the trim is the rest.+ (20 * MB, RESERVE),+ (20 * MB - RESERVE // 2, RESERVE // 2),+ ],+ ids=["fully-resident", "at-the-limit", "just-under-the-limit"],+)+def test_holding_residency_leaves_room_for_the_copies_within_the_limit(+ cache: ModelCache, reserve: int, monkeypatch: pytest.MonkeyPatch, resident_after_lock: int, moved: int+):+ record, vram = _held(cache, monkeypatch, resident_after_lock)++ assert cache.hold_model_residency(record, 20 * MB) == moved+ assert vram.unloads == [moved]+++def test_holding_residency_leaves_a_model_alone_that_is_under_the_limit_by_its_reserve(+ cache: ModelCache, reserve: int, monkeypatch: pytest.MonkeyPatch+):+ record, vram = _held(cache, monkeypatch, 20 * MB - RESERVE)++ assert cache.hold_model_residency(record, 20 * MB) == 0+ assert vram.unloads == []+++def test_holding_residency_without_streaming_counts_resident_bytes_only(+ cache: ModelCache, monkeypatch: pytest.MonkeyPatch+):+ monkeypatch.setattr(CachedModelWithPartialLoad, "weight_streaming_reserve_bytes", lambda self: 0)+ record, vram = _held(cache, monkeypatch, 32 * MB)++ assert cache.hold_model_residency(record, 20 * MB) == 12 * MB+ assert vram.unloads == [12 * MB]+++def test_holding_a_limit_above_the_model_asks_for_no_reserve(cache: ModelCache, monkeypatch: pytest.MonkeyPatch):+ asked: list[bool] = []+ monkeypatch.setattr(+ CachedModelWithPartialLoad, "weight_streaming_reserve_bytes", lambda self: asked.append(True) or RESERVE+ )+ record, vram = _held(cache, monkeypatch, 32 * MB)++ assert cache.hold_model_residency(record, record.cached_model.total_bytes()) == 0+ assert not asked and vram.unloads == []+++def test_a_plain_trim_frees_exactly_what_was_asked(cache: ModelCache, reserve: int, monkeypatch: pytest.MonkeyPatch):+ record, vram = _held(cache, monkeypatch, 32 * MB)++ cache.unload_model_from_vram(record, 10 * MB, keep_required_weights_in_vram=True)++ assert vram.unloads == [10 * MB]+++def _cached(model: torch.nn.Module) -> CachedModelWithPartialLoad:+ return CachedModelWithPartialLoad(model=model, compute_device=torch.device("cuda"), keep_ram_copy=True)+++def test_the_reserve_is_planned_while_something_can_stream(fake_streaming, monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setattr(weight_streaming, "STREAM_BUDGET_BYTES", RESERVE)+ cached = _cached(_model())+ try:+ assert cached.weight_streaming_reserve_bytes() == RESERVE+ finally:+ cached.release_pinned_weights()+++def test_no_reserve_is_planned_while_the_pinned_ram_cap_is_held_by_a_running_model(+ fake_streaming, monkeypatch: pytest.MonkeyPatch+):+ registry, _ = fake_streaming+ monkeypatch.setattr(weight_streaming, "STREAM_BUDGET_BYTES", RESERVE)+ monkeypatch.setattr(weight_streaming, "PINNED_RAM_CAP_BYTES", 2 * WEIGHT_MB * MB)+ running, waiting = _cached(_model()), _cached(_model())+ try:+ running.pin_streamed_weights() # Takes the cap: two of its four weights fit.+ assert registry._pinned_bytes == 2 * WEIGHT_MB * MB+ assert waiting.weight_streaming_reserve_bytes() == 0++ # Once the running model's lock ends, its pins are reclaimable and the waiting model may stream again.+ running.mark_streamed_weights_idle()+ registry.drain_deferred()+ assert waiting.weight_streaming_reserve_bytes() == RESERVE+ finally:+ running.release_pinned_weights()+ waiting.release_pinned_weights()+++def test_a_model_whose_weights_are_registered_keeps_its_reserve_at_a_full_cap(+ fake_streaming, monkeypatch: pytest.MonkeyPatch+):+ registry, _ = fake_streaming+ monkeypatch.setattr(weight_streaming, "STREAM_BUDGET_BYTES", RESERVE)+ monkeypatch.setattr(weight_streaming, "PINNED_RAM_CAP_BYTES", 2 * WEIGHT_MB * MB)+ cached = _cached(_model())+ try:+ cached.pin_streamed_weights()+ assert registry._pinned_bytes == 2 * WEIGHT_MB * MB+ assert cached.weight_streaming_reserve_bytes() == RESERVE+ finally:+ cached.release_pinned_weights()+++def test_a_lock_that_planned_no_reserve_registers_nothing_new_even_if_room_appears(+ fake_streaming, monkeypatch: pytest.MonkeyPatch+):+ """The VRAM was not kept free for copies in flight, so streaming must not start in this lock."""+ registry, runtime = fake_streaming+ monkeypatch.setattr(weight_streaming, "STREAM_BUDGET_BYTES", RESERVE)+ monkeypatch.setattr(weight_streaming, "PINNED_RAM_CAP_BYTES", 2 * WEIGHT_MB * MB)+ running, waiting = _cached(_model()), _cached(_model())+ try:+ running.pin_streamed_weights()+ waiting.begin_streaming_lock()+ assert waiting.weight_streaming_reserve_bytes() == 0 # Planned while the cap was full ...+ running.mark_streamed_weights_idle() # ... and room appears during the move that follows.++ waiting.pin_streamed_weights()++ assert not any(registry.is_registered(s) for s in waiting._streamable_ram_storages())+ waiting.end_streaming_lock()+ # The next lock plans again, and streams.+ waiting.begin_streaming_lock()+ assert waiting.weight_streaming_reserve_bytes() == RESERVE+ waiting.pin_streamed_weights()+ assert any(registry.is_registered(s) for s in waiting._streamable_ram_storages())+ waiting.end_streaming_lock()+ finally:+ running.release_pinned_weights()+ waiting.release_pinned_weights()+++def test_a_cache_lock_keeps_the_ram_copy_registered_through_an_eviction(+ fake_streaming, monkeypatch: pytest.MonkeyPatch+):+ """The partial load, the repair, the fallback copies and the LoRA unpatch of a lock copy from the RAM copy on+ their own streams. Another device's eviction of the shared weights must not unpin them meanwhile."""+ registry, runtime = fake_streaming+ monkeypatch.setattr(weight_streaming, "STREAM_BUDGET_BYTES", RESERVE)+ cached = _cached(_model())+ cached.begin_streaming_lock()+ cached.weight_streaming_reserve_bytes()+ cached.pin_streamed_weights()+ registered = set(runtime.registered)+ assert len(registered) == LAYERS++ cached.release_pinned_weights() # What eviction does.++ assert runtime.registered == registered, "still locked: unregistering would race the copies of the lock"+ cached.end_streaming_lock()++ assert runtime.registered == set() and registry._pinned_bytes == 0, "the last unlock unpins what was left pending"+++def test_a_lock_plans_streaming_afresh_and_does_not_inherit_the_last_ones_plan(+ fake_streaming, monkeypatch: pytest.MonkeyPatch+):+ """The second lock finds the model fitting, so it asks for no reserve, and an in-lock trim then must not stream."""+ registry, runtime = fake_streaming+ monkeypatch.setattr(weight_streaming, "STREAM_BUDGET_BYTES", RESERVE)+ cached = _cached(_model())+ try:+ cached.begin_streaming_lock()+ assert cached.weight_streaming_reserve_bytes() == RESERVE+ cached.end_streaming_lock()+ cached.release_pinned_weights()+ cached._pinning_retired = False++ cached.begin_streaming_lock() # Nothing asks for a reserve this time.+ cached.pin_streamed_weights()++ assert runtime.registered == set()+ cached.end_streaming_lock()+ finally:+ cached.release_pinned_weights()+++def test_a_wrapper_that_never_streamed_locks_the_storages_another_wrapper_registered(fake_streaming):+ """Shared weights: the second device has no holder yet, but it copies from what the first registered."""+ registry, runtime = fake_streaming+ cached = _cached(_model())+ holder = weight_streaming.PinHolder(torch.device("cuda", 0))+ registry.update(holder, cached._streamable_ram_storages())+ cached.begin_streaming_lock()++ registry.release(holder)++ assert len(runtime.registered) == LAYERS+ cached.end_streaming_lock()+ registry.drain_deferred()+ assert runtime.registered == set()+++def test_nothing_is_locked_while_streaming_is_off(fake_streaming, monkeypatch: pytest.MonkeyPatch):+ registry, _ = fake_streaming+ monkeypatch.setattr(weight_streaming, "can_stream_weights_to", lambda device, has_ram_copy: False)+ cached = _cached(_model())++ cached.begin_streaming_lock()++ assert not registry._locked+ cached.end_streaming_lock()+++def test_a_cache_pin_locks_the_model_for_as_long_as_any_lock_lasts(cache: ModelCache, fake_streaming):+ registry, _ = fake_streaming+ record = _record(cache)++ cache._pin(record)+ cache._pin(record)+ assert registry._locked+ cache._unpin(record)+ assert registry._locked, "one lock is still held"+ cache._unpin(record)++ assert not registry._locked+++class _WatchedLock:+ """A lock that says when a thread had to wait for it."""++ def __init__(self, contended: threading.Event) -> None:+ self._lock = threading.Lock()+ self._contended = contended++ def __enter__(self) -> None:+ if not self._lock.acquire(blocking=False):+ self._contended.set()+ self._lock.acquire()++ def __exit__(self, *exc) -> None:+ self._lock.release()+++def test_two_threads_pinning_a_model_for_the_first_time_create_one_holder(+ fake_streaming, monkeypatch: pytest.MonkeyPatch+):+ registry, runtime = fake_streaming+ cached = _cached(_model())+ decided, first_in_factory, proceed = threading.Event(), threading.Event(), threading.Event()+ created: list[weight_streaming.PinHolder] = []++ class _Holder(weight_streaming.PinHolder):+ __slots__ = ()++ def __init__(self, device: torch.device) -> None:+ super().__init__(device)+ created.append(self)+ if len(created) == 1:+ first_in_factory.set()+ assert proceed.wait(timeout=30)+ else:+ decided.set() # A second holder: nothing kept the threads apart.++ monkeypatch.setattr(weight_streaming, "PinHolder", _Holder)+ monkeypatch.setattr(cached, "_pin_lock", _WatchedLock(decided))+ threads = [threading.Thread(target=cached.pin_streamed_weights) for _ in range(2)]+ threads[0].start()+ assert first_in_factory.wait(timeout=30)+ threads[1].start()+ assert decided.wait(timeout=30), "the second thread neither waited for the pin lock nor made a holder"+ proceed.set()+ for thread in threads:+ thread.join(timeout=60)++ try:+ assert not any(thread.is_alive() for thread in threads)+ assert len(created) == 1+ assert len(runtime.registered) == LAYERS+ finally:+ cached.release_pinned_weights()+ assert runtime.registered == set() and registry._pinned_bytes == 0diff --git a/tests/backend/model_manager/load/model_cache/test_pinned_storage_registry.py b/tests/backend/model_manager/load/model_cache/test_pinned_storage_registry.pynew file mode 100644index 0000000000..4d6fff7b46--- /dev/null+++ b/tests/backend/model_manager/load/model_cache/test_pinned_storage_registry.py@@ -0,0 +1,580 @@+"""`PinnedStorageRegistry`, on the CPU, against a runtime that registers nothing for real (`fake_streaming`).++What it guards is the exclusion between cache locks and unregistration: a cache lock copies from the storages of its+model's RAM copy on its own streams, where the registry cannot see the copies, so those storages must neither be+unregistered under it nor be unregistered while it takes hold. The copies and their bit-identity on a GPU are checked+in `cached_model/test_async_weight_streaming.py`.+"""++import threading++import pytest+import torch++from invokeai.backend.model_manager.load.model_cache.torch_module_autocast import weight_streaming+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.weight_streaming import (+ PinHolder,+ storage_keys,+)++MB = 2**20+CUDA0 = torch.device("cuda", 0)+++def _storage(nbytes: int = MB) -> torch.UntypedStorage:+ return torch.empty(nbytes, dtype=torch.uint8).untyped_storage()+++class _SignalingCondition(threading.Condition):+ """Says when a thread is about to wait: the lock is held until `wait` releases it, so the signal cannot be early."""++ def __init__(self, about_to_wait: threading.Event) -> None:+ super().__init__()+ self._about_to_wait = about_to_wait++ def wait(self, timeout: float | None = None) -> bool:+ self._about_to_wait.set()+ return super().wait(timeout)+++def test_a_release_during_a_lock_keeps_the_storage_registered_until_the_lock_ends(fake_streaming):+ registry, runtime = fake_streaming+ storage = _storage()+ keys = storage_keys([storage])+ holder = PinHolder(CUDA0)+ registry.update(holder, [storage])+ registry.lock(keys)++ registry.release(holder)++ assert runtime.registered, "a copy under the lock may still read it"+ assert registry._pinned_bytes == MB and not registry.holds_registrations()+ registry.unlock(keys)+ registry.drain_deferred()+ assert not runtime.registered and registry._pinned_bytes == 0+++def test_a_lock_is_released_per_holder_of_the_storage(fake_streaming):+ registry, runtime = fake_streaming+ storage = _storage()+ keys = storage_keys([storage])+ holder = PinHolder(CUDA0)+ registry.update(holder, [storage])+ registry.lock(keys)+ registry.lock(keys)+ registry.release(holder)++ registry.unlock(keys)+ registry.drain_deferred()+ assert runtime.registered, "one lock is still held"++ registry.unlock(keys)+ registry.drain_deferred()+ assert not runtime.registered+++def test_reclaiming_for_room_skips_a_storage_a_lock_holds(fake_streaming, monkeypatch: pytest.MonkeyPatch):+ registry, runtime = fake_streaming+ monkeypatch.setattr(weight_streaming, "PINNED_RAM_CAP_BYTES", MB)+ idle, taker = PinHolder(CUDA0), PinHolder(CUDA0)+ held, wanted = _storage(), _storage()+ registry.update(idle, [held])+ registry.idle(idle)+ registry.lock(storage_keys([held]))++ registry.update(taker, [wanted])++ assert registry.is_registered(held) and not registry.is_registered(wanted)+ registry.unlock(storage_keys([held]))+ registry.update(taker, [wanted])+ assert registry.is_registered(wanted) and not registry.is_registered(held)+ registry.release(taker)+ registry.release(idle)+++def test_a_storage_registered_again_while_its_release_is_pending_is_not_registered_twice(fake_streaming):+ registry, runtime = fake_streaming+ storage = _storage()+ keys = storage_keys([storage])+ first, second = PinHolder(CUDA0), PinHolder(CUDA0)+ registry.update(first, [storage])+ registry.lock(keys)+ registry.release(first)++ registry.update(second, [storage])++ assert registry.is_registered(storage)+ assert [call for call, _ in runtime.log] == ["register"], "the registration is taken back, not made again"+ assert registry._pinned_bytes == MB+ registry.unlock(keys)+ registry.release(second)+ assert not runtime.registered and registry._pinned_bytes == 0+++def test_a_lock_waits_for_an_unregistration_in_progress(fake_streaming, monkeypatch: pytest.MonkeyPatch):+ """The copies a lock issues must not start while the range is being unregistered: they would race it."""+ registry, runtime = fake_streaming+ storage = _storage()+ keys = storage_keys([storage])+ holder = PinHolder(CUDA0)+ registry.update(holder, [storage])+ in_unregister, proceed, waiting = threading.Event(), threading.Event(), threading.Event()+ registry._cond = _SignalingCondition(waiting)+ unregister = runtime.unregister++ def slow_unregister(ptr: int) -> int:+ in_unregister.set()+ assert proceed.wait(timeout=30)+ return unregister(ptr)++ monkeypatch.setattr(runtime, "unregister", slow_unregister)+ releaser = threading.Thread(target=registry.release, args=(holder,))+ releaser.start()+ assert in_unregister.wait(timeout=30)++ def lock_then_log() -> None:+ registry.lock(keys)+ runtime.log.append(("locked", 0))++ locker = threading.Thread(target=lock_then_log)+ locker.start()+ assert waiting.wait(timeout=30)+ assert ("locked", 0) not in runtime.log+ proceed.set()+ releaser.join(timeout=30)+ locker.join(timeout=30)++ assert [call for call, _ in runtime.log if call != "register"] == ["unregister", "locked"]+ registry.unlock(keys)+++def test_a_release_does_not_wait_for_a_lock_that_is_held(fake_streaming):+ """The unregistering side waits for no lock: a cache lock waits for it, so waiting back would deadlock."""+ registry, runtime = fake_streaming+ storage = _storage()+ holder = PinHolder(CUDA0)+ registry.update(holder, [storage])+ registry.lock(storage_keys([storage]))+ done = threading.Event()++ def release() -> None:+ registry.release(holder)+ done.set()++ thread = threading.Thread(target=release)+ thread.start()++ assert done.wait(timeout=30)+ thread.join(timeout=30)+ registry.unlock(storage_keys([storage]))+ registry.drain_deferred()+++def test_register_new_false_neither_registers_nor_joins_anything_new(fake_streaming):+ """A lock that planned no VRAM for copies in flight must not start streaming from what another device registered."""+ registry, runtime = fake_streaming+ shared, fresh = _storage(), _storage()+ first, second = PinHolder(CUDA0), PinHolder(CUDA0)+ registry.update(first, [shared])++ registry.update(second, [shared, fresh], register_new=False)++ assert not second.keys and not registry.is_registered(fresh)+ assert [call for call, _ in runtime.log] == ["register"]+ registry.release(first)+ registry.release(second)+++def test_register_new_false_keeps_streaming_what_the_holder_holds(fake_streaming):+ registry, _ = fake_streaming+ held, other = _storage(), _storage()+ holder = PinHolder(CUDA0)+ registry.update(holder, [held])++ registry.update(holder, [held, other], register_new=False)++ assert registry.is_registered(held) and not registry.is_registered(other)+ assert holder.keys == storage_keys([held]) and holder.wanted >= storage_keys([held])+ assert registry._entries[next(iter(holder.keys))].wanted_by == 1+ registry.release(holder)+++def test_room_is_found_for_a_storage_that_fits_or_is_registered_only(fake_streaming, monkeypatch: pytest.MonkeyPatch):+ registry, _ = fake_streaming+ monkeypatch.setattr(weight_streaming, "PINNED_RAM_CAP_BYTES", MB)+ holder = PinHolder(CUDA0)+ held, other = _storage(), _storage()+ registry.update(holder, [held])++ assert registry.has_room_for_any([held]), "registered already"+ assert not registry.has_room_for_any([other]), "the cap is held by a storage that is being streamed"+ registry.idle(holder)+ registry.drain_deferred()+ assert registry.has_room_for_any([other]), "its holder is idle: reclaimable"+ registry.release(holder)+++class _InterruptingEntries(dict):+ """`_entries` whose first insert is interrupted, as a KeyboardInterrupt lands between two statements."""++ def __init__(self) -> None:+ super().__init__()+ self.interrupt = True++ def __setitem__(self, key, value) -> None:+ if self.interrupt:+ self.interrupt = False+ raise KeyboardInterrupt+ super().__setitem__(key, value)+++def test_an_interrupt_as_the_driver_call_returns_leaves_nothing_pinned_and_counted(fake_streaming, monkeypatch):+ registry, runtime = fake_streaming+ register = runtime.register++ def register_then_interrupt(ptr: int, nbytes: int) -> int:+ register(ptr, nbytes) # The range is page-locked, and the interrupt arrives before the caller sees it.+ raise KeyboardInterrupt++ monkeypatch.setattr(runtime, "register", register_then_interrupt)+ holder = PinHolder(CUDA0)++ with pytest.raises(KeyboardInterrupt):+ registry.update(holder, [_storage()])++ assert runtime.registered == set() and registry._pinned_bytes == 0 and not registry._entries+ registry.release(holder)+++def test_an_interrupt_while_tracking_the_registration_leaves_nothing_pinned_and_counted(fake_streaming):+ registry, runtime = fake_streaming+ registry._entries = _InterruptingEntries()+ holder = PinHolder(CUDA0)++ with pytest.raises(KeyboardInterrupt):+ registry.update(holder, [_storage()])++ assert runtime.registered == set() and registry._pinned_bytes == 0 and not registry._entries+ registry.release(holder)+++def test_an_interrupt_before_the_join_drops_the_entry_no_holder_holds(fake_streaming, monkeypatch):+ registry, runtime = fake_streaming+ holder = PinHolder(CUDA0)+ join = registry._join_locked+ interrupted: list[bool] = []++ def join_once_interrupted(holder_, key):+ if not interrupted:+ interrupted.append(True)+ raise KeyboardInterrupt+ join(holder_, key)++ monkeypatch.setattr(registry, "_join_locked", join_once_interrupted)++ with pytest.raises(KeyboardInterrupt):+ registry.update(holder, [_storage()])++ assert runtime.registered == set() and registry._pinned_bytes == 0 and not registry._entries+ registry.release(holder)+++def test_an_interrupt_before_the_join_keeps_an_entry_another_holder_holds(fake_streaming, monkeypatch):+ registry, runtime = fake_streaming+ storage = _storage()+ other, holder = PinHolder(CUDA0), PinHolder(CUDA0)++ registered_meanwhile: list[bool] = []++ def another_registers_meanwhile(_storage_) -> None:+ # Between `update`'s read-in and its registration, as a second device's wrapper of shared weights would.+ if not registered_meanwhile:+ registered_meanwhile.append(True)+ registry.update(other, [storage])++ join = registry._join_locked++ def join_interrupted_for_one_holder(holder_, key):+ if holder_ is holder:+ raise KeyboardInterrupt+ join(holder_, key)++ monkeypatch.setattr(weight_streaming, "_fault_in", another_registers_meanwhile)+ monkeypatch.setattr(registry, "_join_locked", join_interrupted_for_one_holder)++ with pytest.raises(KeyboardInterrupt):+ registry.update(holder, [storage])++ assert registry.is_registered(storage) and runtime.registered, "the other holder still streams it"+ registry.release(other)+ assert not runtime.registered+++def test_the_self_test_runs_with_the_models_device_current(monkeypatch: pytest.MonkeyPatch):+ current: list[int | None] = []+ seen: list[int | None] = []++ class _DeviceContext:+ def __init__(self, device) -> None:+ self.index = torch.device(device).index++ def __enter__(self) -> None:+ current.append(self.index)++ def __exit__(self, *exc) -> None:+ current.pop()++ monkeypatch.setattr(torch.cuda, "device", _DeviceContext)+ monkeypatch.setattr(+ weight_streaming, "_self_test_on_current_device", lambda device: seen.append(current[-1] if current else None)+ )++ weight_streaming._registration_self_test(torch.device("cuda", 1))++ assert seen == [1]+++def test_registration_runs_with_the_models_device_current(fake_streaming, monkeypatch: pytest.MonkeyPatch):+ registry, runtime = fake_streaming+ current: list[int | None] = []+ at_call: list[int | None] = []++ class _DeviceContext:+ def __init__(self, device) -> None:+ self.index = torch.device(device).index++ def __enter__(self) -> None:+ current.append(self.index)++ def __exit__(self, *exc) -> None:+ current.pop()++ register = runtime.register+ monkeypatch.setattr(torch.cuda, "device", _DeviceContext)+ monkeypatch.setattr(+ runtime,+ "register",+ lambda ptr, nbytes: at_call.append(current[-1] if current else None) or register(ptr, nbytes),+ )+ holder = PinHolder(torch.device("cuda", 1))++ registry.update(holder, [_storage()])++ assert at_call == [1]+ registry.release(holder)+++def test_a_device_streams_only_what_a_holder_computing_there_wants(fake_streaming):+ """Multi-GPU: the holder on cuda:1 registered the shared weights; the holder on cuda:0 planned no VRAM for copies+ in flight (`register_new=False`), so copies to cuda:0 of those weights stay synchronous."""+ registry, _ = fake_streaming+ cuda0, cuda1 = torch.device("cuda", 0), torch.device("cuda", 1)+ shared = [_storage(), _storage()]+ on1, on0 = PinHolder(cuda1), PinHolder(cuda0)+ registry.update(on1, shared)++ registry.update(on0, shared, register_new=False)++ for storage in shared:+ with registry.lookup(storage, cuda0) as streams:+ assert not streams+ with registry.lookup(storage, cuda1) as streams:+ assert streams+ assert registry.is_registered(storage) and not registry.is_wanted_on(storage, cuda0)+ assert registry.is_wanted_on(storage, cuda1)+ assert not registry.wants_anything_on(cuda0), "the staging gate is closed for the device that planned nothing"+ assert registry.wants_anything_on(cuda1)++ registry.update(on0, shared) # A later lock that planned the reserve joins them.+ with registry.lookup(shared[0], cuda0) as streams:+ assert streams+ assert registry.wants_anything_on(cuda0)++ registry.release(on1) # What cuda:0 holds stays wanted there, and stops being wanted on cuda:1.+ with registry.lookup(shared[0], cuda0) as streams:+ assert streams+ with registry.lookup(shared[0], cuda1) as streams:+ assert not streams+ assert not registry.wants_anything_on(cuda1)+ registry.release(on0)+ assert not registry.wants_anything_on(cuda0)+++def test_an_idle_holder_does_not_stream(fake_streaming):+ registry, _ = fake_streaming+ cuda0 = torch.device("cuda", 0)+ storage = _storage()+ holder = PinHolder(cuda0)+ registry.update(holder, [storage])++ registry.idle(holder)+ registry.drain_deferred()++ assert registry.is_registered(storage) and not registry.is_wanted_on(storage, cuda0)+ with registry.lookup(storage, cuda0) as streams:+ assert not streams+ assert registry.activate(holder)+ assert registry.is_wanted_on(storage, cuda0)+ registry.release(holder)+++def test_an_interrupt_while_unregistering_does_not_leave_keys_that_block_every_lock(fake_streaming):+ registry, runtime = fake_streaming+ storage = _storage()+ keys = storage_keys([storage])+ holder = PinHolder(CUDA0)+ registry.update(holder, [storage])++ class _Interrupt(BaseException):+ pass++ class _InterruptedSet(set):+ def add(self, key) -> None:+ super().add(key)+ raise _Interrupt++ registry._unregistering = _InterruptedSet()+ with pytest.raises(_Interrupt):+ registry.release(holder)++ assert not registry._unregistering+ assert runtime.registered and registry._pinned_bytes == MB, "what was not unregistered stays registered, counted"+ assert [entry.key for entry in registry._stranded] == list(keys), "and kept alive"+ waiter = threading.Thread(target=lambda: (registry.lock(keys), registry.unlock(keys)), daemon=True)+ waiter.start()+ waiter.join(timeout=10)+ assert not waiter.is_alive(), "a later lock waits for an unregistration that never ends"+++def test_a_pending_release_whose_last_unlock_lost_the_drain_is_unregistered_by_the_registration_it_overlapped(+ fake_streaming, monkeypatch: pytest.MonkeyPatch+):+ """The last unlock lands while another thread registers: its non-blocking drain loses the lock, and the+ registration must apply it when it ends."""+ registry, runtime = fake_streaming+ released, other = _storage(), _storage()+ keys = storage_keys([released])+ first, second = PinHolder(CUDA0), PinHolder(CUDA0)+ registry.update(first, [released])+ registry.lock(keys)+ registry.release(first)+ assert runtime.registered, "pending behind the lock"+ register = registry._register_locked++ def register_while_the_lock_ends(*args, **kwargs):+ result = register(*args, **kwargs)+ registry.unlock(keys)+ registry.drain_deferred() # Loses the registration lock, which this thread holds.+ return result++ monkeypatch.setattr(registry, "_register_locked", register_while_the_lock_ends)++ registry.update(second, [other])++ assert runtime.registered == {other.data_ptr()}+ assert registry._pinned_bytes == MB+ registry.release(second)+++def test_pending_entries_cost_a_streamed_copy_no_lock_until_an_unlock_frees_one(fake_streaming):+ registry, runtime = fake_streaming+ storage = _storage()+ keys = storage_keys([storage])+ holder = PinHolder(CUDA0)+ registry.update(holder, [storage])+ registry.lock(keys)+ registry.release(holder)++ class _ForbiddenLock:+ def acquire(self, *args, **kwargs):+ raise AssertionError("the registration lock was taken with nothing to apply")++ real_lock = registry._registration_lock+ registry._registration_lock = _ForbiddenLock()+ try:+ for _ in range(3):+ registry.drain_deferred()+ finally:+ registry._registration_lock = real_lock+ assert runtime.registered++ registry.unlock(keys)+ registry.drain_deferred()++ assert not runtime.registered and registry._pinned_bytes == 0+ registry._registration_lock = _ForbiddenLock()+ try:+ registry.drain_deferred() # The flag is cleared again: nothing is left to retry.+ finally:+ registry._registration_lock = real_lock+++def test_a_last_unlock_during_another_drain_is_drained_by_it_after_it_releases_the_lock(fake_streaming, monkeypatch):+ """Thread A drains and finds the key still locked; B's last unlock then loses the non-blocking acquire, and A's+ drain must go round again after releasing."""+ registry, runtime = fake_streaming+ storage = _storage()+ keys = storage_keys([storage])+ holder = PinHolder(CUDA0)+ registry.update(holder, [storage])+ registry.lock(keys)+ registry.release_deferred(holder)+ unregister_pending = registry._unregister_pending_locked++ def unlock_during_the_drain() -> None:+ unregister_pending() # The key is still locked: it stays pending, and the flag is cleared.+ monkeypatch.setattr(registry, "_unregister_pending_locked", unregister_pending)+ registry.unlock(keys)+ registry.drain_deferred() # Loses the registration lock, which this thread holds.++ monkeypatch.setattr(registry, "_unregister_pending_locked", unlock_during_the_drain)++ registry.drain_deferred()++ assert not runtime.registered and registry._pinned_bytes == 0 and not registry._pending+++def test_holders_on_one_device_count_a_shared_storage_once(fake_streaming):+ registry, _ = fake_streaming+ storage = _storage()+ first, second = PinHolder(CUDA0), PinHolder(CUDA0)+ registry.update(first, [storage])+ registry.update(second, [storage])+ assert registry._wanted_entries_on == {CUDA0: 1}++ registry.release(first)+ assert registry.wants_anything_on(CUDA0), "the second holder still wants it"+ registry.release(second)++ assert not registry.wants_anything_on(CUDA0)+++def test_releasing_a_want_that_an_interrupt_cut_short_does_not_raise(fake_streaming):+ registry, _ = fake_streaming+ storage = _storage()+ holder = PinHolder(CUDA0)+ registry.update(holder, [storage])+ next(iter(registry._entries.values())).wanted_on.clear()+ registry._wanted_entries_on.clear() # A want cut short before its counters were updated.++ registry.release(holder)++ assert not registry._entries+ assert registry._reclaimable_bytes == 0 and not registry._reclaimable+ assert registry._wanted_entries_on.get(CUDA0, 0) == 0+++def test_an_unwant_of_an_already_reclaimable_storage_counts_its_bytes_once(fake_streaming):+ registry, _ = fake_streaming+ holder = PinHolder(CUDA0)+ registry.update(holder, [_storage()])+ registry.idle(holder)+ registry.drain_deferred()+ entry = next(iter(registry._entries.values()))+ assert registry._reclaimable_bytes == MB++ registry._unwant_locked(entry, holder) # What a cut-short want leaves behind.++ assert registry._reclaimable_bytes == MB and list(registry._reclaimable) == [entry.key]+ assert registry._wanted_entries_on.get(CUDA0, 0) == 0+ registry.release(holder)