Skip to content

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.

fix(rocm): harden allocator default, paging warning and SDPA chunking

Alexander Eichhorn97668ebd4bc4
diff --git a/invokeai/app/services/session_processor/session_processor_default.py b/invokeai/app/services/session_processor/session_processor_default.py
index 6580e2e19c..e4151b0dbd 100644
--- a/invokeai/app/services/session_processor/session_processor_default.py
+++ b/invokeai/app/services/session_processor/session_processor_default.py
@@ -559,7 +559,8 @@ class _SessionWorker:
self.cancel_event = ThreadEvent()
self.queue_item: Optional[SessionQueueItem] = None
self.thread: Optional[Thread] = None
- # Paged-out VRAM at the last warning; only this worker's thread reads or writes it.
+ # Paged-out VRAM at the previous session's end and at the last warning; only this worker's thread uses them.
+ self.paging_last_bytes = 0
self.paging_warned_bytes = 0
@property
@@ -849,14 +850,14 @@ class DefaultSessionProcessor(SessionProcessorBase):
)
def _warn_if_vram_paged(self, worker: _SessionWorker) -> None:
- """Say so when Windows keeps part of this worker's GPU memory in shared system memory after a session.
+ """Say so when Windows keeps part of this worker's GPU memory in shared system memory across sessions.
On a ROCm build under Windows an allocation that does not fit the video-memory budget, or finds no contiguous
VRAM, is placed in system memory instead of failing -- and another program on the same GPU can push this
- process's memory out the same way. It stays there, and every generation that touches it slows down, with
- nothing else in the log to explain why. Warns once per episode: again only after it grew by the threshold,
- and re-armed once it drops below it. Measured after the session's VRAM release, so the transient paging of a
- weight upload is over. `paged_bytes` answers None everywhere else, which keeps this silent there.
+ process's memory out the same way. Every generation that touches it slows down, with nothing else in the log to
+ explain why. Only what was paged at the end of two consecutive sessions counts: an overflow at the end of a
+ decode can return to VRAM within seconds. Warns once per episode: again only after that grew by the threshold,
+ re-armed once a reading drops below it. `paged_bytes` answers None everywhere else, which keeps this silent.
"""
try:
paged = paged_bytes(worker.device or TorchDevice.choose_torch_device())
@@ -865,16 +866,19 @@ class DefaultSessionProcessor(SessionProcessorBase):
return
if paged is None:
return
+ sustained = min(paged, worker.paging_last_bytes)
+ worker.paging_last_bytes = paged
if paged < _VRAM_PAGING_WARNING_BYTES:
worker.paging_warned_bytes = 0
return
- if paged < worker.paging_warned_bytes + _VRAM_PAGING_WARNING_BYTES:
+ if sustained < worker.paging_warned_bytes + _VRAM_PAGING_WARNING_BYTES:
return
- worker.paging_warned_bytes = paged
+ worker.paging_warned_bytes = sustained
self._invoker.services.logger.warning(
- f"Windows is keeping {paged / 2**30:.1f} GiB of Invoke's GPU memory on {worker.label} in shared system "
- "memory, which makes generations much slower. Close other programs that use this GPU; if it persists, "
- "restart Invoke to get the memory back into VRAM."
+ f"Windows kept {sustained / 2**30:.1f} GiB of Invoke's GPU memory on {worker.label} in shared system memory "
+ "after the last two generations, which makes them much slower. Close other programs that use this GPU. If "
+ "it keeps happening, lower the image size, set max_cache_vram_gb lower or device_working_mem_gb higher, "
+ "and restart Invoke to get the memory back into VRAM."
)
def resume(self) -> SessionProcessorStatus:
diff --git a/invokeai/app/util/torch_cuda_allocator.py b/invokeai/app/util/torch_cuda_allocator.py
index b7dd513dc5..a6f1d30fbf 100644
--- a/invokeai/app/util/torch_cuda_allocator.py
+++ b/invokeai/app/util/torch_cuda_allocator.py
@@ -36,6 +36,12 @@ def apply_rocm_windows_allocator_default(logger: logging.Logger) -> None:
torch_version = _installed_torch_version()
if torch_version is None or "+rocm" not in torch_version:
return
+ if "torch" in sys.modules:
+ # Setting the variable now would change nothing but the model cache's reading of it.
+ logger.warning(
+ "ROCm on Windows: torch was imported before the allocator default could apply; leaving it unset."
+ )
+ return
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = ROCM_WINDOWS_ALLOC_CONF
logger.info(
f"ROCm on Windows: using the expandable-segments allocator (PYTORCH_CUDA_ALLOC_CONF={ROCM_WINDOWS_ALLOC_CONF}), "
diff --git a/invokeai/backend/util/attention.py b/invokeai/backend/util/attention.py
index 18e8d8ca48..d98f558b90 100644
--- a/invokeai/backend/util/attention.py
+++ b/invokeai/backend/util/attention.py
@@ -188,6 +188,13 @@ def _math_score_bytes(query: torch.Tensor, key: torch.Tensor) -> int:
return batch * heads * query_len * key.shape[-2] * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+def _chunkable_kv(query: torch.Tensor, key: torch.Tensor, value: torch.Tensor) -> bool:
+ """Whether `_chunked_sdpa` slices K/V correctly: 4-D and of the query's batch. Other broadcasts that math SDPA
+ accepts (3-D K/V, a wider K/V batch) stay whole."""
+ batch = query.shape[0]
+ return key.dim() == value.dim() == 4 and key.shape[0] == value.shape[0] == batch
+
+
def _materializes(
query: torch.Tensor,
key: torch.Tensor,
@@ -344,6 +351,7 @@ def install_rocm_sdpa_guard() -> None:
and not args
and not kwargs
and _math_score_bytes(query, key) > SDPA_MATH_CHUNK_BYTES
+ and _chunkable_kv(query, key, value)
and (wide_head or _materializes(query, key, value, attn_mask, scale, enable_gqa))
)
if wide_head:
diff --git a/tests/app/invocations/test_krea2_denoise.py b/tests/app/invocations/test_krea2_denoise.py
index 2a5588042b..39ebc1e8e3 100644
--- a/tests/app/invocations/test_krea2_denoise.py
+++ b/tests/app/invocations/test_krea2_denoise.py
@@ -850,13 +850,15 @@ class TestTheAttentionScoreMatrixReachesTheReservation:
the main blocks also build a score matrix (12.9 GiB per call for 1024px unchunked), and the reservation must
price it: for the heads of the loaded model and the sequence the transformer really attends over."""
- def _reservation_for(self, monkeypatch, tmp_path, score_bytes: int) -> tuple[int, list[dict], _Transformer]:
+ def _reservation_for(
+ self, monkeypatch, tmp_path, score_bytes: int, invocation=None, **context_kwargs
+ ) -> tuple[int, list[dict], _Transformer]:
import invokeai.app.invocations.krea2.krea2_denoise as denoise_module
transformer = _Transformer()
transformer.config = SimpleNamespace(num_attention_heads=48, attention_head_dim=128)
info = _TransformerInfo(transformer)
- context = _runtime_context(tmp_path, transformer)
+ context = _runtime_context(tmp_path, transformer, **context_kwargs)
context.models.load = lambda _identifier: info
_patch_runtime(monkeypatch)
asked: list[dict] = []
@@ -866,7 +868,7 @@ class TestTheAttentionScoreMatrixReachesTheReservation:
return score_bytes
monkeypatch.setattr(denoise_module, "sdpa_score_matrix_bytes", score_matrix_bytes)
- _runtime_invocation(cfg_scale=1.0)._run_diffusion(context)
+ (invocation or _runtime_invocation(cfg_scale=1.0))._run_diffusion(context)
return info.working_mem_bytes, asked, transformer
def test_the_score_matrix_is_reserved_for_the_attended_sequence(self, monkeypatch, tmp_path) -> None:
@@ -877,3 +879,21 @@ class TestTheAttentionScoreMatrixReachesTheReservation:
assert len(asked) == 1
assert (asked[0]["num_heads"], asked[0]["head_dim"]) == (48, 128)
assert asked[0]["seq_len"] == transformer.combined_sequence_lengths[0]
+ assert asked[0]["has_attn_mask"] is False
+
+ def test_the_longer_of_the_cfg_passes_and_the_regional_mask_are_priced(self, monkeypatch, tmp_path) -> None:
+ invocation = _runtime_invocation(cfg_scale=2.0)
+ invocation.positive_conditioning = Krea2ConditioningField(
+ conditioning_name="positive", mask=TensorField(tensor_name="positive-region")
+ )
+ invocation.negative_conditioning = Krea2ConditioningField(
+ conditioning_name="negative", mask=TensorField(tensor_name="negative-region")
+ )
+
+ _, asked, transformer = self._reservation_for(
+ monkeypatch, tmp_path, score_bytes=1, invocation=invocation, negative_text_seq_len=5
+ )
+
+ assert len(set(transformer.combined_sequence_lengths)) == 2, "the passes must attend over different lengths"
+ assert asked[0]["seq_len"] == max(transformer.combined_sequence_lengths)
+ assert asked[0]["has_attn_mask"] is True
diff --git a/tests/app/services/session_processor/conftest.py b/tests/app/services/session_processor/conftest.py
new file mode 100644
index 0000000000..2481f2dad5
--- /dev/null
+++ b/tests/app/services/session_processor/conftest.py
@@ -0,0 +1,10 @@
+import pytest
+
+
[email protected](autouse=True)
+def _no_real_paged_vram_reading(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Every completed session asks Windows how much of the GPU memory is paged out. On a Windows ROCm machine that
+ would be a real PDH query per session; the tests that need an answer script their own."""
+ monkeypatch.setattr(
+ "invokeai.app.services.session_processor.session_processor_default.paged_bytes", lambda device: None
+ )
diff --git a/tests/app/services/session_processor/test_vram_paging_warning.py b/tests/app/services/session_processor/test_vram_paging_warning.py
index a12a0386d1..1746e2e1b4 100644
--- a/tests/app/services/session_processor/test_vram_paging_warning.py
+++ b/tests/app/services/session_processor/test_vram_paging_warning.py
@@ -1,7 +1,8 @@
"""The end-of-session warning when Windows keeps part of a worker's VRAM in shared system memory.
-It must speak once per episode (again only after the paged amount grew by the threshold, re-armed once it fell below
-it), say nothing where the answer is unknown, and never fail the worker.
+It must count only what stayed paged across two session ends, speak once per episode (again only after that grew by
+the threshold, re-armed once a reading fell below it), say nothing where the answer is unknown, and never fail the
+worker.
"""
from types import SimpleNamespace
@@ -63,15 +64,28 @@ def test_warns_once_per_episode_and_again_only_after_growth(monkeypatch, process
threshold = _VRAM_PAGING_WARNING_BYTES
readings = [
6 * MIB, # an idle process
- threshold + 100 * MIB, # paged: warn
- threshold + 300 * MIB, # grew by less than the threshold since the warning
- 2 * threshold + 200 * MIB, # grew by the threshold: warn again
+ threshold + 100 * MIB, # paged, once so far
+ threshold + 300 * MIB, # still paged: warn
+ 2 * threshold + 400 * MIB, # what stayed paged grew by less than the threshold since the warning
+ 2 * threshold + 500 * MIB, # grew by the threshold: warn again
100 * MIB, # recovered below the threshold: re-armed
+ threshold,
threshold, # a new episode: warn
]
- assert _warned_after_each_session(monkeypatch, processor, readings) == [False, True, False, True, False, True]
+ warned = _warned_after_each_session(monkeypatch, processor, readings)
+
+ assert warned == [False, False, True, False, True, False, False, True]
assert "cuda:0" in processor[1].warnings[0]
+ assert "0.6 GiB" in processor[1].warnings[0] # what stayed paged (0.6), not the latest reading (0.8)
+
+
+def test_paging_that_clears_between_sessions_is_not_reported(monkeypatch, processor):
+ """A decode can overflow for a few seconds at the end of every session and then return to VRAM."""
+ paged, cleared = _VRAM_PAGING_WARNING_BYTES + 400 * MIB, 6 * MIB
+ readings = [paged, cleared, paged, cleared, paged]
+
+ assert _warned_after_each_session(monkeypatch, processor, readings) == [False] * 5
def test_silent_where_the_answer_is_unknown(monkeypatch, processor):
@@ -90,3 +104,15 @@ def test_a_failing_counter_is_logged_at_debug_and_does_not_fail_the_worker(monke
assert logger.warnings == []
assert len(logger.debugs) == 1
+
+
+def test_the_worker_checks_after_each_session(monkeypatch):
+ from tests.app.services.session_processor.test_session_processor_cancel_guard import _run_guard_scenario
+
+ checked = []
+ monkeypatch.setattr(DefaultSessionProcessor, "_warn_if_vram_paged", lambda self, worker: checked.append(worker))
+
+ _canceled, run_items, worker = _run_guard_scenario(statuses=["in_progress"], set_cancel_event=False)
+
+ assert run_items == [42]
+ assert checked == [worker]
diff --git a/tests/app/util/test_torch_cuda_allocator.py b/tests/app/util/test_torch_cuda_allocator.py
index 92df4d5327..3e2ddf8715 100644
--- a/tests/app/util/test_torch_cuda_allocator.py
+++ b/tests/app/util/test_torch_cuda_allocator.py
@@ -17,8 +17,12 @@ def rocm_windows(monkeypatch: pytest.MonkeyPatch):
"""A Windows ROCm install with no allocator configuration in the environment."""
monkeypatch.setattr(sys, "platform", "win32")
monkeypatch.setattr(torch_cuda_allocator, "_installed_torch_version", lambda: "2.12.0+rocm7.14.1")
+ monkeypatch.delitem(sys.modules, "torch") # as at startup, before anything imports it
for var in _ALLOCATOR_ENV_VARS:
- monkeypatch.delenv(var, raising=False)
+ # setenv first so teardown also removes what the code under test sets: delenv on an absent
+ # variable records nothing to undo, and the leaked value would reach later tests' allocator.
+ monkeypatch.setenv(var, "")
+ monkeypatch.delenv(var)
return monkeypatch
@@ -56,6 +60,17 @@ class TestRocmWindowsAllocatorDefault:
assert "PYTORCH_CUDA_ALLOC_CONF" not in os.environ
logger.info.assert_not_called()
+ def test_too_late_once_torch_is_imported(self, rocm_windows):
+ """The allocator reads the variable at import; setting it later would only mislead the model cache, which
+ parses it to decide whether allocator-held blocks count as free."""
+ rocm_windows.setitem(sys.modules, "torch", torch)
+ logger = MagicMock()
+
+ apply_rocm_windows_allocator_default(logger)
+
+ assert "PYTORCH_CUDA_ALLOC_CONF" not in os.environ
+ logger.warning.assert_called_once()
+
# These tests are a bit fiddly, because the depend on the import behaviour of torch. They use subprocesses to isolate
# the import behaviour of torch, and then check that the function behaves as expected. We have to hack in some logging
diff --git a/tests/backend/util/test_rocm_sdpa_head_dim_guard.py b/tests/backend/util/test_rocm_sdpa_head_dim_guard.py
index 0b3419d373..d02979d014 100644
--- a/tests/backend/util/test_rocm_sdpa_head_dim_guard.py
+++ b/tests/backend/util/test_rocm_sdpa_head_dim_guard.py
@@ -237,6 +237,10 @@ class TestChunking:
(6, 2, 3, {"enable_gqa": True}),
(6, 2, 2, {"enable_gqa": True}),
(4, 1, 2, {}),
+ (4, 4, 0.5, {"attn_mask": torch.rand(64, 48) > 0.3}),
+ (4, 4, 0.5, {"attn_mask": torch.randn(2, 1, 64, 48)}),
+ (4, 4, 0.5, {"attn_mask": torch.randn(2, 4, 64, 48)}),
+ (4, 4, 0.5, {"attn_mask": torch.rand(2, 1, 1, 48) > 0.2}),
],
ids=[
"bool-2d",
@@ -248,10 +252,14 @@ class TestChunking:
"gqa-whole-groups",
"gqa-group-over-budget",
"kv-broadcast",
+ "rows-bool-2d",
+ "rows-additive-broadcast-heads",
+ "rows-additive-per-head",
+ "rows-bool-broadcast-rows",
],
)
def test_masks_scale_and_grouped_heads_keep_torchs_result(self, monkeypatch, heads, kv_heads, budget_heads, kwargs):
- budget = budget_heads * 2 * 64 * 48 * BYTES
+ budget = int(budget_heads * 2 * 64 * 48 * BYTES) # under one head, the query rows are split
shapes = _install_chunking(monkeypatch, budget=budget)
torch.manual_seed(2)
q = torch.randn(2, heads, 64, 32)
@@ -263,6 +271,21 @@ class TestChunking:
assert all(_scores(pair) <= budget for pair in shapes), "a chunk exceeded the budget"
torch.testing.assert_close(out, TORCH_SDPA(q, k, v, **kwargs), atol=1e-5, rtol=1e-4)
+ @pytest.mark.parametrize(
+ ("q_shape", "kv_shape"),
+ [((2, 4, 64, 32), (4, 48, 32)), ((1, 4, 64, 32), (2, 4, 48, 32))],
+ ids=["3d-kv", "kv-wider-batch"],
+ )
+ def test_kv_broadcasts_the_chunks_cannot_slice_stay_whole(self, monkeypatch, q_shape, kv_shape):
+ shapes = _install_chunking(monkeypatch, budget=BYTES)
+ torch.manual_seed(3)
+ q, k, v = torch.randn(q_shape), torch.randn(kv_shape), torch.randn(kv_shape)
+
+ out = F.scaled_dot_product_attention(q, k, v)
+
+ assert len(shapes) == 1
+ torch.testing.assert_close(out, TORCH_SDPA(q, k, v))
+
@pytest.mark.parametrize("kwargs", [{"is_causal": True}, {"dropout_p": 0.1}], ids=["causal", "dropout"])
def test_causal_and_dropout_calls_stay_whole(self, monkeypatch, kwargs):
shapes = _install_chunking(monkeypatch, budget=BYTES)
@@ -393,15 +416,18 @@ class TestOnRocmHardware:
reference = attention._math_sdpa(q, k, v, None, 0.0, False, None, False).float()
# The unguarded entry point, whether or not the guard is installed in this process.
unguarded = getattr(F.scaled_dot_product_attention, "__wrapped__", F.scaled_dot_product_attention)
- wrong = 0
+ wrong = ran = 0
for backend in (SDPBackend.FLASH_ATTENTION, SDPBackend.EFFICIENT_ATTENTION):
with sdpa_policy([backend]):
try:
out = unguarded(q, k, v).float()
except RuntimeError:
continue # the backend refused the shape: not wrong, just absent
+ ran += 1
err = (out - reference).abs().max().item() / reference.abs().max().item()
wrong += int(not torch.isfinite(out).all() or err > 0.05)
+ if not ran:
+ pytest.skip("no fused kernel runs this shape on this build (e.g. gfx1200)")
assert wrong > 0, "every fused kernel now agrees with math: the ROCm head-dim guard may be unnecessary"
def test_the_guard_is_exact_under_allocation_churn(self, monkeypatch):