Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

Krea 2 regional prompting (#9407)

Jonathan93fd9ae16e60
diff --git a/docs/src/content/docs/features/krea-2.mdx b/docs/src/content/docs/features/krea-2.mdx
index 45e7ad5d63..4346c93514 100644
--- a/docs/src/content/docs/features/krea-2.mdx
+++ b/docs/src/content/docs/features/krea-2.mdx
@@ -64,12 +64,32 @@ transform the text conditioning and are especially useful for the distilled Turb
prompt adherence for variety.
Both are recorded in image metadata and can be recalled.
+When enabled on the canvas, the same enhancer chain is applied independently to the global prompt and
+each positive regional prompt before their conditionings are collected.
## Multiple conditionings
In the workflow editor, the **Denoise - Krea-2** node accepts one conditioning or a collection for both
its positive and negative conditioning inputs. Multiple independently encoded conditionings are concatenated
-after padding tokens are removed. They are global conditionings; spatial masks are not supported.
+after padding tokens are removed.
+
+The **Text Encoder - 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
+workflows, 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.
+
+:::caution[Regional prompting memory]
+Regional prompting builds a dense boolean attention mask whose memory grows quadratically with the combined
+text and image token count. Invoke reserves memory for retained masks, construction scratch space, and the
+dtype-sized additive attention bias created by SDPA. Fused memory-efficient attention support for dense masks
+still depends on the GPU, PyTorch build, dtype, and sequence shape. When no fused kernel is available, PyTorch
+falls back to math attention, which may use substantially more VRAM and can cause an out-of-memory error.
+Reducing image resolution or disabling regional prompting is the practical fallback. Automated CUDA coverage
+is skipped on unsupported hardware and cannot exercise every GPU/backend combination.
+:::
## LoRA
diff --git a/invokeai/app/invocations/fields.py b/invokeai/app/invocations/fields.py
index 572b5707f2..8c86618818 100644
--- a/invokeai/app/invocations/fields.py
+++ b/invokeai/app/invocations/fields.py
@@ -384,6 +384,11 @@ class Krea2ConditioningField(BaseModel):
"""A Krea-2 conditioning tensor primitive value"""
conditioning_name: str = Field(description="The name of conditioning tensor")
+ mask: Optional[TensorField] = Field(
+ default=None,
+ description="The mask associated with this conditioning tensor for regional prompting. "
+ "Excluded regions should be set to False, included regions should be set to True.",
+ )
class AnimaConditioningField(BaseModel):
diff --git a/invokeai/app/invocations/krea2_conditioning_rebalance.py b/invokeai/app/invocations/krea2_conditioning_rebalance.py
index ab52a5033a..bad7c6bce5 100644
--- a/invokeai/app/invocations/krea2_conditioning_rebalance.py
+++ b/invokeai/app/invocations/krea2_conditioning_rebalance.py
@@ -20,7 +20,7 @@ _NUM_TEXT_LAYERS = len(KREA2_SELECT_LAYERS) # 12
title="Conditioning Rebalance - Krea-2",
tags=["conditioning", "krea2", "krea-2"],
category="conditioning",
- version="1.0.0",
+ version="1.1.0",
classification=Classification.Prototype,
)
class Krea2ConditioningRebalanceInvocation(BaseInvocation):
@@ -76,4 +76,4 @@ class Krea2ConditioningRebalanceInvocation(BaseInvocation):
]
)
conditioning_name = context.conditioning.save(new_data)
- return Krea2ConditioningOutput.build(conditioning_name)
+ return Krea2ConditioningOutput.build(conditioning_name, mask=self.conditioning.mask)
diff --git a/invokeai/app/invocations/krea2_denoise.py b/invokeai/app/invocations/krea2_denoise.py
index 6e799ce231..466568d505 100644
--- a/invokeai/app/invocations/krea2_denoise.py
+++ b/invokeai/app/invocations/krea2_denoise.py
@@ -25,7 +25,11 @@ from invokeai.app.invocations.fields import (
from invokeai.app.invocations.model import TransformerField
from invokeai.app.invocations.primitives import LatentsOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
-from invokeai.backend.krea2.attention import Krea2MemoryEfficientAttnProcessor
+from invokeai.backend.krea2.attention import Krea2RegionalPromptingState, build_krea2_attention_processors
+from invokeai.backend.krea2.regional_prompting import (
+ Krea2RegionalPromptingExtension,
+ Krea2TextConditioning,
+)
from invokeai.backend.krea2.sampling_utils import (
KREA2_BASE_IMAGE_SEQ_LEN,
KREA2_BASE_SHIFT,
@@ -56,7 +60,7 @@ KREA2_LATENT_CHANNELS = 16
title="Denoise - Krea-2",
tags=["image", "krea2", "krea-2"],
category="image",
- version="1.1.0",
+ version="1.2.0",
classification=Classification.Prototype,
)
class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
@@ -135,16 +139,18 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
self,
context: InvocationContext,
conditioning_field: Krea2ConditioningField | list[Krea2ConditioningField],
+ grid_height: int,
+ grid_width: int,
dtype: torch.dtype,
device: torch.device,
- ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ ) -> Krea2RegionalPromptingExtension:
conditioning_fields = (
[conditioning_field] if isinstance(conditioning_field, Krea2ConditioningField) else conditioning_field
)
if not conditioning_fields:
raise ValueError("At least one Krea-2 conditioning is required.")
- prompt_embeds: list[torch.Tensor] = []
+ text_conditionings: list[Krea2TextConditioning] = []
for field in conditioning_fields:
cond_data = context.conditioning.load(field.conditioning_name)
assert len(cond_data.conditionings) == 1
@@ -165,11 +171,24 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
embeds = torch.stack(
[batch_embeds[batch_mask] for batch_embeds, batch_mask in zip(embeds, mask, strict=True)]
)
- prompt_embeds.append(embeds)
+ regional_mask = None
+ if field.mask is not None:
+ mask = context.tensors.load(field.mask.tensor_name)
+ regional_mask = Krea2RegionalPromptingExtension.preprocess_regional_prompt_mask(
+ mask=mask,
+ grid_height=grid_height,
+ grid_width=grid_width,
+ dtype=dtype,
+ device=device,
+ )
+ text_conditionings.append(Krea2TextConditioning(prompt_embeds=embeds, mask=regional_mask))
# Masked padding does not contribute to attention. Remove it before concatenation to avoid multiplying
# the text sequence length by the encoder's fixed 512-token allocation for every conditioning.
- return torch.cat(prompt_embeds, dim=1), None
+ return Krea2RegionalPromptingExtension.from_text_conditionings(
+ text_conditionings=text_conditionings,
+ image_seq_len=grid_height * grid_width,
+ )
def _get_noise(self, height: int, width: int, dtype: torch.dtype, device: torch.device, seed: int) -> torch.Tensor:
rand_device = "cpu"
@@ -249,15 +268,20 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
transformer_info = context.models.load(self.transformer.transformer)
- pos_prompt_embeds, pos_prompt_mask = self._load_text_conditioning(
- context, self.positive_conditioning, inference_dtype, device
- )
-
latent_height = self.height // LATENT_SCALE_FACTOR
latent_width = self.width // LATENT_SCALE_FACTOR
grid_height = latent_height // 2
grid_width = latent_width // 2
image_seq_len = grid_height * grid_width
+ pos_extension = self._load_text_conditioning(
+ context,
+ self.positive_conditioning,
+ grid_height,
+ grid_width,
+ inference_dtype,
+ device,
+ )
+ pos_prompt_embeds = pos_extension.regional_text_conditioning.prompt_embeds
# Scheduler: load from the model's scheduler/ dir if present, else construct with Krea-2 defaults.
model_path = context.models.get_absolute_path(context.models.get_config(self.transformer.transformer))
@@ -319,12 +343,18 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
# decided per step below so values at or below 1.0 use the conditional prediction directly.
has_negative_conditioning = bool(self.negative_conditioning)
do_cfg = has_negative_conditioning and any(value > 1.0 for value in cfg_scale)
+ neg_extension: Krea2RegionalPromptingExtension | None = None
neg_prompt_embeds = None
- neg_prompt_mask = None
if do_cfg and self.negative_conditioning is not None:
- neg_prompt_embeds, neg_prompt_mask = self._load_text_conditioning(
- context, self.negative_conditioning, inference_dtype, device
+ neg_extension = self._load_text_conditioning(
+ context,
+ self.negative_conditioning,
+ grid_height,
+ grid_width,
+ inference_dtype,
+ device,
)
+ neg_prompt_embeds = neg_extension.regional_text_conditioning.prompt_embeds
# Load initial latents (img2img).
init_latents = context.tensors.load(self.latents.latents_name) if self.latents else None
@@ -395,6 +425,9 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
negative_text_seq_len=neg_prompt_embeds.shape[1] if neg_prompt_embeds is not None else None,
do_cfg=do_cfg,
num_loras=len(self.transformer.loras),
+ regional_attention_mask_bytes=self._regional_attention_mask_bytes(
+ pos_extension, neg_extension, inference_dtype
+ ),
)
with ExitStack() as exit_stack:
@@ -406,7 +439,11 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
# SDPA for enable_gqa=True, which PyTorch only supports on the math backend — that materializes the
# full O(seq^2) score matrix (~5.7 GB per attention at 1280x720, ~40 GB at 2560x1440) and OOMs. Swap
# in a memory-efficient processor that expands the KV heads and uses the O(seq) SDPA kernel instead.
- transformer.set_attn_processor(Krea2MemoryEfficientAttnProcessor())
+ regional_prompting_state = Krea2RegionalPromptingState()
+ transformer.set_attn_processor(build_krea2_attention_processors(transformer, regional_prompting_state))
+ # The processors remain installed on the cached transformer after this invocation. Do not let them
+ # retain a potentially multi-GB regional mask between generations, including when denoising raises.
+ exit_stack.callback(regional_prompting_state.set_attention_mask, None)
exit_stack.enter_context(
LayerPatcher.apply_smart_model_patches(
@@ -419,14 +456,18 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
)
)
+ pos_regional_attention_mask = pos_extension.get_attention_mask()
+ neg_regional_attention_mask = neg_extension.get_attention_mask() if neg_extension is not None else None
+
for step_idx, t in enumerate(tqdm(timesteps_sched)):
# The pipeline passes timestep / num_train_timesteps to the transformer.
timestep = (t / num_train_timesteps).expand(latents.shape[0]).to(inference_dtype)
+ regional_prompting_state.set_attention_mask(pos_regional_attention_mask)
noise_pred_cond = transformer(
hidden_states=latents,
encoder_hidden_states=pos_prompt_embeds,
- encoder_attention_mask=pos_prompt_mask,
+ encoder_attention_mask=None,
timestep=timestep,
position_ids=position_ids,
return_dict=False,
@@ -435,10 +476,11 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
if self._should_apply_cfg_for_step(
cfg_scale[step_idx], has_negative_conditioning=neg_prompt_embeds is not None
):
+ regional_prompting_state.set_attention_mask(neg_regional_attention_mask)
noise_pred_uncond = transformer(
hidden_states=latents,
encoder_hidden_states=neg_prompt_embeds,
- encoder_attention_mask=neg_prompt_mask,
+ encoder_attention_mask=None,
timestep=timestep,
position_ids=neg_position_ids,
return_dict=False,
@@ -477,6 +519,21 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
latents = latents.unsqueeze(2)
return latents
+ @staticmethod
+ def _regional_attention_mask_bytes(
+ pos_extension: Krea2RegionalPromptingExtension,
+ neg_extension: Krea2RegionalPromptingExtension | None,
+ attention_dtype: torch.dtype,
+ ) -> int:
+ """Return final masks plus peak construction scratch and SDPA's transient additive bias."""
+ extensions = [pos_extension] if neg_extension is None else [pos_extension, neg_extension]
+ final_mask_bytes = sum(extension.attention_mask_numel for extension in extensions)
+ peak_build_scratch_bytes = max(extension.attention_mask_build_scratch_numel for extension in extensions)
+ attention_dtype_bytes = torch.empty((), dtype=attention_dtype).element_size()
+ peak_attention_bias_bytes = max(extension.attention_mask_numel for extension in extensions)
+ peak_attention_bias_bytes *= attention_dtype_bytes
+ return final_mask_bytes + peak_build_scratch_bytes + peak_attention_bias_bytes
+
def _estimate_working_memory(
self,
image_seq_len: int,
@@ -484,15 +541,17 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
negative_text_seq_len: int | None,
do_cfg: bool,
num_loras: int,
+ regional_attention_mask_bytes: int = 0,
) -> int:
"""Estimate peak transformer activation memory (bytes) so the model cache reserves enough headroom.
- Krea-2's attention runs through diffusers' ``dispatch_attention_fn`` (SDPA / flash), so attention
- scores are never materialized and the activation footprint scales ~linearly with the image token
- count with a *small* per-token constant. The previous ~2.6 MiB/token figure assumed materialized
- O(seq^2) scores and massively over-estimated: at 2560x1440 (14400 tokens) it demanded ~36 GB, which
- exceeds a 24 GB card, so the cache offloaded the *transformer itself* to RAM and the forward pass ran
- from system memory over PCIe — no OOM, but effectively hung (no step in minutes).
+ Without regional prompting, Krea-2's attention runs through SDPA / flash without materializing
+ attention scores, so the baseline activation footprint scales ~linearly with the image token count
+ with a *small* per-token constant. Regional bool masks and SDPA's dtype-sized additive bias are added
+ separately through ``regional_attention_mask_bytes``. The previous ~2.6 MiB/token baseline assumed
+ materialized O(seq^2) scores and massively over-estimated: at 2560x1440 (14400 tokens) it demanded
+ ~36 GB, which exceeds a 24 GB card, so the cache offloaded the *transformer itself* to RAM and the
+ forward pass ran from system memory over PCIe — no OOM, but effectively hung (no step in minutes).
The per-token constant below is a safe upper bound on the measured SDPA activation footprint of the
Krea-2-Turbo MMDiT in bf16 (residual stream + one block's attention/SwiGLU intermediates), leaving
@@ -511,6 +570,7 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
# Conditional/unconditional passes are sequential, but the larger combined sequence and extra
# transient buffers warrant a modest bump.
estimated = int(estimated * 1.1)
+ estimated += regional_attention_mask_bytes
if num_loras > 0:
estimated += int(0.5 * num_loras * GB)
return estimated
diff --git a/invokeai/app/invocations/krea2_seed_variance.py b/invokeai/app/invocations/krea2_seed_variance.py
index e72fc8b4f8..65a37f4040 100644
--- a/invokeai/app/invocations/krea2_seed_variance.py
+++ b/invokeai/app/invocations/krea2_seed_variance.py
@@ -15,7 +15,7 @@ from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (
title="Seed Variance - Krea-2",
tags=["conditioning", "krea2", "krea-2", "variance"],
category="conditioning",
- version="1.0.0",
+ version="1.1.0",
classification=Classification.Prototype,
)
class Krea2SeedVarianceInvocation(BaseInvocation):
@@ -60,7 +60,7 @@ class Krea2SeedVarianceInvocation(BaseInvocation):
# No-op when the effect is disabled, so the node can stay wired in the graph without altering output.
if self.strength == 0.0 or self.randomize_percent == 0.0:
- return Krea2ConditioningOutput.build(self.conditioning.conditioning_name)
+ return Krea2ConditioningOutput.build(self.conditioning.conditioning_name, mask=self.conditioning.mask)
# Auto-calibrate the noise magnitude to the embedding scale (same approach as the Z-Image enhancer).
# This keeps the perceptual effect of `strength` stable across prompts and, crucially, whether or not
@@ -83,4 +83,4 @@ class Krea2SeedVarianceInvocation(BaseInvocation):
]
)
conditioning_name = context.conditioning.save(new_data)
- return Krea2ConditioningOutput.build(conditioning_name)
+ return Krea2ConditioningOutput.build(conditioning_name, mask=self.conditioning.mask)
diff --git a/invokeai/app/invocations/krea2_text_encoder.py b/invokeai/app/invocations/krea2_text_encoder.py
index 673ed200be..4624edbeb9 100644
--- a/invokeai/app/invocations/krea2_text_encoder.py
+++ b/invokeai/app/invocations/krea2_text_encoder.py
@@ -8,6 +8,7 @@ from invokeai.app.invocations.fields import (
FieldDescriptions,
Input,
InputField,
+ TensorField,
UIComponent,
)
from invokeai.app.invocations.model import Qwen3VLEncoderField
@@ -44,7 +45,7 @@ _KREA2_SUFFIX = "<|im_end|>\n<|im_start|>assistant\n"
title="Prompt - Krea-2",
tags=["prompt", "conditioning", "krea2", "krea-2"],
category="conditioning",
- version="1.0.0",
+ version="1.1.0",
classification=Classification.Prototype,
)
class Krea2TextEncoderInvocation(BaseInvocation):
@@ -55,6 +56,11 @@ class Krea2TextEncoderInvocation(BaseInvocation):
"""
prompt: str = InputField(description="Text prompt describing the desired image.", ui_component=UIComponent.Textarea)
+ mask: TensorField | None = InputField(
+ default=None,
+ description="A mask defining the image region that this conditioning prompt applies to.",
+ input=Input.Connection,
+ )
qwen3_vl_encoder: Qwen3VLEncoderField = InputField(
title="Qwen3-VL Encoder",
description=FieldDescriptions.qwen3_vl_encoder,
@@ -71,7 +77,7 @@ class Krea2TextEncoderInvocation(BaseInvocation):
conditionings=[Krea2ConditioningInfo(prompt_embeds=prompt_embeds, prompt_embeds_mask=prompt_mask)]
)
conditioning_name = context.conditioning.save(conditioning_data)
- return Krea2ConditioningOutput.build(conditioning_name)
+ return Krea2ConditioningOutput.build(conditioning_name, mask=self.mask)
def _encode(self, context: InvocationContext) -> tuple[torch.Tensor, torch.Tensor | None]:
tokenizer_info = context.models.load(self.qwen3_vl_encoder.tokenizer)
diff --git a/invokeai/app/invocations/primitives.py b/invokeai/app/invocations/primitives.py
index 830d3ecf61..dfe44d0e6e 100644
--- a/invokeai/app/invocations/primitives.py
+++ b/invokeai/app/invocations/primitives.py
@@ -535,8 +535,8 @@ class Krea2ConditioningOutput(BaseInvocationOutput):
conditioning: Krea2ConditioningField = OutputField(description=FieldDescriptions.cond)
@classmethod
- def build(cls, conditioning_name: str) -> "Krea2ConditioningOutput":
- return cls(conditioning=Krea2ConditioningField(conditioning_name=conditioning_name))
+ def build(cls, conditioning_name: str, mask: TensorField | None = None) -> "Krea2ConditioningOutput":
+ return cls(conditioning=Krea2ConditioningField(conditioning_name=conditioning_name, mask=mask))
@invocation_output("anima_conditioning_output")
diff --git a/invokeai/backend/krea2/attention.py b/invokeai/backend/krea2/attention.py
index a35d1854b1..b7f96cd93f 100644
--- a/invokeai/backend/krea2/attention.py
+++ b/invokeai/backend/krea2/attention.py
@@ -13,6 +13,10 @@ is O(seq) in memory). Measured: the same 3600-token attention drops from ~5.7 GB
The math is otherwise identical to ``Krea2AttnProcessor`` (q/k RMSNorm, rotary embeddings, sigmoid output gate).
"""
+import re
+from dataclasses import dataclass
+from typing import Protocol
+
import torch
import torch.nn.functional as F
from diffusers.models.embeddings import apply_rotary_emb
@@ -22,9 +26,22 @@ from torch.nn.attention import SDPBackend, sdpa_kernel
_KREA2_SDPA_BACKENDS = [SDPBackend.EFFICIENT_ATTENTION, SDPBackend.FLASH_ATTENTION, SDPBackend.MATH]
+@dataclass
+class Krea2RegionalPromptingState:
+ """Mutable per-forward regional attention state shared by Krea-2 transformer-block processors."""
+
+ attention_mask: torch.Tensor | None = None
+
+ def set_attention_mask(self, attention_mask: torch.Tensor | None) -> None:
+ self.attention_mask = attention_mask
+
+
class Krea2MemoryEfficientAttnProcessor:
"""Drop-in replacement for ``Krea2AttnProcessor`` that avoids the ``enable_gqa`` math fallback."""
+ def __init__(self, regional_prompting_state: Krea2RegionalPromptingState | None = None) -> None:
+ self.regional_prompting_state = regional_prompting_state
+
def __call__(
self,
attn,
@@ -32,6 +49,17 @@ class Krea2MemoryEfficientAttnProcessor:
attention_mask: torch.Tensor | None = None,
image_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
) -> torch.Tensor:
+ if self.regional_prompting_state is not None and self.regional_prompting_state.attention_mask is not None:
+ regional_attention_mask = self.regional_prompting_state.attention_mask
+ if regional_attention_mask.shape != (hidden_states.shape[1], hidden_states.shape[1]):
+ raise ValueError(
+ f"Krea-2 regional attention mask shape {tuple(regional_attention_mask.shape)} does not match "
+ f"the transformer sequence length {hidden_states.shape[1]}."
+ )
+ attention_mask = (
+ regional_attention_mask if attention_mask is None else attention_mask & regional_attention_mask
+ )
+
query = attn.to_q(hidden_states).unflatten(-1, (attn.num_heads, attn.head_dim))
key = attn.to_k(hidden_states).unflatten(-1, (attn.num_kv_heads, attn.head_dim))
value = attn.to_v(hidden_states).unflatten(-1, (attn.num_kv_heads, attn.head_dim))
@@ -62,3 +90,23 @@ class Krea2MemoryEfficientAttnProcessor:
hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
hidden_states = hidden_states * torch.sigmoid(gate)
return attn.to_out[0](hidden_states)
+
+
+class _Krea2AttentionProcessorContainer(Protocol):
+ @property
+ def attn_processors(self) -> dict[str, object]: ...
+
+
+def build_krea2_attention_processors(
+ transformer: _Krea2AttentionProcessorContainer,
+ regional_prompting_state: Krea2RegionalPromptingState,
+) -> dict[str, Krea2MemoryEfficientAttnProcessor]:
+ """Build processors that apply regional masks to alternating main transformer blocks only."""
+
+ processors: dict[str, Krea2MemoryEfficientAttnProcessor] = {}
+ for name in transformer.attn_processors:
+ match = re.fullmatch(r"transformer_blocks\.(\d+)\.attn\.processor", name)
+ block_index = int(match.group(1)) if match is not None else None
+ state = regional_prompting_state if block_index is not None and block_index % 2 == 0 else None
+ processors[name] = Krea2MemoryEfficientAttnProcessor(regional_prompting_state=state)
+ return processors
diff --git a/invokeai/backend/krea2/regional_prompting.py b/invokeai/backend/krea2/regional_prompting.py
new file mode 100644
index 0000000000..44ea926f69
--- /dev/null
+++ b/invokeai/backend/krea2/regional_prompting.py
@@ -0,0 +1,132 @@
+from dataclasses import dataclass
+
+import torch
+import torchvision
+
+from invokeai.backend.stable_diffusion.diffusion.conditioning_data import Range
+from invokeai.backend.util.mask import to_standard_float_mask
+
+
+@dataclass
+class Krea2TextConditioning:
+ prompt_embeds: torch.Tensor
+ mask: torch.Tensor | None
+
+
+@dataclass
+class Krea2RegionalTextConditioning:
+ prompt_embeds: torch.Tensor
+ image_masks: list[torch.Tensor | None]
+ embedding_ranges: list[Range]
+
+
+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:
+ self.regional_text_conditioning = regional_text_conditioning
+ self.image_seq_len = image_seq_len
+ self._attention_mask: torch.Tensor | None = None
+
+ @property
+ def has_regional_masks(self) -> bool:
+ return any(mask is not None for mask in self.regional_text_conditioning.image_masks)
+
+ @property
+ def attention_mask_numel(self) -> int:
+ if not self.has_regional_masks:
+ return 0
+ total_seq_len = self.regional_text_conditioning.prompt_embeds.shape[1] + self.image_seq_len
+ return total_seq_len**2
+
+ @property
+ def attention_mask_build_scratch_numel(self) -> int:
+ """Peak boolean scratch allocation used while constructing the image-to-image attention block."""
+ if not self.has_regional_masks:
+ return 0
+ return self.image_seq_len**2
+
+ @classmethod
+ def from_text_conditionings(
+ cls, text_conditionings: list[Krea2TextConditioning], image_seq_len: int
+ ) -> "Krea2RegionalPromptingExtension":
+ if not text_conditionings:
+ raise ValueError("At least one Krea-2 text conditioning is required.")
+
+ prompt_embeds: list[torch.Tensor] = []
+ image_masks: list[torch.Tensor | None] = []
+ embedding_ranges: list[Range] = []
+ current_start = 0
+ for conditioning in text_conditionings:
+ sequence_length = conditioning.prompt_embeds.shape[1]
+ if conditioning.mask is not None and conditioning.mask.numel() != image_seq_len:
+ raise ValueError(
+ f"Krea-2 regional mask has {conditioning.mask.numel()} values, expected {image_seq_len}."
+ )
+ prompt_embeds.append(conditioning.prompt_embeds)
+ image_masks.append(conditioning.mask)
+ embedding_ranges.append(Range(start=current_start, end=current_start + sequence_length))
+ current_start += sequence_length
+
+ regional_text_conditioning = Krea2RegionalTextConditioning(
+ prompt_embeds=torch.cat(prompt_embeds, dim=1),
+ image_masks=image_masks,
+ embedding_ranges=embedding_ranges,
+ )
+ return cls(regional_text_conditioning=regional_text_conditioning, image_seq_len=image_seq_len)
+
+ def get_attention_mask(self) -> torch.Tensor | None:
+ if not self.has_regional_masks:
+ return None
+ if self._attention_mask is None:
+ self._attention_mask = self._build_attention_mask()
+ return self._attention_mask
+
+ def _build_attention_mask(self) -> torch.Tensor:
+ conditioning = self.regional_text_conditioning
+ text_seq_len = conditioning.prompt_embeds.shape[1]
+ total_seq_len = text_seq_len + self.image_seq_len
+ device = conditioning.prompt_embeds.device
+ attention_mask = torch.zeros((total_seq_len, total_seq_len), device=device, dtype=torch.bool)
+
+ background_mask = torch.ones(self.image_seq_len, device=device, dtype=torch.bool)
+ 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()
+
+ 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):
+ text_slice = slice(embedding_range.start, embedding_range.end)
+ attention_mask[text_slice, text_slice] = True
+
+ if image_mask is None:
+ attention_mask[text_slice, text_seq_len:] = unmasked_conditioning_mask
+ attention_mask[text_seq_len:, text_slice] = unmasked_conditioning_mask[:, None]
+ continue
+
+ region_mask = image_mask.reshape(-1) > 0.5
+ attention_mask[text_slice, text_seq_len:] = region_mask
+ attention_mask[text_seq_len:, text_slice] = region_mask[:, None]
+ image_attention_mask |= region_mask[:, None] & region_mask[None, :]
+
+ image_attention_mask |= background_mask[:, None] | background_mask[None, :]
+ return attention_mask
+
+ @staticmethod
+ def preprocess_regional_prompt_mask(
+ mask: torch.Tensor,
+ grid_height: int,
+ grid_width: int,
+ dtype: torch.dtype,
+ device: torch.device,
+ ) -> torch.Tensor:
+ mask = to_standard_float_mask(mask, out_dtype=dtype)
+ resize = torchvision.transforms.Resize(
+ (grid_height, grid_width), interpolation=torchvision.transforms.InterpolationMode.NEAREST
+ )
+ return resize(mask.unsqueeze(0)).flatten(start_dim=2).to(device=device)
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index d685000fd7..add72e7ac5 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -49630,6 +49630,18 @@
"description": "The name of conditioning tensor",
"title": "Conditioning Name",
"type": "string"
+ },
+ "mask": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/TensorField"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "The mask associated with this conditioning tensor for regional prompting. Excluded regions should be set to False, included regions should be set to True."
}
},
"required": ["conditioning_name"],
@@ -49737,7 +49749,7 @@
"tags": ["conditioning", "krea2", "krea-2"],
"title": "Conditioning Rebalance - Krea-2",
"type": "object",
- "version": "1.0.0",
+ "version": "1.1.0",
"output": {
"$ref": "#/components/schemas/Krea2ConditioningOutput"
}
@@ -50016,7 +50028,7 @@
"tags": ["image", "krea2", "krea-2"],
"title": "Denoise - Krea-2",
"type": "object",
- "version": "1.1.0",
+ "version": "1.2.0",
"output": {
"$ref": "#/components/schemas/LatentsOutput"
}
@@ -50507,7 +50519,7 @@
"tags": ["conditioning", "krea2", "krea-2", "variance"],
"title": "Seed Variance - Krea-2",
"type": "object",
- "version": "1.0.0",
+ "version": "1.1.0",
"output": {
"$ref": "#/components/schemas/Krea2ConditioningOutput"
}
@@ -50560,6 +50572,22 @@
"title": "Prompt",
"ui_component": "textarea"
},
+ "mask": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/TensorField"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "description": "A mask defining the image region that this conditioning prompt applies to.",
+ "field_kind": "input",
+ "input": "connection",
+ "orig_default": null,
+ "orig_required": false
+ },
"qwen3_vl_encoder": {
"anyOf": [
{
@@ -50588,7 +50616,7 @@
"tags": ["prompt", "conditioning", "krea2", "krea-2"],
"title": "Prompt - Krea-2",
"type": "object",
- "version": "1.0.0",
+ "version": "1.1.0",
"output": {
"$ref": "#/components/schemas/Krea2ConditioningOutput"
}
diff --git a/invokeai/frontend/web/src/features/controlLayers/store/validators.test.ts b/invokeai/frontend/web/src/features/controlLayers/store/validators.test.ts
new file mode 100644
index 0000000000..f0fe5ef42c
--- /dev/null
+++ b/invokeai/frontend/web/src/features/controlLayers/store/validators.test.ts
@@ -0,0 +1,41 @@
+import { getRegionalGuidanceState, initialRegionalGuidanceIPAdapter } from 'features/controlLayers/store/util';
+import { getRegionalGuidanceWarnings } from 'features/controlLayers/store/validators';
+import { describe, expect, it } from 'vitest';
+
+const krea2Model = { base: 'krea-2' } as never;
+
+describe('getRegionalGuidanceWarnings - Krea-2', () => {
+ it('allows positive regional prompts', () => {
+ const region = getRegionalGuidanceState('region', { positivePrompt: 'red fox' });
+
+ const warnings = getRegionalGuidanceWarnings(region, krea2Model);
+
+ expect(warnings).not.toContain('controlLayers.warnings.rgNegativePromptNotSupported');
+ expect(warnings).not.toContain('controlLayers.warnings.rgAutoNegativeNotSupported');
+ expect(warnings).not.toContain('controlLayers.warnings.rgReferenceImagesNotSupported');
+ });
+
+ it('warns for unsupported negative prompts and auto-negative', () => {
+ const region = getRegionalGuidanceState('region', {
+ positivePrompt: 'red fox',
+ negativePrompt: 'blue fox',
+ autoNegative: true,
+ });
+
+ const warnings = getRegionalGuidanceWarnings(region, krea2Model);
+
+ expect(warnings).toContain('controlLayers.warnings.rgNegativePromptNotSupported');
+ expect(warnings).toContain('controlLayers.warnings.rgAutoNegativeNotSupported');
+ });
+
+ it('warns for unsupported regional reference images', () => {
+ const region = getRegionalGuidanceState('region', {
+ positivePrompt: 'red fox',
+ referenceImages: [{ id: 'reference', config: initialRegionalGuidanceIPAdapter }],
+ });
+
+ const warnings = getRegionalGuidanceWarnings(region, krea2Model);
+
+ expect(warnings).toContain('controlLayers.warnings.rgReferenceImagesNotSupported');
+ });
+});
diff --git a/invokeai/frontend/web/src/features/controlLayers/store/validators.ts b/invokeai/frontend/web/src/features/controlLayers/store/validators.ts
index 6966967dd8..80da5a9cc5 100644
--- a/invokeai/frontend/web/src/features/controlLayers/store/validators.ts
+++ b/invokeai/frontend/web/src/features/controlLayers/store/validators.ts
@@ -101,6 +101,21 @@ export const getRegionalGuidanceWarnings = (
}
}
+ if (model.base === 'krea-2') {
+ // Krea-2's canvas graph currently exposes positive regional text only. The denoise node supports
+ // masked negative conditioning in workflows, but canvas auto-negative and regional reference images
+ // require graph integrations that Krea-2 does not provide.
+ if (entity.negativePrompt !== null) {
+ warnings.push(WARNINGS.RG_NEGATIVE_PROMPT_NOT_SUPPORTED);
+ }
+ if (entity.autoNegative) {
+ warnings.push(WARNINGS.RG_AUTO_NEGATIVE_NOT_SUPPORTED);
+ }
+ if (entity.referenceImages.length > 0) {
+ warnings.push(WARNINGS.RG_REFERENCE_IMAGES_NOT_SUPPORTED);
+ }
+ }
+
if (model.base === 'ideogram-4') {
// Ideogram 4 regions contribute only a positive prompt + bbox to the structured caption
// (see collectIdeogram4PromptInputs). Negative prompts, auto-negative and reference images are
diff --git a/invokeai/frontend/web/src/features/nodes/util/graph/generation/addRegions.test.ts b/invokeai/frontend/web/src/features/nodes/util/graph/generation/addRegions.test.ts
new file mode 100644
index 0000000000..4030564267
--- /dev/null
+++ b/invokeai/frontend/web/src/features/nodes/util/graph/generation/addRegions.test.ts
@@ -0,0 +1,158 @@
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('features/controlLayers/store/validators', () => ({
+ getRegionalGuidanceWarnings: vi.fn(() => []),
+}));
+
+import { getRegionalGuidanceState } from 'features/controlLayers/store/util';
+import { addRegions } from 'features/nodes/util/graph/generation/addRegions';
+import { Graph } from 'features/nodes/util/graph/generation/Graph';
+
+describe('addRegions - Krea-2', () => {
+ it('adds a masked Krea-2 encoder that shares the global encoder model', async () => {
+ const g = new Graph('graph');
+ const modelLoader = g.addNode({
+ type: 'krea2_model_loader',
+ id: 'model-loader',
+ model: {
+ key: 'krea',
+ hash: 'hash',
+ name: 'Krea-2',
+ base: 'krea-2',
+ type: 'main',
+ },
+ });
+ const posCond = g.addNode({ type: 'krea2_text_encoder', id: 'global-positive', prompt: 'global' });
+ const posCondCollect = g.addNode({ type: 'collect', id: 'positive-collector' });
+ const ipAdapterCollect = g.addNode({ type: 'collect', id: 'ip-adapter-collector' });
+ g.addEdge(modelLoader, 'qwen3_vl_encoder', posCond, 'qwen3_vl_encoder');
+ g.addEdge(posCond, 'conditioning', posCondCollect, 'item');
+
+ const manager = {
+ adapters: {
+ regionMasks: {
+ get: vi.fn(() => ({
+ renderer: {
+ rasterize: vi.fn(() => Promise.resolve({ image_name: 'region-mask.png' })),
+ },
+ })),
+ },
+ },
+ };
+
+ await addRegions({
+ manager: manager as never,
+ regions: [getRegionalGuidanceState('region', { positivePrompt: 'red fox' })],
+ g,
+ bbox: { x: 0, y: 0, width: 1024, height: 1024 },
+ model: { base: 'krea-2' } as never,
+ posCond,
+ negCond: null,
+ posCondCollect,
+ negCondCollect: null,
+ ipAdapterCollect,
+ fluxReduxCollect: null,
+ });
+
+ const graph = g.getGraph();
+ const regionalEncoder = Object.values(graph.nodes).find(
+ (node) => node.type === 'krea2_text_encoder' && node.id !== posCond.id
+ );
+ expect(regionalEncoder).toBeDefined();
+ expect(regionalEncoder).toMatchObject({ prompt: 'red fox' });
+ expect(graph.edges).toContainEqual(
+ expect.objectContaining({
+ source: { node_id: modelLoader.id, field: 'qwen3_vl_encoder' },
+ destination: { node_id: regionalEncoder!.id, field: 'qwen3_vl_encoder' },
+ })
+ );
+ expect(graph.edges).toContainEqual(
+ expect.objectContaining({
+ destination: { node_id: regionalEncoder!.id, field: 'mask' },
+ })
+ );
+ expect(graph.edges).toContainEqual(
+ expect.objectContaining({
+ source: { node_id: regionalEncoder!.id, field: 'conditioning' },
+ destination: { node_id: posCondCollect.id, field: 'item' },
+ })
+ );
+ });
+
+ it('collects the transformed regional conditioning when a transform is provided', async () => {
+ const g = new Graph('graph');
+ const modelLoader = g.addNode({
+ type: 'krea2_model_loader',
+ id: 'model-loader',
+ model: {
+ key: 'krea',
+ hash: 'hash',
+ name: 'Krea-2',
+ base: 'krea-2',
+ type: 'main',
+ },
+ });
+ const posCond = g.addNode({ type: 'krea2_text_encoder', id: 'global-positive', prompt: 'global' });
+ const posCondCollect = g.addNode({ type: 'collect', id: 'positive-collector' });
+ const ipAdapterCollect = g.addNode({ type: 'collect', id: 'ip-adapter-collector' });
+ g.addEdge(modelLoader, 'qwen3_vl_encoder', posCond, 'qwen3_vl_encoder');
+
+ const manager = {
+ adapters: {
+ regionMasks: {
+ get: vi.fn(() => ({
+ renderer: {
+ rasterize: vi.fn(() => Promise.resolve({ image_name: 'region-mask.png' })),
+ },
+ })),
+ },
+ },
+ };
+ const transformRegionalPositiveConditioning = vi.fn((regionalPosCond: { id: string; type: string }) => {
+ const seedVariance = g.addNode({
+ type: 'krea2_seed_variance',
+ id: 'regional-seed-variance',
+ strength: 0.5,
+ randomize_percent: 50,
+ });
+ g.addEdgeFromObj({
+ source: { node_id: regionalPosCond.id, field: 'conditioning' },
+ destination: { node_id: seedVariance.id, field: 'conditioning' },
+ });
+ return seedVariance;
+ });
+
+ await addRegions({
+ manager: manager as never,
+ regions: [getRegionalGuidanceState('region', { positivePrompt: 'red fox' })],
+ g,
+ bbox: { x: 0, y: 0, width: 1024, height: 1024 },
+ model: { base: 'krea-2' } as never,
+ posCond,
+ negCond: null,
+ posCondCollect,
+ negCondCollect: null,
+ ipAdapterCollect,
+ fluxReduxCollect: null,
+ transformRegionalPositiveConditioning,
+ });
+
+ const graph = g.getGraph();
+ const regionalEncoder = Object.values(graph.nodes).find(
+ (node) => node.type === 'krea2_text_encoder' && node.id !== posCond.id
+ );
+ expect(transformRegionalPositiveConditioning).toHaveBeenCalledWith(regionalEncoder);
+ expect(graph.edges).not.toContainEqual(
+ expect.objectContaining({
+ source: { node_id: regionalEncoder!.id, field: 'conditioning' },
+ destination: { node_id: posCondCollect.id, field: 'item' },
+ })
+ );
+ expect(graph.edges).toContainEqual(
+ expect.objectContaining({
+ source: { node_id: 'regional-seed-variance', field: 'conditioning' },
+ destination: { node_id: posCondCollect.id, field: 'item' },
+ })
+ );
+ });
+});
diff --git a/invokeai/frontend/web/src/features/nodes/util/graph/generation/addRegions.ts b/invokeai/frontend/web/src/features/nodes/util/graph/generation/addRegions.ts
index e4658cf1ef..0069952a60 100644
--- a/invokeai/frontend/web/src/features/nodes/util/graph/generation/addRegions.ts
+++ b/invokeai/frontend/web/src/features/nodes/util/graph/generation/addRegions.ts
@@ -26,20 +26,27 @@ type AddedRegionResult = {
addedFLUXReduxes: number;
};
+type RegionalPositiveConditioning = Invocation<
+ | 'compel'
+ | 'sdxl_compel_prompt'
+ | 'flux_text_encoder'
+ | 'flux2_klein_text_encoder'
+ | 'z_image_text_encoder'
+ | 'anima_text_encoder'
+ | 'krea2_text_encoder'
+>;
+
+type PositiveConditioningSource = Invocation<
+ RegionalPositiveConditioning['type'] | 'krea2_conditioning_rebalance' | 'krea2_seed_variance'
+>;
+
type AddRegionsArg = {
manager: CanvasManager;
regions: CanvasRegionalGuidanceState[];
g: Graph;
bbox: Rect;
model: MainModelConfig;
- posCond: Invocation<
- | 'compel'
- | 'sdxl_compel_prompt'
- | 'flux_text_encoder'
- | 'flux2_klein_text_encoder'
- | 'z_image_text_encoder'
- | 'anima_text_encoder'
- >;
+ posCond: RegionalPositiveConditioning;
negCond: Invocation<
| 'compel'
| 'sdxl_compel_prompt'
@@ -47,11 +54,13 @@ type AddRegionsArg = {
| 'flux2_klein_text_encoder'
| 'z_image_text_encoder'
| 'anima_text_encoder'
+ | 'krea2_text_encoder'
> | null;
posCondCollect: Invocation<'collect'>;
negCondCollect: Invocation<'collect'> | null;
ipAdapterCollect: Invocation<'collect'>;
fluxReduxCollect: Invocation<'collect'> | null;
+ transformRegionalPositiveConditioning?: (conditioning: RegionalPositiveConditioning) => PositiveConditioningSource;
};
/**
@@ -82,12 +91,14 @@ export const addRegions = async ({
negCondCollect,
ipAdapterCollect,
fluxReduxCollect,
+ transformRegionalPositiveConditioning,
}: AddRegionsArg): Promise<AddedRegionResult[]> => {
const isSDXL = model.base === 'sdxl';
const isFLUX = model.base === 'flux';
const isFlux2 = model.base === 'flux2';
const isZImage = model.base === 'z-image';
const isAnima = model.base === 'anima';
+ const isKrea2 = model.base === 'krea-2';
const validRegions = regions
.filter((entity) => entity.isEnabled)
@@ -128,14 +139,7 @@ export const addRegions = async ({
if (region.positivePrompt) {
// The main positive conditioning node
result.addedPositivePrompt = true;
- let regionalPosCond: Invocation<
- | 'compel'
- | 'sdxl_compel_prompt'
- | 'flux_text_encoder'
- | 'flux2_klein_text_encoder'
- | 'z_image_text_encoder'
- | 'anima_text_encoder'
- >;
+ let regionalPosCond: RegionalPositiveConditioning;
if (isSDXL) {
regionalPosCond = g.addNode({
type: 'sdxl_compel_prompt',
@@ -167,6 +171,12 @@ export const addRegions = async ({
id: getPrefixedId('prompt_region_positive_cond'),
prompt: region.positivePrompt,
});
+ } else if (isKrea2) {
+ regionalPosCond = g.addNode({
+ type: 'krea2_text_encoder',
+ id: getPrefixedId('prompt_region_positive_cond'),
+ prompt: region.positivePrompt,
+ });
} else {
regionalPosCond = g.addNode({
type: 'compel',
@@ -176,8 +186,6 @@ export const addRegions = async ({
}
// Connect the mask to the conditioning
g.addEdge(maskToTensor, 'mask', regionalPosCond, 'mask');
- // Connect the conditioning to the collector
- g.addEdge(regionalPosCond, 'conditioning', posCondCollect, 'item');
// Copy the connections to the "global" positive conditioning node to the regional cond
if (posCond.type === 'compel') {
for (const edge of g.getEdgesTo(posCond, ['clip', 'mask'])) {
@@ -215,15 +223,25 @@ export const addRegions = async ({
clone.destination.node_id = regionalPosCond.id;
g.addEdgeFromObj(clone);
}
+ } else if (posCond.type === 'krea2_text_encoder') {
+ for (const edge of g.getEdgesTo(posCond, ['qwen3_vl_encoder', 'mask'])) {
+ const clone = deepClone(edge);
+ clone.destination.node_id = regionalPosCond.id;
+ g.addEdgeFromObj(clone);
+ }
} else {
assert(false, 'Unsupported positive conditioning node type.');
}
+ // Apply any model-specific conditioning transforms before collection.
+ const conditioningSource = transformRegionalPositiveConditioning?.(regionalPosCond) ?? regionalPosCond;
+ g.addEdge(conditioningSource, 'conditioning', posCondCollect, 'item');
}
if (region.negativePrompt) {
// FLUX.2 regions with negative prompts are filtered out by getRegionalGuidanceWarnings; fail
// loudly if that ever changes, because there is no flux2 branch below.
assert(!isFlux2, 'Regional negative prompts are not supported for FLUX.2 Klein');
+ assert(!isKrea2, 'Canvas regional negative prompts are not supported for Krea-2');
assert(negCond, 'Negative conditioning node is required if there is a negative prompt');
assert(negCondCollect, 'Negative conditioning collector is required if there is a negative prompt');
@@ -309,6 +327,7 @@ export const addRegions = async ({
if (region.autoNegative && region.positivePrompt) {
// See note on the negative prompt branch above — unreachable for FLUX.2 via validators.
assert(!isFlux2, 'Auto-negative is not supported for FLUX.2 Klein');
+ assert(!isKrea2, 'Canvas auto-negative is not supported for Krea-2');
assert(negCondCollect, 'Negative conditioning collector is required if there is an auto-negative setting');
result.addedAutoNegativePositivePrompt = true;
@@ -398,6 +417,7 @@ export const addRegions = async ({
for (const { id, config } of region.referenceImages) {
if (isRegionalGuidanceIPAdapterConfig(config)) {
assert(!isFLUX, 'Regional IP adapters are not supported for FLUX.');
+ assert(!isKrea2, 'Regional IP adapters are not supported for Krea-2.');
result.addedIPAdapters++;
const { weight, model, clipVisionModel, method, beginEndStepPct, image } = config;
diff --git a/invokeai/frontend/web/src/features/nodes/util/graph/generation/buildKrea2Graph.regions.test.ts b/invokeai/frontend/web/src/features/nodes/util/graph/generation/buildKrea2Graph.regions.test.ts
new file mode 100644
index 0000000000..99852aa827
--- /dev/null
+++ b/invokeai/frontend/web/src/features/nodes/util/graph/generation/buildKrea2Graph.regions.test.ts
@@ -0,0 +1,280 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+// Unlike buildKrea2Graph.test.ts, this suite deliberately runs the REAL addRegions, addKrea2LoRAs and
+// regional-guidance validators so the composed canvas path is covered end to end.
+
+vi.mock('app/logging/logger', () => ({
+ logger: () => ({
+ debug: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ }),
+}));
+
+let nextId = 0;
+vi.mock('features/controlLayers/konva/util', () => ({
+ getPrefixedId: (prefix: string) => `${prefix}:${nextId++}`,
+}));
+
+const model = {
+ key: 'krea2-model',
+ hash: 'krea2-hash',
+ name: 'Krea-2 Turbo',
+ base: 'krea-2',
+ type: 'main',
+ format: 'diffusers',
+ variant: 'krea2_turbo',
+};
+
+const defaultParams = {
+ cfgScale: 1 as number | number[],
+ steps: 8,
+ krea2VaeModel: null as unknown,
+ krea2Qwen3VlEncoderModel: null as unknown,
+ krea2RebalanceEnabled: false,
+ krea2RebalanceMultiplier: 4,
+ krea2RebalanceWeights: '1,1,1,1,1,1,1,2.5,5,1.1,4,1',
+ krea2SeedVarianceEnabled: false,
+ krea2SeedVarianceStrength: 0.5,
+ krea2SeedVarianceRandomizePercent: 50,
+};
+
+let params = { ...defaultParams };
+let regions: unknown[] = [];
+
+vi.mock('features/controlLayers/store/paramsSlice', () => ({
+ selectMainModelConfig: vi.fn(() => model),
+ selectParamsSlice: vi.fn(() => params),
+}));
+
+vi.mock('features/controlLayers/store/selectors', () => ({
+ selectCanvasMetadata: vi.fn(() => ({})),
+ selectCanvasSlice: vi.fn(() => ({
+ bbox: { rect: { x: 0, y: 0, width: 1024, height: 1024 } },
+ regionalGuidance: { entities: regions },
+ })),
+}));
+
+vi.mock('features/metadata/util/modelFetchingHelpers', () => ({
+ fetchModelConfigWithTypeGuard: vi.fn(() => Promise.resolve(model)),
+}));
+
+vi.mock('features/nodes/util/graph/generation/addNSFWChecker', () => ({
+ addNSFWChecker: vi.fn((_g, node) => node),
+}));
+
+vi.mock('features/nodes/util/graph/generation/addWatermarker', () => ({
+ addWatermarker: vi.fn((_g, node) => node),
+}));
+
+vi.mock('features/nodes/util/graph/generation/addTextToImage', () => ({
+ addTextToImage: vi.fn(({ l2i }) => l2i),
+}));
+
+vi.mock('features/nodes/util/graph/graphBuilderUtils', () => ({
+ selectCanvasOutputFields: vi.fn(() => ({})),
+ selectPresetModifiedPrompts: vi.fn(() => ({
+ positive: 'a global prompt',
+ negative: 'a negative prompt',
+ })),
+}));
+
+vi.mock('features/ui/store/uiSelectors', () => ({
+ selectActiveTab: vi.fn(() => 'canvas'),
+}));
+
+vi.mock('services/api/types', async () => {
+ const actual = await vi.importActual('services/api/types');
+ return {
+ ...actual,
+ isNonRefinerMainModelConfig: vi.fn(() => true),
+ };
+});
+
+import { getRegionalGuidanceState } from 'features/controlLayers/store/util';
+
+import { buildKrea2Graph } from './buildKrea2Graph';
+
+type BuiltGraph = Awaited<ReturnType<typeof buildKrea2Graph>>['g'];
+
+/** A region with a rasterized object, so the real validators do not reject it for being empty. */
+const makeRegion = (id: string, overrides: Record<string, unknown>) => {
+ const region = getRegionalGuidanceState(id, {});
+ Object.assign(region, overrides);
+ region.objects = [{ id: `${id}-object`, type: 'rect' }] as never;
+ return region;
+};
+
+const manager = {
+ id: 'manager',
+ adapters: {
+ regionMasks: {
+ get: (id: string) => ({
+ renderer: {
+ rasterize: () => Promise.resolve({ image_name: `${id}.png` }),
+ },
+ }),
+ },
+ },
+};
+
+const loraState = { loras: [] as unknown[] };
+
+const build = () =>
+ buildKrea2Graph({
+ generationMode: 'txt2img',
+ manager: manager as never,
+ state: {
+ system: { shouldUseNSFWChecker: false, shouldUseWatermarker: false },
+ loras: loraState,
+ } as never,
+ });
+
+const nodesOf = (g: BuiltGraph) => Object.values(g.getGraph().nodes);
+const regionalEncoders = (g: BuiltGraph) =>
+ nodesOf(g).filter((node) => node.type === 'krea2_text_encoder' && node.id.startsWith('prompt_region_'));
+const sourceOf = (g: BuiltGraph, nodeId: string, field: string) =>
+ g.getGraph().edges.find((edge) => edge.destination.node_id === nodeId && edge.destination.field === field)?.source;
+
+describe('buildKrea2Graph - regional guidance (composed)', () => {
+ afterEach(() => {
+ nextId = 0;
+ params = { ...defaultParams };
+ regions = [];
+ loraState.loras = [];
+ vi.clearAllMocks();
+ });
+
+ it('adds only regions the validators accept and wires them into the positive collector', async () => {
+ regions = [
+ makeRegion('valid', { positivePrompt: 'a red fox' }),
+ // Rejected by getRegionalGuidanceWarnings for Krea-2. If it were not filtered out, addRegions would
+ // throw on its `assert(!isKrea2, ...)` guard, so this also proves the validator and the guard agree.
+ makeRegion('with-negative', { positivePrompt: 'a blue fox', negativePrompt: 'blurry' }),
+ makeRegion('with-auto-negative', { positivePrompt: 'a green fox', autoNegative: true }),
+ makeRegion('empty', {}),
+ ];
+
+ const { g } = await build();
+ const graph = g.getGraph();
+
+ const encoders = regionalEncoders(g);
+ expect(encoders).toHaveLength(1);
+ expect(encoders[0]).toMatchObject({ prompt: 'a red fox' });
+
+ // The regional mask comes from the valid region's rasterized image, not another region's.
+ const maskSource = sourceOf(g, encoders[0]!.id, 'mask');
+ expect(maskSource).toBeDefined();
+ expect(graph.nodes[maskSource!.node_id]).toMatchObject({
+ type: 'alpha_mask_to_tensor',
+ image: { image_name: 'valid.png' },
+ });
+
+ // No canvas-side negative or auto-negative regional conditioning is produced for Krea-2.
+ expect(nodesOf(g).some((node) => node.id.startsWith('prompt_region_negative_cond'))).toBe(false);
+ expect(nodesOf(g).some((node) => node.type === 'invert_tensor_mask')).toBe(false);
+
+ // Both the global and the regional conditioning land on the same collector, which feeds denoise.
+ const posCondCollect = nodesOf(g).find((node) => node.id.startsWith('pos_cond_collect'));
+ expect(posCondCollect).toBeDefined();
+ const collectedFrom = graph.edges
+ .filter((edge) => edge.destination.node_id === posCondCollect!.id && edge.destination.field === 'item')
+ .map((edge) => edge.source.node_id);
+ expect(collectedFrom).toHaveLength(2);
+ expect(collectedFrom.some((id) => id.startsWith('pos_prompt:'))).toBe(true);
+ expect(collectedFrom).toContain(encoders[0]!.id);
+ expect(sourceOf(g, nodesOf(g).find((n) => n.type === 'krea2_denoise')!.id, 'positive_conditioning')).toEqual({
+ node_id: posCondCollect!.id,
+ field: 'collection',
+ });
+ });
+
+ it('deletes the placeholder IP adapter collector and leaves no dangling edges', async () => {
+ regions = [makeRegion('valid', { positivePrompt: 'a red fox' })];
+
+ const { g } = await build();
+ const graph = g.getGraph();
+
+ expect(nodesOf(g).some((node) => node.id.startsWith('ip_adapter_collect'))).toBe(false);
+ // Without LoRAs the only surviving collector is the positive conditioning one.
+ expect(nodesOf(g).filter((node) => node.type === 'collect')).toHaveLength(1);
+ for (const edge of graph.edges) {
+ expect(graph.nodes[edge.source.node_id]).toBeDefined();
+ expect(graph.nodes[edge.destination.node_id]).toBeDefined();
+ }
+ });
+
+ it('routes regional encoders through the LoRA collection loader, not the raw model loader', async () => {
+ // addKrea2LoRAs runs before addRegions and rewrites the global encoder's qwen3_vl_encoder edge; the
+ // regional encoders are created afterwards by cloning that edge. If the ordering ever flips, the
+ // regional prompts would silently be encoded without the LoRAs applied.
+ regions = [makeRegion('valid', { positivePrompt: 'a red fox' })];
+ loraState.loras = [
+ {
+ id: 'lora-1',
+ isEnabled: true,
+ weight: 0.8,
+ model: { key: 'lora-key', hash: 'lora-hash', name: 'A LoRA', base: 'krea-2', type: 'lora' },
+ },
+ ];
+
+ const { g } = await build();
+
+ const loraLoader = nodesOf(g).find((node) => node.type === 'krea2_lora_collection_loader');
+ expect(loraLoader).toBeDefined();
+
+ const encoders = regionalEncoders(g);
+ expect(encoders).toHaveLength(1);
+ expect(sourceOf(g, encoders[0]!.id, 'qwen3_vl_encoder')).toEqual({
+ node_id: loraLoader!.id,
+ field: 'qwen3_vl_encoder',
+ });
+ // Sanity: the global encoder is rerouted too, so the regional edge is not accidentally matching a
+ // still-unrouted graph.
+ const globalEncoder = nodesOf(g).find((node) => node.id.startsWith('pos_prompt:'));
+ expect(sourceOf(g, globalEncoder!.id, 'qwen3_vl_encoder')).toEqual({
+ node_id: loraLoader!.id,
+ field: 'qwen3_vl_encoder',
+ });
+ });
+
+ it('applies the enabled conditioning enhancers to the regional prompt as well as the global one', async () => {
+ params = {
+ ...defaultParams,
+ krea2RebalanceEnabled: true,
+ krea2SeedVarianceEnabled: true,
+ krea2SeedVarianceStrength: 0.5,
+ };
+ regions = [makeRegion('valid', { positivePrompt: 'a red fox' })];
+
+ const { g } = await build();
+ const graph = g.getGraph();
+
+ // One enhancer chain per conditioning: global + one region.
+ expect(nodesOf(g).filter((node) => node.type === 'krea2_conditioning_rebalance')).toHaveLength(2);
+ expect(nodesOf(g).filter((node) => node.type === 'krea2_seed_variance')).toHaveLength(2);
+
+ const encoder = regionalEncoders(g)[0]!;
+ const rebalance = graph.edges.find(
+ (edge) =>
+ edge.source.node_id === encoder.id &&
+ graph.nodes[edge.destination.node_id]?.type === 'krea2_conditioning_rebalance'
+ );
+ expect(rebalance).toBeDefined();
+
+ const seedVariance = graph.edges.find(
+ (edge) =>
+ edge.source.node_id === rebalance!.destination.node_id &&
+ graph.nodes[edge.destination.node_id]?.type === 'krea2_seed_variance'
+ );
+ expect(seedVariance).toBeDefined();
+
+ // The end of the regional chain - not the raw encoder - is what gets collected.
+ const posCondCollect = nodesOf(g).find((node) => node.id.startsWith('pos_cond_collect'))!;
+ const collectedFrom = graph.edges
+ .filter((edge) => edge.destination.node_id === posCondCollect.id && edge.destination.field === 'item')
+ .map((edge) => edge.source.node_id);
+ expect(collectedFrom).toContain(seedVariance!.destination.node_id);
+ expect(collectedFrom).not.toContain(encoder.id);
+ });
+});
diff --git a/invokeai/frontend/web/src/features/nodes/util/graph/generation/buildKrea2Graph.test.ts b/invokeai/frontend/web/src/features/nodes/util/graph/generation/buildKrea2Graph.test.ts
index 34043589df..ab25a78f90 100644
--- a/invokeai/frontend/web/src/features/nodes/util/graph/generation/buildKrea2Graph.test.ts
+++ b/invokeai/frontend/web/src/features/nodes/util/graph/generation/buildKrea2Graph.test.ts
@@ -45,6 +45,10 @@ vi.mock('features/controlLayers/store/paramsSlice', () => ({
vi.mock('features/controlLayers/store/selectors', () => ({
selectCanvasMetadata: vi.fn(() => ({})),
+ selectCanvasSlice: vi.fn(() => ({
+ bbox: { rect: { x: 0, y: 0, width: 1024, height: 1024 } },
+ regionalGuidance: { entities: [] },
+ })),
}));
vi.mock('features/metadata/util/modelFetchingHelpers', () => ({
@@ -63,6 +67,10 @@ vi.mock('features/nodes/util/graph/generation/addOutpaint', () => ({
addOutpaint: vi.fn(({ l2i }) => Promise.resolve(l2i)),
}));
+vi.mock('features/nodes/util/graph/generation/addRegions', () => ({
+ addRegions: vi.fn(() => Promise.resolve([])),
+}));
+
vi.mock('features/nodes/util/graph/generation/addKrea2LoRAs', () => ({
addKrea2LoRAs: vi.fn(),
}));
@@ -102,6 +110,7 @@ vi.mock('services/api/types', async () => {
import { addImageToImage } from './addImageToImage';
import { addInpaint } from './addInpaint';
import { addOutpaint } from './addOutpaint';
+import { addRegions } from './addRegions';
import { buildKrea2Graph } from './buildKrea2Graph';
type BuiltGraph = Awaited<ReturnType<typeof buildKrea2Graph>>['g'];
@@ -130,6 +139,7 @@ const posConditioningEdge = (g: BuiltGraph) =>
describe('buildKrea2Graph', () => {
afterEach(() => {
+ vi.clearAllMocks();
nextId = 0;
params = { ...defaultParams };
model = { ...baseModel };
@@ -153,6 +163,7 @@ describe('buildKrea2Graph', () => {
const { g } = await buildCanvasMode(mode);
expect(integration).toHaveBeenCalledOnce();
+ expect(addRegions).toHaveBeenCalledOnce();
expect(nodeTypesOf(g)).toContain('qwen_image_i2l');
expect((g.getMetadataNode() as unknown as Record<string, unknown>).generation_mode).toBe(`krea2_${mode}`);
});
@@ -183,15 +194,23 @@ describe('buildKrea2Graph', () => {
});
describe('conditioning enhancers', () => {
- it('inserts no enhancer nodes by default; positive conditioning flows straight to denoise', async () => {
+ it('inserts no enhancer nodes by default; positive conditioning flows through the regional collector', async () => {
const { g } = await buildTxt2Img();
const types = nodeTypesOf(g);
expect(types).not.toContain('krea2_conditioning_rebalance');
expect(types).not.toContain('krea2_seed_variance');
- // The edge into denoise.positive_conditioning comes directly from the text encoder.
const edge = posConditioningEdge(g);
expect(edge).toBeDefined();
- expect(edge!.source.node_id.startsWith('pos_prompt:')).toBe(true);
+ expect(edge!.source.node_id.startsWith('pos_cond_collect:')).toBe(true);
+ expect(
+ g
+ .getGraph()
+ .edges.some(
+ (candidate) =>
+ candidate.source.node_id.startsWith('pos_prompt:') &&
+ candidate.destination.node_id.startsWith('pos_cond_collect:')
+ )
+ ).toBe(true);
});
it('inserts the rebalance node and reroutes positive conditioning through it when enabled', async () => {
@@ -201,7 +220,16 @@ describe('buildKrea2Graph', () => {
expect(types).toContain('krea2_conditioning_rebalance');
expect(types).not.toContain('krea2_seed_variance');
const edge = posConditioningEdge(g);
- expect(edge!.source.node_id.startsWith('krea2_rebalance:')).toBe(true);
+ expect(edge!.source.node_id.startsWith('pos_cond_collect:')).toBe(true);
+ expect(
+ g
+ .getGraph()
+ .edges.some(
+ (candidate) =>
+ candidate.source.node_id.startsWith('krea2_rebalance:') &&
+ candidate.destination.node_id.startsWith('pos_cond_collect:')
+ )
+ ).toBe(true);
});
it('inserts the seed-variance node when enabled with strength > 0', async () => {
@@ -209,7 +237,7 @@ describe('buildKrea2Graph', () => {
const { g } = await buildTxt2Img();
expect(nodeTypesOf(g)).toContain('krea2_seed_variance');
const edge = posConditioningEdge(g);
- expect(edge!.source.node_id.startsWith('krea2_seed_variance:')).toBe(true);
+ expect(edge!.source.node_id.startsWith('pos_cond_collect:')).toBe(true);
});
it('does not insert the seed-variance node when strength is 0 (a no-op)', async () => {
@@ -236,9 +264,67 @@ describe('buildKrea2Graph', () => {
e.source.node_id.startsWith('krea2_rebalance:') && e.destination.node_id.startsWith('krea2_seed_variance:')
);
expect(rebalanceToSeed).toBeDefined();
- // seed_variance -> denoise.positive_conditioning
+ // seed_variance -> collector -> denoise.positive_conditioning
const edge = posConditioningEdge(g);
- expect(edge!.source.node_id.startsWith('krea2_seed_variance:')).toBe(true);
+ expect(edge!.source.node_id.startsWith('pos_cond_collect:')).toBe(true);
+ expect(
+ graph.edges.some(
+ (candidate) =>
+ candidate.source.node_id.startsWith('krea2_seed_variance:') &&
+ candidate.destination.node_id.startsWith('pos_cond_collect:')
+ )
+ ).toBe(true);
+ });
+
+ it('applies enabled enhancers to regional conditioning before collection', async () => {
+ params = {
+ ...defaultParams,
+ krea2RebalanceEnabled: true,
+ krea2SeedVarianceEnabled: true,
+ krea2SeedVarianceStrength: 0.5,
+ };
+ vi.mocked(addRegions).mockImplementationOnce((arg) => {
+ const regionalPosCond = arg.g.addNode({
+ type: 'krea2_text_encoder',
+ id: 'regional-positive',
+ prompt: 'regional prompt',
+ });
+ const transformRegionalPositiveConditioning = (
+ arg as typeof arg & {
+ transformRegionalPositiveConditioning?: (conditioning: typeof regionalPosCond) => {
+ id: string;
+ type: string;
+ };
+ }
+ ).transformRegionalPositiveConditioning;
+ const conditioningSource = transformRegionalPositiveConditioning?.(regionalPosCond) ?? regionalPosCond;
+ arg.g.addEdgeFromObj({
+ source: { node_id: conditioningSource.id, field: 'conditioning' },
+ destination: { node_id: arg.posCondCollect.id, field: 'item' },
+ });
+ return Promise.resolve([]);
+ });
+
+ const { g } = await buildCanvasMode('img2img');
+ const graph = g.getGraph();
+ const regionalRebalanceEdge = graph.edges.find(
+ (edge) =>
+ edge.source.node_id === 'regional-positive' &&
+ graph.nodes[edge.destination.node_id]?.type === 'krea2_conditioning_rebalance'
+ );
+ expect(regionalRebalanceEdge).toBeDefined();
+ const regionalSeedVarianceEdge = graph.edges.find(
+ (edge) =>
+ edge.source.node_id === regionalRebalanceEdge!.destination.node_id &&
+ graph.nodes[edge.destination.node_id]?.type === 'krea2_seed_variance'
+ );
+ expect(regionalSeedVarianceEdge).toBeDefined();
+ expect(graph.edges).toContainEqual(
+ expect.objectContaining({
+ source: { node_id: regionalSeedVarianceEdge!.destination.node_id, field: 'conditioning' },
+ destination: expect.objectContaining({ field: 'item' }),
+ })
+ );
});
});
diff --git a/invokeai/frontend/web/src/features/nodes/util/graph/generation/buildKrea2Graph.ts b/invokeai/frontend/web/src/features/nodes/util/graph/generation/buildKrea2Graph.ts
index 7f208ea9d9..e8b5287d81 100644
--- a/invokeai/frontend/web/src/features/nodes/util/graph/generation/buildKrea2Graph.ts
+++ b/invokeai/frontend/web/src/features/nodes/util/graph/generation/buildKrea2Graph.ts
@@ -1,13 +1,14 @@
import { logger } from 'app/logging/logger';
import { getPrefixedId } from 'features/controlLayers/konva/util';
import { selectMainModelConfig, selectParamsSlice } from 'features/controlLayers/store/paramsSlice';
-import { selectCanvasMetadata } from 'features/controlLayers/store/selectors';
+import { selectCanvasMetadata, selectCanvasSlice } from 'features/controlLayers/store/selectors';
import { fetchModelConfigWithTypeGuard } from 'features/metadata/util/modelFetchingHelpers';
import { addImageToImage } from 'features/nodes/util/graph/generation/addImageToImage';
import { addInpaint } from 'features/nodes/util/graph/generation/addInpaint';
import { addKrea2LoRAs } from 'features/nodes/util/graph/generation/addKrea2LoRAs';
import { addNSFWChecker } from 'features/nodes/util/graph/generation/addNSFWChecker';
import { addOutpaint } from 'features/nodes/util/graph/generation/addOutpaint';
+import { addRegions } from 'features/nodes/util/graph/generation/addRegions';
import { addTextToImage } from 'features/nodes/util/graph/generation/addTextToImage';
import { addWatermarker } from 'features/nodes/util/graph/generation/addWatermarker';
import { Graph } from 'features/nodes/util/graph/generation/Graph';
@@ -74,6 +75,14 @@ export const buildKrea2Graph = async (arg: GraphBuilderArg): Promise<GraphBuilde
type: 'krea2_text_encoder',
id: getPrefixedId('pos_prompt'),
});
+ const posCondCollect = g.addNode({
+ type: 'collect',
+ id: getPrefixedId('pos_cond_collect'),
+ });
+ const ipAdapterCollect = g.addNode({
+ type: 'collect',
+ id: getPrefixedId('ip_adapter_collect'),
+ });
// Krea-2 supports negative conditioning only when CFG is enabled (cfg_scale > 1).
let negCond: Invocation<'krea2_text_encoder'> | null = null;
@@ -89,6 +98,36 @@ export const buildKrea2Graph = async (arg: GraphBuilderArg): Promise<GraphBuilde
id: getPrefixedId('seed'),
type: 'integer',
});
+
+ type Krea2ConditioningSource = Invocation<
+ 'krea2_text_encoder' | 'krea2_conditioning_rebalance' | 'krea2_seed_variance'
+ >;
+ const addConditioningEnhancers = (conditioning: Invocation<'krea2_text_encoder'>): Krea2ConditioningSource => {
+ let conditioningSource: Krea2ConditioningSource = conditioning;
+ if (krea2RebalanceEnabled) {
+ const rebalance = g.addNode({
+ type: 'krea2_conditioning_rebalance',
+ id: getPrefixedId('krea2_rebalance'),
+ multiplier: krea2RebalanceMultiplier,
+ per_layer_weights: krea2RebalanceWeights,
+ });
+ g.addEdge(conditioningSource, 'conditioning', rebalance, 'conditioning');
+ conditioningSource = rebalance;
+ }
+ if (krea2SeedVarianceEnabled && krea2SeedVarianceStrength > 0) {
+ const seedVariance = g.addNode({
+ type: 'krea2_seed_variance',
+ id: getPrefixedId('krea2_seed_variance'),
+ strength: krea2SeedVarianceStrength,
+ randomize_percent: krea2SeedVarianceRandomizePercent,
+ });
+ g.addEdge(conditioningSource, 'conditioning', seedVariance, 'conditioning');
+ g.addEdge(seed, 'value', seedVariance, 'variance_seed');
+ conditioningSource = seedVariance;
+ }
+ return conditioningSource;
+ };
+
const denoise = g.addNode({
type: 'krea2_denoise',
id: getPrefixedId('denoise_latents'),
@@ -110,41 +149,9 @@ export const buildKrea2Graph = async (arg: GraphBuilderArg): Promise<GraphBuilde
// Optional conditioning enhancers between the text encoder and denoise. Both default OFF (params), so
// by default the conditioning flows straight through and stock Krea-2 behaviour is unchanged. Order:
// rebalance (scale the signal toward the prompt) first, then seed variance (perturb for variety).
- if (krea2RebalanceEnabled) {
- const rebalance = g.addNode({
- type: 'krea2_conditioning_rebalance',
- id: getPrefixedId('krea2_rebalance'),
- multiplier: krea2RebalanceMultiplier,
- per_layer_weights: krea2RebalanceWeights,
- });
- g.addEdge(posCond, 'conditioning', rebalance, 'conditioning');
-
- if (krea2SeedVarianceEnabled && krea2SeedVarianceStrength > 0) {
- const seedVariance = g.addNode({
- type: 'krea2_seed_variance',
- id: getPrefixedId('krea2_seed_variance'),
- strength: krea2SeedVarianceStrength,
- randomize_percent: krea2SeedVarianceRandomizePercent,
- });
- g.addEdge(rebalance, 'conditioning', seedVariance, 'conditioning');
- g.addEdge(seed, 'value', seedVariance, 'variance_seed');
- g.addEdge(seedVariance, 'conditioning', denoise, 'positive_conditioning');
- } else {
- g.addEdge(rebalance, 'conditioning', denoise, 'positive_conditioning');
- }
- } else if (krea2SeedVarianceEnabled && krea2SeedVarianceStrength > 0) {
- const seedVariance = g.addNode({
- type: 'krea2_seed_variance',
- id: getPrefixedId('krea2_seed_variance'),
- strength: krea2SeedVarianceStrength,
- randomize_percent: krea2SeedVarianceRandomizePercent,
- });
- g.addEdge(posCond, 'conditioning', seedVariance, 'conditioning');
- g.addEdge(seed, 'value', seedVariance, 'variance_seed');
- g.addEdge(seedVariance, 'conditioning', denoise, 'positive_conditioning');
- } else {
- g.addEdge(posCond, 'conditioning', denoise, 'positive_conditioning');
- }
+ const positiveConditioningSource = addConditioningEnhancers(posCond);
+ g.addEdge(positiveConditioningSource, 'conditioning', posCondCollect, 'item');
+ g.addEdge(posCondCollect, 'collection', denoise, 'positive_conditioning');
if (negCond !== null) {
g.addEdge(modelLoader, 'qwen3_vl_encoder', negCond, 'qwen3_vl_encoder');
@@ -157,6 +164,29 @@ export const buildKrea2Graph = async (arg: GraphBuilderArg): Promise<GraphBuilde
// Apply any enabled Krea-2 LoRAs (reroutes transformer + Qwen3-VL encoder through the collection loader).
addKrea2LoRAs(state, g, denoise, modelLoader, posCond, negCond);
+ const canvas = selectCanvasSlice(state);
+ if (manager !== null) {
+ await addRegions({
+ manager,
+ regions: canvas.regionalGuidance.entities,
+ g,
+ bbox: canvas.bbox.rect,
+ model,
+ posCond,
+ negCond,
+ posCondCollect,
+ negCondCollect: null,
+ ipAdapterCollect,
+ fluxReduxCollect: null,
+ transformRegionalPositiveConditioning: (conditioning) => {
+ assert(conditioning.type === 'krea2_text_encoder');
+ return addConditioningEnhancers(conditioning);
+ },
+ });
+ }
+ // Krea-2 does not support regional reference-image adapters.
+ g.deleteNode(ipAdapterCollect.id);
+
const modelConfig = await fetchModelConfigWithTypeGuard(model.key, isNonRefinerMainModelConfig);
assert(modelConfig.base === 'krea-2');
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index 70770db161..001aa2233c 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -19644,6 +19644,11 @@ export type components = {
* @description The name of conditioning tensor
*/
conditioning_name: string;
+ /**
+ * @description The mask associated with this conditioning tensor for regional prompting. Excluded regions should be set to False, included regions should be set to True.
+ * @default null
+ */
+ mask?: components["schemas"]["TensorField"] | null;
};
/**
* Krea2ConditioningOutput
@@ -20120,6 +20125,11 @@ export type components = {
* @default null
*/
prompt?: string | null;
+ /**
+ * @description A mask defining the image region that this conditioning prompt applies to.
+ * @default null
+ */
+ mask?: components["schemas"]["TensorField"] | null;
/**
* Qwen3-VL Encoder
* @description Qwen3-VL tokenizer and text encoder
diff --git a/tests/app/invocations/test_krea2_denoise.py b/tests/app/invocations/test_krea2_denoise.py
index 7d4cb7dc59..670bac2d67 100644
--- a/tests/app/invocations/test_krea2_denoise.py
+++ b/tests/app/invocations/test_krea2_denoise.py
@@ -5,7 +5,7 @@ from types import SimpleNamespace
import pytest
import torch
-from invokeai.app.invocations.fields import DenoiseMaskField, Krea2ConditioningField, LatentsField
+from invokeai.app.invocations.fields import DenoiseMaskField, Krea2ConditioningField, LatentsField, TensorField
from invokeai.app.invocations.krea2_denoise import KREA2_LATENT_CHANNELS, Krea2DenoiseInvocation
from invokeai.app.invocations.model import ModelIdentifierField, TransformerField
from invokeai.backend.model_manager.taxonomy import BaseModelType, Krea2VariantType, ModelFormat, ModelType
@@ -189,23 +189,34 @@ def test_load_text_conditioning_concatenates_only_valid_tokens() -> None:
conditionings=[Krea2ConditioningInfo(prompt_embeds=torch.full((1, 3, 12, 8), 2.0))]
),
}
- context = SimpleNamespace(conditioning=SimpleNamespace(load=lambda name: conditionings[name]))
+ regional_mask = torch.tensor([[1.0, 0.0], [1.0, 0.0]])
+ context = SimpleNamespace(
+ conditioning=SimpleNamespace(load=lambda name: conditionings[name]),
+ tensors=SimpleNamespace(load=lambda name: regional_mask if name == "region-mask" else None),
+ )
- prompt_embeds, prompt_mask = invocation._load_text_conditioning(
+ extension = invocation._load_text_conditioning(
context=context,
conditioning_field=[
- Krea2ConditioningField(conditioning_name="first"),
+ Krea2ConditioningField(conditioning_name="first", mask=TensorField(tensor_name="region-mask")),
Krea2ConditioningField(conditioning_name="second"),
],
+ grid_height=1,
+ grid_width=2,
dtype=torch.float32,
device=torch.device("cpu"),
)
+ prompt_embeds = extension.regional_text_conditioning.prompt_embeds
assert prompt_embeds.shape == (1, 5, 12, 8)
assert torch.equal(prompt_embeds[:, 0], torch.full((1, 12, 8), 1.0))
assert torch.equal(prompt_embeds[:, 1], torch.full((1, 12, 8), 3.0))
assert torch.equal(prompt_embeds[:, 2:], torch.full((1, 3, 12, 8), 2.0))
- assert prompt_mask is None
+ assert torch.equal(
+ extension.regional_text_conditioning.image_masks[0],
+ torch.tensor([[[1.0, 0.0]]]),
+ )
+ assert extension.regional_text_conditioning.image_masks[1] is None
def test_load_text_conditioning_compacts_a_single_masked_conditioning() -> None:
@@ -221,17 +232,23 @@ def test_load_text_conditioning_compacts_a_single_masked_conditioning() -> None:
]
)
}
- context = SimpleNamespace(conditioning=SimpleNamespace(load=lambda name: conditionings[name]))
+ context = SimpleNamespace(
+ conditioning=SimpleNamespace(load=lambda name: conditionings[name]),
+ tensors=SimpleNamespace(load=lambda _name: None),
+ )
- prompt_embeds, prompt_mask = invocation._load_text_conditioning(
+ extension = invocation._load_text_conditioning(
context=context,
conditioning_field=Krea2ConditioningField(conditioning_name="prompt"),
+ grid_height=1,
+ grid_width=1,
dtype=torch.float32,
device=torch.device("cpu"),
)
+ prompt_embeds = extension.regional_text_conditioning.prompt_embeds
assert torch.equal(prompt_embeds, embeds[:, [0, 2]])
- assert prompt_mask is None
+ assert extension.get_attention_mask() is None
def test_load_text_conditioning_preserves_none_when_all_masks_are_none() -> None:
@@ -240,20 +257,26 @@ def test_load_text_conditioning_preserves_none_when_all_masks_are_none() -> None
"first": ConditioningFieldData(conditionings=[Krea2ConditioningInfo(prompt_embeds=torch.ones(1, 2, 12, 8))]),
"second": ConditioningFieldData(conditionings=[Krea2ConditioningInfo(prompt_embeds=torch.ones(1, 3, 12, 8))]),
}
- context = SimpleNamespace(conditioning=SimpleNamespace(load=lambda name: conditionings[name]))
+ context = SimpleNamespace(
+ conditioning=SimpleNamespace(load=lambda name: conditionings[name]),
+ tensors=SimpleNamespace(load=lambda _name: None),
+ )
- prompt_embeds, prompt_mask = invocation._load_text_conditioning(
+ extension = invocation._load_text_conditioning(
context=context,
conditioning_field=[
Krea2ConditioningField(conditioning_name="first"),
Krea2ConditioningField(conditioning_name="second"),
],
+ grid_height=1,
+ grid_width=1,
dtype=torch.float32,
device=torch.device("cpu"),
)
+ prompt_embeds = extension.regional_text_conditioning.prompt_embeds
assert prompt_embeds.shape == (1, 5, 12, 8)
- assert prompt_mask is None
+ assert extension.get_attention_mask() is None
def test_load_text_conditioning_rejects_an_empty_collection() -> None:
@@ -264,6 +287,8 @@ def test_load_text_conditioning_rejects_an_empty_collection() -> None:
invocation._load_text_conditioning(
context=context,
conditioning_field=[],
+ grid_height=1,
+ grid_width=1,
dtype=torch.float32,
device=torch.device("cpu"),
)
@@ -282,13 +307,27 @@ class _Scheduler:
class _Transformer:
def __init__(self) -> None:
self.conditioning_values: list[float] = []
+ self.regional_attention_masks: list[torch.Tensor | None] = []
+ self.combined_sequence_lengths: list[int] = []
+ self.attn_processors = {
+ "text_fusion.layerwise_blocks.0.attn.processor": object(),
+ "transformer_blocks.0.attn.processor": object(),
+ "transformer_blocks.1.attn.processor": object(),
+ }
+ self.installed_processors = None
def set_attn_processor(self, processor) -> None:
# The real Krea2Transformer2DModel exposes this; denoise swaps in a memory-efficient attention processor.
- pass
+ self.installed_processors = processor
def __call__(self, *, hidden_states, encoder_hidden_states, **_kwargs):
self.conditioning_values.append(float(encoder_hidden_states.mean()))
+ # The real transformer concatenates [text, image] before attention, so this is the sequence length a
+ # regional mask has to match.
+ self.combined_sequence_lengths.append(encoder_hidden_states.shape[1] + hidden_states.shape[1])
+ regional_processor = self.installed_processors["transformer_blocks.0.attn.processor"]
+ attention_mask = regional_processor.regional_prompting_state.attention_mask
+ self.regional_attention_masks.append(attention_mask.clone() if attention_mask is not None else None)
return (torch.zeros_like(hidden_states),)
@@ -336,16 +375,18 @@ def _runtime_invocation(
)
-def _runtime_context(tmp_path, transformer: _Transformer):
+def _runtime_context(tmp_path, transformer: _Transformer, *, negative_text_seq_len: int = 2):
conditionings = {
"positive": ConditioningFieldData(conditionings=[Krea2ConditioningInfo(prompt_embeds=torch.ones(1, 2, 12, 8))]),
"negative": ConditioningFieldData(
- conditionings=[Krea2ConditioningInfo(prompt_embeds=torch.zeros(1, 2, 12, 8))]
+ conditionings=[Krea2ConditioningInfo(prompt_embeds=torch.zeros(1, negative_text_seq_len, 12, 8))]
),
}
tensors = {
"init": torch.zeros(1, KREA2_LATENT_CHANNELS, 2, 2),
"mask": torch.zeros(1, 1, 16, 16),
+ "positive-region": torch.ones(1, 16, 16),
+ "negative-region": torch.zeros(1, 16, 16),
}
config = SimpleNamespace(format=ModelFormat.Checkpoint, variant=Krea2VariantType.Turbo)
return SimpleNamespace(
@@ -400,6 +441,76 @@ def test_run_diffusion_treats_an_empty_negative_collection_as_absent(monkeypatch
assert transformer.conditioning_values == [1.0, 1.0]
+def test_run_diffusion_switches_regional_masks_between_equal_length_cfg_conditionings(monkeypatch, tmp_path) -> None:
+ _patch_runtime(monkeypatch)
+ transformer = _Transformer()
+ invocation = _runtime_invocation(cfg_scale=2.0)
+ invocation.positive_conditioning = Krea2ConditioningField(
+ conditioning_name="positive", mask=TensorField(tensor_name="positive-region")
+ )
+ invocation.negative_conditioning = Krea2ConditioningField(
+ conditioning_name="negative", mask=TensorField(tensor_name="negative-region")
+ )
+
+ invocation._run_diffusion(_runtime_context(tmp_path, transformer))
+
+ positive_mask, negative_mask, positive_mask_second_step, negative_mask_second_step = (
+ transformer.regional_attention_masks
+ )
+ assert positive_mask is not None
+ assert negative_mask is not None
+ assert not torch.equal(positive_mask, negative_mask)
+ assert torch.equal(positive_mask, positive_mask_second_step)
+ assert torch.equal(negative_mask, negative_mask_second_step)
+ regional_processor = transformer.installed_processors["transformer_blocks.0.attn.processor"]
+ assert regional_processor.regional_prompting_state.attention_mask is None
+
+
+def test_run_diffusion_sizes_regional_masks_per_pass_when_cfg_lengths_differ(monkeypatch, tmp_path) -> None:
+ # The positive and negative prompts tokenize independently, so each pass needs a mask sized for its own
+ # text sequence. A mask carried over from the other pass would trip the processor's shape guard.
+ _patch_runtime(monkeypatch)
+ transformer = _Transformer()
+ invocation = _runtime_invocation(cfg_scale=2.0)
+ invocation.positive_conditioning = Krea2ConditioningField(
+ conditioning_name="positive", mask=TensorField(tensor_name="positive-region")
+ )
+ invocation.negative_conditioning = Krea2ConditioningField(
+ conditioning_name="negative", mask=TensorField(tensor_name="negative-region")
+ )
+
+ invocation._run_diffusion(_runtime_context(tmp_path, transformer, negative_text_seq_len=5))
+
+ # width=height=16 -> 2x2 latent -> a single 2x2 patch, so image_seq_len is 1.
+ assert transformer.combined_sequence_lengths == [3, 6, 3, 6]
+ assert [tuple(mask.shape) for mask in transformer.regional_attention_masks] == [(3, 3), (6, 6), (3, 3), (6, 6)]
+ for mask, sequence_length in zip(
+ transformer.regional_attention_masks, transformer.combined_sequence_lengths, strict=True
+ ):
+ assert mask.shape == (sequence_length, sequence_length)
+
+
+def test_run_diffusion_releases_regional_mask_when_transformer_raises(monkeypatch, tmp_path) -> None:
+ _patch_runtime(monkeypatch)
+
+ class _FailingTransformer(_Transformer):
+ def __call__(self, **kwargs):
+ super().__call__(**kwargs)
+ raise RuntimeError("transformer failure")
+
+ transformer = _FailingTransformer()
+ invocation = _runtime_invocation(cfg_scale=1.0)
+ invocation.positive_conditioning = Krea2ConditioningField(
+ conditioning_name="positive", mask=TensorField(tensor_name="positive-region")
+ )
+
+ with pytest.raises(RuntimeError, match="transformer failure"):
+ invocation._run_diffusion(_runtime_context(tmp_path, transformer))
+
+ regional_processor = transformer.installed_processors["transformer_blocks.0.attn.processor"]
+ assert regional_processor.regional_prompting_state.attention_mask is None
+
+
def test_run_diffusion_reaches_masked_denoising_merge(monkeypatch, tmp_path) -> None:
_patch_runtime(monkeypatch)
transformer = _Transformer()
@@ -432,6 +543,8 @@ def test_run_diffusion_uses_per_prompt_position_ids_when_lengths_differ(monkeypa
image_seq_len = 1 # width=height=16 -> 2x2 latent -> a single 2x2 patch
class _PositionIdChecker:
+ attn_processors = {"transformer_blocks.0.attn.processor": object()}
+
def set_attn_processor(self, processor) -> None:
pass
@@ -617,3 +730,30 @@ def test_estimate_working_memory_accounts_for_the_longest_text_conditioning() ->
assert long_positive > short_text
assert long_negative == long_positive
+
+
+def test_estimate_working_memory_accounts_for_regional_attention_masks() -> None:
+ inv = Krea2DenoiseInvocation.model_construct(transformer=SimpleNamespace(loras=[]))
+
+ without_regional_masks = inv._estimate_working_memory(
+ image_seq_len=3600, positive_text_seq_len=64, negative_text_seq_len=32, do_cfg=True, num_loras=0
+ )
+ with_regional_masks = inv._estimate_working_memory(
+ image_seq_len=3600,
+ positive_text_seq_len=64,
+ negative_text_seq_len=32,
+ do_cfg=True,
+ num_loras=0,
+ regional_attention_mask_bytes=1234,
+ )
+
+ assert with_regional_masks == without_regional_masks + 1234
+
+
+def test_regional_attention_memory_includes_masks_build_scratch_and_dtype_sized_attention_bias() -> None:
+ positive = SimpleNamespace(attention_mask_numel=120, attention_mask_build_scratch_numel=40)
+ negative = SimpleNamespace(attention_mask_numel=100, attention_mask_build_scratch_numel=40)
+
+ assert Krea2DenoiseInvocation._regional_attention_mask_bytes(positive, negative, torch.bfloat16) == 500
+ assert Krea2DenoiseInvocation._regional_attention_mask_bytes(positive, negative, torch.float32) == 740
+ assert Krea2DenoiseInvocation._regional_attention_mask_bytes(positive, None, torch.bfloat16) == 400
diff --git a/tests/app/invocations/test_krea2_enhancers.py b/tests/app/invocations/test_krea2_enhancers.py
index 7bd617618d..4eb5c4ac5d 100644
--- a/tests/app/invocations/test_krea2_enhancers.py
+++ b/tests/app/invocations/test_krea2_enhancers.py
@@ -11,7 +11,7 @@ from types import SimpleNamespace
import pytest
import torch
-from invokeai.app.invocations.fields import Krea2ConditioningField
+from invokeai.app.invocations.fields import Krea2ConditioningField, TensorField
from invokeai.app.invocations.krea2_conditioning_rebalance import Krea2ConditioningRebalanceInvocation
from invokeai.app.invocations.krea2_seed_variance import Krea2SeedVarianceInvocation
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData, Krea2ConditioningInfo
@@ -125,6 +125,19 @@ def test_rebalance_applies_overall_multiplier() -> None:
assert torch.allclose(_saved_embeds(saved), torch.full((1, 1, 12, 2), 3.0))
+def test_rebalance_preserves_the_regional_mask() -> None:
+ regional_mask = TensorField(tensor_name="regional-mask")
+ invocation = Krea2ConditioningRebalanceInvocation.model_construct(
+ conditioning=Krea2ConditioningField(conditioning_name="c", mask=regional_mask),
+ per_layer_weights=",".join(["1.0"] * 12),
+ multiplier=1.0,
+ )
+
+ output = invocation.invoke(_make_context(torch.ones(1, 1, 12, 2), {}))
+
+ assert output.conditioning.mask == regional_mask
+
+
# The noise magnitude is auto-calibrated to the embedding std, so tests must use a non-constant tensor
# (a constant tensor has std 0 and would produce no noise at all).
def _ramp_embeds() -> torch.Tensor:
@@ -212,10 +225,11 @@ def test_seed_variance_scales_noise_with_embedding_std() -> None:
def test_seed_variance_is_a_noop_when_disabled() -> None:
embeds = _ramp_embeds()
+ regional_mask = TensorField(tensor_name="regional-mask")
for strength, percent in ((0.0, 50.0), (0.5, 0.0)):
saved: dict = {}
out = Krea2SeedVarianceInvocation.model_construct(
- conditioning=Krea2ConditioningField(conditioning_name="c"),
+ conditioning=Krea2ConditioningField(conditioning_name="c", mask=regional_mask),
strength=strength,
randomize_percent=percent,
variance_seed=3,
@@ -223,3 +237,18 @@ def test_seed_variance_is_a_noop_when_disabled() -> None:
# Nothing saved, and the output points back at the untouched input conditioning.
assert saved == {}
assert out.conditioning.conditioning_name == "c"
+ assert out.conditioning.mask == regional_mask
+
+
+def test_seed_variance_preserves_the_regional_mask_when_enabled() -> None:
+ regional_mask = TensorField(tensor_name="regional-mask")
+ invocation = Krea2SeedVarianceInvocation.model_construct(
+ conditioning=Krea2ConditioningField(conditioning_name="c", mask=regional_mask),
+ strength=0.5,
+ randomize_percent=50.0,
+ variance_seed=3,
+ )
+
+ output = invocation.invoke(_make_context(_ramp_embeds(), {}))
+
+ assert output.conditioning.mask == regional_mask
diff --git a/tests/app/invocations/test_krea2_text_encoder.py b/tests/app/invocations/test_krea2_text_encoder.py
index 7fc7f733c4..c268671373 100644
--- a/tests/app/invocations/test_krea2_text_encoder.py
+++ b/tests/app/invocations/test_krea2_text_encoder.py
@@ -4,6 +4,7 @@ from types import SimpleNamespace
import pytest
import torch
+from invokeai.app.invocations.fields import TensorField
from invokeai.app.invocations.krea2_text_encoder import Krea2TextEncoderInvocation
from invokeai.app.invocations.model import LoRAField, ModelIdentifierField, Qwen3VLEncoderField
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType, SubModelType
@@ -328,3 +329,19 @@ def test_encode_uses_reference_fixed_length_layout_and_position_ids(monkeypatch)
assert captured["attention_mask"].dtype == torch.bool
assert captured["position_ids"].shape == (3, 1, 546)
assert captured["position_ids"][0, 0, -5:].tolist() == [4, 5, 6, 7, 8]
+
+
+def test_invoke_preserves_the_regional_mask_on_its_conditioning_output(monkeypatch) -> None:
+ regional_mask = TensorField(tensor_name="regional-mask")
+ invocation = _invocation().model_copy(update={"mask": regional_mask})
+ monkeypatch.setattr(
+ invocation,
+ "_encode",
+ lambda _context: (torch.zeros(1, 2, 12, 4), torch.ones(1, 2, dtype=torch.bool)),
+ )
+ context = SimpleNamespace(conditioning=SimpleNamespace(save=lambda _data: "conditioning-name"))
+
+ output = invocation.invoke(context)
+
+ assert output.conditioning.conditioning_name == "conditioning-name"
+ assert output.conditioning.mask == regional_mask
diff --git a/tests/backend/krea2/test_attention.py b/tests/backend/krea2/test_attention.py
index e15243a345..9b0d8e7b22 100644
--- a/tests/backend/krea2/test_attention.py
+++ b/tests/backend/krea2/test_attention.py
@@ -1,7 +1,10 @@
+import pytest
import torch
from diffusers.models.transformers.transformer_krea2 import Krea2Attention, Krea2AttnProcessor
+from torch.nn.attention import SDPBackend
-from invokeai.backend.krea2.attention import Krea2MemoryEfficientAttnProcessor
+import invokeai.backend.krea2.attention as krea2_attention
+from invokeai.backend.krea2.attention import Krea2MemoryEfficientAttnProcessor, Krea2RegionalPromptingState
def _build_gqa_attention() -> Krea2Attention:
@@ -43,3 +46,78 @@ def test_memory_efficient_processor_handles_equal_head_counts() -> None:
out_efficient = attn(hidden_states, attention_mask=None, image_rotary_emb=None)
assert torch.allclose(out_stock, out_efficient, atol=1e-4, rtol=1e-4)
+
+
+def test_regional_state_matches_stock_processor_with_a_dense_attention_mask() -> None:
+ attn = _build_gqa_attention()
+ hidden_states = torch.randn(1, 24, attn.hidden_size)
+ mask = torch.tril(torch.ones(24, 24, dtype=torch.bool))
+ state = Krea2RegionalPromptingState(attention_mask=mask)
+
+ with torch.no_grad():
+ attn.set_processor(Krea2AttnProcessor())
+ out_stock = attn(hidden_states, attention_mask=mask, image_rotary_emb=None)
+ attn.set_processor(Krea2MemoryEfficientAttnProcessor(regional_prompting_state=state))
+ out_regional = attn(hidden_states, attention_mask=None, image_rotary_emb=None)
+
+ assert torch.allclose(out_stock, out_regional, atol=1e-4, rtol=1e-4)
+
+
+def test_regional_state_rejects_a_mask_sized_for_a_different_conditioning() -> None:
+ # The positive and negative conditionings can tokenize to different lengths, so each denoise pass must
+ # install its own mask. If the wrong mask is left on the shared state the processor must fail loudly
+ # rather than broadcast a mismatched mask into attention.
+ attn = _build_gqa_attention()
+ hidden_states = torch.randn(1, 24, attn.hidden_size)
+ state = Krea2RegionalPromptingState(attention_mask=torch.ones(20, 20, dtype=torch.bool))
+ attn.set_processor(Krea2MemoryEfficientAttnProcessor(regional_prompting_state=state))
+
+ with pytest.raises(ValueError, match=r"\(20, 20\) does not match the transformer sequence length 24"):
+ attn(hidden_states, attention_mask=None, image_rotary_emb=None)
+
+
+def test_processor_without_regional_state_ignores_the_shared_mask() -> None:
+ # Odd-numbered main blocks are built with regional_prompting_state=None so they stay unrestricted. Setting
+ # a mask on the shared state must not leak into them.
+ attn = _build_gqa_attention()
+ hidden_states = torch.randn(1, 24, attn.hidden_size)
+ state = Krea2RegionalPromptingState(attention_mask=torch.block_diag(*[torch.ones(12, 12, dtype=torch.bool)] * 2))
+
+ with torch.no_grad():
+ attn.set_processor(Krea2MemoryEfficientAttnProcessor(regional_prompting_state=None))
+ out_unrestricted = attn(hidden_states, attention_mask=None, image_rotary_emb=None)
+ attn.set_processor(Krea2MemoryEfficientAttnProcessor(regional_prompting_state=state))
+ out_restricted = attn(hidden_states, attention_mask=None, image_rotary_emb=None)
+
+ # Sanity check that the mask is strong enough to change the result at all, then that the unrestricted
+ # processor is unaffected by it.
+ assert not torch.allclose(out_unrestricted, out_restricted, atol=1e-4, rtol=1e-4)
+ with torch.no_grad():
+ attn.set_processor(Krea2MemoryEfficientAttnProcessor())
+ out_no_state = attn(hidden_states, attention_mask=None, image_rotary_emb=None)
+ assert torch.equal(out_unrestricted, out_no_state)
+
+
[email protected](not torch.cuda.is_available(), reason="CUDA is required to exercise fused SDPA")
+def test_cuda_memory_efficient_sdpa_accepts_dense_regional_mask(monkeypatch: pytest.MonkeyPatch) -> None:
+ attn = _build_gqa_attention().to(device="cuda", dtype=torch.float16)
+ hidden_states = torch.randn(1, 24, attn.hidden_size, device="cuda", dtype=torch.float16)
+ mask = torch.block_diag(
+ torch.ones(12, 12, device="cuda", dtype=torch.bool),
+ torch.ones(12, 12, device="cuda", dtype=torch.bool),
+ )
+ state = Krea2RegionalPromptingState(attention_mask=mask)
+ monkeypatch.setattr(krea2_attention, "_KREA2_SDPA_BACKENDS", [SDPBackend.EFFICIENT_ATTENTION])
+
+ head_dim = attn.hidden_size // attn.num_heads
+ sdpa_tensor = torch.empty(1, attn.num_heads, 24, head_dim, device="cuda", dtype=torch.float16)
+ sdpa_params = torch.backends.cuda.SDPAParams(sdpa_tensor, sdpa_tensor, sdpa_tensor, mask, 0.0, False, False)
+ if not torch.backends.cuda.can_use_efficient_attention(sdpa_params):
+ pytest.skip("This CUDA device/build does not support dense masks with memory-efficient SDPA")
+
+ with torch.no_grad():
+ attn.set_processor(Krea2MemoryEfficientAttnProcessor(regional_prompting_state=state))
+ output = attn(hidden_states, attention_mask=None, image_rotary_emb=None)
+
+ assert output.is_cuda
+ assert torch.isfinite(output).all()
diff --git a/tests/backend/krea2/test_regional_prompting.py b/tests/backend/krea2/test_regional_prompting.py
new file mode 100644
index 0000000000..3d68d25178
--- /dev/null
+++ b/tests/backend/krea2/test_regional_prompting.py
@@ -0,0 +1,242 @@
+import pytest
+import torch
+from diffusers.models.transformers.transformer_krea2 import Krea2Transformer2DModel
+
+from invokeai.backend.krea2.attention import (
+ Krea2RegionalPromptingState,
+ build_krea2_attention_processors,
+)
+from invokeai.backend.krea2.regional_prompting import (
+ Krea2RegionalPromptingExtension,
+ Krea2TextConditioning,
+)
+from invokeai.backend.krea2.sampling_utils import prepare_position_ids
+
+
+def _conditioning(length: int, value: float, mask: torch.Tensor | None = None) -> Krea2TextConditioning:
+ return Krea2TextConditioning(prompt_embeds=torch.full((1, length, 12, 8), value), mask=mask)
+
+
+def test_no_regional_masks_concatenates_conditionings_without_allocating_an_attention_mask() -> None:
+ extension = Krea2RegionalPromptingExtension.from_text_conditionings(
+ [_conditioning(2, 1.0), _conditioning(3, 2.0)],
+ image_seq_len=4,
+ )
+
+ regional = extension.regional_text_conditioning
+ assert regional.prompt_embeds.shape == (1, 5, 12, 8)
+ assert [(item.start, item.end) for item in regional.embedding_ranges] == [(0, 2), (2, 5)]
+ assert extension.attention_mask_numel == 0
+ assert extension.attention_mask_build_scratch_numel == 0
+ assert extension.get_attention_mask() is None
+
+
+def test_restricted_attention_mask_matches_flux_style_region_semantics() -> None:
+ # Sequence: [global text, regional text, region image token, background image token].
+ region_mask = torch.tensor([[[1.0, 0.0]]])
+ extension = Krea2RegionalPromptingExtension.from_text_conditionings(
+ [_conditioning(1, 1.0), _conditioning(1, 2.0, region_mask)],
+ image_seq_len=2,
+ )
+
+ assert extension.attention_mask_numel == 16
+ assert extension.attention_mask_build_scratch_numel == 4
+ mask = extension.get_attention_mask()
+ assert mask is not None
+ assert mask.dtype == torch.bool
+ assert torch.equal(
+ mask,
+ torch.tensor(
+ [
+ [True, False, False, True],
+ [False, True, True, False],
+ [False, True, True, True],
+ [True, False, True, True],
+ ]
+ ),
+ )
+ assert bool(mask.any(dim=1).all())
+
+
+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]]])
+ extension = Krea2RegionalPromptingExtension.from_text_conditionings(
+ [_conditioning(1, 1.0, left_mask), _conditioning(1, 2.0, right_mask)],
+ image_seq_len=2,
+ )
+
+ mask = extension.get_attention_mask()
+ assert mask is not None
+ # Regional text/image cross-attention remains local.
+ assert mask[0, 2] and mask[2, 0]
+ assert mask[1, 3] and mask[3, 1]
+ assert not mask[0, 3] and not mask[3, 0]
+ assert not mask[1, 2] and not mask[2, 1]
+ # With no background, image self-attention is restricted to each region.
+ assert mask[2, 2] and mask[3, 3]
+ assert not mask[2, 3] and not mask[3, 2]
+
+
+def test_global_conditioning_applies_image_wide_when_regions_cover_the_full_image() -> None:
+ left_mask = torch.tensor([[[1.0, 0.0]]])
+ right_mask = torch.tensor([[[0.0, 1.0]]])
+ extension = Krea2RegionalPromptingExtension.from_text_conditionings(
+ [
+ _conditioning(1, 1.0),
+ _conditioning(1, 2.0, left_mask),
+ _conditioning(1, 3.0, right_mask),
+ ],
+ image_seq_len=2,
+ )
+
+ mask = extension.get_attention_mask()
+ assert mask is not None
+ # With no uncovered background, the unmasked/global conditioning falls back to the full image.
+ assert bool(mask[0, 3:].all())
+ assert bool(mask[3:, 0].all())
+ # Regional text and image self-attention remain isolated.
+ assert mask[1, 3] and not mask[1, 4]
+ assert mask[2, 4] and not mask[2, 3]
+ assert not mask[3, 4] and not mask[4, 3]
+
+
+def test_preprocess_mask_resizes_thresholds_and_flattens() -> None:
+ raw_mask = torch.tensor(
+ [
+ [1.0, 1.0, 0.0, 0.0],
+ [1.0, 1.0, 0.0, 0.0],
+ [1.0, 1.0, 0.0, 0.0],
+ [1.0, 1.0, 0.0, 0.0],
+ ]
+ )
+
+ mask = Krea2RegionalPromptingExtension.preprocess_regional_prompt_mask(
+ mask=raw_mask,
+ grid_height=2,
+ grid_width=2,
+ dtype=torch.float32,
+ device=torch.device("cpu"),
+ )
+
+ assert mask.shape == (1, 1, 4)
+ assert torch.equal(mask.view(2, 2), torch.tensor([[1.0, 0.0], [1.0, 0.0]]))
+
+
+def test_preprocess_mask_rejects_an_unsupported_mask_rank() -> None:
+ # Workflow users can wire any tensor into the encoder's mask input; an unusable rank must be rejected
+ # with a clear error instead of silently reshaping into a wrong region.
+ with pytest.raises(ValueError, match="Unsupported mask shape"):
+ Krea2RegionalPromptingExtension.preprocess_regional_prompt_mask(
+ mask=torch.ones(1, 3, 4, 4),
+ grid_height=2,
+ grid_width=2,
+ dtype=torch.float32,
+ device=torch.device("cpu"),
+ )
+
+
+def _tiny_transformer() -> Krea2Transformer2DModel:
+ return Krea2Transformer2DModel(
+ in_channels=4,
+ num_layers=3,
+ attention_head_dim=8,
+ num_attention_heads=2,
+ num_key_value_heads=1,
+ intermediate_size=16,
+ timestep_embed_dim=8,
+ text_hidden_dim=16,
+ num_text_layers=2,
+ text_num_attention_heads=2,
+ text_num_key_value_heads=2,
+ text_intermediate_size=16,
+ num_layerwise_text_blocks=1,
+ num_refiner_text_blocks=1,
+ axes_dims_rope=(2, 2, 4),
+ )
+
+
+def test_attention_processor_map_applies_regional_state_to_even_main_blocks_only() -> None:
+ transformer = _tiny_transformer()
+ state = Krea2RegionalPromptingState()
+
+ processors = build_krea2_attention_processors(transformer, state)
+
+ assert processors.keys() == transformer.attn_processors.keys()
+ assert processors["text_fusion.layerwise_blocks.0.attn.processor"].regional_prompting_state is None
+ assert processors["text_fusion.refiner_blocks.0.attn.processor"].regional_prompting_state is None
+ assert processors["transformer_blocks.0.attn.processor"].regional_prompting_state is state
+ assert processors["transformer_blocks.1.attn.processor"].regional_prompting_state is None
+ assert processors["transformer_blocks.2.attn.processor"].regional_prompting_state is state
+
+
+def test_only_even_main_blocks_apply_the_regional_mask_during_a_forward() -> None:
+ # The processor map is only a wiring detail; this asserts the actual effect during a real forward pass.
+ # Every block's attention input is captured while the mask is installed, then each block's attention is
+ # re-run on that exact input with the mask cleared. Even blocks must change, odd blocks must not.
+ torch.manual_seed(0)
+ transformer = _tiny_transformer().eval()
+ state = Krea2RegionalPromptingState()
+ transformer.set_attn_processor(build_krea2_attention_processors(transformer, state))
+
+ grid_height = grid_width = 2
+ image_seq_len = grid_height * grid_width
+ region_mask = torch.tensor([[[1.0, 1.0, 0.0, 0.0]]])
+
+ # _tiny_transformer uses num_text_layers=2 / text_hidden_dim=16, so it needs its own embedding shape.
+ def _tiny_conditioning(mask: torch.Tensor | None) -> Krea2TextConditioning:
+ return Krea2TextConditioning(prompt_embeds=torch.randn(1, 2, 2, 16), mask=mask)
+
+ extension = Krea2RegionalPromptingExtension.from_text_conditionings(
+ [_tiny_conditioning(None), _tiny_conditioning(region_mask)], image_seq_len=image_seq_len
+ )
+ prompt_embeds = extension.regional_text_conditioning.prompt_embeds
+ state.set_attention_mask(extension.get_attention_mask())
+
+ captured: dict[int, tuple[torch.Tensor, dict, torch.Tensor]] = {}
+
+ def _make_hook(index: int):
+ def _hook(_module, args, kwargs, output):
+ captured[index] = (args[0].detach().clone(), kwargs, output.detach().clone())
+
+ return _hook
+
+ handles = [
+ block.attn.register_forward_hook(_make_hook(index), with_kwargs=True)
+ for index, block in enumerate(transformer.transformer_blocks)
+ ]
+ try:
+ with torch.no_grad():
+ transformer(
+ hidden_states=torch.randn(1, image_seq_len, 4),
+ encoder_hidden_states=prompt_embeds,
+ timestep=torch.tensor([0.5]),
+ position_ids=prepare_position_ids(prompt_embeds.shape[1], grid_height, grid_width, torch.device("cpu")),
+ return_dict=False,
+ )
+ finally:
+ for handle in handles:
+ handle.remove()
+
+ assert set(captured) == {0, 1, 2}
+ state.set_attention_mask(None)
+ for index, (attn_input, attn_kwargs, masked_output) in captured.items():
+ with torch.no_grad():
+ unmasked_output = transformer.transformer_blocks[index].attn(attn_input, **attn_kwargs)
+ if index % 2 == 0:
+ assert not torch.allclose(masked_output, unmasked_output), f"block {index} was not restricted"
+ else:
+ assert torch.equal(masked_output, unmasked_output), f"block {index} should be unrestricted"
+
+
+def test_regional_state_can_switch_between_positive_and_negative_masks() -> None:
+ state = Krea2RegionalPromptingState()
+ positive = torch.eye(4, dtype=torch.bool)
+ negative = ~positive
+
+ state.set_attention_mask(positive)
+ assert state.attention_mask is positive
+ state.set_attention_mask(negative)
+ assert state.attention_mask is negative
+ state.set_attention_mask(None)
+ assert state.attention_mask is None