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
fix(model cache): harden the allocator-reserve credit after adversarial review
Lincoln Stein46bcf1994322
diff --git a/invokeai/backend/model_manager/load/model_cache/model_cache.py b/invokeai/backend/model_manager/load/model_cache/model_cache.pyindex 23d66d9c38..daca5cfbf1 100644--- a/invokeai/backend/model_manager/load/model_cache/model_cache.py+++ b/invokeai/backend/model_manager/load/model_cache/model_cache.py@@ -1,5 +1,6 @@import gcimport logging+import osimport queueimport threadingimport time@@ -37,6 +38,20 @@ from invokeai.backend.util.level_zero import xpu_device_is_integratedfrom invokeai.backend.util.logging import InvokeAILoggerfrom invokeai.backend.util.prefix_logger_adapter import PrefixedLoggerAdapter++def _expandable_segments_enabled() -> bool:+ """Whether the torch caching allocator runs in expandable-segments mode.++ The mode is configured through the allocator env vars before torch import (InvokeAI's own+ `pytorch_cuda_alloc_conf` setting is plumbed into PYTORCH_CUDA_ALLOC_CONF the same way), so+ parsing them is authoritative for the life of the process.+ """+ for var in ("PYTORCH_ALLOC_CONF", "PYTORCH_CUDA_ALLOC_CONF", "PYTORCH_HIP_ALLOC_CONF"):+ if "expandable_segments:true" in os.environ.get(var, "").replace(" ", "").lower():+ return True+ return False++# Size of a GB in bytes.GB = 2**30@@ -1213,14 +1228,19 @@ class ModelCache:# too-small budget is diagnosable from the default log. First pass only (paced# continuations would repeat it).resident = [- f"{entry.key.split(':')[-1]}={entry.cached_model.cur_vram_bytes() / MB:.0f}MB"+ f"{entry.key}={entry.cached_model.cur_vram_bytes() / MB:.0f}MB"+ (" [locked]" if entry.is_locked else "")for entry in self._cached_models.values()if entry.cached_model.cur_vram_bytes() > 0 and entry.key != cache_entry.key]+ # The reservation _get_vram_available actually applied: callers passing None (the+ # majority) get the configured default, and smaller values are clamped up to it —+ # printing the raw argument would report 0MB for the very number being diagnosed.+ working_mem_bytes_default = int(self._execution_device_working_mem_gb * GB)+ effective_working_mem = max(working_mem_bytes or working_mem_bytes_default, working_mem_bytes_default)self._logger.warning(f"VRAM budget for '{cache_entry.key}' is short by {-vram_available / MB:.0f}MB even after "- f"offloading (working memory reservation: {(working_mem_bytes or 0) / MB:.0f}MB); the model will "+ f"offloading (working memory reservation: {effective_working_mem / MB:.0f}MB); the model will "f"run with minimum weights resident. Other models still in VRAM: {', '.join(resident) or 'none'}.")@@ -1418,8 +1438,14 @@ class ModelCache:inactive-split slack (free space inside partially-occupied segments, which cannot serve alarge contiguous allocation and which empty_cache() cannot return to the driver).- Best-effort: 0 when the backend does not expose allocator stats.+ Best-effort: 0 when the backend does not expose allocator stats, and 0 under+ expandable-segments mode — there, freed blocks inside a segment are NOT counted as+ inactive splits, empty_cache() reclaims nothing, and a large allocation cannot use the+ holes, so the whole (reserved - allocated) figure is untrustworthy (a measured hard OOM+ on an allocation the credited budget claimed would fit)."""+ if _expandable_segments_enabled():+ return 0try:if self._execution_device.type == "cuda":reserved = torch.cuda.memory_reserved(self._execution_device)diff --git a/tests/backend/model_manager/load/model_cache/test_model_cache_vram_accounting.py b/tests/backend/model_manager/load/model_cache/test_model_cache_vram_accounting.pyindex f92c37654e..84d7882667 100644--- a/tests/backend/model_manager/load/model_cache/test_model_cache_vram_accounting.py+++ b/tests/backend/model_manager/load/model_cache/test_model_cache_vram_accounting.py@@ -134,3 +134,23 @@ def test_negative_budget_warns_and_names_locked_residents():cache.unlock(rec_victim)cache.unlock(rec_stuck)torch.cuda.empty_cache()+++@requires_cuda+def test_reclaimable_credit_withheld_under_expandable_segments(monkeypatch: pytest.MonkeyPatch):+ """Under expandable-segments mode the (reserved - allocated) figure counts intra-segment+ holes that empty_cache cannot reclaim and a large allocation cannot use — the credit must be+ withheld entirely (the env parse is authoritative: the mode is fixed before torch import)."""+ cache = _make_cache()++ monkeypatch.setenv("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")+ assert cache._get_reclaimable_allocator_bytes() == 0++ monkeypatch.setenv("PYTORCH_CUDA_ALLOC_CONF", "max_split_size_mb:512")+ monkeypatch.setenv("PYTORCH_HIP_ALLOC_CONF", "expandable_segments: true")+ assert cache._get_reclaimable_allocator_bytes() == 0++ monkeypatch.delenv("PYTORCH_HIP_ALLOC_CONF")+ monkeypatch.delenv("PYTORCH_CUDA_ALLOC_CONF")+ # With no allocator config the credit path is active again (>= 0 by construction).+ assert cache._get_reclaimable_allocator_bytes() >= 0