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
feat(canvas): add regional negatives for Anima, Z-Image, and Krea-2 (#10110)
Josh Corbettaca135d7d2e8
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdxindex 2fcc258f1e..f965fd46c7 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/anima.mdx@@ -149,10 +149,13 @@ The **negative prompt** is used only when CFG Scale is above 1; at CFG 1 it is i## Regional prompting-On the Canvas, **Regional Guidance** layers with a positive prompt work with Anima: each region's prompt is-steered to its masked area, alongside the global prompt. The restriction is applied on alternating-transformer blocks, leaving the others unrestricted to keep the image coherent. Regional negative prompts and regional-reference images are not supported.+On the Canvas, **Regional Guidance** layers support positive and negative prompts: each prompt is steered to+its masked area, alongside the global prompt. The global positive prompt covers the area outside the regions,+while the global negative prompt applies to the whole image. **Auto-Negative** uses the region's positive+prompt as a negative outside its mask. Regional negatives and auto-negative take effect only when **CFG+Scale** is above 1; Turbo's default CFG 1 ignores them. The restriction is applied on alternating transformer+blocks, leaving the others unrestricted to keep the image coherent. Regional reference images are not+supported.In the workflow editor, the **Prompt - Anima** node has an optional **mask** input, and **Denoise -Anima** accepts a collection of conditionings for its positive and negative inputs.diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdxindex caa9368cee..e7f7fc866c 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx@@ -136,13 +136,15 @@ In the workflow editor, the **Denoise - Krea-2** node accepts one conditioning oits positive and negative conditioning inputs. Multiple independently encoded conditionings are concatenatedafter padding tokens are removed.-The **Prompt - Krea-2** node also accepts an optional mask. A masked conditioning applies to that-image region; an unmasked conditioning applies to the background not covered by any regional mask. If-regional masks cover the full image, an unmasked conditioning falls back to the full image instead of being-ignored. Krea-2 uses restricted attention on alternating main transformer blocks, leaving the other blocks-unrestricted to preserve image-wide coherence. Positive regional prompts are available on the canvas. In+The **Prompt - Krea-2** node also accepts an optional mask. A masked conditioning applies to that image+region. An unmasked negative conditioning applies to the whole image; an unmasked positive conditioning+applies to the background not covered by any regional mask, or to the full image if regional masks cover all+of it. Krea-2 uses restricted attention on alternating main transformer blocks, leaving the other blocks+unrestricted to preserve image-wide coherence. Positive and negative regional prompts are available on the+Canvas. **Auto-Negative** uses the region's positive prompt as a negative outside its mask. Regional negatives+and auto-negative take effect only when **CFG Scale** is above 1; Turbo's default CFG 1 ignores them. Inworkflows, masked conditioning collections can also be supplied to the negative input when CFG is enabled.-Canvas regional negative prompts, auto-negative, and regional reference images are not supported.+Regional reference images are not supported.:::caution[Regional prompting memory]Regional prompting builds a dense boolean attention mask whose memory grows quadratically with the combineddiff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/z-image.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/z-image.mdxindex 2b34740b05..4095d0e10c 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/z-image.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/z-image.mdx@@ -134,9 +134,11 @@ control image.## Regional prompting-Z-Image supports **Regional Guidance** layers on the Canvas with **positive** prompts, together with a-control layer if you like. Regional negative prompts, auto-negative and regional reference images are not-supported for Z-Image.+Z-Image supports **Regional Guidance** layers on the Canvas with positive and negative prompts, together with+a control layer if you like. The global positive prompt covers the area outside the regions, while the global+negative prompt applies to the whole image. **Auto-Negative** uses the region's positive prompt as a negative+outside its mask. Regional negatives and auto-negative take effect only when **CFG Scale** is above 1; Turbo's+default CFG 1 ignores them. Regional reference images are not supported.In the workflow editor, **Prompt - Z-Image** takes an optional mask, and **Denoise - Z-Image** acceptseither one conditioning or a collection of them.diff --git a/docs/src/content/docs/Users Guide/07.Canvas/01.introduction.mdx b/docs/src/content/docs/Users Guide/07.Canvas/01.introduction.mdxindex 9c6c3766f8..1ad6c84c7c 100644--- a/docs/src/content/docs/Users Guide/07.Canvas/01.introduction.mdx+++ b/docs/src/content/docs/Users Guide/07.Canvas/01.introduction.mdx@@ -128,7 +128,7 @@ Regional guidance gives one area of the image its own prompt. For example, keepTo guide a region with an image instead of, or as well as, words, choose **Add reference image** from the regional guidance layer's right-click menu, or add a **Regional reference image** layer from the **+** menu. The reference appears as a row under the layer; select that row to choose its image, model and weight in Properties.-Regional guidance works with SD 1.5, SDXL, FLUX.1, FLUX.2, FLUX.3, Krea-2, Z-Image, Anima, MOSS-Image and Ideogram 4. [FLUX.3](/users-guide/models/local-models/flux-3/#layout-boxes-from-regional-guidance), MOSS-Image and Ideogram 4 place each region as a box in a JSON prompt instead of masking its prompt. MOSS-Image offers a **Region type** (Object by default, Character or Text); see [MOSS-Image](/users-guide/models/local-models/moss-image/#layout-with-canvas-regions) and [Ideogram 4](/users-guide/models/local-models/ideogram4/#prompting-ideogram-4). Regional negative prompts are available for SD 1.5 and SDXL, and regional reference images for SD 1.5, SDXL (IP-Adapter) and FLUX.1 (FLUX Redux). With other models, regional layers are skipped, and the layer's Properties say so. For a reference image that applies to the whole picture, use **Add reference image** in the Generate panel instead.+Regional guidance works with SD 1.5, SDXL, FLUX.1, FLUX.2, FLUX.3, Krea-2, Z-Image, Anima, MOSS-Image and Ideogram 4. [FLUX.3](/users-guide/models/local-models/flux-3/#layout-boxes-from-regional-guidance), MOSS-Image and Ideogram 4 place each region as a box in a JSON prompt instead of masking its prompt. MOSS-Image offers a **Region type** (Object by default, Character or Text); see [MOSS-Image](/users-guide/models/local-models/moss-image/#layout-with-canvas-regions) and [Ideogram 4](/users-guide/models/local-models/ideogram4/#prompting-ideogram-4). Regional negative prompts and auto-negative are available for SD 1.5, SDXL, Krea-2, Z-Image and Anima. For Krea-2, Z-Image and Anima, they take effect only at CFG Scale above 1. Regional reference images are available for SD 1.5, SDXL (IP-Adapter) and FLUX.1 (FLUX Redux). With other models, regional layers are skipped, and the layer's Properties say so. For a reference image that applies to the whole picture, use **Add reference image** in the Generate panel instead.## Control layersdiff --git a/invokeai/app/invocations/anima/anima_denoise.py b/invokeai/app/invocations/anima/anima_denoise.pyindex ea044b59b2..f05030d757 100644--- a/invokeai/app/invocations/anima/anima_denoise.py+++ b/invokeai/app/invocations/anima/anima_denoise.py@@ -42,7 +42,10 @@ from invokeai.app.invocations.model import TransformerFieldfrom invokeai.app.invocations.primitives import LatentsOutputfrom invokeai.app.services.shared.invocation_context import InvocationContextfrom invokeai.backend.anima.anima_transformer import IPAdapterBlockFn-from invokeai.backend.anima.anima_transformer_patch import patch_anima_for_regional_prompting+from invokeai.backend.anima.anima_transformer_patch import (+ AnimaRegionalPromptingState,+ patch_anima_for_regional_prompting,+)from invokeai.backend.anima.conditioning_data import AnimaRegionalTextConditioning, AnimaTextConditioningfrom invokeai.backend.anima.control_net_lllite import (AnimaControlNetLLLite,@@ -608,7 +611,9 @@ class AnimaDenoiseInvocation(BaseInvocation):image_masks.append(tc.mask)cur_len += context_2d.shape[0]- concatenated_context = torch.cat(context_embeds_list, dim=0)+ concatenated_context = (+ context_embeds_list[0] if len(context_embeds_list) == 1 else torch.cat(context_embeds_list, dim=0)+ )return AnimaRegionalTextConditioning(context_embeds=concatenated_context,@@ -663,7 +668,6 @@ class AnimaDenoiseInvocation(BaseInvocation):dtype=inference_dtype,device=device,)- has_regional = len(pos_text_conditionings) > 1 or any(tc.mask is not None for tc in pos_text_conditionings)# Load negative conditioning if CFG is enableddo_cfg = not math.isclose(self.guidance_scale, 1.0) and self.negative_conditioning is not None@@ -839,7 +843,7 @@ class AnimaDenoiseInvocation(BaseInvocation):def build_contexts(sigma: float | None,- ) -> tuple[torch.Tensor, torch.Tensor | None, AnimaRegionalTextConditioning | None]:+ ) -> tuple[AnimaRegionalTextConditioning, AnimaRegionalTextConditioning | None]:# float32, as the reference passes it: the connector's timestep embedding scales sigma by# 1000, where bf16's rounding of sigma would move its high frequencies by radians.timesteps = (@@ -847,47 +851,44 @@ class AnimaDenoiseInvocation(BaseInvocation):if sigma is not Noneelse None)- # Must run with the transformer on device since it uses the adapter weights.- if has_regional:- pos_regional = self._run_llm_adapter_for_regions(- transformer, pos_text_conditionings, inference_dtype, timesteps- )- pos = pos_regional.context_embeds.unsqueeze(0) # (1, total_ctx_len, 1024)- # For negative, concatenate all regions without masking (matches Z-Image behavior)- neg = None- if do_cfg and neg_text_conditionings is not None:- neg_regional = self._run_llm_adapter_for_regions(- transformer, neg_text_conditionings, inference_dtype, timesteps- )- neg = neg_regional.context_embeds.unsqueeze(0)- return pos, neg, pos_regional- pos = self._run_llm_adapter(transformer, pos_text_conditionings[0], inference_dtype, timesteps)- neg = None- if do_cfg and neg_text_conditionings is not None:- neg = self._run_llm_adapter(transformer, neg_text_conditionings[0], inference_dtype, timesteps)- return pos, neg, None+ # Both polarities may have regions, independently of the other pass's masks and token count.+ pos = self._run_llm_adapter_for_regions(transformer, pos_text_conditionings, inference_dtype, timesteps)+ neg = (+ self._run_llm_adapter_for_regions(transformer, neg_text_conditionings, inference_dtype, timesteps)+ if neg_text_conditionings is not None+ else None+ )+ return pos, negfirst_sigma = sigmas[0] if uses_connector else None- pos_context, neg_context, pos_regional = build_contexts(first_sigma)+ pos_regional, neg_regional = build_contexts(first_sigma)context_sigma = first_sigmadef contexts_at(sigma: float) -> tuple[torch.Tensor, torch.Tensor | None]:- nonlocal pos_context, neg_context, context_sigma+ nonlocal pos_regional, neg_regional, context_sigmaif uses_connector and sigma != context_sigma:- pos_context, neg_context, _ = build_contexts(sigma)+ pos_regional, neg_regional = build_contexts(sigma)context_sigma = sigma- return pos_context, neg_context+ return (+ pos_regional.context_embeds.unsqueeze(0),+ neg_regional.context_embeds.unsqueeze(0) if neg_regional is not None else None,+ )- # The regional cross-attention mask depends only on how many context tokens each region- # contributes (512 each), not on their values, so it is built once.- regional_extension = (- AnimaRegionalPromptingExtension.from_regional_conditioning(pos_regional, img_seq_len)- if pos_regional is not None+ # Token counts are fixed across timesteps, even when the semantic connector rebuilds their values.+ pos_mask = AnimaRegionalPromptingExtension.from_regional_conditioning(+ pos_regional, img_seq_len+ ).cross_attn_mask+ neg_mask = (+ # The global negative stays image-wide; only the positive pass's unmasked prompt yields to regions.+ AnimaRegionalPromptingExtension.from_regional_conditioning(+ neg_regional, img_seq_len, unmasked_covers_whole_image=True+ ).cross_attn_mask+ if neg_regional is not Noneelse None)-- # Apply regional prompting patch if we have regional masks- exit_stack.enter_context(patch_anima_for_regional_prompting(transformer, regional_extension))+ regional_state = AnimaRegionalPromptingState()+ if pos_mask is not None or neg_mask is not None:+ exit_stack.enter_context(patch_anima_for_regional_prompting(transformer, regional_state))# The positive pass alone gets the reference image: the reference's default CFG mode gives the negative# pass null tokens, which its gate turns into no IP term at all.@@ -932,7 +933,9 @@ class AnimaDenoiseInvocation(BaseInvocation):x: torch.Tensor,t: torch.Tensor,ip_adapter_blocks: Optional[list[Optional[IPAdapterBlockFn]]],+ regional_mask: torch.Tensor | None,) -> torch.Tensor:+ regional_state.cross_attn_mask = regional_maskreturn transformer(x=x.to(transformer.dtype if hasattr(transformer, "dtype") else inference_dtype),timesteps=t,@@ -965,11 +968,13 @@ class AnimaDenoiseInvocation(BaseInvocation):step_pos_context, step_neg_context = contexts_at(it.sigma_curr)noise_pred_cond = _run_transformer(- step_pos_context, latents, timestep, ip_adapter_blocks_at(user_step)+ step_pos_context, latents, timestep, ip_adapter_blocks_at(user_step), pos_mask).float()if do_cfg and step_neg_context is not None:- noise_pred_uncond = _run_transformer(step_neg_context, latents, timestep, None).float()+ noise_pred_uncond = _run_transformer(+ step_neg_context, latents, timestep, None, neg_mask+ ).float()noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_cond - noise_pred_uncond)else:noise_pred = noise_pred_cond@@ -1024,11 +1029,13 @@ class AnimaDenoiseInvocation(BaseInvocation):step_pos_context, step_neg_context = contexts_at(sigma_curr)noise_pred_cond = _run_transformer(- step_pos_context, latents, timestep, ip_adapter_blocks_at(step_idx)+ step_pos_context, latents, timestep, ip_adapter_blocks_at(step_idx), pos_mask).float()if do_cfg and step_neg_context is not None:- noise_pred_uncond = _run_transformer(step_neg_context, latents, timestep, None).float()+ noise_pred_uncond = _run_transformer(+ step_neg_context, latents, timestep, None, neg_mask+ ).float()noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_cond - noise_pred_uncond)else:noise_pred = noise_pred_conddiff --git a/invokeai/app/invocations/krea2/krea2_denoise.py b/invokeai/app/invocations/krea2/krea2_denoise.pyindex dd6039d536..f738c51fdb 100644--- a/invokeai/app/invocations/krea2/krea2_denoise.py+++ b/invokeai/app/invocations/krea2/krea2_denoise.py@@ -248,6 +248,8 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):grid_width: int,dtype: torch.dtype,device: torch.device,+ *,+ unmasked_covers_whole_image: bool = False,) -> Krea2RegionalPromptingExtension:conditioning_fields = ([conditioning_field] if isinstance(conditioning_field, Krea2ConditioningField) else conditioning_field@@ -293,6 +295,7 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):return Krea2RegionalPromptingExtension.from_text_conditionings(text_conditionings=text_conditionings,image_seq_len=grid_height * grid_width,+ unmasked_covers_whole_image=unmasked_covers_whole_image,)def _get_noise(self, height: int, width: int, dtype: torch.dtype, device: torch.device, seed: int) -> torch.Tensor:@@ -559,6 +562,7 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):neg_extension: Krea2RegionalPromptingExtension | None = Noneneg_prompt_embeds = Noneif do_cfg and self.negative_conditioning is not None:+ # The global negative stays image-wide; only the positive pass's unmasked prompt yields to regions.neg_extension = self._load_text_conditioning(context,self.negative_conditioning,@@ -566,6 +570,7 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):grid_width,inference_dtype,device,+ unmasked_covers_whole_image=True,)neg_prompt_embeds = neg_extension.regional_text_conditioning.prompt_embedsdiff --git a/invokeai/app/invocations/z_image/z_image_denoise.py b/invokeai/app/invocations/z_image/z_image_denoise.pyindex 65ccf7a1a2..aa46e028ba 100644--- a/invokeai/app/invocations/z_image/z_image_denoise.py+++ b/invokeai/app/invocations/z_image/z_image_denoise.py@@ -295,13 +295,12 @@ class ZImageDenoiseInvocation(BaseInvocation):# At cfg_scale=1.0: pred = pred_cond (no effect, skip uncond computation)# This matches FLUX's convention where 1.0 means "no CFG"neg_prompt_embeds: torch.Tensor | None = None+ negative_regional_extension: ZImageRegionalPromptingExtension | None = Nonedo_classifier_free_guidance = (not math.isclose(self.guidance_scale, 1.0) and self.negative_conditioning is not None)if do_classifier_free_guidance:assert self.negative_conditioning is not None- # Load all negative conditionings and concatenate embeddings- # Note: We ignore masks for negative conditioning as regional negative prompting is not fully supportedneg_text_conditionings = self._load_text_conditioning(context=context,cond_field=self.negative_conditioning,@@ -310,8 +309,13 @@ class ZImageDenoiseInvocation(BaseInvocation):dtype=inference_dtype,device=device,)- # Concatenate all negative embeddings- neg_prompt_embeds = torch.cat([tc.prompt_embeds for tc in neg_text_conditionings], dim=0)+ # The global negative stays image-wide; only the positive pass's unmasked prompt yields to regions.+ negative_regional_extension = ZImageRegionalPromptingExtension.from_text_conditionings(+ text_conditionings=neg_text_conditionings,+ img_seq_len=img_seq_len,+ unmasked_covers_whole_image=True,+ )+ neg_prompt_embeds = negative_regional_extension.regional_text_conditioning.prompt_embeds# Calculate shift based on image sequence length, or use overrideif self.shift is not None:@@ -441,7 +445,14 @@ class ZImageDenoiseInvocation(BaseInvocation):# 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+ negative_regional_attn_mask = (+ negative_regional_extension.regional_attn_mask if negative_regional_extension is not None else None+ )+ # Both boolean masks are already resident; only the larger additive bias is live per forward.+ regional_attn_mask = max(+ (regional_extension.regional_attn_mask, negative_regional_attn_mask),+ key=lambda mask: mask.numel() if mask is not None else 0,+ )working_memory = estimate_z_image_denoise_working_memory(transformer_info.model,image_seq_len=img_seq_len,@@ -504,6 +515,8 @@ class ZImageDenoiseInvocation(BaseInvocation):regional_attn_mask=regional_extension.regional_attn_mask,img_seq_len=img_seq_len,positive_cap_feats=pos_prompt_embeds,+ negative_regional_attn_mask=negative_regional_attn_mask,+ negative_cap_feats=neg_prompt_embeds,))diff --git a/invokeai/backend/anima/anima_transformer_patch.py b/invokeai/backend/anima/anima_transformer_patch.pyindex 4eff79830e..ffddb23500 100644--- a/invokeai/backend/anima/anima_transformer_patch.py+++ b/invokeai/backend/anima/anima_transformer_patch.py@@ -1,32 +1,34 @@"""Utilities for patching the AnimaTransformer to support regional cross-attention masks."""from contextlib import contextmanager-from typing import Optional+from dataclasses import dataclassimport torchimport torch.nn.functional as Ffrom einops import rearrange-from invokeai.backend.anima.regional_prompting import AnimaRegionalPromptingExtension++@dataclass+class AnimaRegionalPromptingState:+ """The active CFG branch's mask, scoped to one denoise invocation."""++ cross_attn_mask: torch.Tensor | None = Nonedef _patched_cross_attn_forward(original_forward,- attn_mask: torch.Tensor,+ state: AnimaRegionalPromptingState,):"""Create a patched forward for CosmosAttention that injects a cross-attention mask.Args:original_forward: The original CosmosAttention.forward method (bound to self).- attn_mask: Cross-attention mask of shape (img_seq_len, context_seq_len).+ state: Selects the current pass's cross-attention mask."""def forward(x, context=None, rope_emb=None):- # If the context sequence length doesn't match the mask (e.g. negative conditioning- # has a different number of tokens than positive regional conditioning), skip masking- # and use the original unmasked forward.- actual_context = x if context is None else context- if actual_context.shape[-2] != attn_mask.shape[1]:+ attn_mask = state.cross_attn_mask+ if attn_mask is None:return original_forward(x, context, rope_emb=rope_emb)self = original_forward.__self__@@ -53,14 +55,8 @@ def _patched_cross_attn_forward(k = rearrange(k, "b ... h d -> b h ... d").reshape(in_k_shape[0], in_k_shape[-2], -1, in_k_shape[-1])v = rearrange(v, "b ... h d -> b h ... d").reshape(in_k_shape[0], in_k_shape[-2], -1, in_k_shape[-1])- # Convert boolean mask to float additive mask for SDPA- # True (attend) -> 0.0, False (block) -> -inf- # Shape: (img_seq_len, context_seq_len) -> (1, 1, img_seq_len, context_seq_len)- float_mask = torch.zeros_like(attn_mask, dtype=q.dtype)- float_mask[~attn_mask] = float("-inf")- expanded_mask = float_mask.unsqueeze(0).unsqueeze(0)-- result = F.scaled_dot_product_attention(q, k, v, attn_mask=expanded_mask)+ # SDPA accepts the shared boolean mask directly: True allows attention.+ result = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask.unsqueeze(0).unsqueeze(0))result = rearrange(result, "b h s d -> b s (h d)")return self.output_dropout(self.output_proj(result))@@ -70,7 +66,7 @@ def _patched_cross_attn_forward(@contextmanagerdef patch_anima_for_regional_prompting(transformer,- regional_extension: Optional[AnimaRegionalPromptingExtension],+ state: AnimaRegionalPromptingState,):"""Context manager to temporarily patch the Anima transformer for regional prompting.@@ -80,27 +76,18 @@ def patch_anima_for_regional_prompting(Args:transformer: The AnimaTransformer instance.- regional_extension: The regional prompting extension. If None or no mask, no patching.+ state: The caller selects a branch's mask before each transformer pass.Yields:The (possibly patched) transformer."""- if regional_extension is None or regional_extension.cross_attn_mask is None:- yield transformer- return-- # Store original forwardsoriginal_forwards = []- for block_idx, block in enumerate(transformer.blocks):- original_forwards.append(block.cross_attn.forward)-- mask = regional_extension.get_cross_attn_mask(block_idx)- if mask is not None:- block.cross_attn.forward = _patched_cross_attn_forward(block.cross_attn.forward, mask)-try:+ for block in transformer.blocks[::2]:+ original_forwards.append((block.cross_attn, block.cross_attn.forward))+ block.cross_attn.forward = _patched_cross_attn_forward(block.cross_attn.forward, state)yield transformerfinally:- # Restore original forwards- for block_idx, block in enumerate(transformer.blocks):- block.cross_attn.forward = original_forwards[block_idx]+ state.cross_attn_mask = None+ for attention, original_forward in reversed(original_forwards):+ attention.forward = original_forwarddiff --git a/invokeai/backend/anima/regional_prompting.py b/invokeai/backend/anima/regional_prompting.pyindex 54740cf966..2c50a28f03 100644--- a/invokeai/backend/anima/regional_prompting.py+++ b/invokeai/backend/anima/regional_prompting.py@@ -41,29 +41,25 @@ class AnimaRegionalPromptingExtension:self.regional_text_conditioning = regional_text_conditioningself.cross_attn_mask = cross_attn_mask- def get_cross_attn_mask(self, block_index: int) -> torch.Tensor | None:- """Get the cross-attention mask for a given block index.-- Uses alternating pattern: apply mask on even blocks, no mask on odd blocks.- This helps balance regional control with global coherence.- """- if block_index % 2 == 0:- return self.cross_attn_mask- return None-@classmethoddef from_regional_conditioning(cls,regional_text_conditioning: AnimaRegionalTextConditioning,img_seq_len: int,+ *,+ unmasked_covers_whole_image: bool = False,) -> "AnimaRegionalPromptingExtension":"""Create extension from pre-processed regional conditioning.Args:regional_text_conditioning: Regional conditioning with concatenated context and masks.img_seq_len: Number of image tokens (H_patches * W_patches).+ unmasked_covers_whole_image: Let unmasked conditionings reach every image token instead of only the+ background. Set for the negative pass, whose global negative must stay image-wide."""- cross_attn_mask = cls._prepare_cross_attn_mask(regional_text_conditioning, img_seq_len)+ cross_attn_mask = cls._prepare_cross_attn_mask(+ regional_text_conditioning, img_seq_len, unmasked_covers_whole_image=unmasked_covers_whole_image+ )return cls(regional_text_conditioning=regional_text_conditioning,cross_attn_mask=cross_attn_mask,@@ -74,16 +70,21 @@ class AnimaRegionalPromptingExtension:cls,regional_text_conditioning: AnimaRegionalTextConditioning,img_seq_len: int,+ *,+ unmasked_covers_whole_image: bool = False,) -> torch.Tensor | None:"""Prepare a cross-attention mask for regional prompting.The mask shape is (img_seq_len, context_seq_len) where:- Each image token can attend to context tokens from its assigned region- - Global prompts (mask=None) attend to background regions+ - Global prompts (mask=None) attend to background regions, or to every image token when+ `unmasked_covers_whole_image` is set+ - Image tokens no conditioning reaches attend to all context tokens, as on the unmasked blocksArgs:regional_text_conditioning: The regional text conditioning data.img_seq_len: Number of image tokens.+ unmasked_covers_whole_image: Let unmasked conditionings reach every image token.Returns:Cross-attention mask of shape (img_seq_len, context_seq_len), or None@@ -121,15 +122,17 @@ class AnimaRegionalPromptingExtension:# Regional prompt: only masked image tokens attend to this region's contextmask_flat = image_mask.view(img_seq_len)cross_attn_mask[:, ctx_start:ctx_end] = mask_flat.view(img_seq_len, 1)+ elif unmasked_covers_whole_image or background_region_mask is None:+ cross_attn_mask[:, ctx_start:ctx_end] = 1.0else:# Global prompt: background image tokens attend to this context- if background_region_mask is not None:- cross_attn_mask[:, ctx_start:ctx_end] = background_region_mask.view(img_seq_len, 1)- else:- cross_attn_mask[:, ctx_start:ctx_end] = 1.0+ cross_attn_mask[:, ctx_start:ctx_end] = background_region_mask.view(img_seq_len, 1)- # Convert to booleancross_attn_mask = cross_attn_mask > 0.5+ # A list of only masked conditionings leaves uncovered image tokens with no allowed context token. SDPA backends+ # are not guaranteed to agree on such a row (zeros vs NaN), so leave those tokens unrestricted: they then see+ # every regional prompt, as they do on the unmasked odd blocks.+ cross_attn_mask |= ~cross_attn_mask.any(dim=1, keepdim=True)return cross_attn_mask@staticmethoddiff --git a/invokeai/backend/architectures/defs/anima.py b/invokeai/backend/architectures/defs/anima.pyindex c2caaafc52..eec67ceaf1 100644--- a/invokeai/backend/architectures/defs/anima.py+++ b/invokeai/backend/architectures/defs/anima.py@@ -41,8 +41,8 @@ register(guidance_min=1.0,scheduler_set="anima",scheduler_applies_to_graph=True,- # Same shape as Z-Image: masked positive conditioning only.supports_regional_guidance=True,+ regional_negative=True,# `anima_lllite` into `anima_denoise.control_lllite`. Only 3-channel (control image) adapters drive a# control layer; 4-channel inpainting adapters need the inpaint mask and are not control layers.control_kinds=frozenset({"anima_lllite"}),diff --git a/invokeai/backend/architectures/defs/krea_2.py b/invokeai/backend/architectures/defs/krea_2.pyindex ffc2d65dac..f1ea23ab8c 100644--- a/invokeai/backend/architectures/defs/krea_2.py+++ b/invokeai/backend/architectures/defs/krea_2.py@@ -38,6 +38,7 @@ register(# three edit references for ai-toolkit edit LoRAs; `krea2_denoise` refuses more than three.max_reference_images=3,supports_regional_guidance=True,+ regional_negative=True,),VaeFacet(frozenset(diff --git a/invokeai/backend/architectures/defs/z_image.py b/invokeai/backend/architectures/defs/z_image.pyindex 5a18e04261..cee1e48c2d 100644--- a/invokeai/backend/architectures/defs/z_image.py+++ b/invokeai/backend/architectures/defs/z_image.py@@ -39,9 +39,8 @@ register(scheduler_set_by_variant={ZImageVariantType.ZBase: "flow-no-lcm"},scheduler_applies_to_graph=True,control_kinds=frozenset({"z_image_control"}),- # The text encoder masks positive conditioning; the denoiser takes a negative list but- # discards its masks, so a regional negative would act globally and is rejected instead.supports_regional_guidance=True,+ regional_negative=True,),VaeFacet(frozenset(diff --git a/invokeai/backend/architectures/facets/features.py b/invokeai/backend/architectures/facets/features.pyindex 1386f63d14..7f1a326604 100644--- a/invokeai/backend/architectures/facets/features.py+++ b/invokeai/backend/architectures/facets/features.py@@ -129,7 +129,7 @@ class FeaturesFacet(Facet):supports_regional_guidance: bool = Falseregional_negative: bool = False- """Regional *negative* prompts, which only the SD family has."""+ """Whether regional negative conditionings retain their spatial masks."""clip_skip_max: int | None = Nonesupports_seamless: bool = Falsediff --git a/invokeai/backend/krea2/regional_prompting.py b/invokeai/backend/krea2/regional_prompting.pyindex 44ea926f69..d7a3f8a761 100644--- a/invokeai/backend/krea2/regional_prompting.py+++ b/invokeai/backend/krea2/regional_prompting.py@@ -23,9 +23,18 @@ class Krea2RegionalTextConditioning:class Krea2RegionalPromptingExtension:"""Concatenates Krea-2 text conditionings and lazily builds Flux-style regional attention masks."""- def __init__(self, regional_text_conditioning: Krea2RegionalTextConditioning, image_seq_len: int) -> None:+ def __init__(+ self,+ regional_text_conditioning: Krea2RegionalTextConditioning,+ image_seq_len: int,+ *,+ unmasked_covers_whole_image: bool = False,+ ) -> None:self.regional_text_conditioning = regional_text_conditioningself.image_seq_len = image_seq_len+ # Unmasked conditionings reach every image token rather than only the background. Set for the negative+ # pass, whose global negative must stay image-wide.+ self.unmasked_covers_whole_image = unmasked_covers_whole_imageself._attention_mask: torch.Tensor | None = None@property@@ -48,7 +57,11 @@ class Krea2RegionalPromptingExtension:@classmethoddef from_text_conditionings(- cls, text_conditionings: list[Krea2TextConditioning], image_seq_len: int+ cls,+ text_conditionings: list[Krea2TextConditioning],+ image_seq_len: int,+ *,+ unmasked_covers_whole_image: bool = False,) -> "Krea2RegionalPromptingExtension":if not text_conditionings:raise ValueError("At least one Krea-2 text conditioning is required.")@@ -73,7 +86,11 @@ class Krea2RegionalPromptingExtension:image_masks=image_masks,embedding_ranges=embedding_ranges,)- return cls(regional_text_conditioning=regional_text_conditioning, image_seq_len=image_seq_len)+ return cls(+ regional_text_conditioning=regional_text_conditioning,+ image_seq_len=image_seq_len,+ unmasked_covers_whole_image=unmasked_covers_whole_image,+ )def get_attention_mask(self) -> torch.Tensor | None:if not self.has_regional_masks:@@ -93,11 +110,15 @@ class Krea2RegionalPromptingExtension:for image_mask in conditioning.image_masks:if image_mask is not None:background_mask &= ~(image_mask.reshape(-1) > 0.5)- # Canvas graphs always include an unmasked global prompt. If regional masks cover the full image,- # there is no background for it; fall back to image-wide text/image attention instead of silently- # disconnecting that conditioning. Keep background_mask unchanged so regional image/image isolation- # remains intact.- unmasked_conditioning_mask = background_mask | ~background_mask.any()+ if self.unmasked_covers_whole_image:+ # The global negative must not yield to regions, or Auto-Negative would confine it to their insides.+ unmasked_conditioning_mask = torch.ones_like(background_mask)+ else:+ # Canvas graphs always include an unmasked global prompt. If regional masks cover the full image,+ # there is no background for it; fall back to image-wide text/image attention instead of silently+ # disconnecting that conditioning. Keep background_mask unchanged so regional image/image isolation+ # remains intact.+ unmasked_conditioning_mask = background_mask | ~background_mask.any()image_attention_mask = attention_mask[text_seq_len:, text_seq_len:]for image_mask, embedding_range in zip(conditioning.image_masks, conditioning.embedding_ranges, strict=True):diff --git a/invokeai/backend/z_image/denoise_working_memory.py b/invokeai/backend/z_image/denoise_working_memory.pyindex 23a6ccbb29..8df1b9d7c6 100644--- a/invokeai/backend/z_image/denoise_working_memory.py+++ b/invokeai/backend/z_image/denoise_working_memory.py@@ -95,7 +95,7 @@ def padded_tokens(tokens: int) -> int:def _regional_attention_bias_bytes(regional_attn_mask: Optional[torch.Tensor], 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+ """What `regional_forward` allocates per regional pass for regional prompting: a boolean copy of the mask, theadditive bias over the padded unified sequence, and the image-to-image block `torch.where` fills it from. The maskitself is already on the device when the estimate is taken. Measured at 1024px on CUDA: 68 MiB over the plainforward, against 93 MiB charged."""@@ -167,7 +167,7 @@ def estimate_z_image_denoise_working_memory(`transformer` is the model about to be locked, read unlocked for its dequantization and fp8 cast transients.`image_seq_len` and `text_seq_len` are the unpadded token counts, the longer caption of a CFG pair. `control_blocks`- is the ControlNet's block count, `regional_attn_mask` regional prompting's mask, and `has_attention_mask`+ is the ControlNet's block count, `regional_attn_mask` the larger regional mask of a CFG pair, and `has_attention_mask`whether the forward passes an attention mask at all."""dtype_name = _DTYPE_NAMES.get(dtype)diff --git a/invokeai/backend/z_image/extensions/regional_prompting_extension.py b/invokeai/backend/z_image/extensions/regional_prompting_extension.pyindex 26f91749f7..ed4bad8388 100644--- a/invokeai/backend/z_image/extensions/regional_prompting_extension.py+++ b/invokeai/backend/z_image/extensions/regional_prompting_extension.py@@ -41,18 +41,24 @@ class ZImageRegionalPromptingExtension:cls,text_conditionings: list[ZImageTextConditioning],img_seq_len: int,+ *,+ unmasked_covers_whole_image: bool = False,) -> "ZImageRegionalPromptingExtension":"""Create a ZImageRegionalPromptingExtension from a list of text conditionings.Args:text_conditionings: List of text conditionings with optional masks.img_seq_len: The image sequence length (i.e. (H // patch_size) * (W // patch_size)).+ unmasked_covers_whole_image: Let unmasked conditionings reach every image token instead of only the+ background. Set for the negative pass, whose global negative must stay image-wide.Returns:A configured ZImageRegionalPromptingExtension."""regional_text_conditioning = ZImageRegionalTextConditioning.from_text_conditionings(text_conditionings)- attn_mask = cls._prepare_regional_attn_mask(regional_text_conditioning, img_seq_len)+ attn_mask = cls._prepare_regional_attn_mask(+ regional_text_conditioning, img_seq_len, unmasked_covers_whole_image=unmasked_covers_whole_image+ )return cls(regional_text_conditioning=regional_text_conditioning,regional_attn_mask=attn_mask,@@ -63,6 +69,8 @@ class ZImageRegionalPromptingExtension:cls,regional_text_conditioning: ZImageRegionalTextConditioning,img_seq_len: int,+ *,+ unmasked_covers_whole_image: bool = False,) -> torch.Tensor | None:"""Prepare a regional attention mask for Z-Image.@@ -71,6 +79,8 @@ class ZImageRegionalPromptingExtension:- Image tokens attend only to their corresponding regional text- Text tokens attend only to their corresponding regional image- Text tokens attend to themselves+ - Unmasked text attends to and from the background image tokens, or every image token when+ `unmasked_covers_whole_image` is setThe unrestricted image self-attention allows the model to maintain globalcoherence across regions, preventing the generation of separate/disconnected@@ -81,6 +91,7 @@ class ZImageRegionalPromptingExtension:Args:regional_text_conditioning: The regional text conditioning data.img_seq_len: Number of image tokens.+ unmasked_covers_whole_image: Let unmasked conditionings reach every image token.Returns:Attention mask of shape (img_seq_len + txt_seq_len, img_seq_len + txt_seq_len).@@ -133,22 +144,16 @@ class ZImageRegionalPromptingExtension:# 3. txt attends to corresponding regional img# Reshape mask to (1, img_seq_len) for broadcastingregional_attention_mask[txt_start:txt_end, :img_seq_len] = mask_flat.view(1, img_seq_len)+ elif unmasked_covers_whole_image or background_region_mask is None:+ regional_attention_mask[:img_seq_len, txt_start:txt_end] = 1.0+ regional_attention_mask[txt_start:txt_end, :img_seq_len] = 1.0else:# Global prompt: allow attention to/from background regions only- if background_region_mask is not None:- # 2. background img attends to global txt- regional_attention_mask[:img_seq_len, txt_start:txt_end] = background_region_mask.view(- img_seq_len, 1- )-- # 3. global txt attends to background img- regional_attention_mask[txt_start:txt_end, :img_seq_len] = background_region_mask.view(- 1, img_seq_len- )- else:- # No regional masks at all, allow full attention- regional_attention_mask[:img_seq_len, txt_start:txt_end] = 1.0- regional_attention_mask[txt_start:txt_end, :img_seq_len] = 1.0+ # 2. background img attends to global txt+ regional_attention_mask[:img_seq_len, txt_start:txt_end] = background_region_mask.view(img_seq_len, 1)++ # 3. global txt attends to background img+ regional_attention_mask[txt_start:txt_end, :img_seq_len] = background_region_mask.view(1, img_seq_len)# 4. Allow unrestricted image self-attention# This is the key difference from the restricted approach - all image tokensdiff --git a/invokeai/backend/z_image/z_image_transformer_patch.py b/invokeai/backend/z_image/z_image_transformer_patch.pyindex 095af70a9f..1054550a5e 100644--- a/invokeai/backend/z_image/z_image_transformer_patch.py+++ b/invokeai/backend/z_image/z_image_transformer_patch.py@@ -8,9 +8,11 @@ import torchdef create_regional_forward(original_forward: Callable,- regional_attn_mask: torch.Tensor,+ regional_attn_mask: torch.Tensor | None,img_seq_len: int,- positive_cap_feats: torch.Tensor,+ positive_cap_feats: torch.Tensor | None,+ negative_regional_attn_mask: torch.Tensor | None = None,+ negative_cap_feats: torch.Tensor | None = None,) -> Callable:"""Create a modified forward function that uses a regional attention mask.@@ -29,13 +31,10 @@ def create_regional_forward(regional_attn_mask: Boolean attention mask of shape (seq_len, seq_len) whereseq_len = img_seq_len + txt_seq_len, ordered [img, txt].img_seq_len: Number of (unpadded) image tokens in the sequence.- positive_cap_feats: The exact caption-embedding tensor the regional mask was- built for (the conditioned/positive pass). The regional mask is applied only- to forward calls whose ``cap_feats`` is this same object; the negative/CFG- pass supplies a different tensor and is left to run with the plain padding- mask. Identity is used instead of a token-length heuristic so the positive- and negative passes can never be confused even when their padded lengths- coincide.+ positive_cap_feats: The caption tensor paired with ``regional_attn_mask``.+ negative_regional_attn_mask: The negative pass's independent regional mask, if any.+ negative_cap_feats: The caption tensor paired with ``negative_regional_attn_mask``.+ Tensor identity selects each pass's mask, even when their token lengths coincide.Returns:A modified forward function with regional attention support.@@ -59,12 +58,16 @@ def create_regional_forward(device = x[0].device- # Identify which caption inputs belong to the conditioned (positive) pass the regional- # mask was built for. Capture this before patchify_and_embed reassigns ``cap_feats``.- # The negative/CFG pass supplies a different tensor, so object identity distinguishes the- # passes regardless of token length (avoids the positive mask leaking into the uncond- # prediction when prompt lengths happen to pad to the same multiple).- is_positive_pass = [ci is positive_cap_feats for ci in cap_feats]+ # Select before patchify_and_embed replaces the caption tensors. Token lengths cannot+ # distinguish the CFG passes, and either pass may be the only one with regions.+ regional_masks = [+ regional_attn_mask+ if caption is positive_cap_feats+ else negative_regional_attn_mask+ if caption is negative_cap_feats+ else None+ for caption in cap_feats+ ]# Single adaLN embedding for all tokens (basic mode).adaln_input = self.t_embedder(t * self.t_scale).type_as(x[0])@@ -128,27 +131,10 @@ def create_regional_forward(# We therefore scatter the four regional sub-blocks (img-img, img-txt, txt-img, txt-txt)# into their padding-aware positions instead of assuming a contiguous top-left block.#- # The patched forward also runs for the negative/CFG pass (a different prompt). The- # regional mask was built for the positive prompt only, so we apply it only to the- # conditioned items and fall back to the plain padding mask otherwise.- regional = regional_attn_mask.to(device=device, dtype=torch.bool)- txt_seq_len = regional.shape[0] - img_seq_len-- # Decide per item whether the regional mask applies, using only cheap scalar checks, so- # that on passes that never match (e.g. every negative/CFG pass) we avoid materializing- # the (bsz, 1, S, S) float mask at all.- applied_regional = [- is_positive_pass[i]- and txt_seq_len > 0- and img_seq_len <= x_seqlens[i]- and x_seqlens[i] + cap_seqlens[i] <= unified_seqlen- for i in range(bsz)- ]-- # Main transformer layers: alternate regional mask (even) with plain padding mask (odd).- # If no item matched the positive pass, skip regional injection entirely.- use_regional = any(applied_regional)+ use_regional = any(mask is not None for mask in regional_masks)+ # Rebuilt on every forward rather than cached per CFG pass: caching both passes' (S, S) biases keeps them+ # resident (hundreds of MB at 2048 px), while the rebuild costs only a few milliseconds per forward.float_mask = Noneif use_regional:# Build a per-item additive float mask. Start from the plain padding mask (0 where a@@ -170,9 +156,11 @@ def create_regional_forward(.clone())- for i in range(bsz):- if not applied_regional[i]:+ for i, regional in enumerate(regional_masks):+ if regional is None:continue+ regional = regional.to(device=device, dtype=torch.bool)+ txt_seq_len = regional.shape[0] - img_seq_lenx_len = x_seqlens[i]ii, it = slice(0, img_seq_len), slice(img_seq_len, img_seq_len + txt_seq_len)@@ -208,34 +196,47 @@ def patch_transformer_for_regional_prompting(regional_attn_mask: Optional[torch.Tensor],img_seq_len: int,positive_cap_feats: Optional[torch.Tensor] = None,+ negative_regional_attn_mask: Optional[torch.Tensor] = None,+ negative_cap_feats: Optional[torch.Tensor] = None,):"""Context manager to temporarily patch the transformer for regional prompting.Args:transformer: The ZImageTransformer2DModel instance.regional_attn_mask: Regional attention mask of shape (seq_len, seq_len).- If None, the transformer is not patched.+ If both regional masks are None, the transformer is not patched.img_seq_len: Number of image tokens.positive_cap_feats: The caption-embedding tensor the regional mask was built for.Required when ``regional_attn_mask`` is provided; the mask is applied only toforward calls whose ``cap_feats`` is this exact object (the conditioned pass).+ negative_regional_attn_mask: The negative pass's regional mask.+ negative_cap_feats: The corresponding negative caption tensor; required for a negative mask.Yields:The (possibly patched) transformer."""- if regional_attn_mask is None:+ if regional_attn_mask is None and negative_regional_attn_mask is None:# No regional prompting, use original forwardyield transformerreturn- if positive_cap_feats is None:+ if regional_attn_mask is not None and positive_cap_feats is None:raise ValueError("positive_cap_feats is required when regional_attn_mask is provided")+ if negative_regional_attn_mask is not None and negative_cap_feats is None:+ raise ValueError("negative_cap_feats is required when negative_regional_attn_mask is provided")# Store original forwardoriginal_forward = transformer.forward# Create and bind the regional forward- regional_fwd = create_regional_forward(original_forward, regional_attn_mask, img_seq_len, positive_cap_feats)+ regional_fwd = create_regional_forward(+ original_forward,+ regional_attn_mask,+ img_seq_len,+ positive_cap_feats,+ negative_regional_attn_mask,+ negative_cap_feats,+ )transformer.forward = lambda *args, **kwargs: regional_fwd(transformer, *args, **kwargs)try:diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 8ade6956e8..f460ef2e60 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -5629,6 +5629,7 @@"negativePromptAdd": "Negative prompt…","negativePromptHide": "Turn off negative prompt","negativePromptPlaceholder": "Region negative prompt",+ "negativesNeedCfg": "Negative prompts and Auto-Negative take effect only when CFG Scale is above 1.","positivePrompt": "Positive prompt","positivePromptPlaceholder": "Region positive prompt","referenceImage": "Reference image",diff --git a/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json b/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.jsonindex cabb95c2f7..528555a321 100644--- a/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json+++ b/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json@@ -20,7 +20,7 @@"reference_images_require_variant": "anima_qwen3","reference_images_require_format": null,"supports_regional_guidance": true,- "regional_negative": false,+ "regional_negative": true,"clip_skip_max": null,"supports_seamless": false,"supports_cfg_rescale": false,@@ -79,7 +79,7 @@"reference_images_require_variant": "anima_qwen3","reference_images_require_format": null,"supports_regional_guidance": true,- "regional_negative": false,+ "regional_negative": true,"clip_skip_max": null,"supports_seamless": false,"supports_cfg_rescale": false,@@ -685,7 +685,7 @@"reference_images_require_variant": null,"reference_images_require_format": null,"supports_regional_guidance": true,- "regional_negative": false,+ "regional_negative": true,"clip_skip_max": null,"supports_seamless": false,"supports_cfg_rescale": false,@@ -738,7 +738,7 @@"reference_images_require_variant": null,"reference_images_require_format": null,"supports_regional_guidance": true,- "regional_negative": false,+ "regional_negative": true,"clip_skip_max": null,"supports_seamless": false,"supports_cfg_rescale": false,@@ -1421,7 +1421,7 @@"reference_images_require_variant": null,"reference_images_require_format": null,"supports_regional_guidance": true,- "regional_negative": false,+ "regional_negative": true,"clip_skip_max": null,"supports_seamless": false,"supports_cfg_rescale": false,@@ -1472,7 +1472,7 @@"reference_images_require_variant": null,"reference_images_require_format": null,"supports_regional_guidance": true,- "regional_negative": false,+ "regional_negative": true,"clip_skip_max": null,"supports_seamless": false,"supports_cfg_rescale": false,diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.tsindex 9fa6f9d272..651311029e 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.test.ts@@ -254,14 +254,19 @@ describe('getRegionalGuidanceSupport', () => {negativePrompt: false,referenceImages: 'flux_redux',});- for (const base of ['flux2', 'krea-2', 'z-image', 'anima']) {+ for (const base of ['krea-2', 'z-image', 'anima']) {expect(getRegionalGuidanceSupport(base), base).toMatchObject({- autoNegative: false,+ autoNegative: true,mode: 'masks',- negativePrompt: false,+ negativePrompt: true,referenceImages: null,});}+ expect(getRegionalGuidanceSupport('flux2')).toMatchObject({+ autoNegative: false,+ negativePrompt: false,+ referenceImages: null,+ });expect(getRegionalGuidanceSupport('sd-3')).toBeNull();expect(getRegionalGuidanceSupport(null)).toBeNull();});@@ -273,6 +278,7 @@ describe('getRegionalGuidanceSupport', () => {layoutKinds: ['object', 'character', 'text'],mode: 'layout',negativePrompt: false,+ negativesNeedCfg: false,referenceImages: null,});// The structured caption has object elements only.@@ -282,6 +288,7 @@ describe('getRegionalGuidanceSupport', () => {layoutKinds: ['object'],mode: 'layout',negativePrompt: false,+ negativesNeedCfg: false,referenceImages: null,});// Regions become rows of the box table.@@ -291,6 +298,7 @@ describe('getRegionalGuidanceSupport', () => {layoutKinds: ['object'],mode: 'layout',negativePrompt: false,+ negativesNeedCfg: false,referenceImages: null,});});@@ -300,7 +308,7 @@ describe('addRegionalGuidance — Z-Image / Anima', () => {it.each([['z-image', 'z_image_text_encoder'],['anima', 'anima_text_encoder'],- ] as const)('%s wires a masked positive prompt through its Qwen3 encoder, positive only', (base, encoderType) => {+ ] as const)('%s wires masked prompts through its Qwen3 encoder', (base, encoderType) => {const g = run(qwen3BaseGraph(encoderType), {base,regions: [region({ autoNegative: true, negativePrompt: 'blurry' })],@@ -310,10 +318,13 @@ describe('addRegionalGuidance — Z-Image / Anima', () => {expect(hasEdge(g, 'model_loader', 'qwen3_encoder', 'rg_pos_cond_r1', 'qwen3_encoder')).toBe(true);expect(hasEdge(g, 'rg_mask_to_tensor_r1', 'mask', 'rg_pos_cond_r1', 'mask')).toBe(true);expect(hasEdge(g, 'rg_pos_cond_r1', 'conditioning', 'pos_cond_collect', 'item')).toBe(true);- // These backends discard negative masks even when a negative collector exists.- expect(g.nodes.rg_neg_cond_r1).toBeUndefined();- expect(g.nodes.rg_pos_cond_inverted_r1).toBeUndefined();- expect(g.edges.some((e) => e.destination.node_id === 'neg_cond_collect')).toBe(false);+ expect(g.nodes.rg_neg_cond_r1).toMatchObject({ prompt: 'blurry', type: encoderType });+ expect(hasEdge(g, 'model_loader', 'qwen3_encoder', 'rg_neg_cond_r1', 'qwen3_encoder')).toBe(true);+ expect(hasEdge(g, 'rg_mask_to_tensor_r1', 'mask', 'rg_neg_cond_r1', 'mask')).toBe(true);+ expect(hasEdge(g, 'rg_neg_cond_r1', 'conditioning', 'neg_cond_collect', 'item')).toBe(true);+ expect(g.nodes.rg_pos_cond_inverted_r1).toMatchObject({ prompt: 'a cat', type: encoderType });+ expect(hasEdge(g, 'rg_invert_mask_r1', 'mask', 'rg_pos_cond_inverted_r1', 'mask')).toBe(true);+ expect(hasEdge(g, 'rg_pos_cond_inverted_r1', 'conditioning', 'neg_cond_collect', 'item')).toBe(true);});});@@ -564,6 +575,7 @@ describe('addRegionalGuidance — multiple regions coexist', () => {describe('getRegionalGuidanceRejectionReason', () => {const params = {+ cfgScale: 7,hasContent: true,layerName: 'Region 1',mainBase: 'sd-1',@@ -615,9 +627,6 @@ describe('getRegionalGuidanceRejectionReason', () => {it.each([['flux', 'FLUX', 0],['flux2', 'FLUX.2', 1],- ['krea-2', 'Krea-2', 1],- ['z-image', 'Z-Image', 1],- ['anima', 'Anima', 1],])('rejects a %s region that carries only what the base ignores', (mainBase, label, referenceImageCount) => {expect(getRegionalGuidanceRejectionReason({@@ -630,6 +639,29 @@ describe('getRegionalGuidanceRejectionReason', () => {).toBe(`Regional guidance "Region 1" has no prompt or reference image ${label} can use.`);});+ it.each(['krea-2', 'z-image', 'anima'])(+ 'accepts a %s region with only a negative prompt only while CFG is above 1',+ (mainBase) => {+ const negativeOnly = { ...params, mainBase, negativePrompt: 'blurry', positivePrompt: null };++ expect(getRegionalGuidanceRejectionReason({ ...negativeOnly, cfgScale: 1.5 })).toBeNull();+ for (const cfgScale of [1, 0.5]) {+ expect(getRegionalGuidanceRejectionReason({ ...negativeOnly, cfgScale })).toMatch(/no prompt or reference/);+ }+ // A positive prompt still carries the region at CFG 1.+ expect(getRegionalGuidanceRejectionReason({ ...negativeOnly, cfgScale: 1, positivePrompt: 'a cat' })).toBeNull();+ expect(+ getRegionalGuidanceRejectionReason({ ...params, mainBase, positivePrompt: null, referenceImageCount: 1 })+ ).toMatch(/no prompt or reference/);+ }+ );++ it('accepts an SD region with only a negative prompt at CFG 1, where its graph still reads negatives', () => {+ expect(+ getRegionalGuidanceRejectionReason({ ...params, cfgScale: 1, negativePrompt: 'blurry', positivePrompt: null })+ ).toBeNull();+ });+it('keeps a FLUX region that only carries a Redux reference image', () => {expect(getRegionalGuidanceRejectionReason({ ...params, mainBase: 'flux', positivePrompt: null, referenceImageCount: 1 })@@ -639,6 +671,7 @@ describe('getRegionalGuidanceRejectionReason', () => {describe('getRegionalGuidanceRejectionReason — layout bases', () => {const params = {+ cfgScale: 7,hasContent: true,layerName: 'Sign',mainBase: 'moss-image',diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.tsindex c1419b5832..19f303ea00 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/addRegionalGuidance.ts@@ -2,7 +2,10 @@ import type { BackendGraphContract, BackendInvocationContract } from '@features/import type { FamilyConditioning } from '@features/generation/core/familyGraph';import type { PromptTemplateSnapshot } from '@features/generation/core/promptTemplates';-import { getArchitectureFeatures } from '@features/generation/core/architectureCapabilities';+import {+ getArchitectureFeatures,+ getArchitectureGenerationConfig,+} from '@features/generation/core/architectureCapabilities';import { addEdge, addNode } from '@features/generation/core/graphBuilder';import { COMPEL_PROMPT_NODE_TYPES } from '@features/generation/core/prompt/compel';import { getEffectivePositivePrompt, unwrapPromptFence } from '@features/generation/core/promptTemplates';@@ -30,6 +33,11 @@ export interface RegionalGuidanceSupport {negativePrompt: boolean;/** The positive prompt can be re-encoded over the inverted mask as a negative. */autoNegative: boolean;+ /**+ * The base reads negatives only while CFG Scale is above 1 (backend `negative_prompt.usage` is `cfg-gated`), so+ * regional negatives and auto-negatives apply only then. See {@link areRegionalNegativesActive}.+ */+ negativesNeedCfg: boolean;/** Mask-scoped reference images, or `null` when the denoiser has no regional image path. */referenceImages: RegionalReferenceImageKind | null;/** The roles a layout prompt distinguishes; empty for mask bases. */@@ -42,7 +50,10 @@ type LayoutSupportRow = Pick<RegionalGuidanceSupport, 'label' | 'layoutKinds'> &referenceImages: null;};-/** Graph code owns node mapping and each base's mode; the backend owns regional-negative support. */+/**+ * Graph code owns node mapping and each base's mode; the backend owns regional-negative support and whether negatives+ * need CFG above 1.+ */const REGIONAL_GUIDANCE_SUPPORT: Record<MaskRegionalGuidanceBase, MaskSupportRow> &Record<LayoutRegionalGuidanceBase, LayoutSupportRow> = {'sd-1': { label: 'SD 1.x', mode: 'masks', referenceImages: 'ip_adapter' },@@ -82,13 +93,21 @@ export const getRegionalGuidanceSupport = (base: string | null): RegionalGuidancconst row = REGIONAL_GUIDANCE_SUPPORT[base];if (row.mode === 'layout') {- return { ...row, autoNegative: false, negativePrompt: false };+ return { ...row, autoNegative: false, negativePrompt: false, negativesNeedCfg: false };}const negative = getArchitectureFeatures(base)?.regional_negative ?? false;- return { ...row, autoNegative: negative, layoutKinds: [], negativePrompt: negative };+ const negativesNeedCfg = getArchitectureGenerationConfig(base)?.negativePrompt.usage === 'cfg-gated';++ return { ...row, autoNegative: negative, layoutKinds: [], negativePrompt: negative, negativesNeedCfg };};+/** Whether regional negatives and auto-negatives reach the graph at this CFG Scale. */+export const areRegionalNegativesActive = (+ support: Pick<RegionalGuidanceSupport, 'negativePrompt' | 'negativesNeedCfg'>,+ cfgScale: number+): boolean => support.negativePrompt && (!support.negativesNeedCfg || cfgScale > 1);+/** A region's role in a layout prompt; the canvas persists a subset of these and Canvas checks it does. */export type RegionalLayoutKind = 'object' | 'character' | 'text';@@ -474,18 +493,20 @@ export const addRegionalGuidance = (graph: BackendGraphContract, options: AddReg/*** Omit unsupported content without erasing stored values. Count resolved references; auto-negative requires- * positive text. Layout bases need a caption, and a text region its visible text.+ * positive text, and negatives count only at a CFG Scale the base reads them at. Layout bases need a caption, and a+ * text region its visible text.*/export const getRegionalGuidanceRejectionReason = (params: {layerName: string;mainBase: string;+ cfgScale: number;hasContent: boolean;positivePrompt: string | null;negativePrompt: string | null;referenceImageCount: number;layout?: RegionalLayout;}): string | null => {- const { hasContent, layerName, mainBase, negativePrompt, positivePrompt, referenceImageCount } = params;+ const { cfgScale, hasContent, layerName, mainBase, negativePrompt, positivePrompt, referenceImageCount } = params;const support = getRegionalGuidanceSupport(mainBase);if (!support) {@@ -506,7 +527,7 @@ export const getRegionalGuidanceRejectionReason = (params: {}const contributes =Boolean(positivePrompt) ||- (Boolean(negativePrompt) && support.negativePrompt) ||+ (Boolean(negativePrompt) && areRegionalNegativesActive(support, cfgScale)) ||(referenceImageCount > 0 && support.referenceImages !== null);if (!contributes) {return `Regional guidance "${layerName}" has no prompt or reference image ${support.label} can use.`;diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.tsindex cb9158299c..e64871ba13 100644--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts@@ -7,7 +7,10 @@ import type {VaeModelConfig,} from '@features/generation/core/types';-import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';+import {+ architectureCapabilitiesFixture,+ seedArchitectureCapabilities,+} from '@features/generation/core/architectureCapabilities.testing';import { getDefaultGenerateSettings } from '@features/generation/core/baseGenerationPolicies';import { getPidDecoderBaseForMainBase } from '@features/generation/core/pid';import { isPidDecodeNodeType } from '@features/generation/core/pidGraph';@@ -17,6 +20,7 @@ import type { ControlLayerGraphInput } from './addControlLayers';import type { RegionalGuidanceInput } from './addRegionalGuidance';import type { CanvasCompileMode, CanvasCompositingSettings, CanvasScalingSettings, Rect } from './types';+import { areRegionalNegativesActive, getRegionalGuidanceSupport } from './addRegionalGuidance';import { compileCanvasGraph } from './compileCanvasGraph';const sd1Model: MainModelConfig = { base: 'sd-1', key: 'sd1-model', name: 'SD 1.5', type: 'main' };@@ -2193,6 +2197,113 @@ describe('compileCanvasGraph — regional guidance', () => {expect(getEdge(backendGraph, 'neg_cond_collect', 'item')?.source.node_id).toBe('neg_cond');});+ describe.each([+ ['Z-Image', zImageModel, 'z_image_text_encoder', 'qwen3_encoder'],+ ['Anima', animaModel, 'anima_text_encoder', 'qwen3_encoder'],+ ['Krea-2', krea2Model, 'krea2_text_encoder', 'qwen3_vl_encoder'],+ ] as const)('%s regional negatives', (_label, model, encoderType, encoderField) => {+ it('collects masked negatives and inverted positives alongside the global negative', () => {+ const { backendGraph: graph } = compile(model, 'txt2img', {+ regionalGuidance: [+ region('r1', { autoNegative: true, negativePrompt: 'blurry' }),+ region('r2', { negativePrompt: 'text', positivePrompt: null }),+ ],+ settings: { cfgScale: 4 },+ });++ expect(graph.nodes.rg_neg_cond_r1).toMatchObject({ prompt: 'blurry', type: encoderType });+ expect(graph.nodes.rg_neg_cond_r2).toMatchObject({ prompt: 'text', type: encoderType });+ expect(graph.nodes.rg_pos_cond_r2).toBeUndefined();+ expect(graph.nodes.rg_pos_cond_inverted_r1).toMatchObject({ prompt: 'a cat', type: encoderType });+ expect(getEdge(graph, 'rg_neg_cond_r1', 'mask')?.source.node_id).toBe('rg_mask_to_tensor_r1');+ expect(getEdge(graph, 'rg_neg_cond_r2', 'mask')?.source.node_id).toBe('rg_mask_to_tensor_r2');+ expect(getEdge(graph, 'rg_invert_mask_r1', 'mask')?.source.node_id).toBe('rg_mask_to_tensor_r1');+ expect(getEdge(graph, 'rg_pos_cond_inverted_r1', 'mask')?.source.node_id).toBe('rg_invert_mask_r1');+ for (const nodeId of ['rg_neg_cond_r1', 'rg_neg_cond_r2', 'rg_pos_cond_inverted_r1']) {+ expect(getEdge(graph, nodeId, encoderField)?.source.node_id).toBe('model_loader');+ }+ expect(+ graph.edges.filter((edge) => edge.destination.node_id === 'neg_cond_collect').map((edge) => edge.source.node_id)+ ).toEqual(['neg_cond', 'rg_neg_cond_r1', 'rg_pos_cond_inverted_r1', 'rg_neg_cond_r2']);+ expect(getEdge(graph, 'denoise_latents', 'negative_conditioning')?.source).toEqual({+ field: 'collection',+ node_id: 'neg_cond_collect',+ });+ });++ it('does not encode regional negatives or auto-negatives while CFG is off', () => {+ const { backendGraph: graph } = compile(model, 'txt2img', {+ regionalGuidance: [region('r1', { autoNegative: true, negativePrompt: 'blurry' })],+ settings: { cfgScale: 1 },+ });++ expect(graph.nodes.rg_pos_cond_r1).toMatchObject({ prompt: 'a cat', type: encoderType });+ expect(graph.nodes.rg_neg_cond_r1).toBeUndefined();+ expect(graph.nodes.rg_pos_cond_inverted_r1).toBeUndefined();+ expect(graph.nodes.rg_invert_mask_r1).toBeUndefined();+ expect(graph.nodes.neg_cond_collect).toBeUndefined();+ expect(getEdge(graph, 'denoise_latents', 'negative_conditioning')).toBeUndefined();+ });+ });++ // The canvas settings and the region collector decide from the support row which regional negatives a graph keeps,+ // so the row has to agree with where each base graph actually has a negative collector.+ const modelsByBase: Record<string, MainModelConfig> = Object.fromEntries(+ [sd1Model, sd2Model, sdxlModel, zImageModel, animaModel, krea2Model].map((model) => [model.base, model])+ );+ // Collected before capabilities are seeded, so straight from the fixture the tests run against.+ const negativeMaskBases = [+ ...new Set(+ architectureCapabilitiesFixture+ .filter((row) => row.features.supports_regional_guidance && row.features.regional_negative)+ .map((row) => row.base)+ ),+ ];++ it('covers every mask base that reads regional negatives', () => {+ expect(negativeMaskBases.length).toBeGreaterThan(0);+ for (const base of negativeMaskBases) {+ expect(modelsByBase[base], base).toBeDefined();+ }+ });++ it.each(negativeMaskBases)('reads regional negatives on %s exactly at the CFG Scales its support names', (base) => {+ const support = getRegionalGuidanceSupport(base);+ expect(support).toMatchObject({ mode: 'masks', negativePrompt: true });+ for (const cfgScale of [1, 1.5, 4]) {+ const { backendGraph: graph } = compile(modelsByBase[base]!, 'txt2img', {+ regionalGuidance: [region('r1', { negativePrompt: 'blurry' })],+ settings: { cfgScale },+ });++ expect(graph.nodes.rg_neg_cond_r1 !== undefined, `cfg ${cfgScale}`).toBe(+ areRegionalNegativesActive(support!, cfgScale)+ );+ }+ });++ it('copies both Anima-3.8B encoders to regional negatives and auto-negatives', () => {+ const { backendGraph: graph } = compile({ ...animaModel, variant: 'anima_qwen35' }, 'txt2img', {+ regionalGuidance: [region('r1', { autoNegative: true, negativePrompt: 'blurry' })],+ settings: {+ cfgScale: 4,+ qwen35EncoderModel: {+ base: 'any',+ key: 'qwen35',+ name: 'Qwen3.5 4B',+ type: 'qwen3_5_encoder',+ variant: 'qwen3_5_4b',+ },+ },+ });++ for (const nodeId of ['rg_pos_cond_r1', 'rg_neg_cond_r1', 'rg_pos_cond_inverted_r1']) {+ for (const field of ['qwen3_encoder', 'qwen3_5_encoder']) {+ expect(getEdge(graph, nodeId, field)?.source).toEqual({ field, node_id: 'model_loader' });+ }+ }+ });+it('coexists with control layers in one graph', () => {const control: ControlLayerGraphInput = {beginEndStepPct: [0, 0.75],diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.test.tsindex 7469e8d94c..a1b20ffb11 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts@@ -1480,14 +1480,26 @@ describe('Krea-2, Ideogram 4 and Wan graphs', () => {expect(graph.nodes.denoise_latents?.type).toBe('krea2_denoise');});- it('omits Krea-2 negative conditioning while CFG is disabled, and adds it when enabled', () => {+ it('omits Krea-2 negative conditioning while CFG is disabled, and collects it when enabled', () => {// Krea-2-Turbo runs at cfg_scale 1 by default, where the model takes no negative input.- expect(compile(krea2Diffusers, { cfgScale: 1 }).nodes.neg_cond).toBeUndefined();+ const withoutCfg = compile(krea2Diffusers, { cfgScale: 1 });+ expect(withoutCfg.nodes.neg_cond).toBeUndefined();+ expect(withoutCfg.nodes.neg_cond_collect).toBeUndefined();+ expect(getEdge(withoutCfg, 'denoise_latents', 'negative_conditioning')).toBeUndefined();const withCfg = compile(krea2Diffusers, { cfgScale: 4.5 });expect(withCfg.nodes.neg_cond?.type).toBe('krea2_text_encoder');- expect(getEdge(withCfg, 'denoise_latents', 'negative_conditioning')).toBeDefined();+ expect(withCfg.nodes.neg_cond_collect?.type).toBe('collect');+ // Regional negatives join the global one through the collector.+ expect(getEdge(withCfg, 'neg_cond_collect', 'item')?.source).toEqual({+ field: 'conditioning',+ node_id: 'neg_cond',+ });+ expect(getEdge(withCfg, 'denoise_latents', 'negative_conditioning')?.source).toEqual({+ field: 'collection',+ node_id: 'neg_cond_collect',+ });});it('passes standalone Krea-2 submodels to the loader for a non-diffusers transformer', () => {diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.tsindex cb57aefc27..02e306255d 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.ts@@ -1485,6 +1485,7 @@ const buildKrea2Graph = (const posCond = addNode(graph, { id: 'pos_cond', type: 'krea2_text_encoder' });const posCondCollect = addNode(graph, { id: 'pos_cond_collect', type: 'collect' });const negCond = useCfg ? addNode(graph, { id: 'neg_cond', type: 'krea2_text_encoder' }) : null;+ const negCondCollect = useCfg ? addNode(graph, { id: 'neg_cond_collect', type: 'collect' }) : null;const denoise = addNode(graph, {cfg_scale: settings.cfgScale,height: settings.height,@@ -1511,10 +1512,11 @@ const buildKrea2Graph = (addEdge(graph, positiveConditioningSource, 'conditioning', posCondCollect, 'item');addEdge(graph, posCondCollect, 'collection', denoise, 'positive_conditioning');- if (negCond) {+ if (negCond && negCondCollect) {addEdge(graph, loraSource, 'qwen3_vl_encoder', negCond, 'qwen3_vl_encoder');addEdge(graph, negativePrompt, 'value', negCond, 'prompt');- addEdge(graph, negCond, 'conditioning', denoise, 'negative_conditioning');+ addEdge(graph, negCond, 'conditioning', negCondCollect, 'item');+ addEdge(graph, negCondCollect, 'collection', denoise, 'negative_conditioning');}addEdge(graph, seed, 'value', denoise, 'seed');@@ -1577,8 +1579,7 @@ const buildKrea2Graph = (conditioning: {fluxReduxCollector: null,ipAdapterCollector: null,- // Krea-2's negative conditioning feeds the denoise directly, so regional negatives have nothing to join.- negative: null,+ negative: negCond && negCondCollect ? { collector: negCondCollect, node: negCond } : null,positive: posCond,positiveCollector: posCondCollect,},diff --git a/invokeai/frontend/webv2/src/features/generation/graph.ts b/invokeai/frontend/webv2/src/features/generation/graph.tsindex 5442756938..6011d8fc80 100644--- a/invokeai/frontend/webv2/src/features/generation/graph.ts+++ b/invokeai/frontend/webv2/src/features/generation/graph.ts@@ -30,6 +30,7 @@ export {isControlModelUsableForKind,} from './core/canvas/controlValidation';export {+ areRegionalNegativesActive,getEffectiveLayoutKind,getLayoutDraftRejectionReason,getLayoutPromptRejectionReason,diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.browser.test.tsxindex 406df63493..c9fa80520e 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeButton.browser.test.tsx@@ -615,13 +615,14 @@ describe('InvokeButton route card', () => {await act(() => userEvent.hover(button));await expect.element(destinationGroup()).toBeVisible();- expect(cardMode()).toBe('preview');+ const card = document.querySelector('[data-invoke-card-mode]')!;+ expect(card.getAttribute('data-invoke-card-mode')).toBe('preview');await act(() => userEvent.unhover(button));await act(() => userEvent.hover(document.body));await waitPastCloseDelay();- // Closed by now; the card leaves the page once its exit animation ends.- expect(cardMode()).toBe('closed');+ // Retain the element: its exit animation may already have removed it from the document.+ expect(card.getAttribute('data-invoke-card-mode')).toBe('closed');await expect.element(destinationGroup()).not.toBeInTheDocument();});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.tsindex 992fd22e81..61d6b5261a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.test.ts@@ -1731,17 +1731,48 @@ describe('runCanvasInvocation — regional guidance on a Qwen3 base', () => {});it.each([- ['a negative prompt', { negativePrompt: 'blurry' }],- ['auto-negative', { autoNegative: true }],- [- 'a complete IP-Adapter reference',- {+ ['a negative prompt', { negativePrompt: 'blurry' }, 'rg_neg_cond_rg', 'blurry', 'rg_mask_to_tensor_rg'],+ ['auto-negative', { autoNegative: true }, 'rg_pos_cond_inverted_rg', 'a red hat', 'rg_invert_mask_rg'],+ ] as const)(+ 'submits an Anima region with %s and its spatial mask',+ async (_label, overrides, nodeId, prompt, maskId) => {+ const harness = makeAnimaHarness(regionalLayer('rg', overrides));++ await runCanvasInvocation(harness.deps);++ expect(harness.notices()).toHaveLength(0);+ expect(harness.uploadImage).toHaveBeenCalledTimes(1);+ const graph = harness.submittedGraphs()[0]?.graph.backendGraph;+ expect(graph?.nodes.rg_pos_cond_rg).toMatchObject({ prompt: 'a red hat', type: 'anima_text_encoder' });+ expect(graph?.nodes[nodeId]).toMatchObject({ prompt, type: 'anima_text_encoder' });+ expect(+ graph?.edges.find((edge) => edge.destination.node_id === nodeId && edge.destination.field === 'mask')?.source+ ).toEqual({ field: 'mask', node_id: maskId });+ expect(+ graph?.edges+ .filter((edge) => edge.destination.node_id === 'neg_cond_collect')+ .map((edge) => edge.source.node_id)+ ).toEqual(['neg_cond', nodeId]);+ }+ );++ it('submits an Anima regional prompt while omitting its unsupported regional IP-Adapter', async () => {+ const harness = makeAnimaHarness(+ regionalLayer('rg', {referenceImages: [{config: {beginEndStepPct: [0, 1],clipVisionModel: 'ViT-H',- image: { imageName: 'ref.png' },+ image: {+ height: 64,+ imageName: 'ref.png',+ imageUrl: '/images/ref.png',+ queuedAt: '2026-01-01T00:00:00.000Z',+ sourceQueueItemId: 'reference-queue-item',+ thumbnailUrl: '/thumbnails/ref.png',+ width: 64,+ },method: 'full',model: { base: 'anima', key: 'ipa', name: 'IP Adapter', type: 'ip_adapter' },type: 'ip_adapter',@@ -1751,30 +1782,36 @@ describe('runCanvasInvocation — regional guidance on a Qwen3 base', () => {isEnabled: true,},],- },- ],- ] as const)(- 'still submits the positive prompt of an Anima region carrying %s, without the extra',- async (_label, overrides) => {- const harness = makeAnimaHarness(regionalLayer('rg', overrides as Parameters<typeof regionalLayer>[1]));+ })+ );- await runCanvasInvocation(harness.deps);+ await runCanvasInvocation(harness.deps);- expect(harness.notices()).toHaveLength(0);- const graph = harness.submittedGraphs()[0]?.graph.backendGraph;- expect(graph?.nodes.rg_pos_cond_rg).toMatchObject({ prompt: 'a red hat', type: 'anima_text_encoder' });- expect(graph?.nodes.rg_neg_cond_rg).toBeUndefined();- expect(graph?.nodes.rg_pos_cond_inverted_rg).toBeUndefined();- expect(graph?.nodes.ip_adapter_ref).toBeUndefined();- const negativeSources = graph?.edges- .filter((edge) => edge.destination.node_id === 'neg_cond_collect')- .map((edge) => edge.source.node_id);- expect(negativeSources).toEqual(['neg_cond']);- }- );+ expect(harness.notices()).toHaveLength(0);+ const graph = harness.submittedGraphs()[0]?.graph.backendGraph;+ expect(graph?.nodes.rg_pos_cond_rg).toMatchObject({ prompt: 'a red hat', type: 'anima_text_encoder' });+ expect(graph?.nodes.ip_adapter_ref).toBeUndefined();+ });++ it('composites and submits an Anima region that carries only a negative prompt', async () => {+ const harness = makeAnimaHarness(regionalLayer('rg', { negativePrompt: 'blurry', positivePrompt: null }));++ await runCanvasInvocation(harness.deps);++ expect(harness.notices()).toHaveLength(0);+ expect(harness.uploadImage).toHaveBeenCalledTimes(1);+ const graph = harness.submittedGraphs()[0]?.graph.backendGraph;+ expect(graph?.nodes.rg_mask_to_tensor_rg).toMatchObject({ image: { image_name: 'composite-1.png' } });+ expect(graph?.nodes.rg_pos_cond_rg).toBeUndefined();+ expect(graph?.nodes.rg_neg_cond_rg).toMatchObject({ prompt: 'blurry', type: 'anima_text_encoder' });+ expect(+ graph?.edges.filter((edge) => edge.destination.node_id === 'neg_cond_collect').map((edge) => edge.source.node_id)+ ).toEqual(['neg_cond', 'rg_neg_cond_rg']);+ });- it('skips an Anima region that carries only a negative prompt', async () => {+ it('neither composites nor grafts an Anima region with only a negative prompt while CFG Scale is 1', async () => {const harness = makeAnimaHarness(regionalLayer('rg', { negativePrompt: 'blurry', positivePrompt: null }));+ harness.deps.generateValues = { ...animaGenerateValues(), cfgScale: 1 };await runCanvasInvocation(harness.deps);@@ -1783,6 +1820,7 @@ describe('runCanvasInvocation — regional guidance on a Qwen3 base', () => {const graph = harness.submittedGraphs()[0]?.graph.backendGraph;expect(graph?.nodes.denoise_latents?.type).toBe('anima_denoise');expect(graph?.nodes.rg_mask_to_tensor_rg).toBeUndefined();+ expect(graph?.nodes.rg_neg_cond_rg).toBeUndefined();});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.tsindex c923bc0f2a..6c08bddde9 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/invoke/prepareCanvasInvocation.ts@@ -259,7 +259,8 @@ export const resolveRegionalReferenceImages = (* prompt/reference/layout metadata for graph inputs.*/const createRegionalGuidanceCollector = (- model: GenerateModelConfig+ model: GenerateModelConfig,+ cfgScale: number): {shouldComposite(layer: CanvasRegionalGuidanceLayerContract): boolean;toGraphInputs(@@ -275,6 +276,7 @@ const createRegionalGuidanceCollector = (}const referenceImages = resolveRegionalReferenceImages(layer, model.base);const rejection = getRegionalGuidanceRejectionReason({+ cfgScale,hasContent: true,layerName: layer.name,layout: layer.layout,@@ -346,7 +348,7 @@ export const runCanvasInvocation = async (deps: RunCanvasInvocationDeps): Promisawait deps.flushPendingUploads();const controls = createControlLayerCollector(model, deps.models, deps.controlModelMemory);- const regions = createRegionalGuidanceCollector(model);+ const regions = createRegionalGuidanceCollector(model, settings.cfgScale);const composed = await deps.composeForGeneration({// Mode-union drift guard: `detectCanvasMode`'s facts/mode types must stay// structurally identical to canvas-operations' `GenerationModeFacts` /diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.browser.test.tsxindex ae7b5a7c0a..7f6c8d2879 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.browser.test.tsx@@ -24,7 +24,11 @@ import { page, userEvent } from 'vitest/browser';import { RegionalGuidanceSettings } from './RegionalGuidanceSettings';let selectedBase: string | null = null;-vi.mock('./useSelectedModelBase', () => ({ useSelectedModelBase: () => selectedBase }));+let selectedCfgScale: number | null = 7;+vi.mock('./useSelectedModelBase', () => ({+ useSelectedCfgScale: () => selectedCfgScale,+ useSelectedModelBase: () => selectedBase,+}));type Layer = ComponentProps<typeof RegionalGuidanceSettings>['layer'];@@ -63,10 +67,12 @@ const createLayer = (overrides: Partial<CanvasRegionalGuidanceLayerContract> = {const render = async (base: string | null, layer: Layer, translations = i18n) => {selectedBase = base;applyThemeToRoot('classic');- host = document.createElement('div');- host.style.width = '260px';- document.body.append(host);- root = createRoot(host);+ if (!host) {+ host = document.createElement('div');+ host.style.width = '260px';+ document.body.append(host);+ root = createRoot(host);+ }await act(() => {root?.render(<I18nextProvider i18n={translations}>@@ -83,6 +89,7 @@ afterEach(async () => {host?.remove();host = null;root = null;+ selectedCfgScale = 7;resetArchitectureCapabilities();});@@ -115,8 +122,63 @@ describe('RegionalGuidanceSettings per model base', () => {expect(hasAutoNegativeSwitch()).toBe(true);});+ it.each(['krea-2', 'z-image', 'anima'])(+ 'offers %s regional negatives and retains them across model switches',+ async (base) => {+ const layer = createLayer({ autoNegative: true, negativePrompt: 'blurry' });+ await render(base, layer);+ const negativeInput = () => page.getByRole('textbox', { name: 'widgets.layers.regionalGuidance.negativePrompt' });+ const autoNegative = () => page.getByRole('checkbox', { name: 'widgets.layers.regionalGuidance.autoNegative' });++ expect(alerts()).toEqual([]);+ await expect.element(negativeInput()).toHaveValue('blurry');+ await expect.element(autoNegative()).toBeChecked();++ await render('flux2', layer);+ expect(hasNegativeField()).toBe(false);+ expect(hasAutoNegativeSwitch()).toBe(false);++ await render(base, layer);+ await expect.element(negativeInput()).toHaveValue('blurry');+ await expect.element(autoNegative()).toBeChecked();+ }+ );++ it.each(['krea-2', 'z-image', 'anima'])(+ 'tells why %s regional negatives do nothing at CFG Scale 1, keeping them editable',+ async (base) => {+ const hint = 'Negative prompts and Auto-Negative take effect only when CFG Scale is above 1.';+ const negativeInput = () => page.getByRole('textbox', { name: 'Negative prompt' });+ const autoNegative = () => page.getByRole('checkbox', { name: 'Auto-Negative' });+ const layer = createLayer({ autoNegative: true, negativePrompt: 'blurry' });++ selectedCfgScale = 1;+ await render(base, layer, english);++ await expect.element(negativeInput()).toHaveAccessibleDescription(hint);+ await expect.element(autoNegative()).toHaveAccessibleDescription(hint);+ await expect.element(negativeInput()).toBeEnabled();+ await expect.element(negativeInput()).toHaveValue('blurry');+ await expect.element(autoNegative()).toBeChecked();++ selectedCfgScale = 1.5;+ await render(base, layer, english);++ expect(host!.textContent).not.toContain(hint);+ await expect.element(negativeInput()).not.toHaveAccessibleDescription();+ await expect.element(autoNegative()).not.toHaveAccessibleDescription();+ }+ );++ it('gives no CFG hint on an SD base, whose graph reads regional negatives at any CFG Scale', async () => {+ selectedCfgScale = 1;+ await render('sd-1', createLayer({ negativePrompt: 'blurry' }), english);++ expect(host!.textContent).not.toContain('CFG Scale');+ });+it('hides the negative controls on a positive-only base even when the layer still holds a negative', async () => {- await render('anima', createLayer({ autoNegative: true, negativePrompt: 'blurry' }));+ await render('flux2', createLayer({ autoNegative: true, negativePrompt: 'blurry' }));expect(alerts()).toEqual([]);expect(hasNegativeField()).toBe(false);expect(hasAutoNegativeSwitch()).toBe(false);@@ -158,7 +220,7 @@ describe('RegionalGuidanceSettings before the capability table arrives', () => {});it('hides the negative controls once the table says the base ignores them', async () => {- await render('anima', createLayer({ autoNegative: true, negativePrompt: 'blurry' }));+ await render('flux2', createLayer({ autoNegative: true, negativePrompt: 'blurry' }));expect(hasNegativeField()).toBe(true);await act(() => {@@ -225,9 +287,6 @@ describe('RegionalGuidanceSettings on a layout base', () => {expect(hasNegativeField()).toBe(false);expect(hasAutoNegativeSwitch()).toBe(false);expect(alerts()).toEqual([]);- await act(() => root?.unmount());- host?.remove();-await render('sd-1', createLayer());expect(kindGroup().query()).toBeNull();expect(host!.querySelector('[role="status"]')).toBeNull();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsxindex b9803e6d54..fb959c3082 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx@@ -21,6 +21,7 @@ import {} from '@chakra-ui/react';import { PromptTextarea } from '@features/generation/components';import {+ areRegionalNegativesActive,getEffectiveLayoutKind,getLayoutRegionIssue,getRegionalGuidanceSupport,@@ -47,7 +48,7 @@ import { PaletteIcon } from 'lucide-react';import { useCallback, useId, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-import { useSelectedModelBase } from './useSelectedModelBase';+import { useSelectedCfgScale, useSelectedModelBase } from './useSelectedModelBase';/** The regional-guidance fields patchable via `updateCanvasLayerConfig`. */interface RegionalConfigPatch {@@ -86,6 +87,7 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettconst { commit: commitPrepared, preview: previewStructural } = useStructuralPreview(engine);const sampleColor = useColorSampler(engine);const base = useSelectedModelBase();+ const cfgScale = useSelectedCfgScale();const showSyntaxHighlighting = useWorkbenchPreferenceSelector((preferences) => preferences.showPromptSyntaxHighlighting);@@ -114,6 +116,11 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSett// no model/policy is known.const showNegativeControls = !hasCapabilities || support?.negativePrompt !== false;const unsupportedModel = hasCapabilities && base !== null && support === null;+ // Controls stay editable so values carry over; the hint says why they do nothing at this CFG Scale.+ const negativesIgnoredAtCfg =+ support !== null && cfgScale !== null && support.negativePrompt && !areRegionalNegativesActive(support, cfgScale);+ const negativeFieldId = useId();+ const negativeHelpId = negativesIgnoredAtCfg ? `${negativeFieldId}-help` : undefined;// A previewed fill records from where its preview started; any other change from the live layer.const commitConfig = useCallback(@@ -374,8 +381,13 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSett) : null}{isLayout ? <VisuallyHidden role="status">{layoutIssueMessage}</VisuallyHidden> : null}{showNegativeControls && (- <Field label={t('widgets.layers.regionalGuidance.negativePrompt')}>+ <Field+ helpText={negativesIgnoredAtCfg ? t('widgets.layers.regionalGuidance.negativesNeedCfg') : undefined}+ id={negativeFieldId}+ label={t('widgets.layers.regionalGuidance.negativePrompt')}+ ><PromptTextarea+ aria-describedby={negativeHelpId}aria-label={t('widgets.layers.regionalGuidance.negativePrompt')}attentionSyntax={attentionSyntax}defaultHeightPx={REGIONAL_PROMPT_HEIGHT_PX}@@ -392,7 +404,7 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSett)}{showNegativeControls && (<Switch.Root checked={layer.autoNegative} onCheckedChange={handleAutoNegative}>- <Switch.HiddenInput />+ <Switch.HiddenInput aria-describedby={negativeHelpId} /><Switch.Control><Switch.Thumb /></Switch.Control>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectedModel.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectedModel.test.tsnew file mode 100644index 0000000000..fff4bf2ca4--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectedModel.test.ts@@ -0,0 +1,29 @@+import type { WidgetInstanceContract } from '@workbench/widgetContracts';++import { describe, expect, it } from 'vitest';++import { getSelectedCfgScale } from './selectedModel';++const generate = (values: Record<string, unknown>): WidgetInstanceContract => ({+ createdAt: '2026-11-03T00:00:00.000Z',+ id: 'generate',+ state: { id: 'generate', label: 'Generate', values, version: 1 },+ typeId: 'generate',+});++const project = (values: Record<string, unknown>) => ({ widgetInstances: { generate: generate(values) } });++describe('getSelectedCfgScale', () => {+ it('reads a stored finite CFG Scale', () => {+ expect(getSelectedCfgScale(project({ cfgScale: 1 }))).toBe(1);+ expect(getSelectedCfgScale(project({ cfgScale: 4.5 }))).toBe(4.5);+ });++ it('reads no CFG Scale when it is absent or not a finite number', () => {+ expect(getSelectedCfgScale(project({}))).toBeNull();+ expect(getSelectedCfgScale({ widgetInstances: {} })).toBeNull();+ for (const cfgScale of ['4', null, Number.NaN, Number.POSITIVE_INFINITY]) {+ expect(getSelectedCfgScale(project({ cfgScale })), String(cfgScale)).toBeNull();+ }+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectedModel.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectedModel.tsindex 9b4ca55332..9817dcd0d5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/selectedModel.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/selectedModel.ts@@ -6,3 +6,8 @@ export const getSelectedModelBase = (project: Project): string | null => {const model = getProjectWidgetValues(project, 'generate').model;return model && typeof model === 'object' && 'base' in model && typeof model.base === 'string' ? model.base : null;};++export const getSelectedCfgScale = (project: Pick<Project, 'widgetInstances'>): number | null => {+ const cfgScale = getProjectWidgetValues(project, 'generate').cfgScale;+ return typeof cfgScale === 'number' && Number.isFinite(cfgScale) ? cfgScale : null;+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useSelectedModelBase.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useSelectedModelBase.tsindex 566ef066e1..03d3d79bae 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useSelectedModelBase.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useSelectedModelBase.ts@@ -1,8 +1,13 @@import { useActiveProjectSelector } from '@workbench/WorkbenchContext';-import { getSelectedModelBase } from './selectedModel';+import { getSelectedCfgScale, getSelectedModelBase } from './selectedModel';/** Share the Generate model base across control/regional settings and layer creation so adapter kinds agree. */export const useSelectedModelBase = (): string | null => {return useActiveProjectSelector(getSelectedModelBase);};++/** The Generate CFG Scale, which decides whether some bases read regional negatives; null while unset. */+export const useSelectedCfgScale = (): number | null => {+ return useActiveProjectSelector(getSelectedCfgScale);+};diff --git a/tests/app/invocations/test_anima_regional_prompting.py b/tests/app/invocations/test_anima_regional_prompting.pynew file mode 100644index 0000000000..2696978d86--- /dev/null+++ b/tests/app/invocations/test_anima_regional_prompting.py@@ -0,0 +1,174 @@+"""Run the denoiser with lightweight real attention to check regional CFG routing."""++from contextlib import contextmanager, nullcontext+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest+import torch++from invokeai.app.invocations.anima.anima_denoise import AnimaDenoiseInvocation+from invokeai.app.invocations.fields import AnimaConditioningField, TensorField+from invokeai.backend.anima.anima_transformer import CosmosAttention+from invokeai.backend.model_manager.taxonomy import ModelFormat+from invokeai.backend.stable_diffusion.diffusion.conditioning_data import AnimaConditioningInfo, ConditioningFieldData+++class _Transformer(torch.nn.Module):+ def __init__(self, connector: bool = False, fail: bool = False):+ super().__init__()+ self.has_semantic_connector = connector+ self.fail = fail+ self.patch_spatial = 2+ self.blocks = torch.nn.ModuleList([torch.nn.Module()])+ attention = CosmosAttention(query_dim=2, context_dim=2, n_heads=1, head_dim=2)+ with torch.no_grad():+ attention.q_proj.weight.zero_()+ attention.k_proj.weight.zero_()+ attention.v_proj.weight.copy_(torch.eye(2))+ attention.output_proj.weight.copy_(torch.eye(2))+ self.blocks[0].cross_attn = attention+ self.original_forward = attention.forward+ self.outputs: list[torch.Tensor] = []+ self.patched: list[bool] = []+ self.adapter_timesteps: list[torch.Tensor | None] = []++ def preprocess_text_embeds(self, text_embeds, text_ids, **kwargs):+ self.adapter_timesteps.append(kwargs["timesteps"])+ return text_embeds++ def forward(self, x, context, **kwargs):+ self.patched.append(self.blocks[0].cross_attn.forward != self.original_forward)+ output = self.blocks[0].cross_attn(torch.zeros(1, 2, 2), context)+ self.outputs.append(output.detach())+ if self.fail:+ raise RuntimeError("transformer failed")+ return torch.zeros_like(x)+++class _Loaded:+ def __init__(self, model):+ self.model = model+ self.config = SimpleNamespace(format=ModelFormat.Checkpoint)++ @contextmanager+ def model_on_device(self, **kwargs):+ yield None, self.model+++def _run(+ monkeypatch,+ *,+ positive_region: bool = True,+ negative_region: bool = True,+ negative_tokens: int = 1,+ cfg: float = 2.0,+ scheduler: str = "euler",+ transformer: _Transformer | None = None,+):+ module = "invokeai.app.invocations.anima.anima_denoise"+ monkeypatch.setattr(f"{module}.TorchDevice.choose_torch_device", lambda: torch.device("cpu"))+ monkeypatch.setattr(f"{module}.TorchDevice.choose_anima_inference_dtype", lambda _d: torch.float32)+ monkeypatch.setattr(f"{module}.LayerPatcher.apply_smart_model_patches", lambda **_kw: nullcontext())+ if transformer is None:+ transformer = _Transformer()+ context = MagicMock()+ context.models.load.return_value = _Loaded(transformer)+ values = {"pos": [1.0, 0.0], "pos-region": [0.0, 2.0], "neg": [-1.0, 0.0], "neg-region": [0.0, -2.0]}++ def load_conditioning(name):+ if cfg == 1.0:+ assert not name.startswith("neg"), "CFG-off must not load negative conditioning"+ tokens = negative_tokens if name == "neg-region" else 1+ return ConditioningFieldData(+ conditionings=[+ AnimaConditioningInfo(+ qwen3_embeds=torch.tensor([values[name]] * tokens),+ t5xxl_ids=torch.zeros(tokens, dtype=torch.long),+ qwen35_states=torch.zeros(4, 1, 2) if transformer.has_semantic_connector else None,+ qwen35_mask=torch.ones(1, dtype=torch.bool) if transformer.has_semantic_connector else None,+ )+ ]+ )++ context.conditioning.load.side_effect = load_conditioning+ context.tensors.load.side_effect = lambda name: {+ "pos-mask": torch.tensor([[1.0, 0.0]]),+ "neg-mask": torch.tensor([[0.0, 1.0]]),+ }[name]+ positive = [AnimaConditioningField(conditioning_name="pos")]+ negative = [AnimaConditioningField(conditioning_name="neg")]+ if positive_region:+ positive.append(+ AnimaConditioningField(conditioning_name="pos-region", mask=TensorField(tensor_name="pos-mask"))+ )+ if negative_region:+ negative.append(+ AnimaConditioningField(conditioning_name="neg-region", mask=TensorField(tensor_name="neg-mask"))+ )+ invocation = AnimaDenoiseInvocation.model_construct(+ transformer=SimpleNamespace(transformer=object(), loras=[]),+ positive_conditioning=positive, negative_conditioning=negative, guidance_scale=cfg,+ width=32, height=16, steps=2, seed=0, scheduler=scheduler,+ ) # fmt: skip+ invocation._run_diffusion(context)+ assert transformer.blocks[0].cross_attn.forward == transformer.original_forward+ return transformer+++def _expected_negative(negative_tokens: int = 1) -> torch.Tensor:+ """The global negative stays image-wide: the region token averages it with its `negative_tokens` copies."""+ region_token = [-1.0 / (1 + negative_tokens), -2.0 * negative_tokens / (1 + negative_tokens)]+ return torch.tensor([[[-1.0, 0.0], region_token]])++[email protected]("scheduler", ["euler", "heun"])[email protected]("negative_tokens", [1, 3], ids=["equal-context-length", "different-context-length"])+def test_each_cfg_pass_uses_its_own_regions(monkeypatch, scheduler, negative_tokens) -> None:+ transformer = _run(monkeypatch, scheduler=scheduler, negative_tokens=negative_tokens)+ # The positive pass's global prompt yields the region to the regional prompt.+ expected_pos = torch.tensor([[[0.0, 2.0], [1.0, 0.0]]])+ expected_neg = _expected_negative(negative_tokens)+ for positive, negative in zip(transformer.outputs[::2], transformer.outputs[1::2], strict=True):+ torch.testing.assert_close(positive, expected_pos)+ torch.testing.assert_close(negative, expected_neg)++[email protected]("positive_region,negative_region", [(False, True), (True, False), (False, False)])+def test_a_global_branch_is_unmasked_even_when_the_other_branch_has_regions(+ monkeypatch, positive_region, negative_region+) -> None:+ transformer = _run(monkeypatch, positive_region=positive_region, negative_region=negative_region)+ expected_pos = [[[0.0, 2.0], [1.0, 0.0]]] if positive_region else [[[1.0, 0.0], [1.0, 0.0]]]+ expected_neg = _expected_negative() if negative_region else torch.tensor([[[-1.0, 0.0], [-1.0, 0.0]]])+ for positive, negative in zip(transformer.outputs[::2], transformer.outputs[1::2], strict=True):+ torch.testing.assert_close(positive, torch.tensor(expected_pos))+ torch.testing.assert_close(negative, expected_neg)+ # Without any regional mask the cross-attention stays the original, unpatched forward.+ assert set(transformer.patched) == {positive_region or negative_region}+++def test_cfg_off_ignores_negative_regions(monkeypatch) -> None:+ transformer = _run(monkeypatch, cfg=1.0)+ assert len(transformer.outputs) == 2+ for output in transformer.outputs:+ torch.testing.assert_close(output, torch.tensor([[[0.0, 2.0], [1.0, 0.0]]]))+++def test_connector_rebuilds_every_region_on_both_sides_at_each_sigma(monkeypatch) -> None:+ transformer = _run(monkeypatch, transformer=_Transformer(connector=True))+ sigmas = AnimaDenoiseInvocation.model_construct()._get_sigmas(2)+ assert len(transformer.adapter_timesteps) == 8+ for step in range(2):+ for timestep in transformer.adapter_timesteps[step * 4 : (step + 1) * 4]:+ assert timestep is not None and timestep.dtype == torch.float32+ assert timestep.item() == pytest.approx(sigmas[step])+ for output in transformer.outputs[1::2]:+ torch.testing.assert_close(output, _expected_negative())+++def test_transformer_failure_restores_regional_patches(monkeypatch) -> None:+ transformer = _Transformer(fail=True)+ with pytest.raises(RuntimeError, match="transformer failed"):+ _run(monkeypatch, transformer=transformer)+ assert transformer.blocks[0].cross_attn.forward == transformer.original_forwarddiff --git a/tests/app/invocations/test_krea2_denoise.py b/tests/app/invocations/test_krea2_denoise.pyindex 82124911c7..a5cfad48f8 100644--- a/tests/app/invocations/test_krea2_denoise.py+++ b/tests/app/invocations/test_krea2_denoise.py@@ -742,6 +742,39 @@ def test_run_diffusion_sizes_regional_masks_per_pass_when_cfg_lengths_differ(monassert mask.shape == (sequence_length, sequence_length)+def test_run_diffusion_keeps_the_global_negative_image_wide_beside_negative_regions(monkeypatch, tmp_path) -> None:+ _patch_runtime(monkeypatch)+ transformer = _Transformer()++ def with_left_half(name: str) -> list[Krea2ConditioningField]:+ return [+ Krea2ConditioningField(conditioning_name=name),+ Krea2ConditioningField(conditioning_name=name, mask=TensorField(tensor_name="left-half")),+ ]++ invocation = _runtime_invocation(cfg_scale=2.0, negative_conditioning=with_left_half("negative"))+ invocation.positive_conditioning = with_left_half("positive")+ # A 2x2 token grid, so the left-half region leaves a background beside it.+ invocation.width = invocation.height = 32+ context = _runtime_context(tmp_path, transformer)+ left_half = torch.zeros(1, 32, 32)+ left_half[..., :16] = 1+ load_tensor = context.tensors.load+ context.tensors = SimpleNamespace(load=lambda name: left_half if name == "left-half" else load_tensor(name))++ invocation._run_diffusion(context)++ positive_mask, negative_mask = transformer.regional_attention_masks[:2]+ # Sequence: [global text (2), regional text (2), image tokens (4)].+ global_text, image = slice(0, 2), slice(4, 8)+ background = torch.tensor([False, True, False, True])+ assert torch.equal(positive_mask[global_text, image], background.expand(2, 4))+ assert torch.equal(positive_mask[image, global_text], background[:, None].expand(4, 2))+ assert negative_mask[global_text, image].all() and negative_mask[image, global_text].all()+ for mask in (positive_mask, negative_mask):+ assert torch.equal(mask[2:4, image], (~background).expand(2, 4))++def test_run_diffusion_releases_regional_mask_when_transformer_raises(monkeypatch, tmp_path) -> None:_patch_runtime(monkeypatch)diff --git a/tests/app/invocations/test_z_image_denoise_working_memory.py b/tests/app/invocations/test_z_image_denoise_working_memory.pyindex ec3601e86f..a86fcd59b4 100644--- a/tests/app/invocations/test_z_image_denoise_working_memory.py+++ b/tests/app/invocations/test_z_image_denoise_working_memory.py@@ -472,6 +472,7 @@ class TestNodeReservation:negative_tokens=None,loras=0,regional_mask=None,+ negative_regional_mask=None,):from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (ConditioningFieldData,@@ -565,15 +566,19 @@ class TestNodeReservation:control_encode = stack.enter_context(patch.object(ZImageImageToLatentsInvocation, "vae_encode", side_effect=encode))- 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,- )+ if regional_mask is not None or negative_regional_mask is not None:+ regions = [+ ZImageRegionalPromptingExtension(+ regional_text_conditioning=ZImageRegionalTextConditioning(+ prompt_embeds=torch.zeros(tokens, 2560), image_masks=[None], embedding_ranges=[]+ ),+ regional_attn_mask=mask,+ )+ for tokens, mask in ((POSITIVE_TOKENS, regional_mask), (negative_tokens, negative_regional_mask))+ if tokens is not None+ ]stack.enter_context(- patch.object(ZImageRegionalPromptingExtension, "from_text_conditionings", return_value=regional)+ patch.object(ZImageRegionalPromptingExtension, "from_text_conditionings", side_effect=regions))with pytest.raises(_StopBeforeLoad):invocation._run_diffusion(context)@@ -617,6 +622,17 @@ class TestNodeReservation:assert run.estimate["regional_attn_mask"] is maskassert run.estimate["has_attention_mask"] is True+ @pytest.mark.parametrize("positive_regions", [False, True])+ def test_negative_regions_reserve_the_larger_per_pass_bias(self, positive_regions):+ positive_mask = torch.zeros((264, 264), dtype=torch.bool) if positive_regions else None+ negative_mask = torch.zeros((296, 296), dtype=torch.bool)++ run = self._run(negative_tokens=40, regional_mask=positive_mask, negative_regional_mask=negative_mask)++ assert run.estimate["regional_attn_mask"] is negative_mask+ assert run.estimate["has_attention_mask"] is True+ assert run.estimate["text_seq_len"] == 40+def test_a_control_reaches_the_estimate_and_keeps_the_reservation(self):"""The control's block count sizes the hints; its blocks take the base blocks' arguments, so it adds noattention mask. It is locked after the transformer, which can then no longer be offloaded -- so it must ask fordiff --git a/tests/backend/anima/test_anima_regional_attention.py b/tests/backend/anima/test_anima_regional_attention.pynew file mode 100644index 0000000000..8a71a9abb5--- /dev/null+++ b/tests/backend/anima/test_anima_regional_attention.py@@ -0,0 +1,143 @@+"""Regional masks select a CFG branch explicitly, never by its context length."""++from types import SimpleNamespace++import pytest+import torch++from invokeai.backend.anima.anima_transformer import CosmosAttention+from invokeai.backend.anima.anima_transformer_patch import (+ AnimaRegionalPromptingState,+ patch_anima_for_regional_prompting,+)+from invokeai.backend.anima.conditioning_data import AnimaRegionalTextConditioning+from invokeai.backend.anima.regional_prompting import AnimaRegionalPromptingExtension+from invokeai.backend.stable_diffusion.diffusion.conditioning_data import Range+++def _attention() -> CosmosAttention:+ attention = CosmosAttention(query_dim=2, context_dim=2, n_heads=1, head_dim=2)+ with torch.no_grad():+ attention.q_proj.weight.zero_()+ attention.k_proj.weight.zero_()+ attention.v_proj.weight.copy_(torch.eye(2))+ attention.output_proj.weight.copy_(torch.eye(2))+ return attention++[email protected]("fail", [False, True])+def test_switches_equal_length_masks_without_affecting_unmasked_passes_and_restores(fail: bool) -> None:+ transformer = SimpleNamespace(blocks=[SimpleNamespace(cross_attn=_attention()) for _ in range(2)])+ original_forwards = [block.cross_attn.forward for block in transformer.blocks]+ state = AnimaRegionalPromptingState()+ query = torch.zeros(1, 2, 2)+ context = torch.tensor([[[2.0, 0.0], [0.0, 4.0]]])++ class Stop(Exception):+ pass++ try:+ with patch_anima_for_regional_prompting(transformer, state):+ state.cross_attn_mask = torch.eye(2, dtype=torch.bool)+ torch.testing.assert_close(transformer.blocks[0].cross_attn(query, context), context)+ # Odd blocks retain unrestricted attention to keep global coherence.+ torch.testing.assert_close(+ transformer.blocks[1].cross_attn(query, context), torch.tensor([[[1.0, 2.0], [1.0, 2.0]]])+ )+ state.cross_attn_mask = ~state.cross_attn_mask+ torch.testing.assert_close(transformer.blocks[0].cross_attn(query, context), context.flip(1))+ state.cross_attn_mask = None+ torch.testing.assert_close(+ transformer.blocks[0].cross_attn(query, context), torch.tensor([[[1.0, 2.0], [1.0, 2.0]]])+ )+ if fail:+ state.cross_attn_mask = torch.eye(2, dtype=torch.bool)+ raise Stop+ except Stop:+ pass+ assert state.cross_attn_mask is None+ assert [block.cross_attn.forward for block in transformer.blocks] == original_forwards+++def test_restores_already_patched_blocks_when_installation_fails() -> None:+ attention = _attention()+ transformer = SimpleNamespace(blocks=[SimpleNamespace(cross_attn=attention), None, SimpleNamespace()])+ original_forward = attention.forward+ state = AnimaRegionalPromptingState(torch.ones(2, 2, dtype=torch.bool))+ with pytest.raises(AttributeError):+ with patch_anima_for_regional_prompting(transformer, state):+ pytest.fail("The invalid block should fail patch installation")+ assert attention.forward == original_forward+ assert state.cross_attn_mask is None+++def _masks_on_cpu(monkeypatch) -> None:+ monkeypatch.setattr(+ "invokeai.backend.anima.regional_prompting.TorchDevice.choose_torch_device", lambda: torch.device("cpu")+ )++[email protected]("_masks_on_cpu")+def test_unmasked_conditioning_covers_the_whole_image_only_in_negative_mode() -> None:+ # Context: [global token, region token]; image: [region token, background token].+ conditioning = AnimaRegionalTextConditioning(+ context_embeds=torch.zeros(2, 2),+ image_masks=[None, torch.tensor([[[1.0, 0.0]]])],+ context_ranges=[Range(start=0, end=1), Range(start=1, end=2)],+ )+ positive = AnimaRegionalPromptingExtension.from_regional_conditioning(conditioning, img_seq_len=2)+ negative = AnimaRegionalPromptingExtension.from_regional_conditioning(+ conditioning, img_seq_len=2, unmasked_covers_whole_image=True+ )+ assert torch.equal(positive.cross_attn_mask, torch.tensor([[False, True], [True, False]]))+ assert torch.equal(negative.cross_attn_mask, torch.tensor([[True, True], [True, False]]))++ global_only = AnimaRegionalTextConditioning(+ context_embeds=torch.zeros(1, 2), image_masks=[None], context_ranges=[Range(start=0, end=1)]+ )+ unrestricted = AnimaRegionalPromptingExtension.from_regional_conditioning(+ global_only, img_seq_len=2, unmasked_covers_whole_image=True+ )+ assert unrestricted.cross_attn_mask is None++[email protected]("_masks_on_cpu")+def test_image_tokens_outside_every_region_of_a_masked_only_list_attend_all_context() -> None:+ conditioning = AnimaRegionalTextConditioning(+ context_embeds=torch.tensor([[2.0, 0.0], [0.0, 4.0]]),+ image_masks=[torch.tensor([[[1.0, 0.0, 0.0]]]), torch.tensor([[[0.0, 1.0, 0.0]]])],+ context_ranges=[Range(start=0, end=1), Range(start=1, end=2)],+ )+ extension = AnimaRegionalPromptingExtension.from_regional_conditioning(conditioning, img_seq_len=3)+ assert torch.equal(extension.cross_attn_mask, torch.tensor([[True, False], [False, True], [True, True]]))++ state = AnimaRegionalPromptingState(extension.cross_attn_mask)+ attention = _attention()+ with patch_anima_for_regional_prompting(SimpleNamespace(blocks=[SimpleNamespace(cross_attn=attention)]), state):+ output = attention(torch.zeros(1, 3, 2), conditioning.context_embeds.unsqueeze(0))+ assert not output.isnan().any()+ torch.testing.assert_close(output, torch.tensor([[[2.0, 0.0], [0.0, 4.0], [1.0, 2.0]]]))+++def test_boolean_mask_matches_additive_bias_attention(monkeypatch) -> None:+ """Keep the previous masked attention's numerics while avoiding a Python-side bias per block."""+ import torch.nn.functional as functional++ generator = torch.Generator().manual_seed(47)+ transformer = SimpleNamespace(blocks=[SimpleNamespace(cross_attn=CosmosAttention(8, 8, n_heads=2, head_dim=4))])+ query = torch.randn(1, 3, 8, generator=generator)+ context = torch.randn(1, 4, 8, generator=generator)+ mask = torch.tensor([[True, False, True, True], [False, True, False, False], [False, False, False, False]])+ state = AnimaRegionalPromptingState(mask)+ original_sdpa = functional.scaled_dot_product_attention++ def additive_sdpa(q, k, v, *, attn_mask):+ bias = torch.zeros_like(attn_mask, dtype=q.dtype).masked_fill_(~attn_mask, -torch.inf)+ return original_sdpa(q, k, v, attn_mask=bias)++ with patch_anima_for_regional_prompting(transformer, state):+ boolean_output = transformer.blocks[0].cross_attn(query, context)+ monkeypatch.setattr(functional, "scaled_dot_product_attention", additive_sdpa)+ additive_output = transformer.blocks[0].cross_attn(query, context)+ torch.testing.assert_close(boolean_output, additive_output)diff --git a/tests/backend/architectures/test_features.py b/tests/backend/architectures/test_features.pyindex 3cebc5b5a8..2496cca4d0 100644--- a/tests/backend/architectures/test_features.py+++ b/tests/backend/architectures/test_features.py@@ -118,10 +118,8 @@ def test_regional_guidance_and_its_negative_subset() -> None:decides whether a region reaches the graph at all, `regional_negative` whether its negativeprompt and auto-negative do. A wrong declaration here is a region silently applied globally.- Regional negative prompts are a strict subset: only the SD family's `compel` /- `sdxl_compel_prompt` path masks both prompt polarities. The FLUX / FLUX.2 / Krea-2 / Z-Image /- Anima denoisers mask positive conditioning only -- Z-Image and Anima accept a negative list but- discard its masks, so a "regional" negative there would act globally and webv2 rejects it.+ Regional negative prompts are a strict subset: SD, Krea-2, Z-Image and Anima mask both+ prompt polarities. FLUX / FLUX.2 mask positive conditioning only.MOSS-Image, Ideogram 4 and FLUX.3 mask nothing: their regions become boxes in a JSON layoutprompt, structured caption or box table, which has no negative counterpart."""@@ -142,7 +140,7 @@ def test_regional_guidance_and_its_negative_subset() -> None:"ideogram-4","flux3",}- assert negative == {"sd-1", "sd-2", "sdxl"}+ assert negative == {"sd-1", "sd-2", "sdxl", "krea-2", "z-image", "anima"}assert negative < regional, "a regional negative prompt without regional guidance is meaningless"diff --git a/tests/backend/krea2/test_regional_prompting.py b/tests/backend/krea2/test_regional_prompting.pyindex 7fd8152006..c63ed55680 100644--- a/tests/backend/krea2/test_regional_prompting.py+++ b/tests/backend/krea2/test_regional_prompting.py@@ -69,6 +69,25 @@ def test_restricted_attention_mask_matches_flux_style_region_semantics() -> Noneassert bool(mask.any(dim=1).all())+def test_unmasked_conditioning_covers_the_whole_image_only_in_negative_mode() -> None:+ # Sequence: [global text, regional text, region image token, background image token].+ conditionings = [_conditioning(1, 1.0), _conditioning(1, 2.0, torch.tensor([[[1.0, 0.0]]]))]+ positive = Krea2RegionalPromptingExtension.from_text_conditionings(conditionings, image_seq_len=2)+ negative = Krea2RegionalPromptingExtension.from_text_conditionings(+ conditionings, image_seq_len=2, unmasked_covers_whole_image=True+ )+ positive_mask = positive.get_attention_mask()+ negative_mask = negative.get_attention_mask()+ assert positive_mask is not None and negative_mask is not None++ assert positive_mask[0, 2:].tolist() == [False, True]+ assert positive_mask[2:, 0].tolist() == [False, True]+ assert negative_mask[0, 2:].tolist() == [True, True]+ assert negative_mask[2:, 0].tolist() == [True, True]+ # Regional text and image/image isolation are the same in both modes.+ assert torch.equal(positive_mask[1:, 1:], negative_mask[1:, 1:])++def test_fully_covered_disjoint_regions_cannot_attend_across_regions() -> None:left_mask = torch.tensor([[[1.0, 0.0]]])right_mask = torch.tensor([[[0.0, 1.0]]])diff --git a/tests/backend/z_image/test_z_image_transformer_patch.py b/tests/backend/z_image/test_z_image_transformer_patch.pyindex 53cd1baa22..d3b056019b 100644--- a/tests/backend/z_image/test_z_image_transformer_patch.py+++ b/tests/backend/z_image/test_z_image_transformer_patch.py@@ -5,8 +5,19 @@ the case at batch size 1, which is how the denoise node calls the transformer --`None.bool()` for every regional generation."""+from contextlib import nullcontext+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytestimport torch+from invokeai.app.invocations.fields import TensorField, ZImageConditioningField+from invokeai.app.invocations.z_image.z_image_denoise import ZImageDenoiseInvocation+from invokeai.backend.model_manager.taxonomy import ModelFormat+from invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData, ZImageConditioningInfo+from invokeai.backend.z_image.extensions.regional_prompting_extension import ZImageRegionalPromptingExtension+from invokeai.backend.z_image.text_conditioning import ZImageTextConditioningfrom invokeai.backend.z_image.z_image_transformer_patch import patch_transformer_for_regional_promptingLATENT_SIDE = 16 # 8x8 = 64 image tokens after the 2x2 patch, already a multiple of 32@@ -58,3 +69,177 @@ def test_a_restricting_mask_applies_to_the_positive_pass_only(tiny_z_image_transassert torch.isfinite(regional).all()assert not torch.allclose(regional, plain, atol=1e-3)torch.testing.assert_close(negative, plain_negative, rtol=1e-4, atol=1e-5)++[email protected]_grad()[email protected]("negative_tokens", [20, 41])+def test_cfg_passes_use_independent_regional_masks(tiny_z_image_transformer, negative_tokens: int) -> None:+ model = tiny_z_image_transformer+ x, t, positive = _inputs(model, caption_tokens=20)+ negative = torch.randn(negative_tokens, model.config.cap_feat_dim)+ positive_mask = torch.ones(IMAGE_TOKENS + 20, IMAGE_TOKENS + 20, dtype=torch.bool)+ positive_mask[: IMAGE_TOKENS // 2, IMAGE_TOKENS:] = False+ negative_mask = torch.ones(IMAGE_TOKENS + negative_tokens, IMAGE_TOKENS + negative_tokens, dtype=torch.bool)+ negative_mask[IMAGE_TOKENS // 2 : IMAGE_TOKENS, IMAGE_TOKENS:] = False++ # Each prompt's isolated forward is the reference for the shared CFG patch.+ with patch_transformer_for_regional_prompting(model, positive_mask, IMAGE_TOKENS, positive):+ expected_positive = _forward(model, x, t, positive)+ with patch_transformer_for_regional_prompting(model, negative_mask, IMAGE_TOKENS, negative):+ expected_negative = _forward(model, x, t, negative)+ with patch_transformer_for_regional_prompting(+ model, positive_mask, IMAGE_TOKENS, positive, negative_mask, negative+ ):+ for _ in range(2):+ torch.testing.assert_close(_forward(model, x, t, positive), expected_positive)+ torch.testing.assert_close(_forward(model, x, t, negative), expected_negative)++[email protected]_grad()+def test_negative_only_regions_leave_positive_unmasked_and_restore_on_failure(tiny_z_image_transformer) -> None:+ model = tiny_z_image_transformer+ x, t, positive = _inputs(model, caption_tokens=20)+ negative = torch.randn_like(positive)+ plain_positive = _forward(model, x, t, positive)+ plain_negative = _forward(model, x, t, negative)+ negative_mask = torch.ones(IMAGE_TOKENS + 20, IMAGE_TOKENS + 20, dtype=torch.bool)+ negative_mask[:IMAGE_TOKENS, IMAGE_TOKENS:] = False+ original_forward = model.forward++ with pytest.raises(RuntimeError, match="cancelled"):+ with patch_transformer_for_regional_prompting(model, None, IMAGE_TOKENS, positive, negative_mask, negative):+ torch.testing.assert_close(_forward(model, x, t, positive), plain_positive)+ restricted_negative = _forward(model, x, t, negative)+ assert torch.isfinite(restricted_negative).all()+ assert not torch.allclose(restricted_negative, plain_negative, atol=1e-3)+ raise RuntimeError("cancelled")++ assert model.forward == original_forward+ torch.testing.assert_close(_forward(model, x, t, negative), plain_negative)+++def test_unmasked_text_covers_the_whole_image_only_in_negative_mode(monkeypatch) -> None:+ monkeypatch.setattr("invokeai.backend.util.devices.TorchDevice.choose_torch_device", lambda: torch.device("cpu"))+ # Sequence: [region image token, background image token, global text, regional text].+ conditionings = [+ ZImageTextConditioning(prompt_embeds=torch.zeros(1, 4), mask=None),+ ZImageTextConditioning(prompt_embeds=torch.zeros(1, 4), mask=torch.tensor([[[1.0, 0.0]]])),+ ]+ positive = ZImageRegionalPromptingExtension.from_text_conditionings(conditionings, img_seq_len=2)+ negative = ZImageRegionalPromptingExtension.from_text_conditionings(+ conditionings, img_seq_len=2, unmasked_covers_whole_image=True+ )+ global_text, regional_text = 2, 3+ assert positive.regional_attn_mask is not None and negative.regional_attn_mask is not None+ assert positive.regional_attn_mask[:2, global_text].tolist() == [False, True]+ assert positive.regional_attn_mask[global_text, :2].tolist() == [False, True]+ assert negative.regional_attn_mask[:2, global_text].tolist() == [True, True]+ assert negative.regional_attn_mask[global_text, :2].tolist() == [True, True]+ # Regional text keeps its region in both modes.+ for extension in (positive, negative):+ assert extension.regional_attn_mask[:2, regional_text].tolist() == [True, False]+ assert extension.regional_attn_mask[regional_text, :2].tolist() == [True, False]+++def _regional_denoise(model, monkeypatch, *, guidance_scale: float, scheduler: str = "euler"):+ """A denoise node on the tiny transformer, whose "region" tensor masks the left half of the image."""+ transformer_info = MagicMock(model=model)+ transformer_info.model_on_device.side_effect = lambda **kwargs: nullcontext((None, model))+ context = MagicMock()+ context.models.load.return_value = transformer_info+ context.models.get_config.return_value = SimpleNamespace(format=ModelFormat.Diffusers)+ positive = torch.randn(20, model.config.cap_feat_dim)+ negative = torch.randn_like(positive)++ def load_conditioning(name):+ if name == "negative":+ assert guidance_scale > 1.0, "CFG-off must not load or allocate negative conditioning"+ return ConditioningFieldData(+ conditionings=[ZImageConditioningInfo(prompt_embeds=positive if name == "positive" else negative)]+ )++ context.conditioning.load.side_effect = load_conditioning+ mask = torch.zeros(1, LATENT_SIDE, LATENT_SIDE)+ mask[:, :, : LATENT_SIDE // 2] = 1+ context.tensors.load.side_effect = lambda name: mask if name == "region" else None+ monkeypatch.setattr("invokeai.backend.util.devices.TorchDevice.choose_torch_device", lambda: torch.device("cpu"))+ monkeypatch.setattr(+ "invokeai.backend.util.devices.TorchDevice.choose_bfloat16_safe_dtype", lambda device: torch.float32+ )+ node = ZImageDenoiseInvocation.model_construct(+ id="regional",+ width=LATENT_SIDE * 8,+ height=LATENT_SIDE * 8,+ steps=2,+ guidance_scale=guidance_scale,+ positive_conditioning=ZImageConditioningField(conditioning_name="positive"),+ negative_conditioning=ZImageConditioningField(conditioning_name="negative"),+ transformer=MagicMock(transformer="transformer", loras=[]),+ seed=0,+ scheduler=scheduler,+ )+ return node, context+++def _global_and_left_half(name: str) -> list[ZImageConditioningField]:+ return [+ ZImageConditioningField(conditioning_name=name),+ ZImageConditioningField(conditioning_name=name, mask=TensorField(tensor_name="region")),+ ]+++def _record_patches(monkeypatch) -> list[dict]:+ patches: list[dict] = []++ def record_patch(**kwargs):+ patches.append(kwargs)+ return patch_transformer_for_regional_prompting(**kwargs)++ monkeypatch.setattr(+ "invokeai.app.invocations.z_image.z_image_denoise.patch_transformer_for_regional_prompting", record_patch+ )+ return patches++[email protected]_grad()[email protected]("scheduler", ["euler", "heun"])[email protected]("guidance_scale", [1.0, 2.0])+def test_denoise_consumes_negative_masks_only_with_cfg(+ tiny_z_image_transformer, monkeypatch, scheduler: str, guidance_scale: float+) -> None:+ """Run both solvers through loading, regional attention and CFG with a real tiny transformer."""+ model = tiny_z_image_transformer+ original_forward = model.forward+ node, context = _regional_denoise(model, monkeypatch, guidance_scale=guidance_scale, scheduler=scheduler)+ plain = node._run_diffusion(context)+ node.negative_conditioning = _global_and_left_half("negative")+ patches = _record_patches(monkeypatch)+ regional = node._run_diffusion(context)++ assert model.forward == original_forward+ assert torch.isfinite(regional).all()+ if guidance_scale == 1.0:+ torch.testing.assert_close(regional, plain, rtol=0, atol=0)+ context.tensors.load.assert_not_called()+ else:+ assert not torch.allclose(regional, plain, atol=1e-3)+ # The global negative stays image-wide while the regional negative keeps to its region.+ negative_mask = patches[0]["negative_regional_attn_mask"]+ global_text = slice(IMAGE_TOKENS, IMAGE_TOKENS + 20)+ assert negative_mask[:IMAGE_TOKENS, global_text].all() and negative_mask[global_text, :IMAGE_TOKENS].all()+ assert not negative_mask[:IMAGE_TOKENS, IMAGE_TOKENS + 20 :].all()++[email protected]_grad()+def test_denoise_keeps_the_global_positive_prompt_on_the_background(tiny_z_image_transformer, monkeypatch) -> None:+ node, context = _regional_denoise(tiny_z_image_transformer, monkeypatch, guidance_scale=1.0)+ node.positive_conditioning = _global_and_left_half("positive")+ patches = _record_patches(monkeypatch)+ node._run_diffusion(context)++ positive_mask = patches[0]["regional_attn_mask"]+ # 8x8 token grid, row-major: the region holds columns 0-3 of every row, the background columns 4-7.+ background = torch.tensor([False, False, False, False, True, True, True, True]).repeat(8)+ global_text = slice(IMAGE_TOKENS, IMAGE_TOKENS + 20)+ assert torch.equal(positive_mask[:IMAGE_TOKENS, global_text], background[:, None].expand(IMAGE_TOKENS, 20))+ assert torch.equal(positive_mask[global_text, :IMAGE_TOKENS], background[None, :].expand(20, IMAGE_TOKENS))