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(attention): keep a GPU on SageAttention after running out of memory
Alexander Eichhornce561e38ff97
diff --git a/docs/src/content/docs/configuration/Optimization/sage-attention.mdx b/docs/src/content/docs/configuration/Optimization/sage-attention.mdxindex f1d9baad46..def8250fab 100644--- a/docs/src/content/docs/configuration/Optimization/sage-attention.mdx+++ b/docs/src/content/docs/configuration/Optimization/sage-attention.mdx@@ -121,8 +121,9 @@ kernels.running a kernel, cannot be caught at all and ends the generation.- **Memory.** Peak VRAM was unchanged for every measured model. Each call holds quantized copies of its inputs, about1.7 bytes per element of the query, key and value together — around 70 MB for FLUX.1 at 1024×1024, and around 2 GB- per call for Wan 2.2 14B at 1280×720 with 81 frames (not measured). A call that does not fit runs on PyTorch's- attention instead, which needs less.+ per call for Wan 2.2 14B at 1280×720 with 81 frames (not measured). When a call does not fit, the rest of that+ generation runs on PyTorch's attention, which needs less, and the log says so; the next generation tries+ SageAttention again.- **Recall.** `attention_backend` is not stored in an image's metadata, so an image recalled after switching it isgenerated slightly differently.- **Black or noisy images** have been reported with SageAttention for some models in other applications. None appeareddiff --git a/invokeai/backend/util/sage_attention.py b/invokeai/backend/util/sage_attention.pyindex 36879cb892..7510e5a278 100644--- a/invokeai/backend/util/sage_attention.py+++ b/invokeai/backend/util/sage_attention.py@@ -36,6 +36,7 @@ from typing import Anyimport torchfrom invokeai.backend.util.logging import InvokeAILogger+from invokeai.backend.util.oom import is_oom_errorlogger = InvokeAILogger.get_logger(__name__)@@ -60,10 +61,10 @@ _FIRST_CALL_MAX_ERROR = 0.5# tile is among them. A kernel that never ran garbles every row, so a slice catches what the whole output would; the# whole output costs ~14 bytes per element to compare -- about 5 GB for one call of Wan 2.2 14B at 720p._FIRST_CALL_ROWS = 1024-# Failures that say nothing about the kernel -- Triton running out of memory while loading a compiled kernel, or losing-# a race for its cache file to a compile on another GPU -- fall back for that call only. A device that keeps failing-# that way is retired like any other, so a broken Triton cache does not recompile on every call.-_MAX_TRANSIENT_FAILURES = 3+# Triton failing to write a compiled kernel to its cache (on Windows, when two GPUs compile the same kernel at once)+# says nothing about the kernel: that call falls back and the next tries again. A device that fails this way this many+# times in a row is retired like any other, so a cache that can never be written does not recompile on every call.+_MAX_CACHE_FAILURES = 3DOCS_URL = "https://invoke-ai.github.io/InvokeAI-7/configuration/optimization/sage-attention/"@@ -74,6 +75,8 @@ class _Usage:served: int = 0fell_back: Counter[str] = field(default_factory=Counter)+ # Set once SageAttention's quantized copies did not fit; the rest of the scope then stays on SDPA.+ memory_short: bool = False_scope: ContextVar[_Usage | None] = ContextVar("invokeai_sage_attention_scope", default=None)@@ -81,7 +84,7 @@ _lock = threading.Lock()_disabled_devices: set[int] = set()# (device, dtype, head size): the kernel variants whose first result was compared with SDPA._validated: set[tuple[int, torch.dtype, int]] = set()-_transient_failures: Counter[int] = Counter()+_cache_failures: Counter[int] = Counter()_announced_devices: set[int] = set()@@ -131,11 +134,13 @@ def _kernel(without saying why; neither has been measured here, so upstream's choice stands. From the Windows build come thesm100 kernel and the choice by the CUDA version torch was built for: the FP16 accumulation inside the FP8 kernelsneeds CUDA 12.8 to compile, and below that the build replaces it with a trap. Every kernel is called with- ``smooth_k`` off, which ``sageattn`` always leaves on and has no argument to change. Smoothing subtracts K's mean over the sequence before quantizing; in the first- block of Qwen-Image and Krea-2, where one channel of Q and K sits near +600 for every image token, that leaves the- INT8 product Q.K no precision for the rest: cosine 0.18 and 0.53 against a float32 reference, 0.997 and 0.988 with- smoothing off. Everywhere else measured it changes nothing, and off is 2-11 % faster (RTX 4090). Only sm_89 has been- measured in InvokeAI.+ ``smooth_k`` off, which ``sageattn`` always leaves on and has no argument to change.++ Smoothing subtracts K's mean over the sequence before quantizing; in the first block of Qwen-Image and Krea-2,+ where one channel of Q and K sits near +600 for every image token, that leaves the INT8 product Q.K no precision for+ the rest: cosine 0.18 and 0.53 against a float32 reference, 0.997 and 0.988 with smoothing off. Everywhere else+ measured it changes nothing, and off is 2-11 % faster (RTX 4090). Only sm_89 has been measured in InvokeAI; the+ sm86 Triton kernel was checked for accuracy on it."""major, minor = capabilityrecent_cuda = cuda >= (12, 8)@@ -171,7 +176,7 @@ def _cuda_index(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor) ->single-device install with `device: cuda:1` does not."""device = query.device- if device.type != "cuda" or device.index is None or key.device != device or value.device != device:+ if device.type != "cuda" or key.device != device or value.device != device:return Nonereturn device.index@@ -254,20 +259,11 @@ def _check_first_result(_validated.add((index, query.dtype, query.shape[-1]))-def _transient(error: Exception) -> bool:- """Whether a failure says nothing about the kernel: memory, or a file Triton could not write.-- A CUDA fault that poisons the context (illegal address, a trap) is not among them; torch's fallback then raises the- same error, and a restart is the only way out.- """- return isinstance(error, OSError) or "out of memory" in str(error).lower()---def _transient_failure(index: int) -> bool:- """Count a transient failure on this device; True once there were too many to keep retrying."""+def _cache_failure(index: int) -> bool:+ """Count a Triton cache failure on this device; True once it failed too often in a row to keep retrying."""with _lock:- _transient_failures[index] += 1- return _transient_failures[index] >= _MAX_TRANSIENT_FAILURES+ _cache_failures[index] += 1+ return _cache_failures[index] >= _MAX_CACHE_FAILURESdef _disable(index: int, error: Exception, query: torch.Tensor, key: torch.Tensor) -> None:@@ -374,6 +370,8 @@ def install_sage_attention() -> None:usage = _scope.get()if usage is not None:reason = _ineligible(query, key, value, attn_mask, dropout_p, is_causal, enable_gqa, bool(args or kwargs))+ if reason is None and usage.memory_short:+ reason = "memory"if reason is None:index = _cuda_index(query, key, value)kernel = kernels.get(index) if index is not None and index not in _disabled_devices else None@@ -393,14 +391,26 @@ def install_sage_attention() -> None:if (index, query.dtype, query.shape[-1]) not in _validated:_check_first_result(index, original, query, key, value, scale, out)except Exception as e:- # SageAttention's quantized copies did not fit, or Triton could not load or cache a kernel:- # this call uses SDPA, which needs less memory, and the next tries SageAttention again.- if _transient(e) and not _transient_failure(index):- reason = "transient"+ if isinstance(e, RuntimeError) and is_oom_error(e):+ # SageAttention's quantized copies did not fit. SDPA needs less; the rest of this scope+ # uses it rather than flushing the allocator's cache on every call, and the next+ # generation tries SageAttention again. A CUDA fault that poisons the context is no OOM:+ # it retires the device below, and SDPA then fails the same way.+ usage.memory_short = True+ reason = "memory"+ logger.info(+ f"SageAttention ran out of memory on cuda:{index} for query {tuple(query.shape)}; "+ "the rest of this generation uses PyTorch SDPA."+ )+ elif isinstance(e, OSError) and not _cache_failure(index):+ reason = "cache"else:_disable(index, e, query, key)reason = "error"else:+ if _cache_failures[index]:+ with _lock:+ _cache_failures.pop(index, None)usage.served += 1_announce(index, version, kernel)return outdiff --git a/tests/backend/util/test_sage_attention.py b/tests/backend/util/test_sage_attention.pyindex d670f085d1..ca1ae56a50 100644--- a/tests/backend/util/test_sage_attention.py+++ b/tests/backend/util/test_sage_attention.py@@ -120,7 +120,7 @@ def _cuda_build(monkeypatch.setattr(sage, "_cuda_index", lambda q, k, v: 0)monkeypatch.setattr(sage, "_disabled_devices", set())monkeypatch.setattr(sage, "_validated", _all_variants(capabilities))- monkeypatch.setattr(sage, "_transient_failures", Counter())+ monkeypatch.setattr(sage, "_cache_failures", Counter())monkeypatch.setattr(sage, "_announced_devices", set())monkeypatch.setattr(torch.cuda, "device", lambda index: contextlib.nullcontext())return module, torch_calls@@ -402,16 +402,35 @@ class TestFailures:[torch.OutOfMemoryError("CUDA out of memory. Tried to allocate 1.50 GiB"),RuntimeError("Triton Error [CUDA]: out of memory"),- PermissionError("[WinError 5] Access is denied: 'triton\\cache\\tmp.pid_123'"),],- ids=["torch-oom", "triton-oom", "triton-cache-race"],+ ids=["torch-oom", "triton-oom"],)- def test_a_transient_failure_falls_back_for_that_call_only(self, installed, caplog, error):- """Memory or a file Triton could not write says nothing about the kernel: SDPA serves the call, the next one- tries SageAttention again, and nothing is logged as a failure."""+ def test_running_out_of_memory_moves_the_rest_of_the_scope_to_torch_only(self, installed, caplog, error):+ """SDPA needs less memory. Retrying every call would flush the allocator's cache each time; retiring the+ device would cost every later, smaller generation SageAttention."""module, torch_calls = installedmodule.error = errorq, k = _q(1, 2, QUERY_LEN, 64), _q(1, 2, KEY_LEN, 64)+ caplog.set_level(logging.INFO, logger=sage.__name__)++ with sage_attention_scope():+ out = F.scaled_dot_product_attention(q, k, k)+ module.error = None+ F.scaled_dot_product_attention(q, k, k)+ assert len(module.calls) == 1 and len(torch_calls) == 2, "after the OOM, this scope stayed on torch"+ torch.testing.assert_close(out.float(), _reference(q, k, k), atol=2e-3, rtol=2e-3)++ with sage_attention_scope():+ F.scaled_dot_product_attention(q, k, k)+ assert len(module.calls) == 2, "the next scope tries SageAttention again"+ assert any("ran out of memory" in r.message for r in caplog.records if r.levelno == logging.INFO)+ assert not [r for r in caplog.records if r.levelno >= logging.WARNING]++ def test_a_triton_cache_failure_falls_back_for_that_call_only(self, installed, caplog):+ """On Windows two GPUs compiling the same kernel can race for its cache file; that says nothing about it."""+ module, torch_calls = installed+ module.error = PermissionError("[WinError 5] Access is denied: 'triton\\cache\\tmp.pid_123'")+ q, k = _q(1, 2, QUERY_LEN, 64), _q(1, 2, KEY_LEN, 64)caplog.set_level(logging.WARNING, logger=sage.__name__)with sage_attention_scope():@@ -421,21 +440,29 @@ class TestFailures:torch.testing.assert_close(out.float(), _reference(q, k, k), atol=2e-3, rtol=2e-3)assert len(module.calls) == 2 and len(torch_calls) == 1- assert not [r for r in caplog.records if r.levelno >= logging.WARNING]+ assert not caplog.records- def test_a_device_that_keeps_failing_transiently_is_retired(self, installed, caplog):- """A Triton cache that can never be written would otherwise recompile on every call."""+ def test_only_cache_failures_in_a_row_retire_the_device(self, installed, caplog):+ """A cache that can never be written would recompile on every call; one that failed now and then is fine."""module, torch_calls = installed- module.error = PermissionError("Access is denied")q, k = _q(1, 2, QUERY_LEN, 64), _q(1, 2, KEY_LEN, 64)caplog.set_level(logging.WARNING, logger=sage.__name__)- with sage_attention_scope():- for _ in range(sage._MAX_TRANSIENT_FAILURES + 2):+ def call(error):+ module.error = error+ with sage_attention_scope():F.scaled_dot_product_attention(q, k, k)- assert len(module.calls) == sage._MAX_TRANSIENT_FAILURES- assert len(torch_calls) == sage._MAX_TRANSIENT_FAILURES + 2+ for error in [PermissionError("denied")] * (sage._MAX_CACHE_FAILURES - 1) + [None]:+ call(error)+ for _ in range(sage._MAX_CACHE_FAILURES - 1):+ call(PermissionError("denied"))+ assert not caplog.records and 0 not in sage._disabled_devices, "the success in between reset the count"++ call(PermissionError("denied"))+ call(None)+ assert 0 in sage._disabled_devices+ assert len(module.calls) == 2 * sage._MAX_CACHE_FAILURES, "the last call no longer reached the kernel"assert any("cuda:0" in r.message for r in caplog.records if r.levelno == logging.WARNING)def test_the_scope_closes_when_its_block_raises(self, installed):@@ -657,16 +684,23 @@ class TestOnNvidiaHardware:"""Real kernels: needs CUDA, `sageattention` >= 2.2 and compute capability 8.0+, and about 10 GB of free VRAM forthe float32 references. Measured on an RTX 4090."""- @pytest.fixture- def kernel(self, monkeypatch):+ @pytest.fixture(params=["own", "sm86-triton"])+ def kernel(self, request, monkeypatch):+ """The kernel this GPU gets, or the Triton kernel an sm86 card gets: it runs on any Ampere or newer GPU, so this+ one stands in for an sm86 card that is not here."""import sageattentioncapability = torch.cuda.get_device_capability(0)if capability < (8, 0):pytest.skip("SageAttention 2 needs compute capability 8.0 or newer")+ if request.param == "sm86-triton":+ pick = sage._kernel+ monkeypatch.setattr(sage, "_kernel", lambda module, _capability, cuda: pick(module, (8, 6), cuda))monkeypatch.setattr(F, "scaled_dot_product_attention", TORCH_SDPA)monkeypatch.setattr(sage, "_disabled_devices", set())monkeypatch.setattr(sage, "_validated", set())+ monkeypatch.setattr(sage, "_cache_failures", Counter())+ monkeypatch.setattr(sage, "_announced_devices", set())install_sage_attention()if not getattr(F.scaled_dot_product_attention, sage._SENTINEL, False):pytest.skip("the installed sageattention is not one InvokeAI uses (see the startup warning)")@@ -674,9 +708,10 @@ class TestOnNvidiaHardware:assert cuda is not Nonereturn sage._kernel(sageattention, capability, cuda[:2])- def test_every_kernel_takes_the_arguments_it_is_given(self, kernel):+ def test_every_kernel_takes_the_arguments_it_is_given(self, kernel, monkeypatch):import sageattention+ monkeypatch.undo() # the real table, not the fixture's stand-infor capability in ((8, 0), (8, 6), (8, 9), (9, 0), (12, 0)):assert sage._unaccepted_arguments(sage._kernel(sageattention, capability, (13, 0))) == []@@ -686,8 +721,10 @@ class TestOnNvidiaHardware:((1, 24, 4608, 128), (1, 24, 4608, 128), torch.bfloat16, False), # FLUX.1 1024^2((2, 10, 4096, 64), (2, 10, 4096, 64), torch.float16, False), # SDXL 1024^2, level 1((1, 48, 4608, 128), (1, 12, 4608, 128), torch.bfloat16, True), # Krea-2 GQA+ # Lengths that are no multiple of a tile, and cross-attention to a shorter key.+ ((1, 24, 4429, 128), (1, 24, 845, 128), torch.bfloat16, False),],- ids=["flux", "sdxl", "krea2-gqa"],+ ids=["flux", "sdxl", "krea2-gqa", "partial-tile-cross"],)def test_output_stays_close_to_a_float32_reference(self, kernel, shape_q, shape_kv, dtype, gqa):g = torch.Generator(device="cuda").manual_seed(0)@@ -699,6 +736,8 @@ class TestOnNvidiaHardware:with sage_attention_scope():out = F.scaled_dot_product_attention(q, k, v, enable_gqa=gqa)+ # SDPA would pass the bounds below too; the kernel must have served the call.+ assert torch.equal(out, kernel(q, k, v, tensor_layout="HND", is_causal=False, sm_scale=shape_q[-1] ** -0.5))ref = _reference(q, k, v)assert torch.isfinite(out).all()cos = F.cosine_similarity(out.float().flatten(2), ref.flatten(2), dim=-1)@@ -706,20 +745,6 @@ class TestOnNvidiaHardware:assert cos.min() > 0.998assert (out.float() - ref).norm() / ref.norm() < 0.06- def test_the_triton_kernel_chosen_for_sm86_stays_close_to_a_float32_reference(self, kernel):- """No sm86 GPU here; the Triton kernel itself runs on any Ampere or newer GPU, so its numbers are checked."""- import sageattention-- g = torch.Generator(device="cuda").manual_seed(0)- q, k, v = (torch.randn(1, 4608, 24, 128, device="cuda", generator=g).bfloat16().transpose(1, 2) for _ in "qkv")- triton_kernel = sage._kernel(sageattention, (8, 6), (13, 0))-- out = triton_kernel(q, k, v, tensor_layout="HND", is_causal=False, sm_scale=128**-0.5)-- ref = _reference(q, k, v)- assert torch.isfinite(out).all()- assert (out.float() - ref).norm() / ref.norm() < 0.06-def test_the_outlier_channel_of_qwen_images_first_block_stays_accurate(self, kernel):"""Real activations (see the fixture's metadata). With K smoothing on, as `sageattn` runs it, the relativeerror here is 1.62; with it off, 0.10."""