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
perf: feed the MiniMax H3 attention kernel head-major-contiguous Q/K/V
Lincoln Stein3b1e7461b8aa
diff --git a/invokeai/backend/minimax_h3/contiguous_attention.py b/invokeai/backend/minimax_h3/contiguous_attention.pynew file mode 100644index 0000000000..38cfb1ea80--- /dev/null+++ b/invokeai/backend/minimax_h3/contiguous_attention.py@@ -0,0 +1,115 @@+"""Hand the MiniMax H3 attention kernel head-major-contiguous Q/K/V.++``MiniMaxH3AttnProcessor`` computes Q/K/V as ``[B, seq, heads, dim]`` (sequence-major) tensors+and diffusers' ``dispatch_attention_fn`` native backend permutes them to ``[B, heads, seq, dim]``+*views* for ``scaled_dot_product_attention`` — so the flash kernel receives transposed,+non-contiguous inputs. At video sequence lengths that layout costs real throughput, measured+with the H3 attention shape (56 heads, head_dim 128, bf16) on the two dev machines:++- AMD W7900 (torch 2.10+rocm7.1, AOTriton flash), N=59500: 8.8 TFLOPS effective transposed vs+ 17.9 contiguous — 2.0x. This matched a profiled real denoise step (9.33 s/call, 90% of a+ 540 s step) and was the dominant term in H3's ROCm step-time deficit.+- NVIDIA RTX 5060 Ti (cu128), N=59500: 34.3 transposed vs 45.3 contiguous — 1.32x. Neutral at+ N=25000 on NVIDIA; still +20% on AMD there.++The patched ``__call__`` below is upstream's byte-for-byte (see the vendoring note in+``__init__``: the vendored module itself must stay untouched) plus one step before dispatch:+re-materialize each tensor so its memory is head-major ("BHSD") contiguous while keeping the+sequence-major shape dispatch expects — the native backend's permute then yields fully+contiguous kernel inputs. Tensors are converted one at a time and rebound immediately, so at+most one extra ``[seq, heads*dim]`` bf16 tensor (~14 KB per row) is alive beyond the unpatched+peak — inside the denoise working-memory estimate's per-row headroom.++Applied at transformer load time (both the diffusers-folder and single-file loaders),+class-level and idempotent, on every platform: the copies cost ~milliseconds against+attention-kernel savings that reach seconds per call.+"""++import torch++from invokeai.backend.minimax_h3.transformer_minimax_h3 import (+ MiniMaxH3AttnProcessor,+ _apply_rotary_emb,+ dispatch_attention_fn,+)++_SENTINEL = "_invokeai_contiguous_qkv"+++def _head_major_contiguous(x: torch.Tensor) -> torch.Tensor:+ """Return ``x`` (shape ``[B, seq, heads, dim]``) with head-major-contiguous memory.++ The result compares equal element-wise and keeps the same shape; only the underlying+ layout changes, so the downstream ``permute(0, 2, 1, 3)`` produces a contiguous tensor.+ """+ head_major = x.transpose(1, 2)+ if head_major.is_contiguous():+ return x+ return head_major.contiguous().transpose(1, 2)+++def _contiguous_qkv_call(+ self,+ attn: "torch.nn.Module",+ hidden_states: torch.Tensor,+ rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,+ attention_mask: torch.Tensor | None = None,+) -> torch.Tensor:+ # --- begin upstream MiniMaxH3AttnProcessor.__call__ body (unchanged) ---+ if attn.fused_projections:+ query, key, value = attn.to_qkv(hidden_states).chunk(3, dim=-1)+ else:+ query = attn.to_q(hidden_states)+ key = attn.to_k(hidden_states)+ value = attn.to_v(hidden_states)++ query = query.unflatten(-1, (attn.heads, -1))+ key = key.unflatten(-1, (attn.heads, -1))+ value = value.unflatten(-1, (attn.heads, -1))++ query = attn.norm_q(query)+ key = attn.norm_k(key)++ if rotary_emb is not None:+ query = _apply_rotary_emb(query, *rotary_emb)+ key = _apply_rotary_emb(key, *rotary_emb)+ # --- end upstream body ---++ # InvokeAI addition: one tensor at a time so the replaced original is freed before the+ # next copy (bounds the transient to one extra tensor).+ query = _head_major_contiguous(query)+ key = _head_major_contiguous(key)+ value = _head_major_contiguous(value)++ # --- begin upstream body (unchanged) ---+ # Without padding rows the packed sequence is a single attention document and no mask is needed (passing an+ # all-zero float mask here would hard-fail the flash / sage backends). When padding rows are present, the+ # caller supplies a boolean mask that keeps them in their own attention document, mirroring the reference's+ # `cu_seqlens = [0, used, S]` split; masked backends (SDPA & co.) are required in that case.+ hidden_states = dispatch_attention_fn(+ query,+ key,+ value,+ attn_mask=attention_mask,+ dropout_p=0.0,+ is_causal=False,+ backend=self._attention_backend,+ parallel_config=self._parallel_config,+ )+ hidden_states = hidden_states.flatten(2, 3).type_as(query)+ hidden_states = attn.to_out[0](hidden_states)+ hidden_states = attn.to_out[1](hidden_states)+ return hidden_states+ # --- end upstream body ---+++def patch_minimax_h3_attention_contiguous_qkv() -> None:+ """Swap ``MiniMaxH3AttnProcessor.__call__`` for the contiguous-Q/K/V variant.++ Class-level and idempotent, mirroring ``patch_minimax_h3_causal_conv3d_for_rocm``.+ Unconditional across platforms: measured neutral-to-2x on every device tested.+ """+ if getattr(MiniMaxH3AttnProcessor, _SENTINEL, False):+ return+ MiniMaxH3AttnProcessor.__call__ = _contiguous_qkv_call+ setattr(MiniMaxH3AttnProcessor, _SENTINEL, True)diff --git a/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py b/invokeai/backend/model_manager/load/model_loaders/minimax_h3.pyindex da38598519..3f5e8a7c34 100644--- a/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py+++ b/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py@@ -86,7 +86,14 @@ class MiniMaxH3DiffusersModel(ModelLoader):_raise_if_no_weight_shards(submodel_path, "transformer")from invokeai.backend.minimax_h3 import MiniMaxH3Transformer3DModel+ from invokeai.backend.minimax_h3.contiguous_attention import (+ patch_minimax_h3_attention_contiguous_qkv,+ )+ # The attention kernel is ~2x slower on ROCm (and ~1.3x on CUDA) at video+ # sequence lengths when fed the processor's sequence-major Q/K/V layout; see+ # contiguous_attention for the measurements.+ patch_minimax_h3_attention_contiguous_qkv()return MiniMaxH3Transformer3DModel.from_pretrained(submodel_path, torch_dtype=dtype, local_files_only=True)@@ -163,6 +170,9 @@ class MiniMaxH3CheckpointModel(ModelLoader):from safetensors.torch import load_filefrom invokeai.backend.minimax_h3 import MiniMaxH3Transformer3DModel+ from invokeai.backend.minimax_h3.contiguous_attention import (+ patch_minimax_h3_attention_contiguous_qkv,+ )from invokeai.backend.minimax_h3.int8_convrot import Int8ConvrotLinearfrom invokeai.backend.minimax_h3.transformer_minimax_h3_pruned import (MiniMaxH3PrunedTransformer3DModel,@@ -175,6 +185,10 @@ class MiniMaxH3CheckpointModel(ModelLoader):model_path = Path(config.path)+ # Same attention-layout patch as the diffusers-folder path (the pruned subclass reuses+ # the vendored attention classes); see contiguous_attention for the measurements.+ patch_minimax_h3_attention_contiguous_qkv()+# Reject unsupported quantization formats from the header alone, before committing to# the ~20 GiB tensor read (the fp8_scaled repacks share this key layout).unsupported = sorted(diff --git a/tests/backend/minimax_h3/test_contiguous_attention.py b/tests/backend/minimax_h3/test_contiguous_attention.pynew file mode 100644index 0000000000..c305ca2cee--- /dev/null+++ b/tests/backend/minimax_h3/test_contiguous_attention.py@@ -0,0 +1,82 @@+"""Tests for the contiguous-Q/K/V attention layout patch.++The patch must be a pure layout change: same math (within kernel-selection float tolerance),+same shapes, applied idempotently at the class level, covering the pruned subclass too.+"""++import pytest+import torch++from invokeai.backend.minimax_h3.contiguous_attention import (+ _contiguous_qkv_call,+ _head_major_contiguous,+ patch_minimax_h3_attention_contiguous_qkv,+)+from invokeai.backend.minimax_h3.transformer_minimax_h3 import MiniMaxH3Attention, MiniMaxH3AttnProcessor+++def restore_processor():+ """Run a test with the pristine upstream __call__, restoring it afterward."""+ original_call = MiniMaxH3AttnProcessor.__dict__.get("__call__")+ sentinel = getattr(MiniMaxH3AttnProcessor, "_invokeai_contiguous_qkv", None)+ yield+ if original_call is not None:+ MiniMaxH3AttnProcessor.__call__ = original_call+ if sentinel is None and hasattr(MiniMaxH3AttnProcessor, "_invokeai_contiguous_qkv"):+ delattr(MiniMaxH3AttnProcessor, "_invokeai_contiguous_qkv")+++def test_head_major_contiguous_is_elementwise_identity():+ x = torch.randn(1, 64, 4, 8) # [B, seq, heads, dim], seq-major contiguous+ y = _head_major_contiguous(x)+ assert torch.equal(x, y)+ assert y.shape == x.shape+ # The memory layout changed: the head-major permute of the result is contiguous.+ assert y.transpose(1, 2).is_contiguous()+ # Already-head-major input is returned untouched (no copy).+ z = _head_major_contiguous(y)+ assert z is y+++def test_patched_call_matches_upstream(restore_processor):+ torch.manual_seed(0)+ attn = MiniMaxH3Attention(hidden_size=32, heads=4, dim_head=8).eval()+ hidden_states = torch.randn(1, 64, 32)+ # cos/sin are (seq_len, rotary_dim) with an even rotary_dim <= head_dim.+ angles = torch.outer(torch.arange(64, dtype=torch.float32), torch.tensor([1.0, 0.5, 0.25, 0.125]))+ cos, sin = torch.cos(angles), torch.sin(angles)++ with torch.no_grad():+ reference = MiniMaxH3AttnProcessor()(attn, hidden_states, rotary_emb=(cos, sin))+ processor = MiniMaxH3AttnProcessor()+ patched = _contiguous_qkv_call(processor, attn, hidden_states, rotary_emb=(cos, sin))++ assert patched.shape == reference.shape+ torch.testing.assert_close(patched, reference)+++def test_patch_is_class_level_and_idempotent(restore_processor):+ patch_minimax_h3_attention_contiguous_qkv()+ first = MiniMaxH3AttnProcessor.__call__+ patch_minimax_h3_attention_contiguous_qkv()+ assert MiniMaxH3AttnProcessor.__call__ is first+ assert first is _contiguous_qkv_call+++def test_patch_covers_pruned_transformer_blocks(restore_processor):+ """The pruned subclass reuses the vendored attention classes, so the class-level patch+ must reach a block instantiated from either model class."""+ from invokeai.backend.minimax_h3.transformer_minimax_h3 import MiniMaxH3TransformerBlock++ patch_minimax_h3_attention_contiguous_qkv()+ block = MiniMaxH3TransformerBlock(+ hidden_size=32,+ num_attention_heads=4,+ attention_head_dim=8,+ ffn_dim=64,+ time_embed_dim=16,+ norm_eps=1e-6,+ qk_norm_eps=1e-5,+ )+ assert type(block.attn.processor).__call__ is _contiguous_qkv_call