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: Anima regional prompting should mirror width/height calculation for correct mask size (#9356)
Francois Brodeur350eda6f43cb
diff --git a/invokeai/app/invocations/anima_denoise.py b/invokeai/app/invocations/anima_denoise.pyindex 4b6befac45..51274777f6 100644--- a/invokeai/app/invocations/anima_denoise.py+++ b/invokeai/app/invocations/anima_denoise.py@@ -381,6 +381,33 @@ class AnimaDenoiseInvocation(BaseInvocation):generator=torch.Generator(device=rand_device).manual_seed(seed),).to(device=device, dtype=dtype)+ @staticmethod+ def _compute_img_token_grid(height: int, width: int, patch_size: int = 2) -> tuple[int, int]:+ """Compute the (height, width) of the image token grid for regional prompting.++ Anima uses 8x VAE compression and a 2x DiT patch size (16x total). The mask's+ token grid must match the token grid the transformer actually produces.++ Ceiling division mirrors the transformer's MiniTrainDIT._pad_to_patch_size, which+ pads the latent H/W up to a multiple of patch_size BEFORE patchifying. An odd latent+ dimension (e.g. 1080 // 8 = 135) is padded up (135 -> 136 -> 68 tokens); floor+ division here would size the mask for one fewer token row/column than the transformer+ produces, causing a cross-attention mask shape mismatch during regional prompting.++ Args:+ height: Image height in pixels.+ width: Image width in pixels.+ patch_size: DiT spatial patch size (patch_spatial).++ Returns:+ Tuple of (img_token_height, img_token_width).+ """+ latent_height = height // ANIMA_LATENT_SCALE_FACTOR+ latent_width = width // ANIMA_LATENT_SCALE_FACTOR+ img_token_height = math.ceil(latent_height / patch_size)+ img_token_width = math.ceil(latent_width / patch_size)+ return img_token_height, img_token_width+def _get_sigmas(self, num_steps: int) -> list[float]:"""Generate sigma schedule with fixed shift=3.0.@@ -425,8 +452,8 @@ class AnimaDenoiseInvocation(BaseInvocation):Args:context: The invocation context.cond_field: Single conditioning field or list of fields.- img_token_height: Height of the image token grid (H // patch_size).- img_token_width: Width of the image token grid (W // patch_size).+ img_token_height: Height of the image token grid (ceil(latent_H / patch_size)).+ img_token_width: Width of the image token grid (ceil(latent_W / patch_size)).dtype: Target dtype.device: Target device.@@ -523,12 +550,7 @@ class AnimaDenoiseInvocation(BaseInvocation):transformer_info = context.models.load(self.transformer.transformer)# Compute image token grid dimensions for regional prompting- # Anima: 8x VAE compression, 2x patch size → 16x total- patch_size = 2- latent_height = self.height // ANIMA_LATENT_SCALE_FACTOR- latent_width = self.width // ANIMA_LATENT_SCALE_FACTOR- img_token_height = latent_height // patch_size- img_token_width = latent_width // patch_size+ img_token_height, img_token_width = self._compute_img_token_grid(self.height, self.width)img_seq_len = img_token_height * img_token_width# Load positive conditioning with optional regional masksdiff --git a/invokeai/backend/anima/regional_prompting.py b/invokeai/backend/anima/regional_prompting.pyindex c0af366332..54740cf966 100644--- a/invokeai/backend/anima/regional_prompting.py+++ b/invokeai/backend/anima/regional_prompting.py@@ -144,8 +144,8 @@ class AnimaRegionalPromptingExtension:Args:mask: Input mask tensor. If None, returns a mask of all ones.- target_height: Height of the image token grid (H // patch_size).- target_width: Width of the image token grid (W // patch_size).+ target_height: Height of the image token grid (ceil(latent_H / patch_size)).+ target_width: Width of the image token grid (ceil(latent_W / patch_size)).dtype: Target dtype for the mask.device: Target device for the mask.diff --git a/tests/app/invocations/test_anima_denoise.py b/tests/app/invocations/test_anima_denoise.pyindex a67d6a187b..b377066df6 100644--- a/tests/app/invocations/test_anima_denoise.py+++ b/tests/app/invocations/test_anima_denoise.py@@ -1,11 +1,17 @@+from types import SimpleNamespace+import pytest+import torchfrom invokeai.app.invocations.anima_denoise import (+ ANIMA_LATENT_CHANNELS,+ ANIMA_LATENT_SCALE_FACTOR,ANIMA_SHIFT,AnimaDenoiseInvocation,inverse_loglinear_timestep_shift,loglinear_timestep_shift,)+from invokeai.backend.anima.anima_transformer import MiniTrainDITclass TestLoglinearTimestepShift:@@ -125,6 +131,65 @@ class TestGetSigmasEdgeCases:assert sigmas[-1] == pytest.approx(0.0)+class TestComputeImgTokenGrid:+ """Test the regional-prompting image token grid computation.++ The mask's token grid must match the token grid the transformer actually produces.+ The transformer (MiniTrainDIT._pad_to_patch_size) pads the latent H/W up to a multiple+ of patch_spatial before patchifying, so the grid must use ceiling division.+ """++ def test_square_resolution(self):+ """1024x1024 -> latent 128x128 -> 64x64 token grid (even dims, no padding)."""+ assert AnimaDenoiseInvocation._compute_img_token_grid(1024, 1024) == (64, 64)++ def test_odd_latent_dimension_rounds_up(self):+ """1080 -> latent 135 (odd) -> padded to 136 -> 68 tokens; 1920 -> 240 -> 120 tokens."""+ # _compute_img_token_grid(height, width) -> (token_height, token_width)+ assert AnimaDenoiseInvocation._compute_img_token_grid(height=1920, width=1080) == (120, 68)++ def test_regression_1080x1920_seq_len(self):+ """Regression for the cross-attention mask shape mismatch at 1080x1920.++ The mask must be sized for 8160 (68*120) image tokens to match the transformer.+ The previous floor-division bug produced 8040 (67*120), raising:+ "The expanded size of the tensor (8160) must match the existing size (8040)".+ """+ token_h, token_w = AnimaDenoiseInvocation._compute_img_token_grid(height=1920, width=1080)+ assert token_h * token_w == 8160++ @pytest.mark.parametrize(+ "height, width",+ [+ (1024, 1024), # even latent dims+ (1080, 1920), # odd latent height+ (1920, 1080), # odd latent width+ (768, 1344),+ (1536, 640),+ (512, 512),+ ],+ )+ def test_matches_transformer_padding(self, height: int, width: int):+ """The computed grid must equal what MiniTrainDIT actually patchifies the latent to.++ This ties the mask sizing to the transformer's real padding logic, so the two cannot+ silently drift apart in the future.+ """+ patch_size = 2+ latent_h = height // ANIMA_LATENT_SCALE_FACTOR+ latent_w = width // ANIMA_LATENT_SCALE_FACTOR++ # _pad_to_patch_size only reads self.patch_spatial / self.patch_temporal, so a light+ # stub avoids constructing the full (heavyweight) transformer.+ stub = SimpleNamespace(patch_spatial=patch_size, patch_temporal=1)+ x = torch.zeros(1, ANIMA_LATENT_CHANNELS, 1, latent_h, latent_w)+ padded = MiniTrainDIT._pad_to_patch_size(stub, x) # type: ignore[arg-type]++ # PatchEmbed collapses each patch_size block, so token grid = padded_dim // patch_size.+ expected = (padded.shape[-2] // patch_size, padded.shape[-1] // patch_size)+ assert AnimaDenoiseInvocation._compute_img_token_grid(height, width, patch_size) == expected++class TestInverseLoglinearEdgeCases:"""Test edge cases for inverse_loglinear_timestep_shift."""