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: Support multiple conditionings (#9406)

Jonathan802de41e845a
diff --git a/docs/src/content/docs/features/krea-2.mdx b/docs/src/content/docs/features/krea-2.mdx
index 755a8581d4..45e7ad5d63 100644
--- a/docs/src/content/docs/features/krea-2.mdx
+++ b/docs/src/content/docs/features/krea-2.mdx
@@ -1,7 +1,7 @@
---
title: Krea-2
description: Generate images with the Krea-2 text-to-image models (Turbo and Raw), including the GGUF / single-file workflow and the conditioning enhancers.
-lastUpdated: 2026-07-13
+lastUpdated: 2026-07-30
sidebar:
order: 5
---
@@ -65,6 +65,12 @@ transform the text conditioning and are especially useful for the distilled Turb
Both are recorded in image metadata and can be recalled.
+## 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.
+
## LoRA
Krea-2 LoRAs (diffusers PEFT format) are supported and apply to both the transformer and — where the
diff --git a/invokeai/app/invocations/krea2_denoise.py b/invokeai/app/invocations/krea2_denoise.py
index fec604729b..6e799ce231 100644
--- a/invokeai/app/invocations/krea2_denoise.py
+++ b/invokeai/app/invocations/krea2_denoise.py
@@ -56,7 +56,7 @@ KREA2_LATENT_CHANNELS = 16
title="Denoise - Krea-2",
tags=["image", "krea2", "krea-2"],
category="image",
- version="1.0.0",
+ version="1.1.0",
classification=Classification.Prototype,
)
class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
@@ -75,10 +75,10 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
transformer: TransformerField = InputField(
description=FieldDescriptions.krea2_model, input=Input.Connection, title="Transformer"
)
- positive_conditioning: Krea2ConditioningField = InputField(
+ positive_conditioning: Krea2ConditioningField | list[Krea2ConditioningField] = InputField(
description=FieldDescriptions.positive_cond, input=Input.Connection
)
- negative_conditioning: Optional[Krea2ConditioningField] = InputField(
+ negative_conditioning: Krea2ConditioningField | list[Krea2ConditioningField] | None = InputField(
default=None, description=FieldDescriptions.negative_cond, input=Input.Connection
)
# CFG uses the standard formulation (uncond + cfg_scale*(cond-uncond)); cfg_scale <= 1 disables it.
@@ -134,16 +134,42 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
def _load_text_conditioning(
self,
context: InvocationContext,
- conditioning_name: str,
+ conditioning_field: Krea2ConditioningField | list[Krea2ConditioningField],
dtype: torch.dtype,
device: torch.device,
) -> tuple[torch.Tensor, torch.Tensor | None]:
- cond_data = context.conditioning.load(conditioning_name)
- assert len(cond_data.conditionings) == 1
- conditioning = cond_data.conditionings[0]
- assert isinstance(conditioning, Krea2ConditioningInfo)
- conditioning = conditioning.to(dtype=dtype, device=device)
- return conditioning.prompt_embeds, conditioning.prompt_embeds_mask
+ 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] = []
+ for field in conditioning_fields:
+ cond_data = context.conditioning.load(field.conditioning_name)
+ assert len(cond_data.conditionings) == 1
+ conditioning = cond_data.conditionings[0]
+ assert isinstance(conditioning, Krea2ConditioningInfo)
+ conditioning = conditioning.to(dtype=dtype, device=device)
+ embeds = conditioning.prompt_embeds
+ if conditioning.prompt_embeds_mask is not None:
+ mask = conditioning.prompt_embeds_mask.to(device=device, dtype=torch.bool)
+ if mask.shape != embeds.shape[:2]:
+ raise ValueError(
+ f"Krea-2 conditioning mask shape {tuple(mask.shape)} does not match "
+ f"prompt embedding shape {tuple(embeds.shape[:2])}."
+ )
+ valid_token_counts = mask.sum(dim=1)
+ if not torch.equal(valid_token_counts, valid_token_counts[:1].expand_as(valid_token_counts)):
+ raise ValueError("All Krea-2 conditioning batch items must have the same valid token count.")
+ embeds = torch.stack(
+ [batch_embeds[batch_mask] for batch_embeds, batch_mask in zip(embeds, mask, strict=True)]
+ )
+ prompt_embeds.append(embeds)
+
+ # 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
def _get_noise(self, height: int, width: int, dtype: torch.dtype, device: torch.device, seed: int) -> torch.Tensor:
rand_device = "cpu"
@@ -224,7 +250,7 @@ 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.conditioning_name, inference_dtype, device
+ context, self.positive_conditioning, inference_dtype, device
)
latent_height = self.height // LATENT_SCALE_FACTOR
@@ -291,13 +317,13 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
# Load negative conditioning only if at least one active step actually uses CFG. CFG is still
# decided per step below so values at or below 1.0 use the conditional prediction directly.
- has_negative_conditioning = self.negative_conditioning is not None
+ has_negative_conditioning = bool(self.negative_conditioning)
do_cfg = has_negative_conditioning and any(value > 1.0 for value in cfg_scale)
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.conditioning_name, inference_dtype, device
+ context, self.negative_conditioning, inference_dtype, device
)
# Load initial latents (img2img).
@@ -365,6 +391,8 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
# forward OOMs once the LoRA's extra activations are added.
estimated_working_memory = self._estimate_working_memory(
image_seq_len=image_seq_len,
+ positive_text_seq_len=pos_prompt_embeds.shape[1],
+ 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),
)
@@ -449,7 +477,14 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
latents = latents.unsqueeze(2)
return latents
- def _estimate_working_memory(self, image_seq_len: int, do_cfg: bool, num_loras: int) -> int:
+ def _estimate_working_memory(
+ self,
+ image_seq_len: int,
+ positive_text_seq_len: int,
+ negative_text_seq_len: int | None,
+ do_cfg: bool,
+ num_loras: int,
+ ) -> 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
@@ -461,14 +496,16 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
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
- several GB of margin. A fixed base covers the resolution-independent overhead (transient fp8->bf16
- layerwise weight casts, the text-fusion stage, and allocator/reserved-memory slack). LoRA sidecar
+ several GB of margin. Conditional and unconditional passes run sequentially, so peak memory depends
+ on the longer text sequence rather than their sum. A fixed base covers resolution-independent overhead
+ (transient fp8->bf16 layerwise weight casts and allocator/reserved-memory slack). LoRA sidecar
patches add a small extra activation branch per patched layer, so we add a per-LoRA margin.
"""
GB = 1024**3
MB = 1024**2
per_token_bytes = int(0.5 * MB)
- estimated = image_seq_len * per_token_bytes
+ text_seq_len = max(positive_text_seq_len, negative_text_seq_len or 0)
+ estimated = (image_seq_len + text_seq_len) * per_token_bytes
estimated += int(1.5 * GB)
if do_cfg:
# Conditional/unconditional passes are sequential, but the larger combined sequence and extra
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index b79424418d..3fbfbf9c01 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -48876,6 +48876,12 @@
{
"$ref": "#/components/schemas/Krea2ConditioningField"
},
+ {
+ "items": {
+ "$ref": "#/components/schemas/Krea2ConditioningField"
+ },
+ "type": "array"
+ },
{
"type": "null"
}
@@ -48884,13 +48890,20 @@
"description": "Positive conditioning tensor",
"field_kind": "input",
"input": "connection",
- "orig_required": true
+ "orig_required": true,
+ "title": "Positive Conditioning"
},
"negative_conditioning": {
"anyOf": [
{
"$ref": "#/components/schemas/Krea2ConditioningField"
},
+ {
+ "items": {
+ "$ref": "#/components/schemas/Krea2ConditioningField"
+ },
+ "type": "array"
+ },
{
"type": "null"
}
@@ -48900,7 +48913,8 @@
"field_kind": "input",
"input": "connection",
"orig_default": null,
- "orig_required": false
+ "orig_required": false,
+ "title": "Negative Conditioning"
},
"cfg_scale": {
"anyOf": [
@@ -48996,7 +49010,7 @@
"tags": ["image", "krea2", "krea-2"],
"title": "Denoise - Krea-2",
"type": "object",
- "version": "1.0.0",
+ "version": "1.1.0",
"output": {
"$ref": "#/components/schemas/LatentsOutput"
}
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index dfbeaad184..3c391751cc 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -19373,15 +19373,17 @@ export type components = {
*/
transformer?: components["schemas"]["TransformerField"] | null;
/**
+ * Positive Conditioning
* @description Positive conditioning tensor
* @default null
*/
- positive_conditioning?: components["schemas"]["Krea2ConditioningField"] | null;
+ positive_conditioning?: components["schemas"]["Krea2ConditioningField"] | components["schemas"]["Krea2ConditioningField"][] | null;
/**
+ * Negative Conditioning
* @description Negative conditioning tensor
* @default null
*/
- negative_conditioning?: components["schemas"]["Krea2ConditioningField"] | null;
+ negative_conditioning?: components["schemas"]["Krea2ConditioningField"] | components["schemas"]["Krea2ConditioningField"][] | null;
/**
* CFG Scale
* @description Classifier-Free Guidance scale
diff --git a/tests/app/invocations/test_krea2_denoise.py b/tests/app/invocations/test_krea2_denoise.py
index bb86b7ac48..7d4cb7dc59 100644
--- a/tests/app/invocations/test_krea2_denoise.py
+++ b/tests/app/invocations/test_krea2_denoise.py
@@ -166,6 +166,109 @@ def test_get_noise_is_deterministic_and_correctly_shaped() -> None:
assert not torch.equal(noise_a, noise_other)
+def test_load_text_conditioning_concatenates_only_valid_tokens() -> None:
+ invocation = Krea2DenoiseInvocation.model_construct()
+ first_embeds = torch.stack(
+ [
+ torch.full((12, 8), 1.0),
+ torch.full((12, 8), 99.0),
+ torch.full((12, 8), 3.0),
+ ],
+ dim=0,
+ ).unsqueeze(0)
+ conditionings = {
+ "first": ConditioningFieldData(
+ conditionings=[
+ Krea2ConditioningInfo(
+ prompt_embeds=first_embeds,
+ prompt_embeds_mask=torch.tensor([[True, False, True]]),
+ )
+ ]
+ ),
+ "second": ConditioningFieldData(
+ conditionings=[Krea2ConditioningInfo(prompt_embeds=torch.full((1, 3, 12, 8), 2.0))]
+ ),
+ }
+ context = SimpleNamespace(conditioning=SimpleNamespace(load=lambda name: conditionings[name]))
+
+ prompt_embeds, prompt_mask = invocation._load_text_conditioning(
+ context=context,
+ conditioning_field=[
+ Krea2ConditioningField(conditioning_name="first"),
+ Krea2ConditioningField(conditioning_name="second"),
+ ],
+ dtype=torch.float32,
+ device=torch.device("cpu"),
+ )
+
+ 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
+
+
+def test_load_text_conditioning_compacts_a_single_masked_conditioning() -> None:
+ invocation = Krea2DenoiseInvocation.model_construct()
+ embeds = torch.arange(4 * 12 * 8, dtype=torch.float32).reshape(1, 4, 12, 8)
+ conditionings = {
+ "prompt": ConditioningFieldData(
+ conditionings=[
+ Krea2ConditioningInfo(
+ prompt_embeds=embeds,
+ prompt_embeds_mask=torch.tensor([[True, False, True, False]]),
+ )
+ ]
+ )
+ }
+ context = SimpleNamespace(conditioning=SimpleNamespace(load=lambda name: conditionings[name]))
+
+ prompt_embeds, prompt_mask = invocation._load_text_conditioning(
+ context=context,
+ conditioning_field=Krea2ConditioningField(conditioning_name="prompt"),
+ dtype=torch.float32,
+ device=torch.device("cpu"),
+ )
+
+ assert torch.equal(prompt_embeds, embeds[:, [0, 2]])
+ assert prompt_mask is None
+
+
+def test_load_text_conditioning_preserves_none_when_all_masks_are_none() -> None:
+ invocation = Krea2DenoiseInvocation.model_construct()
+ conditionings = {
+ "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]))
+
+ prompt_embeds, prompt_mask = invocation._load_text_conditioning(
+ context=context,
+ conditioning_field=[
+ Krea2ConditioningField(conditioning_name="first"),
+ Krea2ConditioningField(conditioning_name="second"),
+ ],
+ dtype=torch.float32,
+ device=torch.device("cpu"),
+ )
+
+ assert prompt_embeds.shape == (1, 5, 12, 8)
+ assert prompt_mask is None
+
+
+def test_load_text_conditioning_rejects_an_empty_collection() -> None:
+ invocation = Krea2DenoiseInvocation.model_construct()
+ context = SimpleNamespace(conditioning=SimpleNamespace(load=lambda _name: None))
+
+ with pytest.raises(ValueError, match="At least one Krea-2 conditioning is required"):
+ invocation._load_text_conditioning(
+ context=context,
+ conditioning_field=[],
+ dtype=torch.float32,
+ device=torch.device("cpu"),
+ )
+
+
class _Scheduler:
def __init__(self, **_kwargs) -> None:
self.config = SimpleNamespace(num_train_timesteps=1000)
@@ -208,11 +311,18 @@ def _model_identifier() -> ModelIdentifierField:
)
-def _runtime_invocation(*, cfg_scale: float | list[float], with_mask: bool = False) -> Krea2DenoiseInvocation:
+def _runtime_invocation(
+ *,
+ cfg_scale: float | list[float],
+ with_mask: bool = False,
+ negative_conditioning: Krea2ConditioningField | list[Krea2ConditioningField] | None = None,
+) -> Krea2DenoiseInvocation:
return Krea2DenoiseInvocation.model_construct(
transformer=TransformerField(transformer=_model_identifier(), loras=[]),
positive_conditioning=Krea2ConditioningField(conditioning_name="positive"),
- negative_conditioning=Krea2ConditioningField(conditioning_name="negative"),
+ negative_conditioning=negative_conditioning
+ if negative_conditioning is not None
+ else Krea2ConditioningField(conditioning_name="negative"),
cfg_scale=cfg_scale,
width=16,
height=16,
@@ -277,6 +387,19 @@ def test_run_diffusion_applies_mixed_cfg_only_at_enabled_steps(monkeypatch, tmp_
assert transformer.conditioning_values == [1.0, 0.0, 1.0]
+def test_run_diffusion_treats_an_empty_negative_collection_as_absent(monkeypatch, tmp_path) -> None:
+ _patch_runtime(monkeypatch)
+ transformer = _Transformer()
+
+ latents = _runtime_invocation(
+ cfg_scale=2.0,
+ negative_conditioning=[],
+ )._run_diffusion(_runtime_context(tmp_path, transformer))
+
+ assert latents.shape == (1, KREA2_LATENT_CHANNELS, 1, 2, 2)
+ assert transformer.conditioning_values == [1.0, 1.0]
+
+
def test_run_diffusion_reaches_masked_denoising_merge(monkeypatch, tmp_path) -> None:
_patch_runtime(monkeypatch)
transformer = _Transformer()
@@ -463,13 +586,34 @@ def test_estimate_working_memory_stays_within_a_24gb_card_at_high_res() -> None:
transformer_bytes = int(12.3 * GB) # Krea-2-Turbo fp8
# 2560x1440 -> (2560/16) x (1440/16) = 160 x 90 = 14400 image tokens.
- est_hi = inv._estimate_working_memory(image_seq_len=14400, do_cfg=False, num_loras=0)
+ est_hi = inv._estimate_working_memory(
+ image_seq_len=14400, positive_text_seq_len=512, negative_text_seq_len=None, do_cfg=False, num_loras=0
+ )
assert est_hi + transformer_bytes < 24 * GB
# 1280x720 -> 80 x 45 = 3600 image tokens.
- est_lo = inv._estimate_working_memory(image_seq_len=3600, do_cfg=False, num_loras=0)
+ est_lo = inv._estimate_working_memory(
+ image_seq_len=3600, positive_text_seq_len=512, negative_text_seq_len=None, do_cfg=False, num_loras=0
+ )
assert est_lo + transformer_bytes < 24 * GB
# Monotonic in tokens, and a non-trivial (multi-GB) reservation so eviction is actually triggered.
assert est_hi > est_lo
assert est_lo > 1 * GB
+
+
+def test_estimate_working_memory_accounts_for_the_longest_text_conditioning() -> None:
+ inv = Krea2DenoiseInvocation.model_construct(transformer=SimpleNamespace(loras=[]))
+
+ short_text = inv._estimate_working_memory(
+ image_seq_len=3600, positive_text_seq_len=64, negative_text_seq_len=32, do_cfg=True, num_loras=0
+ )
+ long_positive = inv._estimate_working_memory(
+ image_seq_len=3600, positive_text_seq_len=256, negative_text_seq_len=32, do_cfg=True, num_loras=0
+ )
+ long_negative = inv._estimate_working_memory(
+ image_seq_len=3600, positive_text_seq_len=64, negative_text_seq_len=256, do_cfg=True, num_loras=0
+ )
+
+ assert long_positive > short_text
+ assert long_negative == long_positive