Skip to content

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

fix(qwen-image-2-1): load the vision tower only for edits and tighten edit pricing

Alexander Eichhornd0f200e5f9a0
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image-2-1.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image-2-1.mdx
index ecbb119018..8ae96a8bc6 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image-2-1.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image-2-1.mdx
@@ -1,7 +1,7 @@
---
title: Qwen-Image-2.1
description: Generate images with Qwen-Image-2.1 and its 8-step Turbo variant, from the Diffusers folders or a GGUF transformer, including transparent (RGBA) output.
-lastUpdated: 2026-10-17
+lastUpdated: 2026-10-22
sidebar:
order: 8
---
@@ -64,7 +64,9 @@ With a Qwen-Image-2.1 **Diffusers** model, add up to four images with **Add refe
- **Diffusers models only.** Only the encoder that comes with the Diffusers model keeps the Qwen3-VL vision tower, which reads the images. A single-file or GGUF transformer with a standalone encoder does not offer reference images, and on a Diffusers model the references refuse to run while a standalone **Qwen3-VL Encoder** is selected under **Components**; clear it to edit.
- **Size.** Each reference is read at about one megapixel at its own aspect ratio, whatever its size. The generated image takes the size set in the panel; **Use size** on a reference's thumbnail matches it.
- **Transparency.** The encoder sees a transparent reference over white, as the model was trained; its latents keep the transparency.
-- **Memory.** The vision tower adds about 1.1 GB to the Diffusers model's encoder, on every generation with it. Each reference adds about 4,100 tokens to the start of the sequence, which the model keeps for the whole generation: about 2 GB per reference, twice that with **CFG** above 1. Where that would take more than half of the GPU, Invoke reprocesses the references at every step instead of keeping them, which uses less memory but takes noticeably longer. Reading the references also needs encoder memory that grows quickly with their number: about 7 GB beyond its weights for four, so on a 24 GB card part of the encoder then runs from system memory.
+- **At most four.** A graph or API request with more than four references is refused with an error.
+- **Memory.** The encoder's vision tower, about 1.1 GB, is loaded only for generations with references and joins the encoder while it reads them; plain prompts never load it, and the encoder itself is not loaded again when you switch between edits and plain prompts. Each reference adds about 4,100 tokens to the start of the sequence, which the model keeps for the whole generation: about 2 GB per reference, twice that with **CFG** above 1. Where that would take more than half of the GPU, Invoke reprocesses the references at every step instead of keeping them, which uses less memory but takes noticeably longer. Reading the references also needs encoder memory that grows quickly with their number: about 7 GB beyond its weights for four, so on a 24 GB card part of the encoder then runs from system memory.
+- **Reproducing an edit.** Keeping the references and reprocessing them give slightly different images from the same seed, and which one runs depends on the GPU's memory. The image's metadata records which one ran, as `qwen_image_2_1_prefix_kv_cache`: `true` when the references were kept, `false` when they were reprocessed. Generations without references record it too.
### Transparent images
diff --git a/invokeai/app/api/routers/recall_parameters.py b/invokeai/app/api/routers/recall_parameters.py
index 20caef0d1b..f32e18bf00 100644
--- a/invokeai/app/api/routers/recall_parameters.py
+++ b/invokeai/app/api/routers/recall_parameters.py
@@ -65,10 +65,10 @@ class ReferenceImageRecallParameter(BaseModel):
Used for reference images that feed directly into the main model rather
than through a separate IP-Adapter / ControlNet model — for example
- FLUX.2 Klein, FLUX Kontext, and Qwen Image Edit. The receiving frontend
- picks the correct config type (``flux2_reference_image`` /
- ``qwen_image_reference_image`` / ``flux_kontext_reference_image``) based
- on the currently-selected main model.
+ FLUX.2 Klein, FLUX Kontext, Qwen Image Edit and Qwen-Image-2.1. The
+ receiving frontend picks the correct config type (``flux2_reference_image`` /
+ ``qwen_image_reference_image`` / ``qwen_image_2_1_reference_image`` /
+ ``flux_kontext_reference_image``) based on the currently-selected main model.
"""
image_name: str = Field(description="The filename of the reference image in outputs/images")
diff --git a/invokeai/app/invocations/qwen_image_2_1/qwen_image_2_1_denoise.py b/invokeai/app/invocations/qwen_image_2_1/qwen_image_2_1_denoise.py
index 7f69766c47..2fe3dfa4ae 100644
--- a/invokeai/app/invocations/qwen_image_2_1/qwen_image_2_1_denoise.py
+++ b/invokeai/app/invocations/qwen_image_2_1/qwen_image_2_1_denoise.py
@@ -15,12 +15,13 @@ from invokeai.app.invocations.fields import (
Input,
InputField,
LatentsField,
+ MetadataField,
QwenImage21ConditioningField,
WithBoard,
WithMetadata,
)
+from invokeai.app.invocations.metadata_linked import LatentsMetaOutput
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.app.util.startup_utils import log_attention_backends
from invokeai.backend.flux.sampling_utils import clip_timestep_schedule_fractional
@@ -31,13 +32,16 @@ from invokeai.backend.rectified_flow.rectified_flow_inpaint_extension import Rec
from invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateState
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import QwenImage21ConditioningInfo
from invokeai.backend.util.attention import sdpa_score_matrix_bytes
-from invokeai.backend.util.devices import TorchDevice
+from invokeai.backend.util.devices import TorchDevice, device_has_dedicated_vram
from invokeai.backend.util.logging import InvokeAILogger
LATENT_CHANNELS = 64
VAE_SCALE_FACTOR = 16
# One vision-language slot of the transformer's joint sequence covers 2x2 latent tokens.
TOKENS_PER_SLOT = 4
+# The metadata entry that records whether a run kept the prefix KV cache (True) or recomputed the prefix on every
+# step (False).
+PREFIX_CACHE_METADATA_KEY = "qwen_image_2_1_prefix_kv_cache"
logger = InvokeAILogger.get_logger(__name__)
@@ -82,17 +86,18 @@ def check_reference_slots(
"""Refuse references whose latents do not match the prompt's image slots, reference by reference.
Each reference's latents fill one run of the prompt's slots, 2x2 latents per slot, at the slot grid the
- encoder read it at. A mismatch means the prompt was encoded with other images, in another order or at another
- size than the latents: the transformer would place one reference's latents in another's slots.
+ encoder read it at. This catches a different number of references, or one at a different size, than the
+ prompt was encoded with -- including references of different sizes in another order. It cannot tell apart
+ same-size references in another order, or a same-size image swapped for another: the slots carry no identity.
"""
expected = [(h // 2, w // 2) for _, h, w in reference_shapes]
found = list(info.reference_grids)
if found != expected or slot_runs(info.image_pad_mask) != [rows * columns for rows, columns in found]:
raise ValueError(
f"The {prompt} prompt was encoded with {len(found)} reference image(s) ({_describe_grids(found)}), but "
- f"the denoise node received {len(expected)} reference latent(s) ({_describe_grids(expected)}). Encode "
- "each reference with Image to Latents in reference mode, from the same images and in the same order "
- "as the prompts."
+ f"the denoise node received {len(expected)} reference latent(s) ({_describe_grids(expected)}): the "
+ "counts or sizes differ. Encode each reference with Image to Latents in reference mode, from the same "
+ "images and in the same order as the prompts."
)
@@ -102,8 +107,14 @@ def prefix_length(info: QwenImage21ConditioningInfo) -> int:
return info.prompt_embeds.shape[1] + (TOKENS_PER_SLOT - 1) * slots
-# K and V of one prefix token in all 32 blocks: 2 x 4096 x 32 x 2 bytes in bf16.
-KV_BYTES_PER_PREFIX_TOKEN = 2 * 4096 * 32 * 2
+def kv_bytes_per_prefix_token(transformer: torch.nn.Module, dtype: torch.dtype) -> int:
+ """K and V of one prefix token in every block of `transformer`, in the compute dtype the caches are kept in.
+
+ 2 x 4096 x 32 x 2 bytes for the released model in bf16 (32 heads of 128, 32 blocks): 0.5 MiB.
+ """
+ config = transformer.config
+ hidden = config.num_attention_heads * config.attention_head_dim
+ return 2 * hidden * len(transformer.transformer_blocks) * dtype.itemsize
def prefix_cache_fits(cache_bytes: int, device: torch.device) -> bool:
@@ -112,11 +123,41 @@ def prefix_cache_fits(cache_bytes: int, device: torch.device) -> bool:
They cannot be offloaded the way the transformer's weights can, so caches larger than half the card would
leave too little for the model however it streams: four references at CFG above 1 hold ~16 GiB. Past that the
prefix is recomputed every step instead -- slower, but within the memory of an ordinary run. Memory that is
- not a dedicated card's (CPU, MPS) is not limited here.
+ not a dedicated card's (CPU, MPS, an integrated XPU) is not limited here, nor a card that reports no size.
"""
- if device.type != "cuda":
+ if not device_has_dedicated_vram(device):
return True
- return cache_bytes <= torch.cuda.get_device_properties(device).total_memory // 2
+ backend = torch.xpu if device.type == "xpu" else torch.cuda
+ total = int(backend.get_device_properties(device).total_memory)
+ return total == 0 or cache_bytes <= total // 2
+
+
+def prefix_segments(info: QwenImage21ConditioningInfo) -> list[int]:
+ """The prefix's blocks in the joint sequence, in order: each run of text, and each reference widened to 2x2
+ latents per slot. The prefill attends each block over every key up to its end."""
+ if info.image_pad_mask is None:
+ return [info.prompt_embeds.shape[1]]
+ return [
+ len(list(run)) * (TOKENS_PER_SLOT if is_slot else 1)
+ for is_slot, run in itertools.groupby(info.image_pad_mask[0].tolist())
+ ]
+
+
+def largest_attention_call(infos: list[QwenImage21ConditioningInfo], image_seq_len: int) -> int:
+ """Queries x keys of the largest attention call a run makes, over every prompt it runs.
+
+ The prefill runs each prefix block over the keys before and in it, and the target over every key; a cached
+ step repeats only the target's call. With large references and a small target, the last reference's call is
+ the largest: four 1 MP references before a 512x512 target make it ~4x the target's.
+ """
+ largest = 0
+ for info in infos:
+ end = 0
+ for length in prefix_segments(info):
+ end += length
+ largest = max(largest, length * end)
+ largest = max(largest, image_seq_len * (end + image_seq_len))
+ return largest
def pack_latents(latents: torch.Tensor) -> torch.Tensor:
@@ -188,12 +229,20 @@ class QwenImage21DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
return value
@torch.no_grad()
- def invoke(self, context: InvocationContext) -> LatentsOutput:
- latents = self._run_diffusion(context).detach().to("cpu")
- name = context.tensors.save(tensor=latents)
+ def invoke(self, context: InvocationContext) -> LatentsMetaOutput:
+ latents, used_prefix_cache = self._run_diffusion(context)
+ name = context.tensors.save(tensor=latents.detach().to("cpu"))
+ # The two modes sample visibly differently in bf16, and which one runs depends on the card's memory: the
+ # image's metadata has to say, or nothing tells why one graph and seed give another image on another card.
+ # A graph routes this output to the node that saves the image.
+ metadata = dict(self.metadata.root) if self.metadata is not None else {}
+ metadata[PREFIX_CACHE_METADATA_KEY] = used_prefix_cache
# `LatentsOutput.build` assumes 8x latents; these are 16x, so report the requested size directly.
- return LatentsOutput(
- latents=LatentsField(latents_name=name, seed=self.seed), width=self.width, height=self.height
+ return LatentsMetaOutput(
+ latents=LatentsField(latents_name=name, seed=self.seed),
+ width=self.width,
+ height=self.height,
+ metadata=MetadataField.model_validate(metadata),
)
def _load_conditioning(
@@ -245,7 +294,8 @@ class QwenImage21DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
)
return mask.to(device=latents.device, dtype=latents.dtype)
- def _run_diffusion(self, context: InvocationContext) -> torch.Tensor:
+ def _run_diffusion(self, context: InvocationContext) -> tuple[torch.Tensor, bool]:
+ """The denoised latents, and whether the prefix KV cache ran (rather than the prefix being recomputed)."""
from diffusers.models.transformers.transformer_qwenimage21 import QwenImage21KVCache
if self.denoising_start >= self.denoising_end:
@@ -350,7 +400,8 @@ class QwenImage21DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
neg_prefix = prefix_length(neg) if neg is not None else None
# Text and reference keys and values do not depend on the step under `causal_condition`: the first step
# prefills them, the rest compute the image tokens only -- when the caches fit.
- cache_bytes = KV_BYTES_PER_PREFIX_TOKEN * (pos_prefix + (neg_prefix or 0))
+ kv_bytes_per_token = kv_bytes_per_prefix_token(transformer_info.model, dtype)
+ cache_bytes = kv_bytes_per_token * (pos_prefix + (neg_prefix or 0))
use_cache = bool(getattr(transformer_info.model.config, "causal_condition", False))
if use_cache and not prefix_cache_fits(cache_bytes, device):
use_cache = False
@@ -359,10 +410,13 @@ class QwenImage21DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
"this GPU; recomputing the prefix every step instead, which is slower."
)
working_memory = self._estimate_working_memory(
- image_seq_len, pos_prefix, neg_prefix, do_cfg, use_cache, dtype.itemsize
+ image_seq_len, pos_prefix, neg_prefix, do_cfg, use_cache, dtype.itemsize, kv_bytes_per_token
)
working_memory += self._attention_score_bytes(
- transformer_info.model, image_seq_len, max(pos_prefix, neg_prefix or 0), device, dtype
+ transformer_info.model,
+ largest_attention_call([pos] if neg is None else [pos, neg], image_seq_len),
+ device,
+ dtype,
)
working_memory += peak_dequant_transient_bytes(transformer_info.model, dtype)
log_attention_backends(logger, device)
@@ -436,7 +490,7 @@ class QwenImage21DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
)
)
- return unpack_latents(latents, latent_height, latent_width).float()
+ return unpack_latents(latents, latent_height, latent_width).float(), use_cache
@staticmethod
def _estimate_working_memory(
@@ -446,15 +500,16 @@ class QwenImage21DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
do_cfg: bool,
use_cache: bool,
element_size: int,
+ kv_bytes_per_token: int,
) -> int:
"""Peak transformer activations, in bytes, for the model cache to keep free.
Measured on an RTX 4090 in bf16 with the transformer fully resident: 0.55 GiB of activations at
1024x1024 (4096 image tokens) and 2.2 GiB at 2048x2048 (16384), about 0.14 MiB per token. 0.25 MiB per
- token plus a 1 GiB base leaves room for the allocator and the prefix cache, which holds K and V of every
- prefix token -- text and reference latents -- in all 32 blocks (~0.5 MiB per token, per guidance branch).
- Both per-token terms are bf16 figures and scale with `element_size`, the compute dtype's width: a
- float32 fallback needs twice as much.
+ token plus a 1 GiB base leaves room for the allocator. That term is a bf16 figure and scales with
+ `element_size`, the compute dtype's width: a float32 fallback needs twice as much. The prefix cache adds
+ `kv_bytes_per_token` (K and V in every block, already in that dtype: 0.5 MiB for the released model in
+ bf16) for every prefix token -- text and reference latents -- per guidance branch.
"""
mib, gib = 1024**2, 1024**3
width = element_size / 2
@@ -463,29 +518,29 @@ class QwenImage21DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
if use_cache:
branches = 2 if do_cfg else 1
prefix_tokens = branches * (pos_prefix if neg_prefix is None else prefix)
- estimated += int(prefix_tokens * KV_BYTES_PER_PREFIX_TOKEN * width)
+ estimated += prefix_tokens * kv_bytes_per_token
return estimated
@staticmethod
- def _attention_score_bytes(
- transformer: object, image_seq_len: int, prefix: int, device: torch.device, dtype: torch.dtype
- ) -> int:
- """The score matrix attention materializes on a build without a fused kernel for it (0 where it has one)."""
+ def _attention_score_bytes(transformer: object, largest_call: int, device: torch.device, dtype: torch.dtype) -> int:
+ """The score matrix attention materializes on a build without a fused kernel for it (0 where it has one).
+
+ `largest_call` is queries x keys of the largest call, from `largest_attention_call`.
+ """
config = getattr(transformer, "config", None)
num_heads = getattr(config, "num_attention_heads", None)
head_dim = getattr(config, "attention_head_dim", None)
if not isinstance(num_heads, int) or not isinstance(head_dim, int):
return 0
- # The largest call, the image queries over every key, goes unmasked both in the prefill and on decode steps:
- # only the text segments carry a mask, and they are as short as the prompt. All of them go through diffusers'
- # attention dispatch. Its score matrix is image x (prefix + image), which the square helper prices at the
- # side with the same area.
+ # The largest call is a reference block's or the target's, both unmasked: only the text blocks carry a mask,
+ # and they are as short as the prompt. All of them go through diffusers' attention dispatch. The square
+ # helper prices the call at the side with the same area, rounded up.
return sdpa_score_matrix_bytes(
device=device,
dtype=dtype,
num_heads=num_heads,
head_dim=head_dim,
- seq_len=math.isqrt(image_seq_len * (image_seq_len + prefix)),
+ seq_len=math.isqrt(largest_call - 1) + 1 if largest_call > 0 else 0,
via_diffusers_dispatch=True,
)
diff --git a/invokeai/app/invocations/text_encoder/qwen_image_2_1_text_encoder.py b/invokeai/app/invocations/text_encoder/qwen_image_2_1_text_encoder.py
index 7b59a30b17..31b5384f4b 100644
--- a/invokeai/app/invocations/text_encoder/qwen_image_2_1_text_encoder.py
+++ b/invokeai/app/invocations/text_encoder/qwen_image_2_1_text_encoder.py
@@ -7,13 +7,15 @@ from invokeai.app.invocations.fields import FieldDescriptions, ImageField, Input
from invokeai.app.invocations.model import ModelIdentifierField, Qwen3VLEncoderField
from invokeai.app.invocations.primitives import QwenImage21ConditioningOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
+from invokeai.backend.architectures import FeaturesFacet, require
from invokeai.backend.model_manager.load.model_cache.utils import get_effective_device
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType, SubModelType
from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes
from invokeai.backend.qwen_image_2_1.text_encoding import (
+ attached_vision_tower,
encode_prompt,
- has_vision_tower,
sequence_length,
+ vision_attention_bytes,
working_memory_bytes,
)
from invokeai.backend.qwen_image_2_1.vae import to_reference
@@ -51,39 +53,58 @@ class QwenImage21TextEncoderInvocation(BaseInvocation):
)
reference_images: list[ImageField] = InputField(
default=[],
- description="Reference images to edit or draw from, in the order the denoise node receives their latents. "
- "Needs a Qwen-Image-2.1 Diffusers model's own encoder.",
+ description="Reference images to edit or draw from, in the order the denoise node receives their latents, "
+ f"at most {require(BaseModelType.QwenImage21, FeaturesFacet).max_reference_images}. Needs a Qwen-Image-2.1 "
+ "Diffusers model's own encoder.",
)
@torch.no_grad()
def invoke(self, context: InvocationContext) -> QwenImage21ConditioningOutput:
+ max_references = require(BaseModelType.QwenImage21, FeaturesFacet).max_reference_images
+ if len(self.reference_images) > max_references:
+ raise ValueError(
+ f"Qwen-Image-2.1 reads at most {max_references} reference images; this prompt has "
+ f"{len(self.reference_images)}. Remove references until {max_references} remain."
+ )
images = [to_reference(context.images.get_pil(field.image_name)) for field in self.reference_images]
- processor_id = self._processor_identifier(context) if images else None
+ tower_id, processor_id = self._edit_identifiers(context) if images else (None, None)
# The encoder first: loading it evicts unlocked small entries from the RAM cache, which would otherwise drop
- # the tokenizer and processor loaded before it.
+ # the tokenizer, tower and processor loaded after it.
text_encoder_info = context.models.load(self.qwen3_vl_encoder.text_encoder)
tokenizer_info = context.models.load(self.qwen3_vl_encoder.tokenizer)
+ tower_info = context.models.load(tower_id) if tower_id is not None else None
processor_info = context.models.load(processor_id) if processor_id is not None else None
+ if tower_info is not None and tower_info.compute_device != text_encoder_info.compute_device:
+ raise RuntimeError(
+ f"The vision tower runs on {tower_info.compute_device} and the encoder on "
+ f"{text_encoder_info.compute_device}; an edit attaches one to the other, so they need one device."
+ )
+ compute_dtype = TorchDevice.choose_bfloat16_safe_dtype(text_encoder_info.compute_device)
# A GGUF or int8 encoder dequantizes one layer at a time; that transient is the working memory.
- dequant_bytes = peak_dequant_transient_bytes(
- text_encoder_info.model, TorchDevice.choose_bfloat16_safe_dtype(text_encoder_info.compute_device)
+ dequant_bytes = peak_dequant_transient_bytes(text_encoder_info.model, compute_dtype)
+ vision_bytes = (
+ vision_attention_bytes(tower_info.model, images, tower_info.compute_device, compute_dtype)
+ if tower_info is not None
+ else 0
)
- # Before the encoder moves to the GPU: a graph can pair this pipeline's tokenizer with another encoder.
- if images and not has_vision_tower(text_encoder_info.model):
- raise ValueError(_NO_VISION_TOWER)
context.util.signal_progress("Running Qwen3-VL text encoder")
with tokenizer_info as tokenizer:
# Reference images make the sequence long, and its attention grows with the square of it: room the
# model cache has to make, or the driver spills the encode to system memory and it crawls.
- working_memory = dequant_bytes + working_memory_bytes(sequence_length(tokenizer, self.prompt, images))
+ num_tokens = sequence_length(tokenizer, self.prompt, images)
+ working_memory = dequant_bytes + working_memory_bytes(num_tokens, compute_dtype.itemsize, vision_bytes)
+ # The tower locks before the encoder, so the room the encoder reserves is still free once both are on
+ # the device.
with (
processor_info.model_on_device() if processor_info is not None else nullcontext((None, None)) as (
_,
processor,
),
+ tower_info.model_on_device() if tower_info is not None else nullcontext((None, None)) as (_, tower),
text_encoder_info.model_on_device(working_mem_bytes=working_memory) as (_, text_encoder),
+ attached_vision_tower(text_encoder, tower) if tower is not None else nullcontext(),
):
encoding = encode_prompt(
text_encoder,
@@ -102,14 +123,21 @@ class QwenImage21TextEncoderInvocation(BaseInvocation):
name = context.conditioning.save(ConditioningFieldData(conditionings=[conditioning]))
return QwenImage21ConditioningOutput.build(name)
- def _processor_identifier(self, context: InvocationContext) -> ModelIdentifierField:
- """The image processor of the model the tokenizer came from, which has to be a Qwen-Image-2.1 pipeline."""
- tokenizer = self.qwen3_vl_encoder.tokenizer
- config = context.models.get_config(tokenizer)
- if (
- config.base is not BaseModelType.QwenImage21
- or config.type is not ModelType.Main
- or config.format is not ModelFormat.Diffusers
- ):
- raise ValueError(_NO_VISION_TOWER)
- return tokenizer.model_copy(update={"submodel_type": SubModelType.Processor})
+ def _edit_identifiers(self, context: InvocationContext) -> tuple[ModelIdentifierField, ModelIdentifierField]:
+ """The vision tower and the image processor an edit adds, which only a Qwen-Image-2.1 pipeline brings.
+
+ Checked on the configs, before anything loads: a graph can pair a standalone encoder with this pipeline's
+ tokenizer, or the other way round.
+ """
+ for identifier in (self.qwen3_vl_encoder.tokenizer, self.qwen3_vl_encoder.text_encoder):
+ config = context.models.get_config(identifier)
+ if (
+ config.base is not BaseModelType.QwenImage21
+ or config.type is not ModelType.Main
+ or config.format is not ModelFormat.Diffusers
+ ):
+ raise ValueError(_NO_VISION_TOWER)
+ return (
+ self.qwen3_vl_encoder.text_encoder.model_copy(update={"submodel_type": SubModelType.VisionTower}),
+ self.qwen3_vl_encoder.tokenizer.model_copy(update={"submodel_type": SubModelType.Processor}),
+ )
diff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.py
index 5f68261da3..1ba0800730 100644
--- a/invokeai/backend/model_manager/load/load_default.py
+++ b/invokeai/backend/model_manager/load/load_default.py
@@ -51,6 +51,9 @@ _FP8_PROBE_FAILURE_REPORTED: set[str] = set()
# quality, which fp8 rounding degrades. Its tokenizer is listed for symmetry (it is not an nn.Module,
# so casting is a no-op today only by accident).
#
+# The vision tower follows the text encoder it attaches to. It also could not take the cast as it stands:
+# `Qwen3VLModel` casts the pixels to `visual.dtype`, which a cast tower reports as float8.
+#
# Unlike the model-kind rules in `fp8_capability.py`, these are about which *component* of a model is
# being loaded, which no client can see and nothing outside this file asks about.
_FP8_EXCLUDED_SUBMODEL_TYPES: frozenset[SubModelType] = frozenset(
@@ -58,6 +61,7 @@ _FP8_EXCLUDED_SUBMODEL_TYPES: frozenset[SubModelType] = frozenset(
SubModelType.TextEncoder,
SubModelType.TextEncoder2,
SubModelType.TextEncoder3,
+ SubModelType.VisionTower,
SubModelType.Tokenizer,
SubModelType.Tokenizer2,
SubModelType.Tokenizer3,
@@ -342,7 +346,12 @@ class ModelLoader(ModelLoaderBase):
if hasattr(config, "default_settings") and config.default_settings is not None:
if hasattr(config.default_settings, "cpu_only") and config.default_settings.cpu_only is True:
# Only apply CPU execution to text encoder submodels
- if submodel_type in [SubModelType.TextEncoder, SubModelType.TextEncoder2, SubModelType.TextEncoder3]:
+ if submodel_type in [
+ SubModelType.TextEncoder,
+ SubModelType.TextEncoder2,
+ SubModelType.TextEncoder3,
+ SubModelType.VisionTower,
+ ]:
return torch.device("cpu")
# Check if this is a standalone text encoder config with cpu_only field (T5Encoder, Qwen3Encoder, etc.)
diff --git a/invokeai/backend/model_manager/load/model_loaders/qwen_image_2_1.py b/invokeai/backend/model_manager/load/model_loaders/qwen_image_2_1.py
index 08ff7d2999..549ee7f5be 100644
--- a/invokeai/backend/model_manager/load/model_loaders/qwen_image_2_1.py
+++ b/invokeai/backend/model_manager/load/model_loaders/qwen_image_2_1.py
@@ -1,5 +1,7 @@
"""Loaders for Qwen-Image-2.1 main models: diffusers pipelines, single-file and GGUF transformers."""
+import json
+import math
from pathlib import Path
from typing import Any, Optional
@@ -18,6 +20,7 @@ from invokeai.backend.model_manager.load.load_default import ModelLoader, _model
from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistry
from invokeai.backend.model_manager.load.model_loaders.generic_diffusers import GenericDiffusersLoader
from invokeai.backend.model_manager.taxonomy import AnyModel, BaseModelType, ModelFormat, ModelType, SubModelType
+from invokeai.backend.model_manager.util.qwen3_vl import drop_qwen3vl_visual_tower
from invokeai.backend.quantization.fp8_scaled import (
attach_fp8_scales,
cast_state_dict,
@@ -66,10 +69,24 @@ class QwenImage21DiffusersModel(GenericDiffusersLoader):
rather than the declared `Qwen3VLForConditionalGeneration`: the LM head is ~1.2 GiB the encoder never runs,
and `Qwen3VLModel` is what the standalone Qwen3-VL loaders return, so the text encoder node sees one class.
- Unlike those loaders, this one keeps the vision tower (~1.1 GiB): reference images reach the encoder only
- through it, and only this pipeline's encoder carries one into Qwen-Image-2.1.
+ `TextEncoder` drops the vision tower, as the standalone loaders do: text prompts never reach it.
+ `VisionTower` is that tower alone (~1.1 GiB), read from the same folder for edits, which attach it to the
+ cached encoder while they encode. The language model's weights are cached once for both.
"""
+ def get_size_fs(
+ self, config: AnyModelConfig, model_path: Path, submodel_type: Optional[SubModelType] = None
+ ) -> int:
+ if submodel_type is SubModelType.VisionTower:
+ # A few hundred tensors of the encoder's folder, not the folder: reserving its ~17 GB for the tower
+ # would evict models for nothing. Sized at the dtype they load in, whatever the file stores.
+ element_size = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device()).itemsize
+ return sum(
+ math.prod(shape) * element_size
+ for _shard, _key, shape in _vision_tower_tensors(model_path / SubModelType.TextEncoder.value)
+ )
+ return super().get_size_fs(config, model_path, submodel_type)
+
def _load_model(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> AnyModel:
if isinstance(config, Checkpoint_Config_Base):
raise NotImplementedError(
@@ -92,6 +109,11 @@ class QwenImage21DiffusersModel(GenericDiffusersLoader):
dtype = self._torch_dtype_avoiding_float16()
else:
dtype = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device())
+
+ if submodel_type is SubModelType.VisionTower:
+ tower = _load_vision_tower(model_path / SubModelType.TextEncoder.value, dtype)
+ return self._apply_fp8_layerwise_casting(tower, config, submodel_type)
+
repo_variant = config.repo_variant if isinstance(config, Diffusers_Config_Base) else None
variant = repo_variant.value if repo_variant else None
if submodel_type is SubModelType.TextEncoder:
@@ -114,9 +136,65 @@ class QwenImage21DiffusersModel(GenericDiffusersLoader):
else:
raise
+ if submodel_type is SubModelType.TextEncoder:
+ # Text prompts never reach the vision tower; edits load it as `VisionTower` and attach it while they
+ # encode.
+ drop_qwen3vl_visual_tower(result)
+
return self._apply_fp8_layerwise_casting(result, config, submodel_type)
+# The tower's tensors in an encoder folder: `model.visual.*` as `Qwen3VLForConditionalGeneration` saves them (the
+# released pipeline), `visual.*` as `Qwen3VLModel` does.
+_VISION_TOWER_PREFIXES = ("model.visual.", "visual.")
+
+
+def _vision_tower_tensors(folder: Path) -> list[tuple[Path, str, list[int]]]:
+ """(shard, key, shape) of every vision-tower tensor in the folder, read from the headers.
+
+ The shard index names the shards that hold them; without an index, every safetensors file in the folder.
+ """
+ from safetensors import safe_open
+
+ index = folder / "model.safetensors.index.json"
+ if index.exists():
+ weight_map: dict[str, str] = json.loads(index.read_text(encoding="utf-8"))["weight_map"]
+ shards = sorted({folder / shard for key, shard in weight_map.items() if key.startswith(_VISION_TOWER_PREFIXES)})
+ else:
+ shards = sorted(folder.glob("*.safetensors"))
+ tensors = []
+ for shard in shards:
+ with safe_open(shard, framework="pt", device="cpu") as f:
+ for key in f.keys():
+ if key.startswith(_VISION_TOWER_PREFIXES):
+ tensors.append((shard, key, f.get_slice(key).get_shape()))
+ if not tensors:
+ raise ValueError(f"{folder} holds no Qwen3-VL vision tower ({' or '.join(_VISION_TOWER_PREFIXES)} tensors).")
+ return tensors
+
+
+def _load_vision_tower(folder: Path, dtype: torch.dtype) -> torch.nn.Module:
+ """The encoder's vision tower alone, as `Qwen3VLModel.visual` would hold it, without reading the language model."""
+ from safetensors import safe_open
+ from transformers import AutoConfig
+ from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLVisionModel
+
+ vision_config = AutoConfig.from_pretrained(folder, local_files_only=True).vision_config
+ with accelerate.init_empty_weights():
+ tower = Qwen3VLVisionModel._from_config(vision_config, torch_dtype=dtype)
+
+ state_dict: dict[str, torch.Tensor] = {}
+ tensors = _vision_tower_tensors(folder)
+ for shard in sorted({shard for shard, *_ in tensors}):
+ with safe_open(shard, framework="pt", device="cpu") as f:
+ for _shard, key, _shape in (t for t in tensors if t[0] == shard):
+ prefix = next(p for p in _VISION_TOWER_PREFIXES if key.startswith(p))
+ state_dict[key[len(prefix) :]] = f.get_tensor(key).to(dtype)
+ load_state_dict_ignoring_extras(tower, state_dict, source=f"Qwen3-VL vision tower in {folder}", assign=True)
+ reject_incomplete_load(tower, what="Qwen3-VL vision tower")
+ return tower.eval()
+
+
@ModelLoaderRegistry.register(base=BaseModelType.QwenImage21, type=ModelType.Main, format=ModelFormat.Checkpoint)
class QwenImage21CheckpointModel(ModelLoader):
"""Loads a Qwen-Image-2.1 transformer from a single safetensors file.
diff --git a/invokeai/backend/model_manager/taxonomy.py b/invokeai/backend/model_manager/taxonomy.py
index 3a328b436e..4a45c175c5 100644
--- a/invokeai/backend/model_manager/taxonomy.py
+++ b/invokeai/backend/model_manager/taxonomy.py
@@ -123,6 +123,9 @@ class SubModelType(str, Enum):
TextEncoder = "text_encoder"
TextEncoder2 = "text_encoder_2"
TextEncoder3 = "text_encoder_3"
+ # A vision-language encoder's vision tower alone, which the text encoder is loaded without; edits attach it
+ # while they encode, so the language model is cached once. Qwen-Image-2.1 only.
+ VisionTower = "vision_tower"
Tokenizer = "tokenizer"
Tokenizer2 = "tokenizer_2"
Tokenizer3 = "tokenizer_3"
diff --git a/invokeai/backend/qwen_image_2_1/text_encoding.py b/invokeai/backend/qwen_image_2_1/text_encoding.py
index a9f145ef78..bb1a80c7b3 100644
--- a/invokeai/backend/qwen_image_2_1/text_encoding.py
+++ b/invokeai/backend/qwen_image_2_1/text_encoding.py
@@ -1,11 +1,14 @@
"""Qwen-Image-2.1's prompt encoding, as `QwenImage21Pipeline._get_qwen_prompt_embeds` does it."""
-from collections.abc import Sequence
+from collections.abc import Iterator, Sequence
+from contextlib import contextmanager
from typing import NamedTuple
import torch
from PIL import Image
+from invokeai.backend.util.attention import sdpa_score_matrix_bytes
+
SYSTEM_PROMPT = "Comprehend and analyze the provided prompt."
SYSTEM_BLOCK = f"<|im_start|>system\n{SYSTEM_PROMPT}<|im_end|>\n"
# A raw string handed to the tokenizer, not `apply_chat_template`: the two tokenize differently, and the
@@ -14,11 +17,14 @@ T2I_TEMPLATE = SYSTEM_BLOCK + "<|im_start|>user\n{}<|im_end|>\n<|im_start|>assis
IMAGE_PAD = "<|image_pad|>"
# Pixels per side of one vision token: 16px patches, merged 2x2.
_PIXELS_PER_TOKEN = 32
+# The vision tower reads each reference's 16px patches before the 2x2 merge: four per vision token.
+_PATCHES_PER_TOKEN = 4
-# What one encode needs above the weights for a sequence of T tokens, measured on an RTX 4090 (torch 2.13,
+# What one encode needs above the weights for a sequence of T tokens, measured on an RTX 4090 in bf16 (torch 2.13,
# transformers 5.10): ~286 B * T^2 + 224 KiB * T at peak. The quadratic term is the language model's attention,
# which SDPA runs on its math kernel for grouped-query heads; four 1-megapixel references (~4.1k tokens) need
-# ~5.4 GiB. The allocator reserves about a fifth more than it hands out.
+# ~5.4 GiB. Both terms are activations, so they scale with the compute dtype's width. The allocator reserves about
+# a fifth more than it hands out.
_BYTES_PER_TOKEN_PAIR = 286
_BYTES_PER_TOKEN = 224 * 1024
_RESERVED_OVER_ALLOCATED = 1.25
@@ -26,6 +32,10 @@ _RESERVED_OVER_ALLOCATED = 1.25
def format_prompt(prompt: str, num_images: int = 0) -> str:
"""The prompt as the checkpoint was trained on it, with one vision placeholder per reference image first."""
+ if num_images and IMAGE_PAD in prompt:
+ # The processor expands every placeholder into one image's tokens, so a literal one would claim an image
+ # that is not there.
+ raise ValueError(f"A prompt that reads reference images cannot contain {IMAGE_PAD}. Remove it from the prompt.")
placeholders = " ".join(f"<image{i}><|vision_start|>{IMAGE_PAD}<|vision_end|>" for i in range(1, num_images + 1))
# Qwen has no BOS token, so an empty prompt would leave the encoder nothing to read.
return T2I_TEMPLATE.format(placeholders + (prompt or " "))
@@ -40,9 +50,35 @@ def sequence_length(tokenizer, prompt: str, images: Sequence[Image.Image] = ())
return text + sum((w // _PIXELS_PER_TOKEN) * (h // _PIXELS_PER_TOKEN) for w, h in (i.size for i in images))
-def working_memory_bytes(num_tokens: int) -> int:
- """Device memory an encode of `num_tokens` tokens needs above the encoder's weights."""
- return int((_BYTES_PER_TOKEN_PAIR * num_tokens**2 + _BYTES_PER_TOKEN * num_tokens) * _RESERVED_OVER_ALLOCATED)
+def vision_attention_bytes(
+ tower: torch.nn.Module, images: Sequence[Image.Image], device: torch.device, dtype: torch.dtype
+) -> int:
+ """The score matrix the vision tower's attention materializes for the largest reference, 0 where it is fused.
+
+ The tower attends within one image at a time, over its patches: four per vision token, ~4k for 1 megapixel.
+ """
+ if not images:
+ return 0
+ patches = max((w // _PIXELS_PER_TOKEN) * (h // _PIXELS_PER_TOKEN) for w, h in (i.size for i in images))
+ return sdpa_score_matrix_bytes(
+ device=device,
+ dtype=dtype,
+ num_heads=tower.config.num_heads,
+ head_dim=tower.config.hidden_size // tower.config.num_heads,
+ seq_len=_PATCHES_PER_TOKEN * patches,
+ )
+
+
+def working_memory_bytes(num_tokens: int, element_size: int, vision_attention: int = 0) -> int:
+ """Device memory an encode of `num_tokens` tokens needs above the encoder's weights.
+
+ `element_size` is the compute dtype's width. `vision_attention` is the tower's score matrix
+ (`vision_attention_bytes`): the tower runs, and frees it, before the language model starts, so only the larger
+ of the two attention peaks counts.
+ """
+ width = element_size / 2
+ attention = max(_BYTES_PER_TOKEN_PAIR * num_tokens**2 * width, vision_attention)
+ return int((attention + _BYTES_PER_TOKEN * num_tokens * width) * _RESERVED_OVER_ALLOCATED)
def system_prefix_length(tokenizer) -> int:
@@ -61,14 +97,31 @@ def _base_model(text_encoder: torch.nn.Module) -> torch.nn.Module:
def has_vision_tower(text_encoder: torch.nn.Module) -> bool:
- """Whether this encoder can read reference images: only the Qwen-Image-2.1 pipeline's keeps its vision tower.
+ """Whether this encoder can read reference images: whether a vision tower is attached (`attached_vision_tower`).
- The standalone Qwen3-VL loaders replace the tower with an `Identity` rather than deleting it.
+ Every encoder loads with an `Identity` where the tower was.
"""
visual = getattr(_base_model(text_encoder), "visual", None)
return isinstance(visual, torch.nn.Module) and not isinstance(visual, torch.nn.Identity)
+@contextmanager
+def attached_vision_tower(text_encoder: torch.nn.Module, tower: torch.nn.Module) -> Iterator[None]:
+ """Attach the pipeline's vision tower to its cached encoder for one encode.
+
+ The encoder and the tower are separate model-cache entries, so the language model is cached once for text
+ prompts and edits. Both must be locked on the same device for the whole block. Whatever the block does, the
+ encoder leaves it with the module it had, so the cache never holds an encoder with a tower it does not own.
+ """
+ base = _base_model(text_encoder)
+ previous = base.visual
+ base.visual = tower
+ try:
+ yield
+ finally:
+ base.visual = previous
+
+
def on_white(image: Image.Image) -> Image.Image:
"""A reference as the vision encoder reads it: alpha composited over white, as the checkpoint was trained."""
if image.mode != "RGBA":
diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.json
index af354195dc..ef1d9ea1be 100644
--- a/invokeai/frontend/api/openapi.json
+++ b/invokeai/frontend/api/openapi.json
@@ -57786,7 +57786,7 @@
"$ref": "#/components/schemas/PromptTemplateOutput"
},
"qwen_image_2_1_denoise": {
- "$ref": "#/components/schemas/LatentsOutput"
+ "$ref": "#/components/schemas/LatentsMetaOutput"
},
"qwen_image_2_1_i2l": {
"$ref": "#/components/schemas/LatentsOutput"
@@ -96401,7 +96401,7 @@
"type": "object",
"version": "1.1.0",
"output": {
- "$ref": "#/components/schemas/LatentsOutput"
+ "$ref": "#/components/schemas/LatentsMetaOutput"
}
},
"QwenImage21ImageToLatentsInvocation": {
@@ -96877,7 +96877,7 @@
},
"reference_images": {
"default": [],
- "description": "Reference images to edit or draw from, in the order the denoise node receives their latents. Needs a Qwen-Image-2.1 Diffusers model's own encoder.",
+ "description": "Reference images to edit or draw from, in the order the denoise node receives their latents, at most 4. Needs a Qwen-Image-2.1 Diffusers model's own encoder.",
"field_kind": "input",
"input": "any",
"items": {
@@ -99706,7 +99706,7 @@
"type": "object",
"required": ["image_name"],
"title": "ReferenceImageRecallParameter",
- "description": "Global reference-image configuration for recall.\n\nUsed for reference images that feed directly into the main model rather\nthan through a separate IP-Adapter / ControlNet model \u2014 for example\nFLUX.2 Klein, FLUX Kontext, and Qwen Image Edit. The receiving frontend\npicks the correct config type (``flux2_reference_image`` /\n``qwen_image_reference_image`` / ``flux_kontext_reference_image``) based\non the currently-selected main model."
+ "description": "Global reference-image configuration for recall.\n\nUsed for reference images that feed directly into the main model rather\nthan through a separate IP-Adapter / ControlNet model \u2014 for example\nFLUX.2 Klein, FLUX Kontext, Qwen Image Edit and Qwen-Image-2.1. The\nreceiving frontend picks the correct config type (``flux2_reference_image`` /\n``qwen_image_reference_image`` / ``qwen_image_2_1_reference_image`` /\n``flux_kontext_reference_image``) based on the currently-selected main model."
},
"RemoteModelFile": {
"properties": {
@@ -106081,6 +106081,7 @@
"text_encoder",
"text_encoder_2",
"text_encoder_3",
+ "vision_tower",
"tokenizer",
"tokenizer_2",
"tokenizer_3",
diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.ts
index cba788848f..a97d0d0aeb 100644
--- a/invokeai/frontend/api/schema.ts
+++ b/invokeai/frontend/api/schema.ts
@@ -22998,7 +22998,7 @@ export type components = {
pidi_edge_detection: components["schemas"]["ImageOutput"];
prompt_from_file: components["schemas"]["StringCollectionOutput"];
prompt_template: components["schemas"]["PromptTemplateOutput"];
- qwen_image_2_1_denoise: components["schemas"]["LatentsOutput"];
+ qwen_image_2_1_denoise: components["schemas"]["LatentsMetaOutput"];
qwen_image_2_1_i2l: components["schemas"]["LatentsOutput"];
qwen_image_2_1_l2i: components["schemas"]["ImageOutput"];
qwen_image_2_1_model_loader: components["schemas"]["QwenImage21ModelLoaderOutput"];
@@ -41892,7 +41892,7 @@ export type components = {
qwen3_vl_encoder?: components["schemas"]["Qwen3VLEncoderField"] | null;
/**
* Reference Images
- * @description Reference images to edit or draw from, in the order the denoise node receives their latents. Needs a Qwen-Image-2.1 Diffusers model's own encoder.
+ * @description Reference images to edit or draw from, in the order the denoise node receives their latents, at most 4. Needs a Qwen-Image-2.1 Diffusers model's own encoder.
* @default []
*/
reference_images?: components["schemas"]["ImageField"][];
@@ -43354,10 +43354,10 @@ export type components = {
*
* Used for reference images that feed directly into the main model rather
* than through a separate IP-Adapter / ControlNet model — for example
- * FLUX.2 Klein, FLUX Kontext, and Qwen Image Edit. The receiving frontend
- * picks the correct config type (``flux2_reference_image`` /
- * ``qwen_image_reference_image`` / ``flux_kontext_reference_image``) based
- * on the currently-selected main model.
+ * FLUX.2 Klein, FLUX Kontext, Qwen Image Edit and Qwen-Image-2.1. The
+ * receiving frontend picks the correct config type (``flux2_reference_image`` /
+ * ``qwen_image_reference_image`` / ``qwen_image_2_1_reference_image`` /
+ * ``flux_kontext_reference_image``) based on the currently-selected main model.
*/
ReferenceImageRecallParameter: {
/**
@@ -46586,7 +46586,7 @@ export type components = {
* @description Submodel type.
* @enum {string}
*/
- SubModelType: "unet" | "transformer" | "transformer_2" | "text_encoder" | "text_encoder_2" | "text_encoder_3" | "tokenizer" | "tokenizer_2" | "tokenizer_3" | "processor" | "pe" | "pe_tokenizer" | "vae" | "vae_decoder" | "vae_encoder" | "audio_vae" | "vocoder" | "connectors" | "latent_upsampler" | "temporal_latent_upsampler" | "scheduler" | "safety_checker";
+ SubModelType: "unet" | "transformer" | "transformer_2" | "text_encoder" | "text_encoder_2" | "text_encoder_3" | "vision_tower" | "tokenizer" | "tokenizer_2" | "tokenizer_3" | "processor" | "pe" | "pe_tokenizer" | "vae" | "vae_decoder" | "vae_encoder" | "audio_vae" | "vocoder" | "connectors" | "latent_upsampler" | "temporal_latent_upsampler" | "scheduler" | "safety_checker";
/** SubmodelDefinition */
SubmodelDefinition: {
/** Path Or Prefix */
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 6b04ac9322..be79fdeb60 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -2832,6 +2832,7 @@
"referenceImage": "Reference Image",
"referenceImageModel": "Reference image model",
"referenceImages": "Reference images",
+ "referenceImagesNeedFormat": "Reference images need a {{format}} {{base}} model.",
"referenceImagesUnsupported": "Reference images are not supported by the selected model.",
"removeConcept": "Remove concept",
"removeConceptNamed": "Remove {{name}}",
diff --git a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json
index 6d79322aa9..80aac9dfcd 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json
+++ b/invokeai/frontend/webv2/src/features/generation/core/__snapshots__/generateGraphNodeTypes.json
@@ -265,11 +265,14 @@
]
},
"nodeTypes": [
+ "collect",
"core_metadata",
+ "image",
"img_nsfw",
"img_watermark",
"integer",
"qwen_image_2_1_denoise",
+ "qwen_image_2_1_i2l",
"qwen_image_2_1_l2i",
"qwen_image_2_1_model_loader",
"qwen_image_2_1_text_encoder",
@@ -1252,6 +1255,21 @@
"conditioning"
]
},
+ "image": {
+ "inputs": [],
+ "literalInputs": {
+ "image": [],
+ "is_intermediate": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
+ "outputs": [
+ "image"
+ ]
+ },
"img_nsfw": {
"inputs": [
"image"
@@ -1463,13 +1481,17 @@
},
"qwen_image_2_1_denoise": {
"inputs": [
+ "metadata",
+ "negative_conditioning",
"positive_conditioning",
+ "reference_latents",
"seed",
"transformer"
],
"literalInputs": {
"cfg_scale": [
- 1
+ 1,
+ 4
],
"height": [
1024
@@ -1487,6 +1509,27 @@
1024
]
},
+ "outputs": [
+ "latents",
+ "metadata"
+ ]
+ },
+ "qwen_image_2_1_i2l": {
+ "inputs": [
+ "image",
+ "vae"
+ ],
+ "literalInputs": {
+ "is_intermediate": [
+ true
+ ],
+ "reference": [
+ true
+ ],
+ "use_cache": [
+ true
+ ]
+ },
"outputs": [
"latents"
]
@@ -1532,7 +1575,8 @@
"qwen_image_2_1_text_encoder": {
"inputs": [
"prompt",
- "qwen3_vl_encoder"
+ "qwen3_vl_encoder",
+ "reference_images"
],
"literalInputs": {
"is_intermediate": [
diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts
index d0d799bc87..80b62638d1 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.test.ts
@@ -29,6 +29,7 @@ import {
getGenerationUiPolicy,
getGenerationValidationReasons,
getMaxReferenceImages,
+ getMissingReferenceImageFormat,
getPromptPolicy,
getSchedulerOptions,
getSettingsWithModelDefaults,
@@ -1158,6 +1159,20 @@ describe('component policies', () => {
expect(isReferenceImageSupported(createModel('qwen-image-2-1', { format: 'checkpoint' }))).toBe(false);
});
+ // The UI names the missing format only when switching to it would enable references.
+ it('names the format a model lacks for reference images only when the format alone blocks them', () => {
+ expect(getMissingReferenceImageFormat(createModel('qwen-image-2-1', { format: 'gguf_quantized' }))).toBe(
+ 'diffusers'
+ );
+ expect(getMissingReferenceImageFormat(createModel('qwen-image-2-1', { format: 'checkpoint' }))).toBe('diffusers');
+ expect(getMissingReferenceImageFormat(createModel('qwen-image-2-1', { format: 'diffusers' }))).toBeNull();
+ // Qwen-Image needs the Edit variant, not a format; CogView4 takes no references at all.
+ expect(getMissingReferenceImageFormat(createModel('qwen-image', { format: 'gguf_quantized' }))).toBeNull();
+ expect(getMissingReferenceImageFormat(createModel('cogview4', { format: 'gguf_quantized' }))).toBeNull();
+ expect(getMissingReferenceImageFormat(externalModel)).toBeNull();
+ expect(getMissingReferenceImageFormat(undefined)).toBeNull();
+ });
+
it('derives the reference image limit from external provider capabilities', () => {
expect(getMaxReferenceImages(createModel('sdxl'))).toBe(5);
expect(getMaxReferenceImages(createModel('cogview4'))).toBe(0);
diff --git a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
index a97cc615c6..149421d0d2 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/baseGenerationPolicies.ts
@@ -1333,6 +1333,28 @@ export const isReferenceImageSupported = (model: GenerateModelConfig | undefined
);
};
+/**
+ * The model format the selected base needs for reference images, when the model's format is all that keeps them
+ * unavailable, so the UI can say what to switch to instead of hiding the section without a reason.
+ */
+export const getMissingReferenceImageFormat = (model: GenerateModelConfig | undefined): string | null => {
+ if (!model || model.type === 'external_image_generator' || isReferenceImageSupported(model)) {
+ return null;
+ }
+
+ const features = getArchitectureFeatures(model.base);
+
+ if (
+ !features ||
+ features.max_reference_images <= 0 ||
+ (features.reference_images_require_variant !== null && model.variant !== features.reference_images_require_variant)
+ ) {
+ return null;
+ }
+
+ return features.reference_images_require_format;
+};
+
export const getMaxReferenceImages = (model: GenerateModelConfig | undefined): number => {
if (!model || !isReferenceImageSupported(model)) {
return 0;
diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts
index ea3a660c81..5821f83fb2 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts
@@ -712,6 +712,22 @@ describe('compileCanvasGraph — inpaint per base', () => {
expect(metaEdge?.destination.node_id).toBe('canvas_output');
});
+ // Qwen-Image-2.1's denoise adds its cache mode to the record, so the record still passes through it once the blend
+ // takes over the output.
+ it('routes Qwen-Image-2.1 inpaint metadata through the denoise onto the final blend output', () => {
+ const { backendGraph } = compile(qwenImage21Model, 'inpaint');
+ const metadata = getNodeByType(backendGraph, 'core_metadata');
+ const metadataEdges = backendGraph.edges.filter(
+ (edge) => edge.source.field === 'metadata' || edge.destination.field === 'metadata'
+ );
+
+ expect(backendGraph.nodes.canvas_output?.type).toBe('invokeai_img_blend');
+ expect(metadataEdges.map(({ destination, source }) => [source.node_id, destination.node_id])).toEqual([
+ [metadata?.id, 'denoise_latents'],
+ ['denoise_latents', 'canvas_output'],
+ ]);
+ });
+
it('outputs only the generated mask region with transparency when requested', () => {
const { backendGraph } = compile(sd1Model, 'inpaint', { outputOnlyMaskedRegions: true });
diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts
index 625e857b68..679b87ffac 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts
@@ -813,18 +813,18 @@ describe('compileGenerateGraph', () => {
expect(latentImages).toEqual(['a.png', 'b.png']);
});
- it('refuses references with a standalone encoder, which has no vision tower', () => {
- const encoder: ComponentModelConfig = {
- base: 'any',
- key: 'qwen3-vl-8b',
- name: 'Qwen3-VL 8B',
- type: 'qwen3_vl_encoder',
- variant: 'qwen3_vl_8b',
- };
+ // The denoise records whether it reused the prompt's attention cache, which changes the image in bf16.
+ it('passes the image metadata through the denoise to the decoder that saves the image', () => {
+ const graph = compile(qwenImage21Model);
+ const metadata = getNodeByType(graph, 'core_metadata');
+ const metadataEdges = graph.edges.filter(
+ (edge) => edge.source.field === 'metadata' || edge.destination.field === 'metadata'
+ );
- expect(() =>
- compile(qwenImage21Model, { qwen3VLEncoderModel: encoder, referenceImages: references('a.png') })
- ).toThrow(/vision tower/);
+ expect(metadataEdges.map(({ destination, source }) => [source.node_id, destination.node_id])).toEqual([
+ [metadata?.id, 'denoise_latents'],
+ ['denoise_latents', 'canvas_output'],
+ ]);
});
});
});
@@ -1818,7 +1818,10 @@ describe('output filters', () => {
node_id: 'canvas_unfiltered_output',
});
expect(getEdge(graph, 'canvas_output', 'image')?.source).toEqual({ field: 'image', node_id: 'canvas_img_nsfw' });
- expect(getEdge(graph, 'canvas_output', 'metadata')?.source.node_id).toBe(getNodeByType(graph, 'core_metadata')?.id);
+ // Qwen-Image-2.1's denoise adds its cache mode to the record on the way, so the record reaches the result from it.
+ const metadataSource =
+ base === 'qwen-image-2-1' ? 'denoise_latents' : (getNodeByType(graph, 'core_metadata')?.id ?? '');
+ expect(getEdge(graph, 'canvas_output', 'metadata')?.source).toEqual({ field: 'metadata', node_id: metadataSource });
expect(getEdge(graph, 'canvas_unfiltered_output', 'metadata')).toBeUndefined();
});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.ts
index fcf2563b42..c4b0151a21 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/graph.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.ts
@@ -25,7 +25,6 @@ import {
getFlux2DiffusersComponentSource,
getGenerationDimensions,
getGenerationValidationReasons,
- QWEN_IMAGE_21_STANDALONE_ENCODER_REASON,
type SupportedGenerateBase,
} from './baseGenerationPolicies';
import {
@@ -1442,13 +1441,15 @@ const buildQwenImage21Graph = (
addQwenImage21ReferenceImages(graph, settings, {
conditionings: negCond ? [posCond, negCond] : [posCond],
denoise,
- hasStandaloneEncoder: Boolean(qwen3VlEncoderModel),
modelLoader,
});
- addMetadata(graph, output, settings, model, 'qwen_image_2_1_txt2img', projectSettings, {
+ // The denoise adds the prefix-cache mode it ran to the record, which changes the image, so the metadata passes
+ // through it on the way to the decoder.
+ addMetadata(graph, denoise, settings, model, 'qwen_image_2_1_txt2img', projectSettings, {
qwen3_vl_encoder: qwen3VlEncoderModel ?? undefined,
vae: vaeModel ?? undefined,
});
+ addEdge(graph, denoise, 'metadata', output, 'metadata');
addReferenceImageMetadata(graph, output, settings);
return graph;
@@ -1465,7 +1466,6 @@ const addQwenImage21ReferenceImages = (
nodes: {
conditionings: BackendInvocationContract[];
denoise: BackendInvocationContract;
- hasStandaloneEncoder: boolean;
modelLoader: BackendInvocationContract;
}
): void => {
@@ -1473,10 +1473,6 @@ const addQwenImage21ReferenceImages = (
if (referenceImages.length === 0) {
return;
}
- // A backstop: validation reports this before Invoke.
- if (nodes.hasStandaloneEncoder) {
- throw new Error(QWEN_IMAGE_21_STANDALONE_ENCODER_REASON);
- }
let imageCollect: BackendInvocationContract | null = null;
let latentsCollect: BackendInvocationContract | null = null;
diff --git a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.testing.ts b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.testing.ts
index 81e4ec21c2..885e623419 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.testing.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/graphCoverage.testing.ts
@@ -6,11 +6,18 @@ import type {
GenerateComponentValueKey,
SupportedGenerateBase,
} from './baseGenerationPolicies';
-import type { GenerateSettings, MainModelConfig, ModelIdentifierConfig } from './types';
+import type {
+ GenerateReferenceImage,
+ GenerateReferenceImageAsset,
+ GenerateSettings,
+ MainModelConfig,
+ ModelIdentifierConfig,
+} from './types';
import {
getComponentSectionPolicy,
getDefaultGenerateSettings,
+ isReferenceImageSupported,
SUPPORTED_GENERATE_BASES,
} from './baseGenerationPolicies';
import { getIsPidSupportedBase } from './pid';
@@ -210,6 +217,23 @@ export const fullyFilledSettingsFor = (base: SupportedGenerateBase, shape: Model
return { filled: [...allFilled].sort(), model, settings };
};
+/** References for the families whose builders wire them through their own nodes rather than an adapter. */
+const tunedReferenceImagesFor = (
+ model: MainModelConfig,
+ image: GenerateReferenceImageAsset
+): GenerateReferenceImage[] | undefined => {
+ if (model.base === 'krea-2') {
+ return [{ config: { image, styleStrength: 1, type: 'krea2_reference_image' }, id: 'style', isEnabled: true }];
+ }
+
+ // Only the Diffusers pipeline's own encoder reads references; other shapes compile without them.
+ if (model.base === 'qwen-image-2-1' && isReferenceImageSupported(model)) {
+ return [{ config: { image, type: 'qwen_image_2_1_reference_image' }, id: 'edit', isEnabled: true }];
+ }
+
+ return undefined;
+};
+
/**
* The optional per-family tuning and output filters, all switched on, so the backend contract also covers the nodes
* and literal values a default recipe never emits. Settings a family ignores are harmless to carry.
@@ -224,21 +248,14 @@ export const tunedSettingsFor = (base: SupportedGenerateBase, shape: ModelShape)
projectSettings: { useCpuNoise: true, useNsfwChecker: true, useWatermark: true },
settings: {
...settings,
+ // CFG above 1 adds the negative prompt, which Qwen-Image-2.1 also encodes with the references.
+ cfgScale: base === 'qwen-image-2-1' ? 4 : settings.cfgScale,
fluxDypeExponent: 1,
fluxDypePreset: 'manual' as const,
fluxDypeScale: 3,
qwenImageEncoderQuantization: 'nf4' as const,
qwenImageShift: 3,
- referenceImages:
- base === 'krea-2'
- ? [
- {
- config: { image, styleStrength: 1, type: 'krea2_reference_image' as const },
- id: 'style',
- isEnabled: true,
- },
- ]
- : settings.referenceImages,
+ referenceImages: tunedReferenceImagesFor(model, image) ?? settings.referenceImages,
zImageSeedVarianceEnabled: true,
zImageSeedVarianceStrength: 0.2,
zImageShift: 3,
diff --git a/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts b/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts
index f5d373e07d..0f81cc4707 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/settings.test.ts
@@ -191,6 +191,46 @@ describe('normalizeGenerateSettings', () => {
).toBe(false);
});
+ // Qwen-Image-2.1 references are their own flavor, so a stored one must not fold into Qwen-Image Edit's.
+ it('keeps persisted Qwen-Image-2.1 reference images as their own flavor', () => {
+ const normalized = normalizeGenerateSettings({
+ ...legacyStoredValues,
+ referenceImages: [
+ {
+ id: 'edit-1',
+ isEnabled: false,
+ config: {
+ type: 'qwen_image_2_1_reference_image',
+ image: {
+ height: 640,
+ imageName: 'edit.png',
+ imageUrl: '/api/v1/images/i/edit.png/full',
+ queuedAt: '2026-01-01T00:00:00.000Z',
+ sourceQueueItemId: 'backend-gallery',
+ thumbnailUrl: '/api/v1/images/i/edit.png/thumbnail',
+ width: 480,
+ },
+ },
+ },
+ { id: 'empty', isEnabled: true, config: { type: 'qwen_image_2_1_reference_image', image: null } },
+ { id: 'broken', isEnabled: true, config: { type: 'qwen_image_2_1_reference_image', image: { width: 1 } } },
+ ],
+ });
+
+ expect(normalized?.referenceImages).toEqual([
+ {
+ config: {
+ image: { original: { image: { height: 640, image_name: 'edit.png', width: 480 } } },
+ type: 'qwen_image_2_1_reference_image',
+ },
+ id: 'edit-1',
+ isEnabled: false,
+ },
+ { config: { image: null, type: 'qwen_image_2_1_reference_image' }, id: 'empty', isEnabled: true },
+ ]);
+ expect(normalized && isGenerateSettings(normalized)).toBe(true);
+ });
+
it('keeps more than five valid persisted reference images for provider-specific caps', () => {
const referenceImages = Array.from({ length: 6 }, (_, index) => ({
id: `ref-${index}`,
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateGuidanceSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateGuidanceSection.tsx
index 5bc8723152..4043d29380 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateGuidanceSection.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateGuidanceSection.tsx
@@ -2,7 +2,10 @@ import type { GenerationModelCatalogItem as ModelConfig } from '@features/genera
import type { GenerateModelConfig, GenerateSettings, LoraModelConfig } from '@features/generation/core/types';
import { Badge, Separator, Stack } from '@chakra-ui/react';
-import { isReferenceImageSupported } from '@features/generation/core/baseGenerationPolicies';
+import {
+ getMissingReferenceImageFormat,
+ isReferenceImageSupported,
+} from '@features/generation/core/baseGenerationPolicies';
import {
type GenerateDraft,
type GenerateSettingsUpdate,
@@ -85,7 +88,9 @@ export const GenerateGuidanceSection = ({
onCommit={onReferenceCommit}
onCommitImmediate={onCommitImmediate}
/>
- {referenceImagesSupported || referenceImageCount > 0 ? <Separator borderColor="bg.subtle" /> : null}
+ {referenceImagesSupported || referenceImageCount > 0 || getMissingReferenceImageFormat(selectedModel) ? (
+ <Separator borderColor="bg.subtle" />
+ ) : null}
<GenerateConceptsContent
loraModels={loraModels}
loras={settings.loras}
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx
index 5ac47f0b06..94a7923149 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/GenerateReferenceImagesSection.tsx
@@ -19,6 +19,7 @@ import {
getDefaultReferenceImageConfig,
getGenerationDimensions,
getMaxReferenceImages,
+ getMissingReferenceImageFormat,
isReferenceImageSupported,
} from '@features/generation/core/baseGenerationPolicies';
import { generatedImageToReferenceImage, getEffectiveReferenceImage } from '@features/generation/core/referenceImage';
@@ -32,6 +33,8 @@ import { useTranslation } from 'react-i18next';
import { ReferenceImageCard } from './ReferenceImageCard';
const UPLOAD_ZONE_HOVER_STYLES = { bg: 'bg.muted', color: 'fg' };
+/** Display names for the formats the backend can require of reference-image models. */
+const MODEL_FORMAT_LABELS: Record<string, string> = { diffusers: 'Diffusers' };
const IMAGE_ONLY = ['image'] as const;
interface GenerateReferenceImagesContentProps {
@@ -50,8 +53,9 @@ export const GenerateReferenceImagesContent = ({
selectedModel,
}: GenerateReferenceImagesContentProps) => {
const { t } = useTranslation();
- const { gallery } = useGenerationUi();
+ const { gallery, models: modelUi } = useGenerationUi();
const isSupported = isReferenceImageSupported(selectedModel);
+ const missingFormat = getMissingReferenceImageFormat(selectedModel);
const maxReferenceImages = getMaxReferenceImages(selectedModel);
const canAdd = referenceImages.length < maxReferenceImages;
const { acceptsActiveDrag, isOver, setNodeRef } = useGalleryImageDroppable({
@@ -194,8 +198,21 @@ export const GenerateReferenceImagesContent = ({
},
});
+ // A model that only lacks the right format says which one would take references.
+ const unsupportedMessage =
+ selectedModel && missingFormat
+ ? t('widgets.generate.referenceImagesNeedFormat', {
+ base: modelUi.getBaseLabel(selectedModel.base),
+ format: MODEL_FORMAT_LABELS[missingFormat] ?? missingFormat,
+ })
+ : t('widgets.generate.referenceImagesUnsupported');
+
if (!isSupported && referenceImageCount === 0) {
- return null;
+ return missingFormat ? (
+ <Text color="fg.muted" fontSize="xs">
+ {unsupportedMessage}
+ </Text>
+ ) : null;
}
// Unsupported-model references remain read-only with removal as recovery.
@@ -203,7 +220,7 @@ export const GenerateReferenceImagesContent = ({
return (
<HStack gap="2" justify="space-between">
<Text color="fg.muted" fontSize="xs" minW="0">
- {t('widgets.generate.referenceImagesUnsupported')}
+ {unsupportedMessage}
</Text>
<Button colorPalette="red" flexShrink="0" variant="outline" onClick={clearReferenceImages}>
{t('widgets.generate.clearReferenceImages')}
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageFormatHint.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageFormatHint.browser.test.tsx
new file mode 100644
index 0000000000..462c56e71e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/generation/ui/reference-images/referenceImageFormatHint.browser.test.tsx
@@ -0,0 +1,113 @@
+import type { GenerateModelConfig, GenerateReferenceImage } from '@features/generation/core/types';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { DndContext } from '@dnd-kit/core';
+import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';
+import { type GenerationUiAdapter, GenerationUiProvider } from '@features/generation/ui/GenerationUiContext';
+import { system } from '@theme/system';
+import i18next from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { GenerateReferenceImagesContent } from './GenerateReferenceImagesSection';
+
+/** A model that only lacks the right format explains why the reference section is gone; other models stay silent. */
+const i18n = i18next.createInstance();
+// The shipped copy, so a change to the hint's wording or placeholders fails here.
+await i18n.use(initReactI18next).init({
+ fallbackLng: 'en',
+ lng: 'en',
+ resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },
+});
+
+seedArchitectureCapabilities();
+
+const ADAPTER = {
+ gallery: { findImage: vi.fn() },
+ models: { getBaseLabel: (base: string) => (base === 'qwen-image-2-1' ? 'Qwen-Image-2.1' : base) },
+} as unknown as GenerationUiAdapter;
+
+const QWEN21_GGUF: GenerateModelConfig = {
+ base: 'qwen-image-2-1',
+ format: 'gguf_quantized',
+ key: 'qwen21-q4',
+ name: 'Qwen-Image-2.1 Q4',
+ type: 'main',
+};
+const NO_MODELS: [] = [];
+const COGVIEW4: GenerateModelConfig = { base: 'cogview4', key: 'cogview4', name: 'CogView4', type: 'main' };
+const QWEN21_REFERENCE: GenerateReferenceImage = {
+ config: {
+ image: { original: { image: { height: 512, image_name: 'edit.png', width: 512 } } },
+ type: 'qwen_image_2_1_reference_image',
+ },
+ id: 'edit',
+ isEnabled: true,
+};
+
+let host: HTMLDivElement | null = null;
+// DndContext renders its own screen-reader instructions, so assertions read only the section's output.
+const section = (): HTMLElement | null | undefined => host?.querySelector('[data-testid="section"]');
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const render = async (selectedModel: GenerateModelConfig, referenceImages: GenerateReferenceImage[] = []) => {
+ await act(() =>
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <GenerationUiProvider adapter={ADAPTER}>
+ <DndContext>
+ <div data-testid="section">
+ <GenerateReferenceImagesContent
+ models={NO_MODELS}
+ referenceImages={referenceImages}
+ selectedModel={selectedModel}
+ onCommit={vi.fn()}
+ onCommitImmediate={vi.fn()}
+ />
+ </div>
+ </DndContext>
+ </GenerationUiProvider>
+ </ChakraProvider>
+ </I18nextProvider>
+ )
+ );
+};
+
+beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('reference image format hint', () => {
+ it('names the Diffusers format where a GGUF Qwen-Image-2.1 model would show references', async () => {
+ await render(QWEN21_GGUF);
+
+ expect(section()?.textContent).toBe('Reference images need a Diffusers Qwen-Image-2.1 model.');
+ expect(section()?.querySelector('button')).toBeNull();
+ });
+
+ it('keeps the format hint next to the clear action for references the model cannot read', async () => {
+ await render(QWEN21_GGUF, [QWEN21_REFERENCE]);
+
+ expect(section()?.textContent).toContain('Reference images need a Diffusers Qwen-Image-2.1 model.');
+ expect(section()?.querySelector('button')?.textContent).toBe('Remove all');
+ });
+
+ it('renders nothing for a model whose base takes no references in any format', async () => {
+ await render(COGVIEW4);
+
+ expect(section()?.textContent).toBe('');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts b/invokeai/frontend/webv2/src/workbench/canvasMigration.ts
index b51c568a60..cc1805ea6a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasMigration.ts
@@ -192,7 +192,6 @@ const zReferenceImage = z.object({
}),
z.object({ image: zGeneratedImage.nullable(), type: z.literal('flux2_reference_image') }),
z.object({ image: zGeneratedImage.nullable(), type: z.literal('qwen_image_reference_image') }),
- z.object({ image: zGeneratedImage.nullable(), type: z.literal('qwen_image_2_1_reference_image') }),
z.object({ image: zGeneratedImage.nullable(), type: z.literal('external_reference_image') }),
]),
id: z.string(),
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
index 800ef1f7e9..562f5ceedf 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/imageRecall.test.ts
@@ -341,6 +341,48 @@ describe('image recall', () => {
expect(result?.fields).toContain('referenceImages');
});
+ // Only the Diffusers pipeline reads Qwen-Image-2.1 references, so the recalled flavor survives there and nowhere else.
+ it('recalls Qwen-Image-2.1 reference images onto a Diffusers model and drops them on a GGUF one', () => {
+ const recall = (model: MainModelConfig) =>
+ buildImageRecallSettings({
+ currentValues: createValues({ model, modelKey: model.key }),
+ image,
+ kind: 'all',
+ metadata: {
+ positive_prompt: 'swap the jacket',
+ ref_images: [
+ {
+ config: {
+ image: { height: 640, image_name: 'edit.png', width: 480 },
+ type: 'qwen_image_2_1_reference_image',
+ },
+ id: 'edit-1',
+ isEnabled: true,
+ },
+ ],
+ },
+ models: [],
+ supportedModels: [model],
+ vaeModels: [],
+ });
+ const diffusers = recall({ base: 'qwen-image-2-1', format: 'diffusers', key: 'q21', name: 'Q21', type: 'main' });
+ const gguf = recall({ base: 'qwen-image-2-1', format: 'gguf_quantized', key: 'q21-q4', name: 'Q4', type: 'main' });
+
+ expect(diffusers?.values.referenceImages).toEqual([
+ {
+ config: {
+ image: { original: { image: { height: 640, image_name: 'edit.png', width: 480 } } },
+ type: 'qwen_image_2_1_reference_image',
+ },
+ id: 'edit-1',
+ isEnabled: true,
+ },
+ ]);
+ expect(diffusers?.fields).toContain('referenceImages');
+ expect(gguf?.values.referenceImages).toEqual([]);
+ expect(gguf?.fields).not.toContain('referenceImages');
+ });
+
it('preserves canonical original and crop provenance from legacy metadata', () => {
const crop = {
box: { height: 256, width: 320, x: 12, y: 24 },
diff --git a/tests/app/invocations/test_qwen_image_2_1_nodes.py b/tests/app/invocations/test_qwen_image_2_1_nodes.py
index cb6e29a747..4de2d880fa 100644
--- a/tests/app/invocations/test_qwen_image_2_1_nodes.py
+++ b/tests/app/invocations/test_qwen_image_2_1_nodes.py
@@ -12,13 +12,14 @@ import pytest
import torch
from PIL import Image
-from invokeai.app.invocations.fields import ImageField, LatentsField, QwenImage21ConditioningField
+from invokeai.app.invocations.fields import ImageField, LatentsField, MetadataField, QwenImage21ConditioningField
from invokeai.app.invocations.model import ModelIdentifierField, Qwen3VLEncoderField, TransformerField, VAEField
from invokeai.app.invocations.qwen_image_2_1.qwen_image_2_1_denoise import (
- KV_BYTES_PER_PREFIX_TOKEN,
LATENT_CHANNELS,
+ PREFIX_CACHE_METADATA_KEY,
QwenImage21DenoiseInvocation,
clip_sigmas,
+ kv_bytes_per_prefix_token,
pack_latents,
prefix_cache_fits,
prefix_length,
@@ -41,6 +42,8 @@ from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (
)
DENOISE = "invokeai.app.invocations.qwen_image_2_1.qwen_image_2_1_denoise"
+# K and V of one prefix token in the released model: 32 blocks of 32 heads x 128, two bytes each in bf16.
+RELEASED_KV_BYTES = 2 * 32 * 4096 * 2
def test_latents_pack_one_token_per_pixel_in_raster_order() -> None:
@@ -230,11 +233,26 @@ def test_a_strength_on_base_names_whole_steps_and_always_runs_one(
assert clipped == sigmas[first_step : first_step + len(clipped)]
+def _released_transformer(num_blocks: int = 32) -> SimpleNamespace:
+ return SimpleNamespace(
+ config=SimpleNamespace(num_attention_heads=32, attention_head_dim=128), transformer_blocks=[None] * num_blocks
+ )
+
+
+def test_the_prefix_cache_is_priced_from_the_loaded_transformers_shape() -> None:
+ assert kv_bytes_per_prefix_token(_released_transformer(), torch.bfloat16) == RELEASED_KV_BYTES == 2**19
+ # A shallower model keeps fewer blocks of K and V; a float32 fallback keeps each at twice the width.
+ assert kv_bytes_per_prefix_token(_released_transformer(16), torch.bfloat16) == RELEASED_KV_BYTES // 2
+ assert kv_bytes_per_prefix_token(_released_transformer(), torch.float32) == 2 * RELEASED_KV_BYTES
+
+
def test_a_float32_fallback_reserves_twice_the_bfloat16_activations() -> None:
estimate = QwenImage21DenoiseInvocation._estimate_working_memory
base = 1024**3
- bf16 = estimate(4096, 300, 300, True, True, 2) - base
- assert estimate(4096, 300, 300, True, True, 4) - base == 2 * bf16
+ bf16_kv = kv_bytes_per_prefix_token(_released_transformer(), torch.bfloat16)
+ fp32_kv = kv_bytes_per_prefix_token(_released_transformer(), torch.float32)
+ bf16 = estimate(4096, 300, 300, True, True, 2, bf16_kv) - base
+ assert estimate(4096, 300, 300, True, True, 4, fp32_kv) - base == 2 * bf16
@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16])
@@ -247,7 +265,7 @@ def test_the_estimate_is_priced_at_the_compute_dtypes_width(
estimate = QwenImage21DenoiseInvocation._estimate_working_memory
def spy(*args):
- widths.append(args[-1])
+ widths.append(args[5])
return estimate(*args)
monkeypatch.setattr(QwenImage21DenoiseInvocation, "_estimate_working_memory", staticmethod(spy))
@@ -460,18 +478,30 @@ def test_the_prefix_counts_each_reference_slot_as_four_latent_tokens() -> None:
def test_the_prefix_caches_are_reserved_only_when_they_are_kept() -> None:
estimate = QwenImage21DenoiseInvocation._estimate_working_memory
prefix = 4200
- cached = estimate(4096, prefix, prefix, True, True, 2)
- recomputed = estimate(4096, prefix, prefix, True, False, 2)
+ cached = estimate(4096, prefix, prefix, True, True, 2, RELEASED_KV_BYTES)
+ recomputed = estimate(4096, prefix, prefix, True, False, 2, RELEASED_KV_BYTES)
# K and V of every prefix token in all 32 blocks, per guidance branch: ~2 GiB per 1 MP reference.
- assert cached - recomputed == 2 * prefix * KV_BYTES_PER_PREFIX_TOKEN
+ assert cached - recomputed == 2 * prefix * RELEASED_KV_BYTES
def test_caches_larger_than_half_the_card_are_not_kept(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(torch.cuda, "get_device_properties", lambda _device: SimpleNamespace(total_memory=24 * 2**30))
cuda = torch.device("cuda")
# Two references at CFG fit a 24 GB card; four do not.
- assert prefix_cache_fits(2 * 2 * 4200 * KV_BYTES_PER_PREFIX_TOKEN, cuda)
- assert not prefix_cache_fits(2 * 4 * 4200 * KV_BYTES_PER_PREFIX_TOKEN, cuda)
+ assert prefix_cache_fits(2 * 2 * 4200 * RELEASED_KV_BYTES, cuda)
+ assert not prefix_cache_fits(2 * 4 * 4200 * RELEASED_KV_BYTES, cuda)
+
+
[email protected](("integrated", "fits"), [(False, False), (True, True)], ids=["discrete", "integrated"])
+def test_a_discrete_xpu_card_is_limited_like_any_dedicated_card(
+ monkeypatch: pytest.MonkeyPatch, integrated: bool, fits: bool
+) -> None:
+ # Four references at CFG hold ~16 GiB: more than half a 16 GB Arc card. An integrated GPU shares system RAM,
+ # which the cache does not budget as a card.
+ monkeypatch.setattr("invokeai.backend.util.devices.xpu_device_is_integrated", lambda _device: integrated)
+ monkeypatch.setattr(torch.xpu, "get_device_properties", lambda _device: SimpleNamespace(total_memory=16 * 2**30))
+ assert prefix_cache_fits(2 * 4 * 4200 * RELEASED_KV_BYTES, torch.device("xpu")) is fits
+ assert prefix_cache_fits(2 * 4 * 4200 * RELEASED_KV_BYTES, torch.device("cpu"))
def test_without_room_for_the_caches_every_step_runs_the_whole_prefix(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -483,6 +513,67 @@ def test_without_room_for_the_caches_every_step_runs_the_whole_prefix(monkeypatc
assert {(cache, mode) for _prompt, cache, mode, _t in transformer.calls} == {(id(None), None)}
+def test_a_later_step_decodes_from_the_cache_its_prefill_filled_with_the_references() -> None:
+ transformer = _Transformer()
+ reference = torch.randn(1, LATENT_CHANNELS, 4, 8)
+ _denoise(reference_latents=[LatentsField(latents_name="ref")], steps=2)._run_diffusion(
+ _edit_context(transformer, [(2, 4)], {"ref": reference})
+ )
+
+ assert [(prompt, mode) for prompt, _cache, mode, _t in transformer.calls] == [("pos", "extract"), ("pos", "cached")]
+ # One cache for the run: the cached step reads what the prefill wrote.
+ assert len({cache for _prompt, cache, _mode, _t in transformer.calls}) == 1
+ # The transformer rebuilds the joint sequence on every step, so the cached step still needs the references in
+ # front of the target, and the same layout.
+ for seen in transformer.inputs:
+ assert seen.img_shapes == [[(1, 4, 8), (1, 4, 4)]]
+ assert torch.equal(seen.hidden_states[:, :32], pack_latents(reference))
+ assert seen.img_mask.tolist() == [[False] + [True] * 8 + [False] + [True] * 4]
+
+
+def test_large_references_before_a_small_target_price_the_last_references_attention(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ sides: list[int] = []
+
+ def score_bytes(*, seq_len: int, **_kwargs) -> int:
+ sides.append(seq_len)
+ return 0
+
+ monkeypatch.setattr(f"{DENOISE}.sdpa_score_matrix_bytes", score_bytes)
+ # Four 1 MP references (32x32 slots, 64x64 latents each) before a 256x256 target (16x16 latents).
+ grids = [(32, 32)] * 4
+ references = {f"ref{i}": torch.zeros(1, LATENT_CHANNELS, 64, 64) for i in range(4)}
+ _denoise(
+ reference_latents=[LatentsField(latents_name=name) for name in references], width=256, height=256, steps=1
+ )._run_diffusion(_edit_context(_Transformer(), grids, references))
+
+ # The prompt's layout: one text token, then each reference's 4096 latent tokens and one text token. The last
+ # reference's 4096 queries attend over every key up to its end: 4 * 4096 + 4 of them. The target's call is
+ # 256 x (16389 + 256), a sixteenth of that.
+ largest = 4096 * (4 * 4096 + 4)
+ assert len(sides) == 1
+ assert (sides[0] - 1) ** 2 < largest <= sides[0] ** 2
+
+
[email protected]("cache_fits", [True, False], ids=["cached", "recomputed"])
+def test_the_metadata_records_whether_the_prefix_was_cached(cache_fits: bool, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(f"{DENOISE}.prefix_cache_fits", lambda _bytes, _device: cache_fits)
+ context = _edit_context(_Transformer(), [(2, 4)], {"ref": torch.zeros(1, LATENT_CHANNELS, 4, 8)})
+ context.tensors.save = lambda tensor: "out"
+ node = _denoise(
+ reference_latents=LatentsField(latents_name="ref"),
+ cfg_scale=4.0,
+ metadata=MetadataField.model_validate({"seed": 7, "steps": 3}),
+ )
+
+ output = node.invoke(context)
+
+ # What the graph recorded passes through, with the mode this run took beside it.
+ assert output.metadata.root == {"seed": 7, "steps": 3, PREFIX_CACHE_METADATA_KEY: cache_fits}
+ assert (output.latents.latents_name, output.width, output.height) == ("out", 64, 64)
+
+
def test_a_standalone_encoder_cannot_read_references() -> None:
encoder = ModelIdentifierField(
key="enc", hash="h", name="qwen3vl_8b", base=BaseModelType.Any, type=ModelType.Qwen3VLEncoder
@@ -504,16 +595,22 @@ def test_a_standalone_encoder_cannot_read_references() -> None:
node.invoke(context)
-def test_the_processor_comes_from_the_qwen_image_2_1_pipeline_the_tokenizer_is_from() -> None:
+def _pipeline_encoder_node(num_references: int) -> QwenImage21TextEncoderInvocation:
main = ModelIdentifierField(
key="qwen21", hash="h", name="Qwen-Image-2.1", base=BaseModelType.QwenImage21, type=ModelType.Main
)
- tokenizer = main.model_copy(update={"submodel_type": SubModelType.Tokenizer})
- node = QwenImage21TextEncoderInvocation.model_construct(
- prompt="swap them",
- qwen3_vl_encoder=Qwen3VLEncoderField(tokenizer=tokenizer, text_encoder=tokenizer, loras=[]),
- reference_images=[ImageField(image_name="ref.png")],
+ return QwenImage21TextEncoderInvocation.model_construct(
+ prompt="Combine the subjects of all reference images.",
+ qwen3_vl_encoder=Qwen3VLEncoderField(
+ tokenizer=main.model_copy(update={"submodel_type": SubModelType.Tokenizer}),
+ text_encoder=main.model_copy(update={"submodel_type": SubModelType.TextEncoder}),
+ loras=[],
+ ),
+ reference_images=[ImageField(image_name=f"ref{i}.png") for i in range(num_references)],
)
+
+
+def test_the_processor_comes_from_the_qwen_image_2_1_pipeline_the_tokenizer_is_from() -> None:
context = SimpleNamespace(
models=SimpleNamespace(
get_config=lambda _identifier: SimpleNamespace(
@@ -521,24 +618,38 @@ def test_the_processor_comes_from_the_qwen_image_2_1_pipeline_the_tokenizer_is_f
)
)
)
- processor = node._processor_identifier(context)
+ tower, processor = _pipeline_encoder_node(1)._edit_identifiers(context)
+ assert (tower.key, tower.submodel_type) == ("qwen21", SubModelType.VisionTower)
assert (processor.key, processor.submodel_type) == ("qwen21", SubModelType.Processor)
+def test_a_standalone_encoder_beside_the_pipelines_tokenizer_cannot_read_references() -> None:
+ # The tokenizer passes; the encoder, whose pipeline would have to bring the vision tower, does not.
+ def get_config(identifier):
+ if identifier.submodel_type is SubModelType.Tokenizer:
+ return SimpleNamespace(base=BaseModelType.QwenImage21, type=ModelType.Main, format=ModelFormat.Diffusers)
+ return SimpleNamespace(base=BaseModelType.Any, type=ModelType.Qwen3VLEncoder, format=ModelFormat.Checkpoint)
+
+ with pytest.raises(ValueError, match="vision tower"):
+ _pipeline_encoder_node(1)._edit_identifiers(SimpleNamespace(models=SimpleNamespace(get_config=get_config)))
+
+
+def test_more_references_than_the_architecture_reads_are_refused_before_anything_loads() -> None:
+ # The context has no images or models: reaching either would fail with another error.
+ with pytest.raises(ValueError, match="at most 4 reference images; this prompt has 5"):
+ _pipeline_encoder_node(5).invoke(SimpleNamespace())
+
+
class _ReservationRecorded(Exception):
pass
[email protected]("num_references", [0, 4])
-def test_the_encoder_reserves_room_for_the_attention_its_references_need(num_references: int) -> None:
+def _encode_until_reservation(num_references: int, image_size: int = 1024) -> tuple[list[int], list[SubModelType]]:
+ """Runs the node until the encoder would move to the device; returns what it reserved and what it loaded."""
from invokeai.backend.qwen3_vl.qwen3_vl_assets import load_bundled_qwen3_vl_tokenizer
- main = ModelIdentifierField(
- key="qwen21", hash="h", name="Qwen-Image-2.1", base=BaseModelType.QwenImage21, type=ModelType.Main
- )
- tokenizer = main.model_copy(update={"submodel_type": SubModelType.Tokenizer})
- encoder = main.model_copy(update={"submodel_type": SubModelType.TextEncoder})
reserved: list[int] = []
+ loaded: list[SubModelType] = []
@contextmanager
def on_device(*, working_mem_bytes: int):
@@ -548,32 +659,139 @@ def test_the_encoder_reserves_room_for_the_attention_its_references_need(num_ref
text_encoder = torch.nn.Module()
text_encoder.language_model = torch.nn.Linear(2, 2)
- text_encoder.visual = torch.nn.Linear(2, 2)
+ text_encoder.visual = torch.nn.Identity()
+ tower = torch.nn.Linear(2, 2)
+ # The released tower's attention geometry.
+ tower.config = SimpleNamespace(num_heads=16, hidden_size=1152)
infos = {
SubModelType.TextEncoder: SimpleNamespace(
model=text_encoder, compute_device=torch.device("cpu"), model_on_device=on_device
),
+ SubModelType.VisionTower: SimpleNamespace(
+ model=tower, compute_device=torch.device("cpu"), model_on_device=lambda: nullcontext((None, tower))
+ ),
SubModelType.Tokenizer: nullcontext(load_bundled_qwen3_vl_tokenizer()),
SubModelType.Processor: SimpleNamespace(model_on_device=lambda: nullcontext((None, None))),
}
- node = QwenImage21TextEncoderInvocation.model_construct(
- prompt="Combine the subjects of all reference images.",
- qwen3_vl_encoder=Qwen3VLEncoderField(tokenizer=tokenizer, text_encoder=encoder, loras=[]),
- reference_images=[ImageField(image_name=f"ref{i}.png") for i in range(num_references)],
+
+ def load(identifier):
+ loaded.append(identifier.submodel_type)
+ return infos[identifier.submodel_type]
+
+ context = SimpleNamespace(
+ images=SimpleNamespace(get_pil=lambda _name: Image.new("RGB", (image_size, image_size))),
+ models=SimpleNamespace(
+ get_config=lambda _identifier: SimpleNamespace(
+ base=BaseModelType.QwenImage21, type=ModelType.Main, format=ModelFormat.Diffusers
+ ),
+ load=load,
+ ),
+ util=SimpleNamespace(signal_progress=lambda _message: None),
)
+ with pytest.raises(_ReservationRecorded):
+ _pipeline_encoder_node(num_references).invoke(context)
+ return reserved, loaded
+
+
[email protected]("num_references", [0, 2], ids=["text-only", "edit"])
+def test_only_an_edit_loads_the_vision_tower(num_references: int) -> None:
+ _, loaded = _encode_until_reservation(num_references, image_size=64)
+ # The encoder is the tower-less one either way: its language model is cached once for both.
+ assert loaded[0] is SubModelType.TextEncoder and SubModelType.TextEncoder not in loaded[1:]
+ assert (SubModelType.VisionTower in loaded) is bool(num_references)
+ assert (SubModelType.Processor in loaded) is bool(num_references)
+
+
+class _EncodeFailed(Exception):
+ pass
+
+
[email protected]("fail", [False, True], ids=["encoded", "failed"])
+def test_an_edit_encodes_with_the_tower_attached_and_detaches_it(fail: bool, monkeypatch: pytest.MonkeyPatch) -> None:
+ """End to end through the node with a tiny Qwen3-VL split the way the pipeline loader caches it."""
+ import copy
+
+ from transformers import Qwen2VLImageProcessor, Qwen3VLModel, Qwen3VLProcessor
+ from transformers.models.qwen3_vl.video_processing_qwen3_vl import Qwen3VLVideoProcessor
+
+ from invokeai.app.invocations.text_encoder import qwen_image_2_1_text_encoder as node_module
+ from invokeai.backend.model_manager.util.qwen3_vl import drop_qwen3vl_visual_tower
+ from invokeai.backend.qwen3_vl.qwen3_vl_assets import load_bundled_qwen3_vl_tokenizer
+ from invokeai.backend.qwen_image_2_1.text_encoding import encode_prompt
+ from invokeai.backend.qwen_image_2_1.vae import to_reference
+ from tests.backend.model_manager.load.qwen3vl_gguf_fixture import tiny_qwen3vl_config
+
+ monkeypatch.setattr(f"{node_module.__name__}.TorchDevice.choose_bfloat16_safe_dtype", lambda _d: torch.float32)
+ tokenizer = load_bundled_qwen3_vl_tokenizer()
+ processor = Qwen3VLProcessor(
+ image_processor=Qwen2VLImageProcessor(patch_size=16, merge_size=2, temporal_patch_size=2),
+ tokenizer=tokenizer,
+ video_processor=Qwen3VLVideoProcessor(),
+ )
+ config = tiny_qwen3vl_config()
+ config.text_config.vocab_size = len(tokenizer)
+ torch.manual_seed(0)
+ built_in = Qwen3VLModel(config).float().eval()
+ tower = copy.deepcopy(built_in.visual)
+ encoder = copy.deepcopy(built_in)
+ drop_qwen3vl_visual_tower(encoder)
+
+ def info(model):
+ return SimpleNamespace(
+ model=model, compute_device=torch.device("cpu"), model_on_device=lambda **_kw: nullcontext((None, model))
+ )
+
+ infos = {
+ SubModelType.TextEncoder: info(encoder),
+ SubModelType.VisionTower: info(tower),
+ SubModelType.Tokenizer: nullcontext(tokenizer),
+ SubModelType.Processor: info(processor),
+ }
+ saved: list[ConditioningFieldData] = []
+ reference = Image.new("RGB", (64, 64), (200, 30, 30))
context = SimpleNamespace(
- images=SimpleNamespace(get_pil=lambda _name: Image.new("RGB", (1024, 1024))),
+ images=SimpleNamespace(get_pil=lambda _name: reference),
models=SimpleNamespace(
get_config=lambda _identifier: SimpleNamespace(
base=BaseModelType.QwenImage21, type=ModelType.Main, format=ModelFormat.Diffusers
),
load=lambda identifier: infos[identifier.submodel_type],
),
+ conditioning=SimpleNamespace(save=lambda data: saved.append(data) or "cond"),
util=SimpleNamespace(signal_progress=lambda _message: None),
)
+ node = _pipeline_encoder_node(1)
+ if fail:
- with pytest.raises(_ReservationRecorded):
+ def failing_encode(*_args, **_kwargs):
+ raise _EncodeFailed
+
+ monkeypatch.setattr(node_module, "encode_prompt", failing_encode)
+ with pytest.raises(_EncodeFailed):
+ node.invoke(context)
+ else:
node.invoke(context)
+ expected = encode_prompt(
+ built_in, tokenizer, node.prompt, torch.device("cpu"), processor=processor, images=[to_reference(reference)]
+ )
+ info_out = saved[0].conditionings[0]
+ assert torch.equal(info_out.prompt_embeds, expected.embeds)
+ assert torch.equal(info_out.image_pad_mask, expected.image_pad_mask)
+
+ # The cached encoder is left as it was loaded, whether the encode finished or not.
+ assert isinstance(encoder.visual, torch.nn.Identity)
+
+
[email protected]("num_references", [0, 4])
+def test_the_encoder_reserves_room_for_the_attention_its_references_need(
+ num_references: int, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # The measurement below is a bf16 one; on a CPU without bf16 the node would price float32, twice as much.
+ monkeypatch.setattr(
+ "invokeai.app.invocations.text_encoder.qwen_image_2_1_text_encoder.TorchDevice.choose_bfloat16_safe_dtype",
+ lambda _device: torch.bfloat16,
+ )
+ reserved, _ = _encode_until_reservation(num_references)
if num_references:
# Measured on an RTX 4090: four 1-megapixel references peak 5.44 GiB above the weights, and the allocator
@@ -583,6 +801,18 @@ def test_the_encoder_reserves_room_for_the_attention_its_references_need(num_ref
assert reserved[0] < 2**28
+def test_a_float32_encoder_reserves_twice_the_bfloat16_room(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The encoder runs in float32 where the device has no bf16 (CPU, older MPS); its activations are twice as wide.
+ reserved = {}
+ for dtype in (torch.bfloat16, torch.float32):
+ monkeypatch.setattr(
+ "invokeai.app.invocations.text_encoder.qwen_image_2_1_text_encoder.TorchDevice.choose_bfloat16_safe_dtype",
+ lambda _device, dtype=dtype: dtype,
+ )
+ reserved[dtype] = _encode_until_reservation(4)[0][0]
+ assert reserved[torch.float32] == pytest.approx(2 * reserved[torch.bfloat16], rel=1e-6)
+
+
class _VAE:
"""Records what it encodes and answers with bf16 latents, as the real VAE runs in bf16."""
diff --git a/tests/backend/model_manager/load/test_load_default_cpu_only.py b/tests/backend/model_manager/load/test_load_default_cpu_only.py
index d99eb5466d..0aa27d8a04 100644
--- a/tests/backend/model_manager/load/test_load_default_cpu_only.py
+++ b/tests/backend/model_manager/load/test_load_default_cpu_only.py
@@ -47,3 +47,13 @@ def test_config_without_cpu_only_attr_returns_none():
# A config type that has neither `cpu_only` nor `default_settings` must be left on the
# cache default (return None), not crash.
assert _loader()._get_execution_device(SimpleNamespace(), None) is None
+
+
+def test_a_main_models_cpu_only_puts_its_encoder_and_vision_tower_on_the_cpu():
+ # Qwen-Image-2.1 attaches the tower to the encoder while it reads references, so the two must share a device;
+ # the denoiser stays on the cache default.
+ config = SimpleNamespace(default_settings=SimpleNamespace(cpu_only=True))
+ loader = _loader()
+ assert loader._get_execution_device(config, SubModelType.TextEncoder) == torch.device("cpu")
+ assert loader._get_execution_device(config, SubModelType.VisionTower) == torch.device("cpu")
+ assert loader._get_execution_device(config, SubModelType.Transformer) is None
diff --git a/tests/backend/model_manager/load/test_load_default_fp8.py b/tests/backend/model_manager/load/test_load_default_fp8.py
index 0ac15ed4ca..236986cd00 100644
--- a/tests/backend/model_manager/load/test_load_default_fp8.py
+++ b/tests/backend/model_manager/load/test_load_default_fp8.py
@@ -183,6 +183,18 @@ def test_should_use_fp8_excludes_prompt_enhancer(submodel_type: SubModelType):
assert loader._should_use_fp8(config, SubModelType.Transformer) is True
+def test_should_use_fp8_excludes_the_vision_tower():
+ """Qwen-Image-2.1's vision tower attaches to the text encoder for edits and follows its exclusion. It could
+ not take the cast either: `Qwen3VLModel` casts the pixels to `visual.dtype`, which a cast tower reports as
+ float8."""
+ loader = _make_loader(device="cuda")
+ config = _make_config(ModelType.Main, fp8=True, base=BaseModelType.QwenImage21)
+ with _device_holds_fp8():
+ assert loader._should_use_fp8(config, SubModelType.VisionTower) is False
+ # Sanity: the same config opts the transformer in, so the assertion above is about the exclusion.
+ assert loader._should_use_fp8(config, SubModelType.Transformer) is True
+
+
class _RaisingModule(torch.nn.Module):
"""A module whose forward unconditionally raises — used to test that the FP8 wrapper's
storage-dtype cleanup runs even when forward fails."""
diff --git a/tests/backend/model_manager/load/test_qwen3_vl_visual_tower.py b/tests/backend/model_manager/load/test_qwen3_vl_visual_tower.py
index c807f5c73c..bd3fb1df4f 100644
--- a/tests/backend/model_manager/load/test_qwen3_vl_visual_tower.py
+++ b/tests/backend/model_manager/load/test_qwen3_vl_visual_tower.py
@@ -3,7 +3,8 @@
Krea-2 and Ideogram 4 condition on the language tower's hidden states; `Qwen3VLModel.forward`
reaches `self.visual` only for `pixel_values`, which neither invocation passes, and Ideogram 4 does
not go through `forward` at all. The tower is therefore never executed, and dropping it takes
-0.39-0.77 GiB off the 4B encoder depending on the container.
+0.39-0.77 GiB off the 4B encoder depending on the container. Qwen-Image-2.1 drops it for text
+prompts too, and loads the tower on its own for edits.
These tests use a real (tiny) `Qwen3VLModel`, so what disappears is the architecture's actual vision
tower rather than a stand-in. MiniMax H3 does run this tower and loads through
@@ -302,22 +303,95 @@ def test_the_folder_loader_drops_the_tower(tmp_path: Path) -> None:
_assert_tower_gone(model)
-def test_the_qwen_image_2_1_pipeline_encoder_keeps_the_tower(monkeypatch, tmp_path: Path) -> None:
- """The one encoder that keeps it: Qwen-Image-2.1 reads reference images through it, and the node refuses an
- encoder without it."""
- from transformers import Qwen3VLModel
+def _qwen_image_2_1_pipeline(
+ monkeypatch,
+ tmp_path: Path,
+ *,
+ conditional_generation: bool,
+ saved_dtype: torch.dtype = torch.float32,
+ max_shard_size: str | None = None,
+):
+ """A Qwen-Image-2.1 pipeline folder holding a tiny encoder, saved as `Qwen3VLForConditionalGeneration` (the
+ released layout, `model.visual.*`) or as `Qwen3VLModel` (`visual.*`); the loader over it, which loads in
+ float32; the saved encoder."""
+ from transformers import Qwen3VLForConditionalGeneration
from invokeai.backend.model_manager.configs.main import Main_Diffusers_QwenImage21_Config
from invokeai.backend.model_manager.load.model_loaders.qwen_image_2_1 import QwenImage21DiffusersModel
- from invokeai.backend.qwen_image_2_1.text_encoding import has_vision_tower
- encoder = _tiny_encoder()
+ torch.manual_seed(0)
+ saved = Qwen3VLForConditionalGeneration(tiny_qwen3vl_config()) if conditional_generation else _tiny_encoder()
+ saved = saved.to(saved_dtype)
+ shard_kwargs = {"max_shard_size": max_shard_size} if max_shard_size else {}
+ saved.save_pretrained(tmp_path / "text_encoder", **shard_kwargs)
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.qwen_image_2_1.TorchDevice.choose_bfloat16_safe_dtype",
+ lambda _device: torch.float32,
+ )
config = Main_Diffusers_QwenImage21_Config.model_construct(path=str(tmp_path), repo_variant=None)
loader = object.__new__(QwenImage21DiffusersModel)
loader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: model
- monkeypatch.setattr(Qwen3VLModel, "from_pretrained", classmethod(lambda _cls, *_a, **_k: encoder))
+ encoder = saved.model if conditional_generation else saved
+ return loader, config, encoder
- model = loader._load_model(config, SubModelType.TextEncoder)
- assert has_vision_tower(model)
- assert list(model.visual.parameters())
+def _assert_tower_loaded(tower, saved) -> None:
+ from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLVisionModel
+
+ assert isinstance(tower, Qwen3VLVisionModel)
+ expected = saved.visual.state_dict()
+ loaded = tower.state_dict()
+ assert loaded.keys() == expected.keys()
+ for key, value in expected.items():
+ assert torch.equal(loaded[key], value), key
+
+
[email protected]("conditional_generation", [True, False], ids=["model.visual", "visual"])
+def test_the_qwen_image_2_1_pipeline_loads_the_tower_on_its_own(
+ monkeypatch, tmp_path: Path, conditional_generation: bool
+) -> None:
+ """Text prompts load the encoder without the tower, as every other loader does. Edits load the tower alone,
+ from the same folder and with the weights it was saved with, and attach it while they encode."""
+ loader, config, saved = _qwen_image_2_1_pipeline(
+ monkeypatch, tmp_path, conditional_generation=conditional_generation
+ )
+
+ _assert_tower_gone(loader._load_model(config, SubModelType.TextEncoder))
+ _assert_tower_loaded(loader._load_model(config, SubModelType.VisionTower), saved)
+
+
+def _shard_the_tower_and_leave_a_stray_file(tmp_path: Path) -> None:
+ """The released encoder is sharded; check the tower spans several shards, and leave a stray safetensors file
+ beside them (a leftover variant) that the index does not name, holding zeros under the tower's keys."""
+ from safetensors import safe_open
+ from safetensors.torch import save_file
+
+ folder = tmp_path / "text_encoder"
+ weight_map = json.loads((folder / "model.safetensors.index.json").read_text())["weight_map"]
+ tower_keys = [key for key in weight_map if key.startswith("model.visual.")]
+ assert len({weight_map[key] for key in tower_keys}) > 1
+ first_shard = folder / weight_map[tower_keys[0]]
+ with safe_open(first_shard, framework="pt") as f:
+ stray = {key: torch.zeros_like(f.get_tensor(key)) for key in f.keys() if key.startswith("model.visual.")}
+ save_file(stray, str(folder / "model.fp16.safetensors"))
+
+
+def test_a_sharded_tower_loads_from_the_shards_its_index_names(monkeypatch, tmp_path: Path) -> None:
+ loader, config, saved = _qwen_image_2_1_pipeline(
+ monkeypatch, tmp_path, conditional_generation=True, max_shard_size="40KB"
+ )
+ _shard_the_tower_and_leave_a_stray_file(tmp_path)
+
+ _assert_tower_loaded(loader._load_model(config, SubModelType.VisionTower), saved)
+
+
+def test_the_tower_reserves_its_own_size_at_the_dtype_it_loads_in(monkeypatch, tmp_path: Path) -> None:
+ """The cache makes room for this size before the load: the encoder folder's would evict ~17 GB for ~1 GB.
+ Saved in bf16, sharded, and loaded in float32: four bytes per element, counted once, from the index's shards."""
+ loader, config, saved = _qwen_image_2_1_pipeline(
+ monkeypatch, tmp_path, conditional_generation=True, saved_dtype=torch.bfloat16, max_shard_size="40KB"
+ )
+ _shard_the_tower_and_leave_a_stray_file(tmp_path)
+
+ elements = sum(v.nelement() for v in saved.visual.state_dict().values())
+ assert loader.get_size_fs(config, tmp_path, SubModelType.VisionTower) == 4 * elements
diff --git a/tests/backend/qwen_image_2_1/test_text_encoding.py b/tests/backend/qwen_image_2_1/test_text_encoding.py
index 349af91694..1c770c40d2 100644
--- a/tests/backend/qwen_image_2_1/test_text_encoding.py
+++ b/tests/backend/qwen_image_2_1/test_text_encoding.py
@@ -10,12 +10,15 @@ from PIL import Image
from invokeai.backend.qwen3_vl.qwen3_vl_assets import load_bundled_qwen3_vl_tokenizer
from invokeai.backend.qwen_image_2_1.text_encoding import (
SYSTEM_BLOCK,
+ attached_vision_tower,
encode_prompt,
format_prompt,
has_vision_tower,
on_white,
sequence_length,
system_prefix_length,
+ vision_attention_bytes,
+ working_memory_bytes,
)
from tests.backend.model_manager.load.qwen3vl_gguf_fixture import tiny_qwen3vl_config
@@ -142,3 +145,110 @@ def test_transparency_is_flattened_over_white_for_the_vision_encoder() -> None:
half_red = Image.new("RGBA", (1, 1), (255, 0, 0, 128))
assert on_white(half_red).getpixel((0, 0)) == (255, 127, 127)
assert on_white(Image.new("RGBA", (1, 1), (0, 0, 0, 0))).getpixel((0, 0)) == (255, 255, 255)
+
+
+def test_a_text_prompt_encodes_the_same_without_the_vision_tower(text_encoder, tokenizer) -> None:
+ """Text-only encodes load the encoder without its tower; they must read exactly what the full encoder reads."""
+ import copy
+
+ from invokeai.backend.model_manager.util.qwen3_vl import drop_qwen3vl_visual_tower
+
+ without_tower = copy.deepcopy(text_encoder)
+ drop_qwen3vl_visual_tower(without_tower)
+ assert has_vision_tower(text_encoder) and not has_vision_tower(without_tower)
+
+ for prompt in ("a fox in the snow", ""):
+ with_embeds, _, _ = encode_prompt(text_encoder, tokenizer, prompt, torch.device("cpu"))
+ without_embeds, _, _ = encode_prompt(without_tower, tokenizer, prompt, torch.device("cpu"))
+ assert torch.equal(with_embeds, without_embeds)
+
+
+def test_a_literal_image_placeholder_in_an_edit_prompt_is_refused(text_encoder, tokenizer, processor) -> None:
+ prompt = "put <|image_pad|> here"
+ reference = Image.new("RGB", (32, 32))
+ # Refused where the node counts the tokens, before the encoder loads, and again where it encodes.
+ with pytest.raises(ValueError, match=r"cannot contain <\|image_pad\|>"):
+ sequence_length(tokenizer, prompt, [reference])
+ with pytest.raises(ValueError, match=r"cannot contain <\|image_pad\|>"):
+ encode_prompt(text_encoder, tokenizer, prompt, torch.device("cpu"), processor=processor, images=[reference])
+ # Without references there is nothing for it to claim: it encodes as text.
+ encode_prompt(text_encoder, tokenizer, prompt, torch.device("cpu"))
+
+
+def test_the_encoder_reserve_scales_with_the_compute_dtype() -> None:
+ assert working_memory_bytes(4100, 4) == pytest.approx(2 * working_memory_bytes(4100, 2), abs=1)
+
+
+def test_the_vision_towers_attention_is_reserved_when_it_outgrows_the_language_models() -> None:
+ # One 1 MP reference: ~1.1k tokens for the language model, but ~4k patches for the tower, whose scores
+ # outweigh the language model's attention when they are materialized.
+ language_only = working_memory_bytes(1100, 2)
+ tower = 16 * 4096**2 * 17
+ assert working_memory_bytes(1100, 2, tower) >= 1.2 * tower
+ # The tower frees its scores before the language model starts: a tower term below the language model's
+ # attention adds nothing.
+ assert working_memory_bytes(1100, 2, 1024) == language_only
+
+
+def test_the_vision_tower_is_priced_for_its_largest_reference_at_four_patches_per_token(
+ text_encoder, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ calls: list[dict] = []
+
+ def score_bytes(**kwargs) -> int:
+ calls.append(kwargs)
+ return 123
+
+ monkeypatch.setattr("invokeai.backend.qwen_image_2_1.text_encoding.sdpa_score_matrix_bytes", score_bytes)
+ references = [Image.new("RGB", (64, 96)), Image.new("RGB", (128, 64)), Image.new("RGB", (32, 32))]
+ vision = text_encoder.visual.config
+
+ assert vision_attention_bytes(text_encoder.visual, references, torch.device("cpu"), torch.bfloat16) == 123
+ # The largest reference is 128x64: 4x2 vision tokens, 32 patches of 16px. The tower attends one image at a time.
+ assert len(calls) == 1
+ assert calls[0]["seq_len"] == 32
+ assert (calls[0]["num_heads"], calls[0]["head_dim"]) == (vision.num_heads, vision.hidden_size // vision.num_heads)
+ assert vision_attention_bytes(text_encoder.visual, [], torch.device("cpu"), torch.bfloat16) == 0
+
+
+def _split(text_encoder):
+ """The encoder as the pipeline loader caches it for an edit: without its tower, and the tower on its own."""
+ import copy
+
+ from invokeai.backend.model_manager.util.qwen3_vl import drop_qwen3vl_visual_tower
+
+ tower = copy.deepcopy(text_encoder.visual)
+ encoder = copy.deepcopy(text_encoder)
+ drop_qwen3vl_visual_tower(encoder)
+ return encoder, tower
+
+
+def test_an_attached_tower_reads_references_exactly_as_a_built_in_one(text_encoder, tokenizer, processor) -> None:
+ encoder, tower = _split(text_encoder)
+ references = [Image.new("RGB", (64, 96), (255, 0, 0)), Image.new("RGB", (128, 64), (0, 0, 255))]
+ built_in = _encode(text_encoder, tokenizer, processor, references)
+
+ with attached_vision_tower(encoder, tower):
+ attached = _encode(encoder, tokenizer, processor, references)
+
+ assert torch.equal(attached.embeds, built_in.embeds)
+ assert torch.equal(attached.image_pad_mask, built_in.image_pad_mask)
+ assert attached.reference_grids == built_in.reference_grids
+ # The cached encoder is left as it was loaded, so a later text prompt or another session never sees the tower.
+ assert isinstance(encoder.visual, torch.nn.Identity)
+ assert not has_vision_tower(encoder)
+
+
+def test_a_failed_encode_detaches_the_tower(text_encoder, tokenizer, processor) -> None:
+ encoder, tower = _split(text_encoder)
+ with pytest.raises(ValueError, match="image_pad"), attached_vision_tower(encoder, tower):
+ assert has_vision_tower(encoder)
+ encode_prompt(
+ encoder,
+ tokenizer,
+ "<|image_pad|>",
+ torch.device("cpu"),
+ processor=processor,
+ images=[Image.new("RGB", (32, 32))],
+ )
+ assert isinstance(encoder.visual, torch.nn.Identity)