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(z-image): reserve denoise working memory

Alexander Eichhorne573c45cacc5
diff --git a/invokeai/app/invocations/z_image/z_image_denoise.py b/invokeai/app/invocations/z_image/z_image_denoise.py
index 3d011994ca..991cadb41c 100644
--- a/invokeai/app/invocations/z_image/z_image_denoise.py
+++ b/invokeai/app/invocations/z_image/z_image_denoise.py
@@ -36,6 +36,7 @@ from invokeai.backend.quantization.dequantizing_linear import peak_dequant_trans
from invokeai.backend.rectified_flow.rectified_flow_inpaint_extension import RectifiedFlowInpaintExtension
from invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateState
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import ZImageConditioningInfo
+from invokeai.backend.util.attention import sdpa_score_matrix_bytes
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.fp8 import get_model_compute_dtype
from invokeai.backend.z_image.extensions.regional_prompting_extension import ZImageRegionalPromptingExtension
@@ -45,8 +46,20 @@ from invokeai.backend.z_image.z_image_controlnet_extension import (
ZImageControlNetExtension,
z_image_forward_with_control,
)
+from invokeai.backend.z_image.z_image_patchify_utils import SEQ_MULTI_OF
from invokeai.backend.z_image.z_image_transformer_patch import patch_transformer_for_regional_prompting
+# The transformer's width and head count, which its ControlNet adapters share: 30 heads of 128.
+Z_IMAGE_HIDDEN_SIZE = 3840
+Z_IMAGE_ATTENTION_HEADS = 30
+# Peak reserved activation bytes per attended token on a fused SDPA kernel; see `_estimate_working_memory`.
+Z_IMAGE_BYTES_PER_TOKEN = int(0.25 * 1024**2)
+
+
+def _padded(tokens: int) -> int:
+ """The transformer pads the image and the caption token runs to a multiple of `SEQ_MULTI_OF` each."""
+ return tokens + (-tokens) % SEQ_MULTI_OF
+
@invocation(
"z_image_denoise",
@@ -274,6 +287,75 @@ class ZImageDenoiseInvocation(BaseInvocation):
return sigmas
+ @staticmethod
+ def _estimate_working_memory(
+ image_seq_len: int,
+ text_seq_len: int,
+ num_loras: int,
+ num_control_blocks: int = 0,
+ regional_attention_bias_bytes: int = 0,
+ has_attention_mask: bool = False,
+ device: torch.device | None = None,
+ dtype: torch.dtype = torch.bfloat16,
+ ) -> int:
+ """Estimate peak transformer working memory (bytes) so the model cache keeps that much VRAM free.
+
+ The transformer attends over one unified sequence of image and caption tokens, each run padded to a
+ multiple of ``SEQ_MULTI_OF``. On a fused SDPA kernel its activations scale linearly with that sequence.
+ Measured as peak reserved memory in bf16 on CUDA with a 512-token caption, by
+ `scripts/calibrate_z_image_working_memory.py`: 0.99 GiB at 1024px (4608 tokens), 1.96 GiB at 1440px (8640)
+ and 3.85 GiB at 2048px (16896) -- 0.22 to 0.23 MB per token, unchanged between 2 and 4 blocks, because a
+ no-grad forward frees each block's intermediates. 0.25 MB per token bounds every point on its own, with
+ room for the ~5% more ROCm needed on FLUX.2. The fixed base covers what does not scale with the sequence
+ -- GGUF and fp8 weights cast per forward, and allocator slack across steps. Conditional and unconditional
+ passes run one after the other, so only the longer caption counts.
+
+ Where SDPA has no fused kernel for these shapes it materializes the score matrices, and those dominate:
+ on ROCm under Windows, whose fused kernels are disabled, a 1024px generation spilled 7.7 GB into shared
+ system memory while this node reserved only the default working memory. ``sdpa_score_matrix_bytes`` adds
+ the term only where it is really built. An attention mask narrows which fused kernels a build can use, so
+ the call is told whether one is passed: regional prompting's additive bias, or the padding mask the
+ ControlNet forward always builds. The plain forward passes none at batch size 1.
+
+ A ControlNet adapter first runs its own blocks over a sequence of the same length and keeps one hint per
+ block, alive through the main layers. Measured over the plain forward at 1024px: 3.3, 5.9 and 18.9
+ hint-sized tensors (sequence x width x element size) for 1, 6 and 15 blocks, so n + 4 are charged.
+ """
+ GB = 1024**3
+ seq_len = _padded(image_seq_len) + _padded(text_seq_len)
+ estimated = seq_len * Z_IMAGE_BYTES_PER_TOKEN + int(1.0 * GB)
+ estimated += regional_attention_bias_bytes
+ estimated += sdpa_score_matrix_bytes(
+ device=device if device is not None else TorchDevice.choose_torch_device(),
+ dtype=dtype,
+ num_heads=Z_IMAGE_ATTENTION_HEADS,
+ head_dim=Z_IMAGE_HIDDEN_SIZE // Z_IMAGE_ATTENTION_HEADS,
+ seq_len=seq_len,
+ has_attn_mask=has_attention_mask,
+ # The attention goes through diffusers' `dispatch_attention_fn`, which can route around torch's SDPA.
+ via_diffusers_dispatch=True,
+ )
+ if num_control_blocks:
+ estimated += (num_control_blocks + 4) * seq_len * Z_IMAGE_HIDDEN_SIZE * dtype.itemsize
+ estimated += int(0.5 * num_loras * GB)
+ return estimated
+
+ @staticmethod
+ def _regional_attention_bias_bytes(
+ regional_attn_mask: torch.Tensor | None, image_seq_len: int, dtype: torch.dtype
+ ) -> int:
+ """What `regional_forward` allocates per positive pass for regional prompting: a boolean copy of the mask,
+ the additive bias over the padded unified sequence, and the image-to-image block `torch.where` fills it
+ from. The mask itself is already on the device when the estimate is taken. Measured at 1024px on CUDA: 68 MiB
+ over the plain forward, against 93 MiB charged."""
+ if regional_attn_mask is None:
+ return 0
+ mask_side = regional_attn_mask.shape[0]
+ unified_seq_len = _padded(image_seq_len) + _padded(mask_side - image_seq_len)
+ return (
+ mask_side * mask_side + (unified_seq_len * unified_seq_len + image_seq_len * image_seq_len) * dtype.itemsize
+ )
+
def _run_diffusion(self, context: InvocationContext) -> torch.Tensor:
device = TorchDevice.choose_torch_device()
inference_dtype = TorchDevice.choose_bfloat16_safe_dtype(device)
@@ -443,21 +525,39 @@ class ZImageDenoiseInvocation(BaseInvocation):
):
raise ValueError(f"Unsupported Z-Image model format: {transformer_config.format}")
- # An int8_tensorwise or nvfp4 build materializes each quantized linear's weight per forward.
- # That transient is not part of the model's resident size, so the cache has to be told to
- # keep room for it or the first forward competes with weights it just placed. Read from the
- # unlocked model, before the VRAM lock the reservation applies to; zero for every other build.
- #
- # Passed alone rather than added to an activation estimate because this node has none --
- # the cache's `device_working_mem_gb` floor is what covers activations here, as it did
- # before. That floor (3 GiB by default) is about 20x Z-Image's largest transient under either
- # scheme, so this only ever raises the reservation; a node that grows a real activation
- # estimate should add the two, since the transient is alive alongside the activations.
- dequant_bytes = peak_dequant_transient_bytes(transformer_info.model, inference_dtype)
+ # Into RAM ahead of the transformer's VRAM lock, so the estimate below can size the adapter's hints.
+ control_model_info = context.models.load(self.control.control_model) if self.control is not None else None
+ num_control_blocks = 0
+ if control_model_info is not None:
+ assert isinstance(control_model_info.model, ZImageControlAdapter)
+ num_control_blocks = len(control_model_info.model.control_layers)
+
+ # Ask the model cache to keep the forward's working memory free; it offloads as much of the
+ # transformer as that takes. Without it the cache reserves only `device_working_mem_gb`, which a
+ # build that materializes the score matrices (ROCm on Windows, MPS) overruns several times at 1024px.
+ regional_attn_mask = regional_extension.regional_attn_mask
+ working_mem_bytes = self._estimate_working_memory(
+ image_seq_len=img_seq_len,
+ text_seq_len=max(
+ pos_prompt_embeds.shape[0], neg_prompt_embeds.shape[0] if neg_prompt_embeds is not None else 0
+ ),
+ num_loras=len(self.transformer.loras),
+ num_control_blocks=num_control_blocks,
+ regional_attention_bias_bytes=self._regional_attention_bias_bytes(
+ regional_attn_mask, img_seq_len, inference_dtype
+ ),
+ has_attention_mask=regional_attn_mask is not None or control_model_info is not None,
+ device=device,
+ dtype=inference_dtype,
+ )
+ # An int8_tensorwise or nvfp4 build materializes each quantized linear's weight per forward, alive
+ # alongside the activations above and invisible to them. Read from the unlocked model; zero for
+ # every other build.
+ working_mem_bytes += peak_dequant_transient_bytes(transformer_info.model, inference_dtype)
# Load transformer - always use base transformer, control is handled via extension
(cached_weights, transformer) = exit_stack.enter_context(
- transformer_info.model_on_device(working_mem_bytes=dequant_bytes)
+ transformer_info.model_on_device(working_mem_bytes=working_mem_bytes)
)
# Whether LoRA has to go on as a sidecar. Asked of the loaded module tree, not the
@@ -471,15 +571,16 @@ class ZImageDenoiseInvocation(BaseInvocation):
control_extension: ZImageControlNetExtension | None = None
if self.control is not None:
- # Load control adapter using context manager (proper GPU memory management)
- control_model_info = context.models.load(self.control.control_model)
- (_, control_adapter) = exit_stack.enter_context(control_model_info.model_on_device())
+ assert control_model_info is not None
+ # Locked with the same working memory: the transformer can no longer be offloaded, so an
+ # adapter placed with only the default reservation would fill the room kept for the forward.
+ (_, control_adapter) = exit_stack.enter_context(
+ control_model_info.model_on_device(working_mem_bytes=working_mem_bytes)
+ )
assert isinstance(control_adapter, ZImageControlAdapter)
# Get control_in_dim from adapter config (16 for V1, 33 for V2.0)
- adapter_config = control_adapter.config
- control_in_dim = adapter_config.get("control_in_dim", 16)
- num_control_blocks = adapter_config.get("num_control_blocks", 6)
+ control_in_dim = control_adapter.config.get("control_in_dim", 16)
# Log control configuration for debugging
version = "V2.0" if control_in_dim > 16 else "V1"
diff --git a/invokeai/backend/z_image/z_image_control_adapter.py b/invokeai/backend/z_image/z_image_control_adapter.py
index e1efb0b9a4..b8af273232 100644
--- a/invokeai/backend/z_image/z_image_control_adapter.py
+++ b/invokeai/backend/z_image/z_image_control_adapter.py
@@ -54,19 +54,17 @@ class ZImageControlTransformerBlock(ZImageTransformerBlock):
attn_mask: torch.Tensor,
freqs_cis: torch.Tensor,
adaln_input: Optional[torch.Tensor] = None,
- ) -> torch.Tensor:
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ """Advance the control state by one block; returns ``(hint, control_state)``.
+
+ Upstream stacks every hint onto the running state and copies that stack in each block. Every copy is
+ larger than any block the caching allocator has freed, so reserved memory grew by (n+1)(n+2)/2
+ hint-sized tensors -- measured 4.5 GiB for a 15-block adapter at 1024px, 0.6 GiB with the hints kept apart.
+ """
if self.block_id == 0:
c = self.before_proj(c) + x
- all_c: list[torch.Tensor] = []
- else:
- all_c = list(torch.unbind(c))
- c = all_c.pop(-1)
-
c = super().forward(c, attn_mask=attn_mask, freqs_cis=freqs_cis, adaln_input=adaln_input)
- c_skip = self.after_proj(c)
- all_c += [c_skip, c]
- c = torch.stack(all_c)
- return c
+ return self.after_proj(c), c
class ZImageControlAdapter(ModelMixin, ConfigMixin):
@@ -225,14 +223,14 @@ class ZImageControlAdapter(ModelMixin, ConfigMixin):
c = control_context_unified
# Process through control layers
+ hints = []
for layer in self.control_layers:
- c = layer(
+ hint, c = layer(
c,
x=unified_hidden_states,
attn_mask=attn_mask,
freqs_cis=freqs_cis,
adaln_input=adaln_input,
)
-
- hints = torch.unbind(c)[:-1]
- return hints
+ hints.append(hint)
+ return tuple(hints)
diff --git a/invokeai/backend/z_image/z_image_controlnet_extension.py b/invokeai/backend/z_image/z_image_controlnet_extension.py
index 0be440e33e..ee6171a489 100644
--- a/invokeai/backend/z_image/z_image_controlnet_extension.py
+++ b/invokeai/backend/z_image/z_image_controlnet_extension.py
@@ -85,126 +85,6 @@ class ZImageControlNetExtension:
step_percent = step_index / total_steps
return self._begin_step_percent <= step_percent <= self._end_step_percent
- def prepare_control_state(
- self,
- base_transformer: ZImageTransformer2DModel,
- cap_feats: torch.Tensor,
- timestep_emb: torch.Tensor,
- x_item_seqlens: List[int],
- cap_item_seqlens: List[int],
- x_freqs_cis: torch.Tensor,
- patch_size: int = 2,
- f_patch_size: int = 1,
- ) -> torch.Tensor:
- """Prepare control state (control_unified) for incremental hint computation.
-
- This processes the control condition through patchify and noise_refiner,
- returning the control_unified tensor that will be used incrementally.
- """
- bsz = 1
- device = self._control_cond.device
-
- # Patchify control context
- control_context = [self._control_cond]
- (
- control_patches,
- _,
- _control_pos_ids,
- control_pad_mask,
- ) = patchify_control_context(
- control_context,
- patch_size,
- f_patch_size,
- cap_feats.size(1),
- )
-
- # Embed control context
- ctrl_item_seqlens = [len(p) for p in control_patches]
- ctrl_max_seqlen = max(ctrl_item_seqlens)
-
- control_cat = torch.cat(control_patches, dim=0)
- embedder_key = f"{patch_size}-{f_patch_size}"
- control_cat = self._adapter.control_all_x_embedder[embedder_key](control_cat)
-
- # Apply padding token
- adaln_input = timestep_emb.type_as(control_cat)
- x_pad_token = self._adapter.x_pad_token.to(dtype=control_cat.dtype)
- control_cat[torch.cat(control_pad_mask)] = x_pad_token
-
- control_list = list(control_cat.split(ctrl_item_seqlens, dim=0))
- control_padded = pad_sequence(control_list, batch_first=True, padding_value=0.0)
-
- # Use x_freqs_cis from main path for aligned position encoding
- ctrl_freqs_cis_for_refiner = x_freqs_cis[:, : control_padded.shape[1]]
-
- ctrl_attn_mask = torch.zeros((bsz, ctrl_max_seqlen), dtype=torch.bool, device=device)
- for i, seq_len in enumerate(ctrl_item_seqlens):
- ctrl_attn_mask[i, :seq_len] = 1
-
- # Refine control context through control_noise_refiner
- for layer in self._adapter.control_noise_refiner:
- control_padded = layer(control_padded, ctrl_attn_mask, ctrl_freqs_cis_for_refiner, adaln_input)
-
- # Store these for compute_single_hint
- self._ctrl_item_seqlens = ctrl_item_seqlens
- self._adaln_input = adaln_input
-
- # Unify control with caption features
- control_unified = []
- for i in range(bsz):
- ctrl_len = ctrl_item_seqlens[i]
- cap_len = cap_item_seqlens[i]
- control_unified.append(torch.cat([control_padded[i][:ctrl_len], cap_feats[i][:cap_len]]))
-
- control_unified = pad_sequence(control_unified, batch_first=True, padding_value=0.0)
-
- if not hasattr(self, "_prepare_printed"):
- self._prepare_printed = True
- logger.debug("Control state prepared: shape %s", control_unified.shape)
-
- return control_unified
-
- def compute_single_hint(
- self,
- control_layer_idx: int,
- control_state: torch.Tensor,
- unified_hidden_states: torch.Tensor,
- attn_mask: torch.Tensor,
- freqs_cis: torch.Tensor,
- adaln_input: torch.Tensor,
- ) -> Tuple[torch.Tensor, torch.Tensor]:
- """Compute a single hint from one control layer.
-
- Args:
- control_layer_idx: Which control layer to use (0, 1, 2, ...)
- control_state: Current control state (stacked tensor from previous layers)
- unified_hidden_states: Current unified hidden states from main transformer
- attn_mask: Attention mask
- freqs_cis: RoPE frequencies
- adaln_input: Timestep embedding
-
- Returns:
- Tuple of (hint tensor, updated control_state)
- """
- layer = self._adapter.control_layers[control_layer_idx]
-
- # Run control layer with CURRENT unified_hidden_states
- control_state = layer(
- control_state,
- x=unified_hidden_states,
- attn_mask=attn_mask,
- freqs_cis=freqs_cis,
- adaln_input=adaln_input,
- )
-
- # Extract hint from stacked state
- # After control layer, control_state is stacked: [skip_0, ..., skip_n, running_state]
- # We want the latest skip (second to last element)
- unbinded = torch.unbind(control_state)
- hint = unbinded[-2] # Latest skip connection
-
- return hint, control_state
-
def compute_hints(
self,
base_transformer: ZImageTransformer2DModel,
@@ -321,17 +201,17 @@ class ZImageControlNetExtension:
if hasattr(refiner0, "attn"):
logger.debug("noise_refiner[0] attn.wq norm: %.6f", refiner0.attn.wq.weight.norm().item())
+ hint_list = []
for layer in self._adapter.control_layers:
- c = layer(
+ hint, c = layer(
c,
x=unified_hidden_states,
attn_mask=attn_mask,
freqs_cis=freqs_cis,
adaln_input=adaln_input,
)
-
- # Extract hints (all but the last element which is the running state)
- hints = tuple(torch.unbind(c)[:-1])
+ hint_list.append(hint)
+ hints = tuple(hint_list)
if not hasattr(self, "_hints_printed"):
self._hints_printed = True
diff --git a/scripts/calibrate_z_image_working_memory.py b/scripts/calibrate_z_image_working_memory.py
new file mode 100644
index 0000000000..7ed5c90fb9
--- /dev/null
+++ b/scripts/calibrate_z_image_working_memory.py
@@ -0,0 +1,303 @@
+"""Calibrate the Z-Image denoise working-memory estimate against measured peak CUDA/HIP memory.
+
+Background
+----------
+The Z-Image transformer attends over one unified sequence -- image tokens and caption tokens, each padded to a
+multiple of 32 -- through diffusers' `dispatch_attention_fn`. Three numbers decide how much VRAM the model cache has
+to keep free for one transformer forward (``ZImageDenoiseInvocation._estimate_working_memory``):
+
+1. the activation cost per attended token on a fused SDPA kernel, which scales linearly with the sequence;
+2. the materialized score matrix, only where SDPA has no fused kernel for these shapes -- ROCm/Windows without
+ the experimental AOTriton kernels, MPS -- which `sdpa_score_matrix_bytes` charges at the shipped
+ `SDPA_MATH_BYTES_PER_SCORE_ELEMENT`;
+3. with a ControlNet attached, the adapter's hints: one per control block, live next to the transformer's own
+ activations.
+
+This measures all three on the real geometry (dim 3840, 30 heads of 128, caption features 2560 wide) with randomly
+initialized models and a reduced transformer block count: memory depends on shapes, not on weight values, and a
+no-grad forward frees each block's intermediates. `--extra-blocks` re-checks that on the build at hand. Every point
+runs in a fresh subprocess, so the caching allocator's history cannot contaminate the peak-reserved reading, and a
+point that runs out of memory is recorded as such rather than aborting the run.
+
+Peak *reserved*, not allocated: the estimate is compared against free memory, so it has to bound what the
+allocator actually takes off the card.
+
+Every point is priced before it runs -- the node's own estimate for it, the forced-math score matrix where that is
+the point, and the weights -- and skipped when that exceeds free device memory. An oversized allocation does not
+always fail: where the driver backs it with system RAM (NVIDIA's sysmem fallback, AMD on Windows) it pages and can
+stall the whole machine. On a build whose default kernel materializes the score matrix, that skips every size above
+1024px. `--force` runs them anyway.
+
+Usage
+-----
+ python scripts/calibrate_z_image_working_memory.py
+ python scripts/calibrate_z_image_working_memory.py --extra-blocks 4 --control-blocks 6
+ python scripts/calibrate_z_image_working_memory.py --max-px 1024 --control-blocks 0
+"""
+
+import argparse
+import json
+import subprocess
+import sys
+from contextlib import nullcontext
+
+import torch
+from torch.nn.attention import SDPBackend, sdpa_kernel
+
+from invokeai.app.invocations.constants import LATENT_SCALE_FACTOR
+from invokeai.app.invocations.z_image.z_image_denoise import (
+ Z_IMAGE_ATTENTION_HEADS,
+ Z_IMAGE_HIDDEN_SIZE,
+ ZImageDenoiseInvocation,
+ _padded,
+)
+from invokeai.backend.util.attention import SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+
+GIB = 1024**3
+MIB = 1024**2
+
+CAP_FEAT_DIM = 2560
+PATCH_SIZE = 2
+CONTROL_IN_DIM = 33 # V2.0 adapters; the channel count only sizes the patch embedder
+# One transformer block at full width: attention 4 dim^2, SwiGLU 8 dim^2, adaLN and norms, rounded up.
+BLOCK_PARAMS = 13 * Z_IMAGE_HIDDEN_SIZE**2
+
+SIZES = (1024, 1440, 2048)
+TEXT_TOKENS = 512
+
+DTYPES = {"float16": torch.float16, "bfloat16": torch.bfloat16, "float32": torch.float32}
+
+
+def image_tokens(px: int) -> int:
+ side = px // LATENT_SCALE_FACTOR // PATCH_SIZE
+ return side * side
+
+
+def unified_tokens(px: int, text_tokens: int) -> int:
+ return _padded(image_tokens(px)) + _padded(text_tokens)
+
+
+def predicted_bytes(px: int, blocks: int, dtype: torch.dtype, force_math: bool, control_blocks: int) -> int:
+ """What a point is expected to take: working memory as the node estimates it, plus the weights."""
+ working = ZImageDenoiseInvocation._estimate_working_memory(
+ image_seq_len=image_tokens(px),
+ text_seq_len=TEXT_TOKENS,
+ num_loras=0,
+ num_control_blocks=control_blocks,
+ has_attention_mask=control_blocks > 0,
+ device=torch.device("cuda"),
+ dtype=dtype,
+ )
+ if force_math:
+ tokens = unified_tokens(px, TEXT_TOKENS)
+ working += Z_IMAGE_ATTENTION_HEADS * tokens * tokens * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+ # Main blocks plus refiners and embedders; adapter blocks plus its refiners.
+ modules = blocks + 4 + (control_blocks + 2 if control_blocks else 0)
+ return working + modules * BLOCK_PARAMS * dtype.itemsize
+
+
+def _peak_reserved(fn) -> int | None:
+ """Run ``fn`` and return the growth in peak reserved bytes, or ``None`` if it ran out of memory."""
+ torch.cuda.synchronize()
+ torch.cuda.empty_cache()
+ torch.cuda.reset_peak_memory_stats()
+ baseline = torch.cuda.memory_reserved()
+ try:
+ fn()
+ torch.cuda.synchronize()
+ except (torch.cuda.OutOfMemoryError, RuntimeError) as e:
+ if "out of memory" not in str(e).lower():
+ raise
+ return None
+ return torch.cuda.max_memory_reserved() - baseline
+
+
+def _control_adapter(blocks: int, device: torch.device, dtype: torch.dtype) -> torch.nn.Module:
+ """A randomly initialized adapter, allocated directly in ``dtype`` on the device: 15 blocks are ~3B parameters,
+ which would otherwise pass through the host in float32 first."""
+ from invokeai.backend.z_image.z_image_control_adapter import ZImageControlAdapter
+
+ with torch.device("meta"):
+ adapter = ZImageControlAdapter(
+ num_control_blocks=blocks,
+ control_in_dim=CONTROL_IN_DIM,
+ dim=Z_IMAGE_HIDDEN_SIZE,
+ n_heads=Z_IMAGE_ATTENTION_HEADS,
+ n_kv_heads=Z_IMAGE_ATTENTION_HEADS,
+ )
+ adapter = adapter.to(dtype).to_empty(device=device)
+ for param in adapter.parameters():
+ torch.nn.init.normal_(param, std=0.02)
+ return adapter.eval()
+
+
+def measure(px: int, text_tokens: int, blocks: int, dtype: torch.dtype, force_math: bool, control_blocks: int) -> dict:
+ """Peak reserved memory for one transformer forward at one resolution."""
+ from diffusers import ZImageTransformer2DModel
+
+ from invokeai.backend.z_image.z_image_controlnet_extension import (
+ ZImageControlNetExtension,
+ z_image_forward_with_control,
+ )
+
+ device = torch.device("cuda")
+ model = (
+ ZImageTransformer2DModel(
+ all_patch_size=(PATCH_SIZE,),
+ all_f_patch_size=(1,),
+ in_channels=16,
+ dim=Z_IMAGE_HIDDEN_SIZE,
+ n_layers=blocks,
+ n_refiner_layers=1,
+ n_heads=Z_IMAGE_ATTENTION_HEADS,
+ n_kv_heads=Z_IMAGE_ATTENTION_HEADS,
+ norm_eps=1e-05,
+ qk_norm=True,
+ cap_feat_dim=CAP_FEAT_DIM,
+ rope_theta=256.0,
+ t_scale=1000.0,
+ axes_dims=[32, 48, 48],
+ axes_lens=[1024, 512, 512],
+ )
+ .to(device=device, dtype=dtype)
+ .eval()
+ )
+ latent = px // LATENT_SCALE_FACTOR
+ x = [torch.randn(16, 1, latent, latent, device=device, dtype=dtype)]
+ t = torch.full((1,), 0.5, device=device, dtype=dtype)
+ cap_feats = [torch.randn(text_tokens, CAP_FEAT_DIM, device=device, dtype=dtype)]
+
+ extension = None
+ if control_blocks:
+ extension = ZImageControlNetExtension(
+ control_adapter=_control_adapter(control_blocks, device, dtype),
+ control_cond=torch.randn(CONTROL_IN_DIM, 1, latent, latent, device=device, dtype=dtype),
+ )
+
+ def forward() -> None:
+ with sdpa_kernel(SDPBackend.MATH) if force_math else nullcontext():
+ if extension is None:
+ model(x=x, t=t, cap_feats=cap_feats)
+ else:
+ z_image_forward_with_control(
+ transformer=model, x=x, t=t, cap_feats=cap_feats, control_extension=extension
+ )
+
+ row = {
+ "px": px,
+ "tokens": unified_tokens(px, text_tokens),
+ "blocks": blocks,
+ "force_math": force_math,
+ "control_blocks": control_blocks,
+ }
+ # Warm up first: the cold call pays one-off workspace costs the per-token slope must not absorb.
+ if _peak_reserved(forward) is None:
+ return row | {"oom": True}
+ peak = _peak_reserved(forward)
+ return row | ({"oom": True} if peak is None else {"oom": False, "reserved_delta": peak})
+
+
+def _run_point(px: int, blocks: int, dtype_name: str, force_math: bool, control_blocks: int) -> dict | None:
+ args = [str(px), str(TEXT_TOKENS), str(blocks), dtype_name, "1" if force_math else "0", str(control_blocks)]
+ proc = subprocess.run([sys.executable, __file__, "--single", *args], capture_output=True, text=True)
+ line = proc.stdout.strip().splitlines()[-1] if proc.stdout.strip() else ""
+ try:
+ return json.loads(line)
+ except Exception:
+ tail = proc.stderr.strip().splitlines()[-1:] or ["(no stderr)"]
+ print(f" FAILED {' '.join(args)}: {tail[0]}")
+ return None
+
+
+def report(
+ dtype_name: str, blocks: int, extra_blocks: int | None, control_blocks: int, max_px: int, force: bool
+) -> None:
+ dtype = DTYPES[dtype_name]
+ sizes = [px for px in SIZES if px <= max_px]
+ free, _ = torch.cuda.mem_get_info()
+ print(f"{'kernel':>7} {'blocks':>6} {'control':>7} {'px':>5} {'tokens':>7} {'reserved(GiB)':>14}")
+ print("-" * 52)
+
+ def run(kernel: str, count: int, px: int, force_math: bool, control: int) -> int | None:
+ need = predicted_bytes(px, count, dtype, force_math, control)
+ if need > free and not force:
+ print(
+ f"{kernel:>7} {count:>6} {control:>7} {px:>5} {'':>7} {'skipped':>14}"
+ f" needs ~{need / GIB:.1f} GiB, {free / GIB:.1f} GiB free"
+ )
+ return None
+ row = _run_point(px, count, dtype_name, force_math, control)
+ if row is None or row.get("oom"):
+ print(f"{kernel:>7} {count:>6} {control:>7} {px:>5} {'':>7} {'OOM':>14}")
+ return None
+ print(f"{kernel:>7} {count:>6} {control:>7} {px:>5} {row['tokens']:>7} {row['reserved_delta'] / GIB:>14.3f}")
+ return row["reserved_delta"]
+
+ counts = [blocks] + ([extra_blocks] if extra_blocks else [])
+ fused: dict[int, dict[int, int]] = {}
+ for count in counts:
+ for px in sizes:
+ if (peak := run("auto", count, px, False, 0)) is not None:
+ fused.setdefault(count, {})[px] = peak
+ math_peak = run("math", blocks, SIZES[0], True, 0)
+ control_peak = run("auto", blocks, SIZES[0], False, control_blocks) if control_blocks else None
+
+ print()
+ for count, peaks in fused.items():
+ for px, peak in peaks.items():
+ tokens = unified_tokens(px, TEXT_TOKENS)
+ print(f"auto kernel, {count} blocks, {px}px: {peak / tokens / MIB:.4f} MB per attended token")
+ if len(peaks) >= 2:
+ lo, hi = min(peaks), max(peaks)
+ slope = (peaks[hi] - peaks[lo]) / (unified_tokens(hi, TEXT_TOKENS) - unified_tokens(lo, TEXT_TOKENS))
+ base = peaks[lo] - slope * unified_tokens(lo, TEXT_TOKENS)
+ print(f"auto kernel, {count} blocks: {slope / MIB:.4f} MB/token, intercept {base / GIB:.3f} GiB")
+
+ tokens = unified_tokens(SIZES[0], TEXT_TOKENS)
+ reference = fused.get(blocks, {}).get(SIZES[0])
+ if math_peak is not None and reference is not None:
+ extra = math_peak - reference
+ charged = Z_IMAGE_ATTENTION_HEADS * tokens * tokens * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+ print(
+ f"math kernel, {SIZES[0]}px: {extra / GIB:.3f} GiB over the auto kernel, "
+ f"{extra / (Z_IMAGE_ATTENTION_HEADS * tokens * tokens):.2f} bytes/score element; shipped constant charges "
+ f"{charged / GIB:.3f} GiB ({SDPA_MATH_BYTES_PER_SCORE_ELEMENT})"
+ )
+ if control_peak is not None and reference is not None:
+ extra = control_peak - reference
+ hint_bytes = tokens * Z_IMAGE_HIDDEN_SIZE * dtype.itemsize
+ print(
+ f"control, {control_blocks} blocks, {SIZES[0]}px: {extra / GIB:.3f} GiB over no control, "
+ f"{extra / hint_bytes:.2f} hint-sized tensors; the estimate charges n + 4 = {control_blocks + 4}"
+ )
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--dtype", choices=list(DTYPES), default="bfloat16")
+ parser.add_argument("--blocks", type=int, default=2, help="Main transformer blocks. Default 2.")
+ parser.add_argument("--extra-blocks", type=int, default=None, help="Measure a second block count as well.")
+ parser.add_argument("--control-blocks", type=int, default=15, help="ControlNet blocks; 0 skips. Default 15.")
+ parser.add_argument("--max-px", type=int, default=SIZES[-1], help="Largest fused-kernel size to measure.")
+ parser.add_argument("--force", action="store_true", help="Run points predicted not to fit free device memory.")
+ parser.add_argument("--single", nargs="*", default=None, help=argparse.SUPPRESS)
+ args = parser.parse_args()
+
+ if not torch.cuda.is_available():
+ raise SystemExit("No CUDA/HIP device available.")
+ if args.single:
+ px, text_tokens, blocks, dtype_name, force_math, control_blocks = args.single
+ row = measure(
+ int(px), int(text_tokens), int(blocks), DTYPES[dtype_name], force_math == "1", int(control_blocks)
+ )
+ print(json.dumps(row))
+ return
+ print(
+ f"torch {torch.__version__} | device {torch.cuda.get_device_name(0)} | hip={torch.version.hip} | {args.dtype}"
+ )
+ report(args.dtype, args.blocks, args.extra_blocks, args.control_blocks, args.max_px, args.force)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/app/invocations/test_int8_denoise_working_memory.py b/tests/app/invocations/test_int8_denoise_working_memory.py
deleted file mode 100644
index 70add2f220..0000000000
--- a/tests/app/invocations/test_int8_denoise_working_memory.py
+++ /dev/null
@@ -1,113 +0,0 @@
-"""The per-forward int8 dequant transient has to reach `model_on_device()`.
-
-`Int8ConvrotLinear` keeps its weight int8 and materializes the dequantized, derotated weight per
-forward. That allocation is not part of the model's resident size, so unless the node asks the
-cache to hold room for it, the cache is free to pack the device with weights right up to the
-default working memory and the first forward competes with what it just placed.
-
-`peak_dequant_transient_bytes` is unit-tested next to the modules it reads. What is
-pinned here is the wire: deleting the `working_mem_bytes=` argument from the node leaves every
-other test green. Z-Image only -- MiniMax H3 adds the same term; reaching its `model_on_device()` call needs a packed sequence.
-Krea-2's wiring is pinned separately, in `tests/app/invocations/test_krea2_denoise.py`.
-"""
-
-from types import SimpleNamespace
-from unittest.mock import MagicMock, patch
-
-import pytest
-import torch
-
-from invokeai.app.invocations.fields import ZImageConditioningField
-from invokeai.app.invocations.z_image.z_image_denoise import ZImageDenoiseInvocation
-from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType
-from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, Int8ConvrotLinear
-
-
-class _StopBeforeLoad(Exception):
- """Raised out of the mocked `model_on_device()` so the node stops at the reservation."""
-
-
-def _int8_model(out_features: int, in_features: int) -> torch.nn.Module:
- model = torch.nn.Module()
- model.proj = Int8ConvrotLinear(
- torch.zeros(out_features, in_features, dtype=torch.int8),
- torch.ones(out_features, 1),
- convrot=False,
- )
- return model
-
-
-class TestZImage:
- """Z-Image has no activation estimate, so the transient is the whole request; the cache floors
- it at `device_working_mem_gb`, which is what covers activations there."""
-
- def _reserved_by(self, transformer: torch.nn.Module) -> int:
- from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (
- ConditioningFieldData,
- ZImageConditioningInfo,
- )
-
- transformer_info = MagicMock()
- transformer_info.model = transformer
- transformer_info.model_on_device = MagicMock(side_effect=_StopBeforeLoad)
-
- context = MagicMock()
- context.models.load.return_value = transformer_info
- context.models.get_config.return_value = SimpleNamespace(
- base=BaseModelType.ZImage, type=ModelType.Main, format=ModelFormat.Checkpoint
- )
- context.conditioning.load.return_value = ConditioningFieldData(
- conditionings=[ZImageConditioningInfo(prompt_embeds=torch.zeros(1, 8, 2560))]
- )
-
- invocation = ZImageDenoiseInvocation.model_construct(
- latents=None,
- noise=None,
- denoise_mask=None,
- denoising_start=0.0,
- denoising_end=1.0,
- add_noise=True,
- transformer=MagicMock(transformer=MagicMock(), loras=[]),
- positive_conditioning=ZImageConditioningField(conditioning_name="pos"),
- negative_conditioning=None,
- control=None,
- vae=None,
- guidance_scale=1.0,
- width=256,
- height=256,
- steps=2,
- scheduler="euler",
- seed=0,
- cfg_scale_start_step=0,
- cfg_scale_end_step=-1,
- )
-
- with (
- patch(
- "invokeai.app.invocations.z_image.z_image_denoise.TorchDevice.choose_torch_device",
- return_value=torch.device("cpu"),
- ),
- patch(
- "invokeai.app.invocations.z_image.z_image_denoise.TorchDevice.choose_bfloat16_safe_dtype",
- return_value=torch.bfloat16,
- ),
- patch.object(ZImageDenoiseInvocation, "_get_noise", return_value=torch.zeros(1, 16, 32, 32)),
- pytest.raises(_StopBeforeLoad),
- ):
- invocation._run_diffusion(context)
-
- transformer_info.model_on_device.assert_called_once()
- return transformer_info.model_on_device.call_args.kwargs["working_mem_bytes"]
-
- def test_the_transient_reaches_the_model_cache(self) -> None:
- """Two weight-sized bf16 tensors of the largest int8 layer."""
- reserved = self._reserved_by(_int8_model(1024, CONVROT_GROUP_SIZE))
-
- assert reserved == 2 * 1024 * CONVROT_GROUP_SIZE * torch.bfloat16.itemsize
-
- def test_an_unquantized_transformer_asks_for_nothing_extra(self) -> None:
- """Zero falls through the cache's `or`, leaving the configured default exactly as before."""
- dense = torch.nn.Module()
- dense.proj = torch.nn.Linear(CONVROT_GROUP_SIZE, 8)
-
- assert self._reserved_by(dense) == 0
diff --git a/tests/app/invocations/test_z_image_denoise_working_memory.py b/tests/app/invocations/test_z_image_denoise_working_memory.py
new file mode 100644
index 0000000000..0c6582acca
--- /dev/null
+++ b/tests/app/invocations/test_z_image_denoise_working_memory.py
@@ -0,0 +1,286 @@
+"""Z-Image denoise working memory: the estimate, and what the node hands `model_on_device()`.
+
+Until this estimate existed the node reserved only the per-forward dequant transient, so the model cache kept just
+`device_working_mem_gb` free. Where SDPA materializes the score matrices -- ROCm on Windows, MPS -- a 1024px
+generation needs several times that, and on Windows the driver pages the shortfall into shared system memory instead
+of failing: 7.7 GB of it, and a 185 s denoise, on an RX 9060 XT.
+
+The `MEASURED_*` tables are peak *reserved* memory on CUDA (RTX 4090) in bf16 with a 512-token caption, from
+`scripts/calibrate_z_image_working_memory.py`. Every estimate must stay an upper bound on them.
+
+MiniMax H3 and Krea-2 add the same dequant transient to their own estimates. Krea-2's wiring is pinned in
+`tests/app/invocations/test_krea2_denoise.py`; MiniMax H3's is not, since reaching its `model_on_device()` call needs a
+packed sequence.
+"""
+
+from contextlib import ExitStack, contextmanager, nullcontext
+from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
+
+import pytest
+import torch
+
+from invokeai.app.invocations.fields import ZImageConditioningField
+from invokeai.app.invocations.z_image.z_image_control import ZImageControlField
+from invokeai.app.invocations.z_image.z_image_denoise import ZImageDenoiseInvocation
+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType
+from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, Int8ConvrotLinear
+from invokeai.backend.util import attention
+from invokeai.backend.util.attention import SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+from invokeai.backend.z_image.extensions.regional_prompting_extension import ZImageRegionalPromptingExtension
+from invokeai.backend.z_image.text_conditioning import ZImageRegionalTextConditioning
+from invokeai.backend.z_image.z_image_control_adapter import ZImageControlAdapter
+
+MB = 1024**2
+GB = 1024**3
+
+# Only the device's type is read: every question the estimate asks about it is answered by `_sdpa` below.
+DEVICE = torch.device("cuda")
+
+
+@contextmanager
+def _sdpa(materializes):
+ """Answer the three dispatch questions `sdpa_score_matrix_bytes` asks, so no test depends on the torch build, the
+ diffusers attention backend or the ROCm head-dim guard of the machine it runs on."""
+ with (
+ patch.object(attention, "_diffusers_attention_dispatch", return_value=attention._DISPATCH_TORCH),
+ patch.object(attention, "rocm_sdpa_uses_math_kernel", return_value=False),
+ patch.object(
+ attention, "_torch_sdpa_materializes_score_matrix", side_effect=lambda *args: materializes(args[-1])
+ ),
+ ):
+ yield
+
+
+def _estimate(image_seq_len, text_seq_len=512, num_control_blocks=0, has_mask=False, materializes=lambda mask: False):
+ with _sdpa(materializes):
+ return ZImageDenoiseInvocation._estimate_working_memory(
+ image_seq_len=image_seq_len,
+ text_seq_len=text_seq_len,
+ num_loras=0,
+ num_control_blocks=num_control_blocks,
+ has_attention_mask=has_mask,
+ device=DEVICE,
+ )
+
+
+def _image_tokens(px: int) -> int:
+ return (px // 16) ** 2
+
+
+class TestEstimate:
+ # (pixels per side, ControlNet blocks, measured peak reserved MiB)
+ MEASURED_FUSED = [
+ (1024, 0, 1012),
+ (1440, 0, 2004),
+ (2048, 0, 3942),
+ (1024, 1, 1122),
+ (1024, 6, 1212),
+ (1024, 15, 1650),
+ ]
+
+ @pytest.mark.parametrize("px, control_blocks, measured_mb", MEASURED_FUSED)
+ def test_estimate_is_an_upper_bound_on_measured_peak(self, px, control_blocks, measured_mb):
+ """The cache treats the estimate as the amount it must keep free, so under-estimating runs out of memory."""
+ assert _estimate(_image_tokens(px), num_control_blocks=control_blocks) >= measured_mb * MB
+
+ @pytest.mark.parametrize("px, control_blocks, measured_mb", MEASURED_FUSED)
+ def test_estimate_does_not_wildly_over_reserve(self, px, control_blocks, measured_mb):
+ """Every byte reserved beyond need is transformer offloaded to RAM and run over PCIe."""
+ assert _estimate(_image_tokens(px), num_control_blocks=control_blocks) <= measured_mb * MB + 2 * GB
+
+ def test_image_and_caption_are_counted_as_the_transformer_pads_them(self):
+ """Each run is padded to a multiple of 32 before the two are joined, and the padding is attended too."""
+ assert _estimate(4096, text_seq_len=97) == _estimate(4096, text_seq_len=128)
+ assert _estimate(4001, text_seq_len=128) == _estimate(4032, text_seq_len=128)
+ assert _estimate(4096, text_seq_len=129) > _estimate(4096, text_seq_len=128)
+
+
+class TestMaterializedScoreMatrix:
+ def test_the_score_matrix_is_charged_only_where_it_is_built(self):
+ """Measured at 1024px: a forced math kernel took 9.4 GiB where the fused one took 1.0. The attention mask
+ decides the dispatch, so it has to reach the probe."""
+ seq_len = 4096 + 512
+ unmasked = _estimate(4096, materializes=lambda has_mask: has_mask)
+ masked = _estimate(4096, has_mask=True, materializes=lambda has_mask: has_mask)
+
+ assert unmasked == _estimate(4096)
+ assert masked - unmasked == 30 * seq_len * seq_len * SDPA_MATH_BYTES_PER_SCORE_ELEMENT
+
+ def test_estimate_bounds_the_measured_math_kernel(self):
+ assert _estimate(_image_tokens(1024), materializes=lambda has_mask: True) >= 9632 * MB
+
+
+class TestRegionalAttentionBias:
+ def test_no_regional_mask_costs_nothing(self):
+ assert ZImageDenoiseInvocation._regional_attention_bias_bytes(None, 4096, torch.bfloat16) == 0
+
+ def test_bias_is_sized_on_the_padded_unified_sequence(self):
+ """4096 image tokens and a 100-token caption: the boolean copy covers the 4196 real tokens, the additive bias
+ the 4096 + 128 padded ones, and `torch.where` fills the image block from a 4096 x 4096 scratch."""
+ mask = torch.empty((4196, 4196), dtype=torch.float16, device="meta")
+
+ bias_bytes = ZImageDenoiseInvocation._regional_attention_bias_bytes(mask, 4096, torch.bfloat16)
+
+ assert bias_bytes == 4196**2 + 4224**2 * 2 + 4096**2 * 2
+
+
+class _StopBeforeLoad(Exception):
+ """Raised out of a mocked `model_on_device()` so the node stops at a reservation."""
+
+
+# Stands in for the activation estimate, which is tested above; any value the transient cannot produce.
+ACTIVATION_ESTIMATE = 3_000_000_007
+POSITIVE_TOKENS = 8
+
+
+def _dense_transformer() -> torch.nn.Module:
+ model = torch.nn.Module()
+ model.proj = torch.nn.Linear(CONVROT_GROUP_SIZE, 8)
+ return model
+
+
+class TestNodeReservation:
+ """The wire from the node to `model_on_device()`: deleting any of these arguments leaves the estimate's own tests
+ green."""
+
+ def _run(self, transformer=None, *, control_blocks=None, negative_tokens=None, loras=0, regional_mask=None):
+ from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (
+ ConditioningFieldData,
+ ZImageConditioningInfo,
+ )
+
+ transformer = transformer if transformer is not None else _dense_transformer()
+ transformer_info = MagicMock()
+ transformer_info.model = transformer
+
+ control = None
+ control_info = MagicMock()
+ if control_blocks is None:
+ transformer_info.model_on_device = MagicMock(side_effect=_StopBeforeLoad)
+ else:
+ # Past the transformer's lock, up to the adapter's.
+ transformer_info.model_on_device = MagicMock(return_value=nullcontext((None, transformer)))
+ control = ZImageControlField.model_construct(control_model=MagicMock(), image_name="control")
+ control_info.model = MagicMock(spec=ZImageControlAdapter)
+ control_info.model.control_layers = [torch.nn.Identity()] * control_blocks
+ control_info.model_on_device = MagicMock(side_effect=_StopBeforeLoad)
+
+ caption_tokens = {"pos": POSITIVE_TOKENS, "neg": negative_tokens}
+ context = MagicMock()
+ context.models.load.side_effect = lambda identifier: (
+ control_info if control is not None and identifier is control.control_model else transformer_info
+ )
+ context.models.get_config.return_value = SimpleNamespace(
+ base=BaseModelType.ZImage, type=ModelType.Main, format=ModelFormat.Checkpoint
+ )
+ context.conditioning.load.side_effect = lambda name: ConditioningFieldData(
+ conditionings=[ZImageConditioningInfo(prompt_embeds=torch.zeros(caption_tokens[name], 2560))]
+ )
+
+ invocation = ZImageDenoiseInvocation.model_construct(
+ latents=None,
+ noise=None,
+ denoise_mask=None,
+ denoising_start=0.0,
+ denoising_end=1.0,
+ add_noise=True,
+ transformer=MagicMock(transformer=MagicMock(), loras=[MagicMock() for _ in range(loras)]),
+ positive_conditioning=ZImageConditioningField(conditioning_name="pos"),
+ negative_conditioning=ZImageConditioningField(conditioning_name="neg") if negative_tokens else None,
+ control=control,
+ vae=None,
+ guidance_scale=2.0 if negative_tokens else 1.0,
+ width=256,
+ height=256,
+ steps=2,
+ scheduler="euler",
+ seed=0,
+ )
+
+ with ExitStack() as stack:
+ stack.enter_context(
+ patch(
+ "invokeai.app.invocations.z_image.z_image_denoise.TorchDevice.choose_torch_device",
+ return_value=torch.device("cpu"),
+ )
+ )
+ stack.enter_context(
+ patch(
+ "invokeai.app.invocations.z_image.z_image_denoise.TorchDevice.choose_bfloat16_safe_dtype",
+ return_value=torch.bfloat16,
+ )
+ )
+ stack.enter_context(
+ patch.object(ZImageDenoiseInvocation, "_get_noise", return_value=torch.zeros(1, 16, 32, 32))
+ )
+ estimate = stack.enter_context(
+ patch.object(ZImageDenoiseInvocation, "_estimate_working_memory", return_value=ACTIVATION_ESTIMATE)
+ )
+ if regional_mask is not None:
+ regional = ZImageRegionalPromptingExtension(
+ regional_text_conditioning=ZImageRegionalTextConditioning(
+ prompt_embeds=torch.zeros(POSITIVE_TOKENS, 2560), image_masks=[None], embedding_ranges=[]
+ ),
+ regional_attn_mask=regional_mask,
+ )
+ stack.enter_context(
+ patch.object(ZImageRegionalPromptingExtension, "from_text_conditionings", return_value=regional)
+ )
+ with pytest.raises(_StopBeforeLoad):
+ invocation._run_diffusion(context)
+
+ return SimpleNamespace(
+ reserved=transformer_info.model_on_device.call_args.kwargs["working_mem_bytes"],
+ estimate=estimate.call_args.kwargs,
+ adapter_reserved=(
+ control_info.model_on_device.call_args.kwargs.get("working_mem_bytes") if control is not None else None
+ ),
+ )
+
+ def test_an_unquantized_transformer_reserves_the_estimate_for_its_sequence(self):
+ run = self._run()
+
+ assert run.reserved == ACTIVATION_ESTIMATE
+ # 256px is a 16x16 token grid.
+ assert (run.estimate["image_seq_len"], run.estimate["text_seq_len"]) == (256, POSITIVE_TOKENS)
+ assert (run.estimate["num_loras"], run.estimate["num_control_blocks"]) == (0, 0)
+ assert (run.estimate["regional_attention_bias_bytes"], run.estimate["has_attention_mask"]) == (0, False)
+
+ def test_the_dequant_transient_is_added_to_the_estimate(self):
+ """An int8 layer materializes two weight-sized bf16 tensors per forward, alive alongside the activations."""
+ model = torch.nn.Module()
+ model.proj = Int8ConvrotLinear(
+ torch.zeros(1024, CONVROT_GROUP_SIZE, dtype=torch.int8), torch.ones(1024, 1), convrot=False
+ )
+
+ run = self._run(model)
+
+ assert run.reserved == ACTIVATION_ESTIMATE + 2 * 1024 * CONVROT_GROUP_SIZE * torch.bfloat16.itemsize
+
+ def test_a_longer_negative_caption_sizes_the_sequence(self):
+ """With CFG the unconditional pass runs its own forward, so the longer of the two captions is the peak."""
+ assert self._run(negative_tokens=40).estimate["text_seq_len"] == 40
+
+ def test_loras_are_counted(self):
+ assert self._run(loras=2).estimate["num_loras"] == 2
+
+ def test_a_regional_mask_reaches_the_estimate(self):
+ mask = torch.zeros((256 + POSITIVE_TOKENS, 256 + POSITIVE_TOKENS), dtype=torch.float16)
+
+ run = self._run(regional_mask=mask)
+
+ expected_bias = ZImageDenoiseInvocation._regional_attention_bias_bytes(mask, 256, torch.bfloat16)
+ assert (run.estimate["regional_attention_bias_bytes"], run.estimate["has_attention_mask"]) == (
+ expected_bias,
+ True,
+ )
+
+ def test_a_control_adapter_reaches_the_estimate_and_keeps_the_reservation(self):
+ """The adapter's block count sizes the hints and its forward always passes a padding mask. It is locked after
+ the transformer, which can then no longer be offloaded -- so it must ask for the same working memory, or its
+ weights fill the room kept for the forward."""
+ run = self._run(control_blocks=15)
+
+ assert (run.estimate["num_control_blocks"], run.estimate["has_attention_mask"]) == (15, True)
+ assert run.adapter_reserved == run.reserved == ACTIVATION_ESTIMATE
diff --git a/tests/backend/z_image/conftest.py b/tests/backend/z_image/conftest.py
new file mode 100644
index 0000000000..842dcaeb89
--- /dev/null
+++ b/tests/backend/z_image/conftest.py
@@ -0,0 +1,33 @@
+import pytest
+import torch
+from diffusers import ZImageTransformer2DModel
+
+
+def tiny_z_image_transformer() -> ZImageTransformer2DModel:
+ """The real Z-Image transformer at toy width (64, two heads of 32), in float32 on the CPU.
+
+ Every parameter is drawn from N(0, 0.1): the pad tokens start uninitialized, and the zero-initialized projections
+ would hide any attention mask or control hint a test is looking for.
+ """
+ torch.manual_seed(0)
+ model = ZImageTransformer2DModel(
+ all_patch_size=(2,),
+ all_f_patch_size=(1,),
+ in_channels=16,
+ dim=64,
+ n_layers=2,
+ n_refiner_layers=1,
+ n_heads=2,
+ n_kv_heads=2,
+ norm_eps=1e-05,
+ qk_norm=True,
+ cap_feat_dim=32,
+ rope_theta=256.0,
+ t_scale=1000.0,
+ axes_dims=[8, 12, 12],
+ axes_lens=[128, 32, 32],
+ ).eval()
+ for param in model.parameters():
+ torch.nn.init.normal_(param, std=0.1)
+ return model
diff --git a/tests/backend/z_image/test_z_image_control_adapter.py b/tests/backend/z_image/test_z_image_control_adapter.py
new file mode 100644
index 0000000000..557f3fbeba
--- /dev/null
+++ b/tests/backend/z_image/test_z_image_control_adapter.py
@@ -0,0 +1,82 @@
+"""Z-Image control blocks hand back each hint on its own instead of stacking it onto the running state.
+
+Upstream (VideoX-Fun) returns ``torch.stack([hint_0, ..., hint_k, state])`` from every block and unbinds it again in
+the next. Each stack is a fresh allocation larger than any the caching allocator has freed, so a 15-block adapter
+reserved 136 hint-sized tensors at 1024px -- 4.5 GiB -- where separate hints need 19. The rewrite must not change a
+single hint.
+"""
+
+import torch
+from diffusers.models.transformers.transformer_z_image import ZImageTransformerBlock
+
+from invokeai.backend.z_image.z_image_control_adapter import ZImageControlAdapter
+from invokeai.backend.z_image.z_image_controlnet_extension import (
+ ZImageControlNetExtension,
+ z_image_forward_with_control,
+)
+
+LATENT_SIDE = 16
+
+
+def _upstream_hints(adapter: ZImageControlAdapter, c, x, attn_mask, freqs_cis, adaln_input) -> tuple[torch.Tensor, ...]:
+ """The stacked formulation, as VideoX-Fun's `ZImageControlTransformerBlock.forward` and its caller wrote it."""
+ for layer in adapter.control_layers:
+ if layer.block_id == 0:
+ c = layer.before_proj(c) + x
+ all_c = []
+ else:
+ all_c = list(torch.unbind(c))
+ c = all_c.pop(-1)
+ c = ZImageTransformerBlock.forward(layer, c, attn_mask=attn_mask, freqs_cis=freqs_cis, adaln_input=adaln_input)
+ all_c += [layer.after_proj(c), c]
+ c = torch.stack(all_c)
+ return torch.unbind(c)[:-1]
+
+
+def test_the_control_forward_computes_the_stacked_formulations_hints(tiny_z_image_transformer) -> None:
+ """Driven through `z_image_forward_with_control`, the path the denoise node takes, with the padding mask it builds
+ and a caption that needs padding. The first control block's inputs are captured and replayed through the upstream
+ formulation."""
+ model = tiny_z_image_transformer
+ adapter = ZImageControlAdapter(
+ num_control_blocks=3,
+ control_in_dim=16,
+ dim=model.config.dim,
+ n_refiner_layers=1,
+ n_heads=model.config.n_heads,
+ n_kv_heads=model.config.n_kv_heads,
+ ).eval()
+ for param in adapter.parameters():
+ torch.nn.init.normal_(param, std=0.1)
+ extension = ZImageControlNetExtension(
+ control_adapter=adapter, control_cond=torch.randn(16, 1, LATENT_SIDE, LATENT_SIDE)
+ )
+
+ first_block_inputs = {}
+ adapter.control_layers[0].register_forward_pre_hook(
+ lambda module, args, kwargs: first_block_inputs.update(c=args[0], **kwargs), with_kwargs=True
+ )
+ computed = []
+ compute_hints = extension.compute_hints
+
+ def recording_compute_hints(**kwargs):
+ computed.append(compute_hints(**kwargs))
+ return computed[-1]
+
+ extension.compute_hints = recording_compute_hints
+
+ z_image_forward_with_control(
+ transformer=model,
+ x=[torch.randn(16, 1, LATENT_SIDE, LATENT_SIDE)],
+ t=torch.full((1,), 0.5),
+ cap_feats=[torch.randn(20, model.config.cap_feat_dim)],
+ control_extension=extension,
+ )
+
+ assert first_block_inputs["attn_mask"] is not None
+ expected = _upstream_hints(adapter, **first_block_inputs)
+ (hints,) = computed
+ assert len(hints) == len(expected) == 3
+ for hint, reference in zip(hints, expected, strict=True):
+ assert torch.equal(hint, reference)