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): follow upstream's sm86 kernel and recover from transient SageAttention failures
Alexander Eichhorne9aa6c6e2fdb
diff --git a/docs/src/content/docs/configuration/Optimization/sage-attention.mdx b/docs/src/content/docs/configuration/Optimization/sage-attention.mdxindex 5b5aea9df7..f1d9baad46 100644--- a/docs/src/content/docs/configuration/Optimization/sage-attention.mdx+++ b/docs/src/content/docs/configuration/Optimization/sage-attention.mdx@@ -24,8 +24,8 @@ so every model keeps PyTorch's attention.## Requirements- **An NVIDIA GPU with compute capability 8.0 or newer** — RTX 30-series, RTX 40-series, RTX 50-series, A100, H100.- InvokeAI has measured it on an RTX 4090; the other generations use SageAttention's own kernels for them, which- InvokeAI has not validated.+ InvokeAI has measured it on an RTX 4090; the other generations use the kernels SageAttention picks for them, which+ InvokeAI has not validated (on RTX 30-series cards, its Triton kernel). Jetson Orin is not supported.- **SageAttention 2.2, installed separately.** InvokeAI was validated with 2.2.0. The `sageattention` package on PyPI isthe older SageAttention 1 and is not used. On Windows it also needs the `triton-windows` package.- Not available on AMD (ROCm), Apple Silicon (MPS), Intel (XPU) or CPU. There InvokeAI keeps PyTorch's attention.@@ -98,26 +98,31 @@ calls ran on SageAttention and why the others did not. To go back, set `attentioSageAttention serves the attention inside the denoising model of the families under [Supported models](#supported-models).Everything else keeps PyTorch's attention:-- **Text encoders, image encoders and VAEs.** They run outside the denoising loop.+- **Text encoders, image encoders and VAEs.** They run outside the denoising loop. What runs inside it, such as a+ ControlNet, is served like the model itself.- **Masked attention**, such as regional prompts. SageAttention has no mask input.- **Short sequences** — fewer than 1536 query or 512 key tokens. There the cost of quantizing the inputs outweighs thefaster kernel.- **Head sizes other than 64 and 128.**- **Models not listed under Supported models**, such as SD 1.5 and SD 2.-Pinning a PyTorch kernel through diffusers' `DIFFUSERS_ATTN_BACKEND` does not stop SageAttention; set-`attention_backend: auto` to measure PyTorch's own kernels.+Pinning a PyTorch kernel through diffusers' `DIFFUSERS_ATTN_BACKEND`, or in a custom node with+`torch.nn.attention.sdpa_kernel`, does not stop SageAttention; set `attention_backend: auto` to measure PyTorch's own+kernels.## Notes- **The first generation pauses briefly.** SageAttention compiles a few Triton kernels on first use, about two secondson an RTX 4090; they are cached on disk afterwards.-- **Each GPU's first SageAttention call is checked against PyTorch's attention.** If the result is wrong or the kernel- fails, InvokeAI logs a warning once and that GPU uses PyTorch's attention until restart. A fault the GPU raises- later, while running a kernel, cannot be caught that way and ends the generation.+- **Each GPU's first SageAttention call is checked against PyTorch's attention**, once for each precision and head+ size. If the result is wrong or the kernel fails, InvokeAI logs a warning once and that GPU uses PyTorch's attention+ until restart. Some GPU faults (an illegal memory access, for example) leave the GPU unusable for the rest of the+ process: then PyTorch's attention fails the same way, and only a restart helps. A fault the GPU raises later, while+ 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).+ 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.- **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 da590ba1ca..36879cb892 100644--- a/invokeai/backend/util/sage_attention.py+++ b/invokeai/backend/util/sage_attention.py@@ -60,6 +60,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 = 3DOCS_URL = "https://invoke-ai.github.io/InvokeAI-7/configuration/optimization/sage-attention/"@@ -75,7 +79,9 @@ class _Usage:_scope: ContextVar[_Usage | None] = ContextVar("invokeai_sage_attention_scope", default=None)_lock = threading.Lock()_disabled_devices: set[int] = set()-_validated_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()_announced_devices: set[int] = set()@@ -120,10 +126,12 @@ def _kernel() -> Callable[..., torch.Tensor] | None:"""SageAttention's kernel for a GPU of this compute capability, or None where it has none.- The same kernels and accumulation SageAttention 2.2's own ``sageattn`` dispatches to -- including its choice by the- CUDA version torch was built for: the FP16 accumulation inside the FP8 kernels needs CUDA 12.8 to compile, and- below that the build replaces it with a trap -- but 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+ The kernels and accumulation upstream SageAttention 2.2's ``sageattn`` (thu-ml) dispatches to: the FP16 CUDA+ kernel on sm80, the Triton one on sm86, nothing on sm87. The Windows build moved sm86 and sm87 to the CUDA kernel+ without saying why; neither has been measured here, so upstream's choice stands. From the Windows build come the+ sm100 kernel and the choice by the CUDA version torch was built for: the FP16 accumulation inside the FP8 kernels+ needs 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 firstblock of Qwen-Image and Krea-2, where one channel of Q and K sits near +600 for every image token, that leaves theINT8 product Q.K no precision for the rest: cosine 0.18 and 0.53 against a float32 reference, 0.997 and 0.988 withsmoothing off. Everywhere else measured it changes nothing, and off is 2-11 % faster (RTX 4090). Only sm_89 has been@@ -131,8 +139,10 @@ def _kernel("""major, minor = capabilityrecent_cuda = cuda >= (12, 8)- if major == 8 and minor != 9: # Ampere: FP16 P.V+ if (major, minor) == (8, 0): # A100: FP16 P.Vkernel, options = sageattention.sageattn_qk_int8_pv_fp16_cuda, {"pv_accum_dtype": "fp32"}+ elif (major, minor) == (8, 6): # RTX 30-series, A10, A40: FP16 P.V in Triton+ kernel, options = sageattention.sageattn_qk_int8_pv_fp16_triton, {}elif (major, minor) == (8, 9): # Ada: FP8 P.Vkernel = sageattention.sageattn_qk_int8_pv_fp8_cudaoptions = {"pv_accum_dtype": "fp32+fp16" if recent_cuda else "fp32+fp32"}@@ -154,15 +164,16 @@ def _unaccepted_arguments(kernel: functools.partial) -> list[str]:def _cuda_index(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor) -> int | None:- """The CUDA index of q/k/v when all three live on this thread's current device, else None.+ """The CUDA index of q/k/v when all three live on the same CUDA device, else None.- SageAttention launches its kernels on the thread's current device without switching to the tensors' device, so- tensors anywhere else would be read from the wrong GPU. Session workers pin their thread to their own device.+ SageAttention launches its kernels on the thread's current device without switching to the tensors' device, so the+ wrapper makes that device current for the call. Session workers pin their thread to their device already; a+ single-device install with `device: cuda:1` does not."""device = query.device- if device.type != "cuda" or key.device != device or value.device != device:+ if device.type != "cuda" or device.index is None or key.device != device or value.device != device:return None- return device.index if device.index == torch.cuda.current_device() else None+ return device.indexdef _ineligible(@@ -222,13 +233,14 @@ def _check_first_result(scale: float | None,out: torch.Tensor,) -> None:- """Raise unless a device's first SageAttention result agrees with PyTorch's.+ """Raise unless the first SageAttention result of this kernel variant agrees with PyTorch's.SageAttention launches its CUDA kernels without checking for errors, so a kernel the installed build lacks forthis GPU raises nothing: it returns uninitialized memory, and the launch error surfaces in some later, unrelatedtorch operation -- outside the fallback. Recomputing a slice of the first result with PyTorch, and reading the- comparison back to the host, brings both into the caller's ``try``. Once per device; later calls are not compared.- The slice is the first sample's first K/V head group and its last ``_FIRST_CALL_ROWS`` query rows.+ comparison back to the host, brings both into the caller's ``try``. Once per device, precision and head size --+ the inputs that pick a different compiled kernel; later calls are not compared. The slice is the first sample's+ first K/V head group and its last ``_FIRST_CALL_ROWS`` query rows."""group = query.shape[1] // key.shape[1]rows = slice(-_FIRST_CALL_ROWS, None)@@ -239,7 +251,23 @@ def _check_first_result(if not math.isfinite(error) or error > _FIRST_CALL_MAX_ERROR:raise RuntimeError(f"its first result differs from PyTorch SDPA by {error:.2f} (relative L2)")with _lock:- _validated_devices.add(index)+ _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."""+ with _lock:+ _transient_failures[index] += 1+ return _transient_failures[index] >= _MAX_TRANSIENT_FAILURESdef _disable(index: int, error: Exception, query: torch.Tensor, key: torch.Tensor) -> None:@@ -353,22 +381,25 @@ def install_sage_attention() -> None:reason = "device"else:try:- out = kernel(- query,- key,- value,- tensor_layout="HND",- is_causal=False,- sm_scale=scale if scale is not None else query.shape[-1] ** -0.5,- )- if index not in _validated_devices:- _check_first_result(index, original, query, key, value, scale, out)- except torch.OutOfMemoryError:- # A resource condition, not a sign the kernel cannot serve this device.- raise+ with torch.cuda.device(index):+ out = kernel(+ query,+ key,+ value,+ tensor_layout="HND",+ is_causal=False,+ sm_scale=scale if scale is not None else query.shape[-1] ** -0.5,+ )+ if (index, query.dtype, query.shape[-1]) not in _validated:+ _check_first_result(index, original, query, key, value, scale, out)except Exception as e:- _disable(index, e, query, key)- reason = "error"+ # 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"+ else:+ _disable(index, e, query, key)+ reason = "error"else:usage.served += 1_announce(index, version, kernel)diff --git a/tests/backend/util/test_sage_attention.py b/tests/backend/util/test_sage_attention.pyindex f86ecfa444..d670f085d1 100644--- a/tests/backend/util/test_sage_attention.py+++ b/tests/backend/util/test_sage_attention.py@@ -9,9 +9,12 @@ CPU tensors stand in for the CUDA device and a fake `sageattention` module for thow the real kernels behave; `TestOnNvidiaHardware` does, on a GPU with SageAttention installed (`-m slow`)."""+import contextlib+import functoolsimport importlib.utilimport loggingimport threading+from collections import Counterfrom importlib.metadata import PackageNotFoundErrorfrom pathlib import Pathfrom types import SimpleNamespace@@ -28,6 +31,7 @@ TORCH_SDPA = F.scaled_dot_product_attentionVERSION = "2.2.0+cu130torch2.10.0andhigher.post6"KERNELS = ("sageattn_qk_int8_pv_fp16_cuda",+ "sageattn_qk_int8_pv_fp16_triton","sageattn_qk_int8_pv_fp8_cuda","sageattn_qk_int8_pv_fp8_cuda_sm90",)@@ -115,11 +119,20 @@ def _cuda_build(monkeypatch.setattr(sage, "_import_sageattention", lambda: (VERSION, module))monkeypatch.setattr(sage, "_cuda_index", lambda q, k, v: 0)monkeypatch.setattr(sage, "_disabled_devices", set())- monkeypatch.setattr(sage, "_validated_devices", set(capabilities))+ monkeypatch.setattr(sage, "_validated", _all_variants(capabilities))+ monkeypatch.setattr(sage, "_transient_failures", Counter())monkeypatch.setattr(sage, "_announced_devices", set())+ monkeypatch.setattr(torch.cuda, "device", lambda index: contextlib.nullcontext())return module, torch_calls+def _all_variants(devices) -> set:+ """Every kernel variant of these devices, as if each had passed its first-call check."""+ return {+ (index, dtype, head_dim) for index in devices for dtype in sage._HALF_PRECISION for head_dim in sage._HEAD_DIMS+ }++@pytest.fixturedef installed(monkeypatch):"""The wrapper installed on a build that looks like CUDA 13 with one sm_89 device."""@@ -135,7 +148,8 @@ class TestKernelTable:("capability", "cuda", "kernel", "options"),[((8, 0), (13, 0), "sageattn_qk_int8_pv_fp16_cuda", {"pv_accum_dtype": "fp32"}),- ((8, 6), (13, 0), "sageattn_qk_int8_pv_fp16_cuda", {"pv_accum_dtype": "fp32"}),+ # Upstream's `sageattn` picks the Triton kernel here; the Windows build moved sm86 to CUDA unexplained.+ ((8, 6), (13, 0), "sageattn_qk_int8_pv_fp16_triton", {}),((8, 9), (13, 0), "sageattn_qk_int8_pv_fp8_cuda", {"pv_accum_dtype": "fp32+fp16"}),((8, 9), (12, 6), "sageattn_qk_int8_pv_fp8_cuda", {"pv_accum_dtype": "fp32+fp32"}),((9, 0), (13, 0), "sageattn_qk_int8_pv_fp8_cuda_sm90", {"pv_accum_dtype": "fp32+fp32"}),@@ -155,7 +169,9 @@ class TestKernelTable:assert module.calls[0]["kernel"] == kernelassert {name: module.calls[0][name] for name in (*options, "smooth_k")} == options | {"smooth_k": False}- @pytest.mark.parametrize("capability", [(7, 5), (10, 3), (11, 0)], ids=["turing", "sm103", "sm110"])+ @pytest.mark.parametrize(+ "capability", [(7, 5), (8, 7), (10, 3), (11, 0)], ids=["turing", "jetson-orin", "sm103", "sm110"]+ )def test_gpus_sageattention_has_no_kernel_for_get_none(self, capability):assert sage._kernel(FakeSageAttention(), capability, (13, 0)) is None@@ -255,6 +271,24 @@ class TestRouting:assert module.calls == [] and len(torch_calls) == 1+ def test_a_call_under_cuda_autocast_reaches_torch(self, installed, monkeypatch):+ """Autocast would hand SageAttention whatever dtype it picks; torch's SDPA applies autocast's rules itself."""+ module, torch_calls = installed+ monkeypatch.setattr(torch, "is_autocast_enabled", lambda device_type=None: device_type == "cuda")+ q, k = _q(1, 2, QUERY_LEN, 64), _q(1, 2, KEY_LEN, 64)++ with sage_attention_scope():+ F.scaled_dot_product_attention(q, k, k)++ assert module.calls == [] and len(torch_calls) == 1++ @pytest.mark.filterwarnings("ignore:The PyTorch API of nested tensors")+ def test_a_nested_query_is_not_eligible(self):+ """Nested (jagged) tensors report four dimensions but have no fixed sequence length to quantize over."""+ q = torch.nested.nested_tensor([_q(2, QUERY_LEN, 64), _q(2, QUERY_LEN + 1, 64)])+ k = _q(2, 2, KEY_LEN, 64)+ assert sage._ineligible(q, k, k, None, 0.0, False, False, False) == "shape"+def test_an_unknown_keyword_reaches_torch_rather_than_being_dropped(self, installed):module, torch_calls = installedq, k = _q(1, 2, QUERY_LEN, 64), _q(1, 2, KEY_LEN, 64)@@ -278,7 +312,7 @@ class TestRouting:class TestFirstCallCheck:def test_a_devices_first_result_is_compared_with_torch_once(self, monkeypatch):module, torch_calls = _cuda_build(monkeypatch, {0: (8, 9)})- monkeypatch.setattr(sage, "_validated_devices", set())+ monkeypatch.setattr(sage, "_validated", set())install_sage_attention()q, k = _q(1, 2, QUERY_LEN, 64), _q(1, 2, KEY_LEN, 64)@@ -289,11 +323,41 @@ class TestFirstCallCheck:assert len(module.calls) == 2, "both calls ran on the kernel"assert len(torch_calls) == 1, "only the first was also computed by torch, for the comparison"+ def test_the_check_pairs_a_gqa_query_group_with_its_own_kv_head(self, monkeypatch):+ """Query heads 0-3 attend to K/V head 0; comparing them with head 1 instead would retire a correct kernel."""+ module, torch_calls = _cuda_build(monkeypatch, {0: (8, 9)})+ monkeypatch.setattr(sage, "_validated", set())+ install_sage_attention()+ q, k, v = _q(1, 8, QUERY_LEN, 64), _q(1, 2, KEY_LEN, 64), _q(1, 2, KEY_LEN, 64)+ v[:, 1] += 3.0 # a K/V head unlike head 0, so a wrong pairing cannot pass++ with sage_attention_scope():+ F.scaled_dot_product_attention(q, k, v, enable_gqa=True)+ F.scaled_dot_product_attention(q, k, v, enable_gqa=True)++ assert len(module.calls) == 2, "the check passed, so the device stays on the kernel"+ assert len(torch_calls) == 1 and torch_calls[0]["gqa"] and torch_calls[0]["q"] == (1, 4, 1024, 64)++ def test_each_precision_and_head_size_is_checked_on_its_first_call(self, monkeypatch):+ """They select different compiled kernels; one passing says nothing about the others."""+ module, torch_calls = _cuda_build(monkeypatch, {0: (8, 9)})+ monkeypatch.setattr(sage, "_validated", set())+ install_sage_attention()+ hd64, hd128 = _q(1, 2, QUERY_LEN, 64), _q(1, 2, QUERY_LEN, 128)+ bf16 = _q(1, 2, QUERY_LEN, 64, dtype=torch.bfloat16)++ with sage_attention_scope():+ for q in (hd64, hd64, hd128, hd128, bf16, bf16):+ F.scaled_dot_product_attention(q, q, q)++ assert len(module.calls) == 6+ assert len(torch_calls) == 3, "one comparison per variant"+@pytest.mark.parametrize("garbage", [torch.nan, 50.0], ids=["non-finite", "wrong"])def test_a_wrong_first_result_retires_the_device_and_returns_torchs(self, monkeypatch, caplog, garbage):"""A kernel the build lacks for this GPU returns uninitialized memory instead of raising."""module, torch_calls = _cuda_build(monkeypatch, {0: (8, 9)})- monkeypatch.setattr(sage, "_validated_devices", set())+ monkeypatch.setattr(sage, "_validated", set())install_sage_attention()q, k = _q(1, 2, QUERY_LEN, 64), _q(1, 2, KEY_LEN, 64)module.result = torch.full((1, 2, QUERY_LEN, 64), garbage, dtype=torch.float16)@@ -333,18 +397,46 @@ class TestFailures:F.scaled_dot_product_attention(q, k, k)assert len(module.calls) == 2, "another device is unaffected"- def test_out_of_memory_propagates_and_does_not_retire_the_device(self, installed):- module, _ = installed- module.error = torch.OutOfMemoryError("CUDA out of memory")+ @pytest.mark.parametrize(+ "error",+ [+ 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"],+ )+ 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."""+ module, torch_calls = installed+ module.error = errorq, 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(), pytest.raises(torch.OutOfMemoryError):+ with sage_attention_scope():+ out = F.scaled_dot_product_attention(q, k, k)+ module.error = NoneF.scaled_dot_product_attention(q, k, k)- module.error = None+ 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]++ 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."""+ 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():- F.scaled_dot_product_attention(q, k, k)- assert len(module.calls) == 2+ for _ in range(sage._MAX_TRANSIENT_FAILURES + 2):+ 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+ 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):module, torch_calls = installed@@ -397,21 +489,43 @@ class TestDeviceRule:def _on(index: int) -> SimpleNamespace:return SimpleNamespace(device=torch.device("cuda", index))- def test_tensors_on_the_threads_current_device_are_eligible(self, monkeypatch):- monkeypatch.setattr(torch.cuda, "current_device", lambda: 1)+ def test_tensors_on_one_cuda_device_give_its_index(self):assert sage._cuda_index(self._on(1), self._on(1), self._on(1)) == 1- def test_tensors_on_another_device_are_not(self, monkeypatch):- """SageAttention launches on the thread's current device; tensors elsewhere would be read from the wrong GPU."""- monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)- assert sage._cuda_index(self._on(1), self._on(1), self._on(1)) is None-- def test_mixed_devices_and_cpu_are_not(self, monkeypatch):- monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)+ def test_mixed_devices_and_cpu_do_not(self):assert sage._cuda_index(self._on(0), self._on(1), self._on(0)) is Nonecpu = SimpleNamespace(device=torch.device("cpu"))assert sage._cuda_index(cpu, cpu, cpu) is None+ def test_the_kernel_runs_with_the_tensors_device_current(self, monkeypatch):+ """SageAttention launches on the thread's current device. A single-device install with `device: cuda:1` never+ makes that device current, so the wrapper does, for the call only."""+ module, _ = _cuda_build(monkeypatch, {0: (8, 9), 1: (8, 9)})+ events: list[str] = []+ kernel = module.sageattn_qk_int8_pv_fp8_cuda++ @functools.wraps(kernel)+ def recording_kernel(*args, **kwargs):+ events.append("kernel")+ return kernel(*args, **kwargs)++ @contextlib.contextmanager+ def recording_device(index):+ events.append(f"enter cuda:{index}")+ yield+ events.append("exit")++ module.sageattn_qk_int8_pv_fp8_cuda = recording_kernel+ monkeypatch.setattr(torch.cuda, "device", recording_device)+ monkeypatch.setattr(sage, "_cuda_index", lambda q, k, v: 1)+ install_sage_attention()+ q, k = _q(1, 2, QUERY_LEN, 64), _q(1, 2, KEY_LEN, 64)++ with sage_attention_scope():+ F.scaled_dot_product_attention(q, k, k)++ assert events == ["enter cuda:1", "kernel", "exit"]+def _raise(error: Exception):def raiser():@@ -552,7 +666,7 @@ class TestOnNvidiaHardware:pytest.skip("SageAttention 2 needs compute capability 8.0 or newer")monkeypatch.setattr(F, "scaled_dot_product_attention", TORCH_SDPA)monkeypatch.setattr(sage, "_disabled_devices", set())- monkeypatch.setattr(sage, "_validated_devices", set())+ monkeypatch.setattr(sage, "_validated", 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)")@@ -563,7 +677,7 @@ class TestOnNvidiaHardware:def test_every_kernel_takes_the_arguments_it_is_given(self, kernel):import sageattention- for capability in ((8, 0), (8, 9), (9, 0), (12, 0)):+ for capability in ((8, 0), (8, 6), (8, 9), (9, 0), (12, 0)):assert sage._unaccepted_arguments(sage._kernel(sageattention, capability, (13, 0))) == []@pytest.mark.parametrize(@@ -592,6 +706,20 @@ 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."""