Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(krea2): add edit mode with reference images for ai-toolkit edit LoRAs
Alexander Eichhorn5e7b97fdb8ac
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdxindex aae0692f43..6c672973df 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/krea-2.mdx@@ -1,7 +1,7 @@---title: Krea-2-description: Generate images with the Krea-2 text-to-image models (Turbo and Raw), including the GGUF / single-file workflow, the conditioning enhancers and training-free style reference.-lastUpdated: 2026-09-30+description: Generate images with the Krea-2 text-to-image models (Turbo and Raw), including the GGUF / single-file workflow, the conditioning enhancers, training-free style reference and edit LoRAs with reference images.+lastUpdated: 2026-10-18sidebar:order: 7---@@ -83,8 +83,9 @@ encoder closely; the remaining difference is the quantization of the encoder.- Use a Qwen3-VL GGUF, such as the files in `Qwen/Qwen3-VL-4B-Instruct-GGUF`. A plain Qwen3 GGUF has thesame shapes but conditions wrongly, so InvokeAI identifies the encoder from the file's`qwen3vl` architecture tag and does not install a plain Qwen3 file as one.-- The `mmproj-*.gguf` file next to it holds the vision part and is not needed. Installing it is refused- with a message saying so.+- The `mmproj-*.gguf` file next to it holds the vision part and is not needed for text-to-image. Installing+ it is refused with a message saying so. Without the vision part, a GGUF encoder cannot encode the+ reference images of [edit LoRAs](#edit-loras-and-reference-images).- ComfyUI-GGUF's `Q8_CR` encoder files are refused at install; only the transformer loads from `Q8_CR`.- LoRAs with text-encoder layers still apply to a quantized encoder.@@ -108,7 +109,7 @@ In the workflow editor, the **Denoise - Krea-2** node accepts one conditioning oits positive and negative conditioning inputs. Multiple independently encoded conditionings are concatenatedafter padding tokens are removed.-The **Text Encoder - Krea-2** node also accepts an optional mask. A masked conditioning applies to that+The **Prompt - Krea-2** node also accepts an optional mask. A masked conditioning applies to thatimage region; an unmasked conditioning applies to the background not covered by any regional mask. Ifregional masks cover the full image, an unmasked conditioning falls back to the full image instead of beingignored. Krea-2 uses restricted attention on alternating main transformer blocks, leaving the other blocks@@ -159,7 +160,76 @@ input of **Denoise - Krea-2**.Krea-2 LoRAs (diffusers PEFT format) are supported and apply to both the transformer and — where theLoRA includes text-encoder layers — the Qwen3-VL encoder. On quantized builds (GGUF, int8, NVFP4) the LoRA-is applied alongside the packed weights rather than merged into them.+is applied alongside the packed weights rather than merged into them. LoRAs trained to edit an input image+need reference images; see [Edit LoRAs](#edit-loras-and-reference-images).++## Edit LoRAs and reference images++Some Krea-2 LoRAs are trained to transform one or more input images rather than to generate from text+alone. They come from ai-toolkit's Krea-2 edit training (`edit: true`) and include the pose and depth+"controlnet" LoRAs: you give them a pose skeleton or a depth map as a reference image, and the prompt+describes the result. Such a LoRA does nothing useful without its reference images, and an ordinary Krea-2+LoRA gains nothing from them.++A reference image reaches the model twice, and both are needed:++- **The text encoder looks at it.** The Qwen3-VL encoder sees each reference next to the prompt, scaled to+ an area of about 384×384 pixels with its aspect ratio kept (the Qwen3-VL processor then works on 32-pixel+ cells, with a floor of 65,536 pixels). This needs the encoder's vision weights. The encoder of the Krea-2+ Diffusers models has them, and so do Qwen3-VL single files and folders that include the vision weights.+ [GGUF encoders](#qwen3-vl-gguf-encoders) do not. An encoder without them is refused when reference images+ are connected.+- **The transformer sees it as clean image tokens.** The reference is encoded with the VAE and its tokens+ are added after the image being generated. They are always presented as fully denoised. An image above+ 1 megapixel is scaled to about 1 megapixel, keeping its aspect ratio, and both sides are then rounded to+ a multiple of 16 pixels, so the result can be slightly above 1 megapixel and a tiny image is enlarged to+ 16 pixels per side. Smaller images are otherwise not scaled up.++Both keep the image's RGB and drop its alpha channel, as in ai-toolkit training: a transparent PNG shows+the colors hidden under its transparent areas, not a background.++Reference images are set up in the workflow editor:++1. For each reference, an **Image to Latents - Qwen Image** node (`qwen_image_i2l`) with **Reference**+ (`reference`) enabled and width and height left unset. It applies the transformer sizing above.+2. The same images, in the same order, on the **Reference Images** input+ (`krea2_text_encoder.reference_images`) of each **Prompt - Krea-2** node: the positive prompt's, and the+ negative prompt's when CFG is above 1.+3. The latents from step 1, in the same order, on the **Reference Latents** input+ (`krea2_denoise.reference_latents`) of **Denoise - Krea-2**. With CFG, both the conditional and the+ unconditional pass see the references.+4. The edit LoRA on the transformer, as for any other LoRA.++### Reference K/V cache++Edit LoRAs come in two kinds, and the **Reference K/V Cache** input (`krea2_denoise.reference_kv_cache`)+of **Denoise - Krea-2** has to match how the LoRA was trained:++- **Off** (the default) is for normal edit LoRAs, such as the depth LoRAs. The references join every+ transformer pass, and everything attends to everything.+- **On** is for LoRAs trained with ai-toolkit's `kv_cache` option, such as the Krea-2 pose ControlNet LoRA.+ They were trained with reference images that only attend to each other. The references then run+ through the transformer once per generation, at the start, and every step reuses what they computed,+ so generation is faster than with the cache off.++Nothing in a LoRA file says which kind it is. Use what its model card says. Dark blotches or extra+figures with reference images can mean the LoRA was trained with isolated references: turn the cache on.++:::caution[Limits]+- At most **3** reference images. Both the prompt node and the denoise node refuse more.+- The denoise node refuses a prompt that was encoded with a different number of reference images than it+ has reference latents, for the positive prompt and, when CFG is above 1, the negative prompt.+- With the K/V cache off, every reference adds about **4096 tokens per megapixel** to every transformer+ pass. A 1 megapixel reference doubles the image sequence of a 1024² generation, so each step takes at+ least twice as long and needs more VRAM. The memory reserved for the transformer accounts for the extra tokens.+- With the reference K/V cache on, the references are not in the per-step passes, but what they computed+ stays in memory for the whole generation: about 0.7 GB per 1 megapixel reference. The reserved memory+ accounts for it.+- References cannot be combined with **Style reference** or with **regional (masked) prompts**. The denoise+ node refuses either combination before it loads the model.+- Image-to-image and inpainting work as usual: they act only on the image being generated, not on the+ references.+:::## Attention backenddiff --git a/invokeai/app/invocations/krea2/krea2_conditioning_rebalance.py b/invokeai/app/invocations/krea2/krea2_conditioning_rebalance.pyindex bad7c6bce5..efccbb1803 100644--- a/invokeai/app/invocations/krea2/krea2_conditioning_rebalance.py+++ b/invokeai/app/invocations/krea2/krea2_conditioning_rebalance.py@@ -72,7 +72,11 @@ class Krea2ConditioningRebalanceInvocation(BaseInvocation):new_data = ConditioningFieldData(conditionings=[- Krea2ConditioningInfo(prompt_embeds=embeds, prompt_embeds_mask=conditioning.prompt_embeds_mask)+ Krea2ConditioningInfo(+ prompt_embeds=embeds,+ prompt_embeds_mask=conditioning.prompt_embeds_mask,+ num_reference_images=conditioning.num_reference_images,+ )])conditioning_name = context.conditioning.save(new_data)diff --git a/invokeai/app/invocations/krea2/krea2_denoise.py b/invokeai/app/invocations/krea2/krea2_denoise.pyindex 294fd01839..ddda18a4b0 100644--- a/invokeai/app/invocations/krea2/krea2_denoise.py+++ b/invokeai/app/invocations/krea2/krea2_denoise.py@@ -34,6 +34,12 @@ from invokeai.backend.krea2.attention import (build_krea2_attention_processors,resolve_krea2_sdpa_backends,)+from invokeai.backend.krea2.reference_edit import (+ Krea2ReferenceKVCache,+ forward_with_references,+ precompute_reference_kv,+ reference_kv_cache_bytes,+)from invokeai.backend.krea2.regional_prompting import (Krea2RegionalPromptingExtension,Krea2TextConditioning,@@ -48,9 +54,17 @@ from invokeai.backend.krea2.sampling_utils import (calculate_shift,pack_latents,prepare_position_ids,+ prepare_position_ids_with_references,+ prepare_reference_position_ids,unpack_latents,)-from invokeai.backend.krea2.style_reference_extension import Krea2StyleReferenceExtension+from invokeai.backend.krea2.style_reference import KREA2_NUM_BLOCKS+from invokeai.backend.krea2.style_reference_extension import (+ KREA2_HEAD_DIM,+ KREA2_NUM_KV_HEADS,+ Krea2StyleReferenceExtension,+)+from invokeai.backend.krea2.text_encoding import KREA2_MAX_REFERENCE_IMAGESfrom invokeai.backend.model_manager.taxonomy import BaseModelTypefrom invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpecfrom invokeai.backend.patches.lora_conversions.krea2_lora_constants import KREA2_LORA_TRANSFORMER_PREFIX@@ -136,7 +150,7 @@ class _Krea2StepBenchmark:title="Denoise - Krea-2",tags=["image", "krea2", "krea-2"],category="image",- version="1.3.0",+ version="1.4.0",classification=Classification.Prototype,)class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):@@ -191,6 +205,23 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):input=Input.Connection,title="Style Reference Prompt",)+ reference_latents: LatentsField | list[LatentsField] | None = InputField(+ default=None,+ description="Edit references for Krea-2 edit LoRAs, encoded by 'Image to Latents - Qwen Image' with "+ f"'reference' enabled. Up to {KREA2_MAX_REFERENCE_IMAGES}. They join every transformer pass as clean "+ "(t=0) image tokens, about 4096 tokens per megapixel each; with Reference K/V Cache on they run once "+ "instead of in every pass. Not combinable with style reference or regional prompts.",+ input=Input.Connection,+ title="Reference Latents",+ )+ reference_kv_cache: bool = InputField(+ default=False,+ description="For edit LoRAs trained with ai-toolkit's 'kv_cache' option, where reference tokens attend only "+ "to each other. The references then run through the transformer once per generation instead of in every "+ "pass, which is faster. Leave off for normal edit LoRAs. The LoRA file does not say which kind it is; "+ "check its model card. No effect without reference latents.",+ title="Reference K/V Cache",+ )@field_validator("cfg_scale")@classmethod@@ -325,6 +356,102 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):raise ValueError("denoising_start must be less than denoising_end.")if self.denoise_mask is not None and self.latents is None:raise ValueError("Initial latents are required when a denoise mask is provided.")+ self._validate_reference_latent_combination()++ def _reference_latent_fields(self) -> list[LatentsField]:+ if self.reference_latents is None:+ return []+ return [self.reference_latents] if isinstance(self.reference_latents, LatentsField) else self.reference_latents++ def _validate_reference_latent_combination(self) -> None:+ reference_fields = self._reference_latent_fields()+ if not reference_fields:+ return+ if len(reference_fields) > KREA2_MAX_REFERENCE_IMAGES:+ raise ValueError(+ f"Krea-2 accepts at most {KREA2_MAX_REFERENCE_IMAGES} reference latents, got {len(reference_fields)}."+ )+ # Style reference splices its keys/values in assuming the image tokens are the tail of the sequence,+ # and a regional mask is sized for exactly [text | target]. Reference tokens break both.+ if self.style_reference is not None and self.style_reference.style_strength > 0:+ raise ValueError("Krea-2 reference latents cannot be combined with a style reference. Disconnect one.")+ conditioning_fields = [+ field+ for conditioning in (self.positive_conditioning, self.negative_conditioning)+ if conditioning is not None+ for field in (conditioning if isinstance(conditioning, list) else [conditioning])+ ]+ if any(field.mask is not None for field in conditioning_fields):+ raise ValueError(+ "Krea-2 reference latents cannot be combined with regional (masked) prompts. Remove the masks "+ "or disconnect the reference latents."+ )+ if (+ self.reference_kv_cache+ and type(self)._install_attention_processors is not Krea2DenoiseInvocation._install_attention_processors+ ):+ # The cache lives in this node's own attention processors, which a subclass replaces.+ raise ValueError(+ f"'{type(self).__name__}' installs its own Krea-2 attention processors, which the reference K/V "+ "cache would replace. Use the stock 'Denoise - Krea-2' node for it."+ )++ def _validate_reference_counts(self, context: InvocationContext) -> None:+ """Each prompt must have seen exactly the references the denoise is given.++ The encoder numbers the references it saw ("Picture 1", ...) and the transformer numbers the reference+ latents by their position ids. An edit LoRA is trained with the two agreeing; a mismatch -- a reference+ missing on one side, or a prompt encoded without them -- would condition on an image the other side+ never sees.+ """+ reference_count = len(self._reference_latent_fields())+ # The negative prompt only runs when some step applies CFG; an unused one need not match.+ cfg_values = self.cfg_scale if isinstance(self.cfg_scale, list) else [self.cfg_scale]+ checked = [("positive", self.positive_conditioning)]+ if any(value > 1.0 for value in cfg_values):+ checked.append(("negative", self.negative_conditioning))+ for label, conditioning in checked:+ if conditioning is None:+ continue+ for field in conditioning if isinstance(conditioning, list) else [conditioning]:+ info = context.conditioning.load(field.conditioning_name).conditionings[0]+ encoded_count = getattr(info, "num_reference_images", 0)+ if encoded_count != reference_count:+ raise ValueError(+ f"The {label} Krea-2 prompt was encoded with {encoded_count} reference image(s), but the "+ f"denoise node has {reference_count} reference latents. Connect the same reference images, "+ "in the same order, to the prompt and (through 'Image to Latents - Qwen Image') to the "+ "denoise node."+ )++ def _load_reference_latents(+ self, context: InvocationContext, dtype: torch.dtype, device: torch.device+ ) -> tuple[torch.Tensor | None, list[tuple[int, int]]]:+ """Load and pack the reference latents: every reference's tokens in order, and each one's patch grid."""+ packed: list[torch.Tensor] = []+ grids: list[tuple[int, int]] = []+ for index, field in enumerate(self._reference_latent_fields(), start=1):+ latents = context.tensors.load(field.latents_name)+ if latents.dim() == 5 and latents.shape[2] == 1:+ # The Qwen-Image VAE emits a single-frame axis.+ latents = latents.squeeze(2)+ if latents.dim() != 4 or latents.shape[0] != 1 or latents.shape[1] != KREA2_LATENT_CHANNELS:+ raise ValueError(+ f"Krea-2 reference latents {index} have shape {tuple(latents.shape)}; expected "+ f"(1, {KREA2_LATENT_CHANNELS}, height, width) from the Qwen-Image VAE."+ )+ _, _, height, width = latents.shape+ if height == 0 or width == 0 or height % 2 or width % 2:+ raise ValueError(+ f"Krea-2 reference latents {index} are {height}x{width}; the transformer packs 2x2 patches, so "+ "both sides must be even. Encode the reference at a multiple of 16 pixels."+ )+ latents = latents.to(device=device, dtype=dtype)+ packed.append(pack_latents(latents, 1, KREA2_LATENT_CHANNELS, height, width))+ grids.append((height // 2, width // 2))+ if not packed:+ return None, []+ return torch.cat(packed, dim=1), gridsdef _is_distilled(self, context: InvocationContext) -> bool:"""Whether the transformer is the distilled Turbo checkpoint (fixed mu) vs. Raw (dynamic mu).@@ -360,6 +487,14 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):device = TorchDevice.choose_torch_device()inference_dtype = TorchDevice.choose_bfloat16_safe_dtype(device)+ # Before the transformer loads, so a malformed reference fails before anything is spent on the model.+ self._validate_reference_counts(context)+ reference_tokens, reference_grids = self._load_reference_latents(context, inference_dtype, device)+ reference_seq_len = 0 if reference_tokens is None else reference_tokens.shape[1]+ # K/V-cache mode keeps the references out of the per-step sequence: they run once, alone, before the loop.+ cache_references = self.reference_kv_cache and reference_tokens is not None+ joint_references = None if cache_references else reference_tokens+transformer_info = context.models.load(self.transformer.transformer)latent_height = self.height // LATENT_SCALE_FACTOR@@ -476,17 +611,17 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):# Pack latents into 2x2 patches: (B, C, H, W) -> (B, grid_h*grid_w, C*4).latents = pack_latents(latents, 1, KREA2_LATENT_CHANNELS, latent_height, latent_width)- # Position ids: text tokens at origin, image tokens carry their grid coords.- text_seq_len = pos_prompt_embeds.shape[1]- position_ids = prepare_position_ids(text_seq_len, grid_height, grid_width, device)+ # Position ids: text tokens at origin, image tokens carry their grid coords, reference i its (i, h, w).+ def build_position_ids(text_seq_len: int) -> torch.Tensor:+ if joint_references is None:+ return prepare_position_ids(text_seq_len, grid_height, grid_width, device)+ return prepare_position_ids_with_references(text_seq_len, grid_height, grid_width, reference_grids, device)++ position_ids = build_position_ids(pos_prompt_embeds.shape[1])# The negative prompt can tokenize to a different length than the positive prompt, so it needs its# own position ids. Reusing the positive ids would leave the rotary embedding (text + image tokens)# a different length than the uncond query sequence and crash in the transformer's apply_rotary_emb.- neg_position_ids = (- prepare_position_ids(neg_prompt_embeds.shape[1], grid_height, grid_width, device)- if neg_prompt_embeds is not None- else None- )+ neg_position_ids = build_position_ids(neg_prompt_embeds.shape[1]) if neg_prompt_embeds is not None else None# Inpaint extension operates in 4D, so unpack/repack around each merge.inpaint_mask = self._prep_inpaint_mask(context, noise)@@ -558,8 +693,10 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):regional_attention_mask_bytes = self._regional_attention_mask_bytes(pos_extension, neg_extension, inference_dtype)+ # Joint references are image tokens to every block and count in full toward the activations. Cached ones+ # only run in the one reference-only pass, and their K/V stay resident for the whole loop.estimated_working_memory = self._estimate_working_memory(- image_seq_len=image_seq_len,+ image_seq_len=image_seq_len + (0 if cache_references else reference_seq_len),positive_text_seq_len=pos_prompt_embeds.shape[1],negative_text_seq_len=neg_prompt_embeds.shape[1] if neg_prompt_embeds is not None else None,do_cfg=do_cfg,@@ -568,13 +705,28 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):style_reference_kv_bytes=(style_extension.kv_cache_bytes(inference_dtype) if style_extension is not None else 0),+ reference_precompute_seq_len=reference_seq_len if cache_references else 0,+ reference_kv_bytes=(+ self._reference_kv_cache_bytes(transformer_info.model, reference_seq_len, inference_dtype)+ if cache_references+ else 0+ ),)# The activation estimate assumes a fused kernel. Where the build has none for this attention -- ROCm on# Windows, MPS -- the score matrix is built as well (chunked on ROCm, see `install_rocm_sdpa_guard`).+ step_seq_len = image_seq_len + max(+ pos_prompt_embeds.shape[1], neg_prompt_embeds.shape[1] if neg_prompt_embeds is not None else 0+ )+ if cache_references:+ # Each pass's S queries see S + R keys, and the one reference-only pass is R x R. The helper prices a+ # square, so it gets the side of the larger area, rounded up.+ score_area = max(step_seq_len * (step_seq_len + reference_seq_len), reference_seq_len**2)+ score_seq_len = math.isqrt(score_area - 1) + 1+ else:+ score_seq_len = step_seq_len + reference_seq_lenestimated_working_memory += self._attention_score_bytes(transformer_info.model,- seq_len=image_seq_len- + max(pos_prompt_embeds.shape[1], neg_prompt_embeds.shape[1] if neg_prompt_embeds is not None else 0),+ seq_len=score_seq_len,has_attn_mask=regional_attention_mask_bytes > 0,device=device,dtype=inference_dtype,@@ -604,6 +756,11 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):attention_state = self._install_attention_processors(transformer, exit_stack)if style_extension is not None:self._install_style_reference_processors(transformer, exit_stack, attention_state, style_extension)+ reference_kv = (+ self._install_reference_kv_processors(transformer, exit_stack, attention_state)+ if cache_references+ else None+ )exit_stack.enter_context(LayerPatcher.apply_smart_model_patches(@@ -626,6 +783,18 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):# the sampler will use.style_extension.prepare([sigma.item() for sigma in sigmas_sched[:total_steps]])+ if reference_kv is not None:+ assert reference_tokens is not None+ # After the LoRA patcher, whose weights shape the reference K/V. Once per generation: the cache+ # depends on neither the prompt nor the timestep, so it serves every step and both CFG passes.+ context.util.signal_progress("Precomputing reference K/V")+ precompute_reference_kv(+ transformer,+ reference_tokens,+ prepare_reference_position_ids(reference_grids, device),+ reference_kv,+ )+# An INVOKE_KREA2_SDPA_BACKEND override pins one PyTorch kernel to measure it; SageAttention must not# serve those calls instead.if resolve_krea2_sdpa_backends().override is None:@@ -633,6 +802,28 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):benchmark = _Krea2StepBenchmark.create(device)+ def predict(+ model_latents: torch.Tensor,+ prompt_embeds: torch.Tensor,+ timestep: torch.Tensor,+ pass_position_ids: torch.Tensor,+ ) -> torch.Tensor:+ if joint_references is None:+ # Cached references enter through the attention processors.+ return transformer(+ hidden_states=model_latents,+ encoder_hidden_states=prompt_embeds,+ encoder_attention_mask=None,+ timestep=timestep,+ position_ids=pass_position_ids,+ return_dict=False,+ )[0]+ # Both CFG passes carry the references (as in Qwen-Image-Edit), so guidance contrasts the+ # prompts and not the presence of the edit reference.+ return forward_with_references(+ transformer, model_latents, prompt_embeds, timestep, pass_position_ids, joint_references+ )+for step_idx, t in enumerate(tqdm(timesteps_sched)):if benchmark is not None:benchmark.start_step()@@ -664,27 +855,13 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):# cfg ~4. The single reference pass above is shared by both.with style_pass:self._install_attention_payload(attention_state, pos_attention_payload)- noise_pred_cond = transformer(- hidden_states=model_latents,- encoder_hidden_states=pos_prompt_embeds,- encoder_attention_mask=None,- timestep=timestep,- position_ids=position_ids,- return_dict=False,- )[0]+ noise_pred_cond = predict(model_latents, pos_prompt_embeds, timestep, position_ids)if self._should_apply_cfg_for_step(cfg_scale[step_idx], has_negative_conditioning=neg_prompt_embeds is not None):self._install_attention_payload(attention_state, neg_attention_payload)- noise_pred_uncond = transformer(- hidden_states=model_latents,- encoder_hidden_states=neg_prompt_embeds,- encoder_attention_mask=None,- timestep=timestep,- position_ids=neg_position_ids,- return_dict=False,- )[0]+ noise_pred_uncond = predict(model_latents, neg_prompt_embeds, timestep, neg_position_ids)noise_pred = noise_pred_uncond + cfg_scale[step_idx] * (noise_pred_cond - noise_pred_uncond)else:noise_pred = noise_pred_cond@@ -783,6 +960,38 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):# to ~1.7 GiB at 2560x1440 and would otherwise stay on the cached transformer.exit_stack.callback(style_state.clear)+ def _install_reference_kv_processors(+ self,+ transformer: torch.nn.Module,+ exit_stack: ExitStack,+ attention_state: Krea2RegionalPromptingState,+ ) -> Krea2ReferenceKVCache:+ """Re-install the processors so every main block also carries the edit-reference K/V cache.++ Like style reference, kept out of ``_install_attention_processors`` so that seam's signature stays as node+ packs know it; subclasses overriding it are refused in validation.+ """+ cache = Krea2ReferenceKVCache()+ transformer.set_attn_processor(+ build_krea2_attention_processors(transformer, attention_state, reference_kv_cache=cache)+ )+ # ~0.66 GiB per 1 MP reference in bf16, retained on the cached transformer's processors unless dropped here.+ exit_stack.callback(cache.clear)+ return cache++ @staticmethod+ def _reference_kv_cache_bytes(transformer: object, reference_seq_len: int, dtype: torch.dtype) -> int:+ """Size of the edit-reference K/V cache, from the loaded model's config (Krea-2 defaults where absent)."""+ config = getattr(transformer, "config", None)+ return reference_kv_cache_bytes(+ num_layers=getattr(config, "num_layers", KREA2_NUM_BLOCKS),+ num_heads=getattr(config, "num_attention_heads", 48),+ num_kv_heads=getattr(config, "num_key_value_heads", KREA2_NUM_KV_HEADS),+ head_dim=getattr(config, "attention_head_dim", KREA2_HEAD_DIM),+ reference_seq_len=reference_seq_len,+ element_size=torch.empty((), dtype=dtype).element_size(),+ )+@staticmethoddef _clear_attention_state(state: Krea2RegionalPromptingState) -> None:"""Drop every tensor the shared attention state retains. Override alongside the state object."""@@ -854,6 +1063,8 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):num_loras: int,regional_attention_mask_bytes: int = 0,style_reference_kv_bytes: int = 0,+ reference_precompute_seq_len: int = 0,+ reference_kv_bytes: int = 0,) -> int:"""Estimate peak transformer activation memory (bytes) so the model cache reserves enough headroom.@@ -876,7 +1087,9 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):MB = 1024**2per_token_bytes = int(0.5 * MB)text_seq_len = max(positive_text_seq_len, negative_text_seq_len or 0)- estimated = (image_seq_len + text_seq_len) * per_token_bytes+ # The edit-reference K/V precompute runs the references alone, before the loop; its peak is the larger+ # one when the references outnumber the per-step tokens.+ estimated = max(image_seq_len + text_seq_len, reference_precompute_seq_len) * per_token_bytesestimated += int(1.5 * GB)if do_cfg:# Conditional/unconditional passes are sequential, but the larger combined sequence and extra@@ -894,6 +1107,8 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):# after the multiplier rather than scaled by it.estimated = int(estimated * 1.35)estimated += style_reference_kv_bytes+ # The cached reference K/V are an exact size and stay resident through the loop, like the style cache.+ estimated += reference_kv_bytesif num_loras > 0:estimated += int(0.5 * num_loras * GB)return estimateddiff --git a/invokeai/app/invocations/krea2/krea2_seed_variance.py b/invokeai/app/invocations/krea2/krea2_seed_variance.pyindex 65a37f4040..f5866378a1 100644--- a/invokeai/app/invocations/krea2/krea2_seed_variance.py+++ b/invokeai/app/invocations/krea2/krea2_seed_variance.py@@ -79,7 +79,11 @@ class Krea2SeedVarianceInvocation(BaseInvocation):new_data = ConditioningFieldData(conditionings=[- Krea2ConditioningInfo(prompt_embeds=embeds, prompt_embeds_mask=conditioning.prompt_embeds_mask)+ Krea2ConditioningInfo(+ prompt_embeds=embeds,+ prompt_embeds_mask=conditioning.prompt_embeds_mask,+ num_reference_images=conditioning.num_reference_images,+ )])conditioning_name = context.conditioning.save(new_data)diff --git a/invokeai/app/invocations/text_encoder/krea2_text_encoder.py b/invokeai/app/invocations/text_encoder/krea2_text_encoder.pyindex e6b807faf4..1a5f53db54 100644--- a/invokeai/app/invocations/text_encoder/krea2_text_encoder.py+++ b/invokeai/app/invocations/text_encoder/krea2_text_encoder.py@@ -7,6 +7,7 @@ import torchfrom invokeai.app.invocations.baseinvocation import BaseInvocation, Classification, invocationfrom invokeai.app.invocations.fields import (FieldDescriptions,+ ImageField,Input,InputField,TensorField,@@ -15,8 +16,16 @@ from invokeai.app.invocations.fields import (from invokeai.app.invocations.model import Qwen3VLEncoderFieldfrom invokeai.app.invocations.primitives import Krea2ConditioningOutputfrom invokeai.app.services.shared.invocation_context import InvocationContext-from invokeai.backend.krea2.text_encoding import encode_krea2_prompt+from invokeai.backend.krea2.text_encoding import (+ KREA2_MAX_REFERENCE_IMAGES,+ encode_krea2_prompt,+ encode_krea2_prompt_with_images,+ prepare_vlm_reference,+ tokenize_krea2_prompt_with_images,+ working_memory_bytes,+)from invokeai.backend.model_manager.load.model_cache.utils import get_effective_device+from invokeai.backend.model_manager.taxonomy import SubModelTypefrom invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpecfrom invokeai.backend.patches.lora_conversions.krea2_lora_constants import KREA2_LORA_QWEN3VL_PREFIXfrom invokeai.backend.patches.model_patch_raw import ModelPatchRaw@@ -33,7 +42,9 @@ from invokeai.backend.util.devices import TorchDevice# layers now resolve to no module. Left to the patcher that is one "Failed to find module for LoRA# layer key" per layer per generation (~108 lines on the 4B, whose vision tower has 27 blocks),# reading as though the adapter were broken. It is not, and it never did anything: patching a module-# that `forward` does not reach cannot change an image.+# that `forward` does not reach cannot change an image. With reference images the tower is a separate cache+# entry lent to the encoder only after the patches are in place, so its layers stay unpatched there too:+# ai-toolkit trains edit LoRAs with the encoder frozen._VISUAL_TOWER_LORA_LAYERS = re.compile(rf"^{re.escape(KREA2_LORA_QWEN3VL_PREFIX)}visual\.")@@ -42,7 +53,7 @@ _VISUAL_TOWER_LORA_LAYERS = re.compile(rf"^{re.escape(KREA2_LORA_QWEN3VL_PREFIX)title="Prompt - Krea-2",tags=["prompt", "conditioning", "krea2", "krea-2"],category="conditioning",- version="1.1.0",+ version="1.2.0",classification=Classification.Prototype,idle_gpu_offloadable=True,)@@ -51,6 +62,9 @@ class Krea2TextEncoderInvocation(BaseInvocation):The encoder taps 12 decoder hidden-state layers and stacks them per token, producing a 4Dconditioning tensor (B, seq, 12, hidden) that the Krea-2 transformer's text-fusion stage consumes.++ With reference images (edit mode, for edit LoRAs) the Qwen3-VL vision tower reads them into the prompt,+ ahead of the text, and the conditioning has the prompt's natural length rather than 512 tokens."""prompt: str = InputField(description="Text prompt describing the desired image.", ui_component=UIComponent.Textarea)@@ -64,6 +78,12 @@ class Krea2TextEncoderInvocation(BaseInvocation):description=FieldDescriptions.qwen3_vl_encoder,input=Input.Connection,)+ reference_images: list[ImageField] = InputField(+ default=[],+ max_length=KREA2_MAX_REFERENCE_IMAGES,+ description="Up to three reference images for an edit LoRA, read by the Qwen3-VL vision tower in this order "+ "(Picture 1, 2, 3). Needs a safetensors or Diffusers encoder: a GGUF encoder has no vision tower.",+ )@torch.no_grad()def invoke(self, context: InvocationContext) -> Krea2ConditioningOutput:@@ -72,12 +92,30 @@ class Krea2TextEncoderInvocation(BaseInvocation):prompt_mask = prompt_mask.detach().to("cpu") if prompt_mask is not None else Noneconditioning_data = ConditioningFieldData(- conditionings=[Krea2ConditioningInfo(prompt_embeds=prompt_embeds, prompt_embeds_mask=prompt_mask)]+ conditionings=[+ Krea2ConditioningInfo(+ prompt_embeds=prompt_embeds,+ prompt_embeds_mask=prompt_mask,+ num_reference_images=len(self.reference_images),+ )+ ])conditioning_name = context.conditioning.save(conditioning_data)return Krea2ConditioningOutput.build(conditioning_name, mask=self.mask)def _encode(self, context: InvocationContext) -> tuple[torch.Tensor, torch.Tensor | None]:+ images = [prepare_vlm_reference(context.images.get_pil(field.image_name)) for field in self.reference_images]+ vision_info = processor_info = None+ if images:+ # Before the encoder: the loader refuses an encoder without a tower (GGUF) here, ahead of reading+ # the far larger language tower for nothing. Both are their own cache entries, so text-only+ # prompts never pay for them.+ vision_info = context.models.load(+ self.qwen3_vl_encoder.text_encoder.model_copy(update={"submodel_type": SubModelType.VisionEncoder})+ )+ processor_info = context.models.load(+ self.qwen3_vl_encoder.tokenizer.model_copy(update={"submodel_type": SubModelType.Processor})+ )tokenizer_info = context.models.load(self.qwen3_vl_encoder.tokenizer)text_encoder_info = context.models.load(self.qwen3_vl_encoder.text_encoder)text_encoder_format = context.models.get_config(self.qwen3_vl_encoder.text_encoder).format@@ -92,8 +130,15 @@ class Krea2TextEncoderInvocation(BaseInvocation):with ExitStack() as exit_stack:tokenizer = exit_stack.enter_context(tokenizer_info)+ working_mem_bytes = dequant_bytes+ image_inputs = None+ if processor_info is not None:+ processor = exit_stack.enter_context(processor_info)+ image_inputs = tokenize_krea2_prompt_with_images(self.prompt, images, processor, tokenizer)+ # The references lengthen the sequence, and attention grows with its square.+ working_mem_bytes += working_memory_bytes(image_inputs["input_ids"].shape[1])(cached_weights, text_encoder) = exit_stack.enter_context(- text_encoder_info.model_on_device(working_mem_bytes=dequant_bytes)+ text_encoder_info.model_on_device(working_mem_bytes=working_mem_bytes))device = get_effective_device(text_encoder)@@ -119,7 +164,15 @@ class Krea2TextEncoderInvocation(BaseInvocation):))- prompt_embeds, prompt_mask, _ = encode_krea2_prompt(self.prompt, tokenizer, text_encoder)+ if image_inputs is None:+ prompt_embeds, prompt_mask, _ = encode_krea2_prompt(self.prompt, tokenizer, text_encoder)+ else:+ assert vision_info is not None+ # Locked after the encoder and released before it (the stack unwinds in reverse), and the+ # encode undoes the swap before returning: neither cache entry may be moved while the tower is+ # part of the encoder's module tree.+ (_, vision_tower) = exit_stack.enter_context(vision_info.model_on_device())+ prompt_embeds, prompt_mask = encode_krea2_prompt_with_images(image_inputs, text_encoder, vision_tower)return prompt_embeds, prompt_maskdiff --git a/invokeai/app/invocations/vae/qwen_image_image_to_latents.py b/invokeai/app/invocations/vae/qwen_image_image_to_latents.pyindex 6331494c0f..69d7c2dc8a 100644--- a/invokeai/app/invocations/vae/qwen_image_image_to_latents.py+++ b/invokeai/app/invocations/vae/qwen_image_image_to_latents.py@@ -1,5 +1,9 @@+import math+import einopsimport torch+import torch.nn.functional as F+import torchvision.transforms.functional as tv_functionalfrom PIL import Image as PILImagefrom invokeai.app.invocations.baseinvocation import BaseInvocation, Classification, invocation@@ -25,13 +29,50 @@ from invokeai.backend.util.qwen_image_vae import ()from invokeai.backend.util.vae_working_memory import estimate_vae_working_memory_qwen_image+# Krea-2 edit-reference sizing, as ai-toolkit trains Krea-2 edit LoRAs (krea2 `_encode_ref_latents`):+# references above 1 MP are scaled to that area, and every side rounds to the VAE (8) x patch (2) grid.+REFERENCE_MAX_PIXELS = 1024 * 1024+REFERENCE_GRID = 16+++def reference_image_size(height: int, width: int) -> tuple[int, int]:+ """The (height, width) a Krea-2 edit reference is encoded at, exactly as ai-toolkit sizes it.++ An image above 1 MP is scaled to about 1 MP, keeping its aspect ratio; a smaller one keeps its size.+ Each side then rounds to the nearest multiple of 16 (at least 16), so the result can land slightly+ above 1 MP and a side under 16 pixels grows to 16.+ """+ new_height, new_width = float(height), float(width)+ if height * width > REFERENCE_MAX_PIXELS:+ ratio = height / width+ new_height = math.sqrt(REFERENCE_MAX_PIXELS * ratio)+ new_width = new_height / ratio+ return (+ max(REFERENCE_GRID, int(round(new_height / REFERENCE_GRID)) * REFERENCE_GRID),+ max(REFERENCE_GRID, int(round(new_width / REFERENCE_GRID)) * REFERENCE_GRID),+ )+++def reference_image_tensor(image: PILImage.Image) -> torch.Tensor:+ """An edit reference as a (1, 3, H, W) tensor in [-1, 1].++ RGB with any alpha dropped (not composited), resized bilinearly without antialiasing, and only when+ the size changes -- the exact preprocessing the edit LoRAs saw in training.+ """+ tensor = tv_functional.to_tensor(image.convert("RGB")).unsqueeze(0)+ height, width = tensor.shape[-2:]+ size = reference_image_size(height, width)+ if size != (height, width):+ tensor = F.interpolate(tensor, size=size, mode="bilinear")+ return tensor * 2.0 - 1.0+@invocation("qwen_image_i2l",title="Image to Latents - Qwen Image",tags=["image", "latents", "vae", "i2l", "qwen_image"],category="image",- version="1.1.0",+ version="1.2.0",classification=Classification.Prototype,)class QwenImageImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard):@@ -56,6 +97,13 @@ class QwenImageImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard)default=None,description="Resize the image to this height before encoding. If not set, encodes at the image's original size.",)+ reference: bool = InputField(+ default=False,+ description="Encode as a Krea-2 edit reference (for 'Denoise - Krea-2' reference latents), sized as "+ "ai-toolkit trains Krea-2 edit LoRAs: RGB with alpha dropped; an image above 1 megapixel is scaled to "+ "about 1 megapixel keeping its aspect ratio; each side is rounded to a multiple of 16; resized "+ "bilinearly. Not the Qwen-Image Edit path. Width and height must be left unset.",+ )@staticmethoddef vae_encode(@@ -113,22 +161,28 @@ class QwenImageImageToLatentsInvocation(BaseInvocation, WithMetadata, WithBoard)def invoke(self, context: InvocationContext) -> LatentsOutput:image = context.images.get_pil(self.image.image_name)- # If target dimensions are specified, resize the image BEFORE encoding- # (matching the diffusers pipeline which resizes in pixel space, not latent space).- ## `width`/`height` are `int | None`, but the workflow UI cannot represent None in a number# input and sends 0 for "unset" — which `is not None`, so a naive check reached# `resize((0, 0))` and raised "height and width must be > 0". Treat any non-positive value# as unset, which is also how `tile_size` uses 0. Note this means a half-filled pair (e.g.# width=1024, height=0) encodes at the original size rather than raising.- if (self.width or 0) > 0 and (self.height or 0) > 0:- image = image.convert("RGB").resize((self.width, self.height), resample=PILImage.LANCZOS)-- # multiple_of=16 ensures the post-VAE latents (vae_scale_factor=8) have even- # spatial dims, which the transformer's 2x2 patch packing requires.- image_tensor = image_resized_to_grid_as_tensor(image.convert("RGB"), multiple_of=16)- if image_tensor.dim() == 3:- image_tensor = einops.rearrange(image_tensor, "c h w -> 1 c h w")+ has_target_size = (self.width or 0) > 0 and (self.height or 0) > 0++ if self.reference:+ if has_target_size:+ raise ValueError("An edit reference is sized automatically; leave width and height unset.")+ image_tensor = reference_image_tensor(image)+ else:+ # If target dimensions are specified, resize the image BEFORE encoding+ # (matching the diffusers pipeline which resizes in pixel space, not latent space).+ if has_target_size:+ image = image.convert("RGB").resize((self.width, self.height), resample=PILImage.LANCZOS)++ # multiple_of=16 ensures the post-VAE latents (vae_scale_factor=8) have even+ # spatial dims, which the transformer's 2x2 patch packing requires.+ image_tensor = image_resized_to_grid_as_tensor(image.convert("RGB"), multiple_of=16)+ if image_tensor.dim() == 3:+ image_tensor = einops.rearrange(image_tensor, "c h w -> 1 c h w")vae_info = context.models.load(self.vae.vae)diff --git a/invokeai/backend/krea2/attention.py b/invokeai/backend/krea2/attention.pyindex 97769302e3..cecae07d99 100644--- a/invokeai/backend/krea2/attention.py+++ b/invokeai/backend/krea2/attention.py@@ -31,6 +31,7 @@ import torch.nn.functional as Ffrom diffusers.models.embeddings import apply_rotary_embfrom torch.nn.attention import SDPBackend+from invokeai.backend.krea2.reference_edit import Krea2ReferenceKVCache, Krea2ReferenceKVModefrom invokeai.backend.krea2.style_reference import (Krea2StyleReferenceMode,Krea2StyleReferenceState,@@ -140,6 +141,7 @@ class Krea2MemoryEfficientAttnProcessor:sdpa_backends: Krea2SdpaBackends | None = None,style_reference_state: Krea2StyleReferenceState | None = None,block_index: int | None = None,+ reference_kv_cache: Krea2ReferenceKVCache | None = None,) -> None:self.regional_prompting_state = regional_prompting_state# Resolved once per generation and handed down, not read per attention call.@@ -148,6 +150,8 @@ class Krea2MemoryEfficientAttnProcessor:# nothing beyond the identity check below.self.style_reference_state = style_reference_stateself.block_index = block_index+ # Only set on the main blocks while an edit reference runs in K/V-cache mode; see reference_edit.py.+ self.reference_kv_cache = reference_kv_cachedef __call__(self,@@ -184,6 +188,15 @@ class Krea2MemoryEfficientAttnProcessor:key = key.transpose(1, 2)value = value.transpose(1, 2)+ # The edit-reference K/V cache hooks in at the same point as style reference below: post-RoPE, so the+ # cached keys carry the references' own rotation, and pre GQA expansion. The two never run together.+ reference_kv = self.reference_kv_cache+ if reference_kv is not None and self.block_index is not None:+ if reference_kv.mode is Krea2ReferenceKVMode.CAPTURE:+ reference_kv.store(self.block_index, key, value)+ elif reference_kv.mode is Krea2ReferenceKVMode.APPEND:+ key, value = reference_kv.extend(self.block_index, key, value, attention_mask)+# Style reference hooks in here: after RoPE (so the captured keys carry their rotation) but before# the GQA head expansion, which keeps the retained cache 4x smaller. See style_reference.py.style_state = self.style_reference_state@@ -295,6 +308,7 @@ def build_krea2_attention_processors(regional_prompting_state: Krea2RegionalPromptingState,style_reference_state: Krea2StyleReferenceState | None = None,style_reference_blocks: Iterable[int] | None = None,+ reference_kv_cache: Krea2ReferenceKVCache | None = None,) -> dict[str, Krea2MemoryEfficientAttnProcessor]:"""Build processors that apply regional masks to alternating main transformer blocks only.@@ -302,8 +316,10 @@ def build_krea2_attention_processors(parities), so it gets a second state object rather than sharing the regional one. Leaving both stylearguments unset reproduces the pre-style behaviour exactly.- The text-fusion blocks do not match the main-block pattern, so they never receive either state. That is- correct: they only ever see text tokens.+ The edit-reference K/V cache, when given, goes to every main block: each one captures and appends its own.++ The text-fusion blocks do not match the main-block pattern, so they never receive any of these states. That+ is correct: they only ever see text tokens."""style_blocks = frozenset(style_reference_blocks or ())@@ -331,5 +347,6 @@ def build_krea2_attention_processors(sdpa_backends=sdpa_backends,style_reference_state=style,block_index=block_index,+ reference_kv_cache=reference_kv_cache if block_index is not None else None,)return processorsdiff --git a/invokeai/backend/krea2/reference_edit.py b/invokeai/backend/krea2/reference_edit.pynew file mode 100644index 0000000000..f5876e62a6--- /dev/null+++ b/invokeai/backend/krea2/reference_edit.py@@ -0,0 +1,256 @@+"""Reference-image ("edit") conditioning for the Krea-2 transformer.++Krea-2 edit LoRAs (ai-toolkit ``krea2`` trained with ``edit: true``, e.g. pose or depth "controlnet"+LoRAs) condition on clean reference latents that ride along in the image sequence. This is ComfyUI's+"index_timestep_zero" reference method, and it is what those LoRAs were trained with:++- every reference is packed like the target and appended after it: ``[text | target | ref 1 | ...]``,+ all through ``img_in`` together;+- reference ``i`` gets rotary coordinates ``(i, h, w)``+ (``sampling_utils.prepare_position_ids_with_references``);+- text and target are modulated with the real timestep, the reference span with timestep 0 -- the+ references are clean, so they are presented as fully denoised;+- attention is full joint attention over the whole sequence, and only the target tokens are returned.++Some edit LoRAs are trained with ai-toolkit's ``kv_cache`` option ("isolate_refs") instead: reference+queries attend only to reference keys, everyone else sees everything. The reference hidden states then+depend on neither the text nor the timestep, so ``precompute_reference_kv`` runs the references alone+through the blocks once, at t=0, and ``Krea2ReferenceKVCache`` hands every block's post-RoPE K/V to its+attention processor, which appends them to the keys/values of the ordinary ``[text | target]`` pass. This+is exactly the joint pass with the isolating mask, at a fraction of the cost (ostris+``_precompute_ref_kv`` / ``_forward_with_cached_refs``). Nothing in a LoRA file says which mode it was+trained with.++The diffusers forward has no seam for a second modulation, so ``forward_with_references`` restates it+(``Krea2Transformer2DModel.forward``, diffusers 0.41) from the model's own modules. Every submodule is+still called as a module, so InvokeAI's attention processors, LoRA patches and layer-wise casting+apply unchanged. Without references it reproduces the stock forward exactly; the tests pin both.++References: ComfyUI ``comfy/ldm/krea2/model.py`` (``_forward``, ``timestep_zero_index``), ostris+``ComfyUI-Krea2-Ostris-Edit`` (``_forward_with_refs``), ai-toolkit+``extensions_built_in/diffusion_models/krea2/src/mmdit.py``.+"""++from dataclasses import dataclass, field+from enum import Enum++import torch+import torch.nn.functional as F+++def block_forward_split(+ block: torch.nn.Module,+ hidden_states: torch.Tensor,+ temb_mod: torch.Tensor,+ temb_mod_ref: torch.Tensor,+ split: int,+ image_rotary_emb: tuple[torch.Tensor, torch.Tensor],+ attention_mask: torch.Tensor | None = None,+) -> torch.Tensor:+ """``Krea2TransformerBlock.forward`` with two modulations: ``temb_mod`` for tokens ``[:split]``+ (text + target) and ``temb_mod_ref`` for tokens ``[split:]`` (the references).++ Both halves are modulated and gated separately and joined again, so attention and the MLP still see+ the whole sequence. The arithmetic per token is the stock block's, out of place, so mixed parameter+ dtypes promote exactly as they do there.+ """+ modulation = temb_mod.unflatten(-1, (6, -1)) + block.scale_shift_table+ ref_modulation = temb_mod_ref.unflatten(-1, (6, -1)) + block.scale_shift_table+ prescale, preshift, pregate, postscale, postshift, postgate = modulation.unbind(-2)+ ref_prescale, ref_preshift, ref_pregate, ref_postscale, ref_postshift, ref_postgate = ref_modulation.unbind(-2)++ def modulate(+ normed: torch.Tensor,+ scale: torch.Tensor,+ shift: torch.Tensor,+ ref_scale: torch.Tensor,+ ref_shift: torch.Tensor,+ ) -> torch.Tensor:+ return torch.cat(+ [(1.0 + scale) * normed[:, :split] + shift, (1.0 + ref_scale) * normed[:, split:] + ref_shift], dim=1+ )++ def gate(output: torch.Tensor, gate: torch.Tensor, ref_gate: torch.Tensor) -> torch.Tensor:+ return torch.cat([gate * output[:, :split], ref_gate * output[:, split:]], dim=1)++ attn_out = block.attn(+ modulate(block.norm1(hidden_states), prescale, preshift, ref_prescale, ref_preshift),+ attention_mask=attention_mask,+ image_rotary_emb=image_rotary_emb,+ )+ hidden_states = hidden_states + gate(attn_out, pregate, ref_pregate)+ ff_out = block.ff(modulate(block.norm2(hidden_states), postscale, postshift, ref_postscale, ref_postshift))+ hidden_states = hidden_states + gate(ff_out, postgate, ref_postgate)+ return hidden_states+++def forward_with_references(+ transformer: torch.nn.Module,+ hidden_states: torch.Tensor,+ encoder_hidden_states: torch.Tensor,+ timestep: torch.Tensor,+ position_ids: torch.Tensor,+ reference_hidden_states: torch.Tensor | None,+ encoder_attention_mask: torch.Tensor | None = None,+) -> torch.Tensor:+ """Predict the velocity for the target tokens with clean reference tokens in the sequence.++ Args:+ transformer: a diffusers ``Krea2Transformer2DModel``.+ hidden_states: packed noisy target latents, ``(B, target_len, in_channels)``.+ encoder_hidden_states: tapped text-encoder states, ``(B, text_len, num_text_layers, text_dim)``.+ timestep: flow time in ``[0, 1]``, ``(B,)``.+ position_ids: ``(text_len + target_len + reference_len, 3)``, from+ ``prepare_position_ids_with_references``.+ reference_hidden_states: all packed reference latents concatenated along the token axis,+ ``(B or 1, reference_len, in_channels)``. ``None`` runs this restated forward with the stock blocks;+ it exists so the restatement can be pinned against ``Krea2Transformer2DModel.forward`` -- the denoise+ node itself calls the stock transformer when there are no references.+ encoder_attention_mask: optional ``(B, text_len)`` boolean mask of valid text tokens.++ Returns:+ The velocity for the target tokens only, ``(B, target_len, in_channels)``.+ """+ batch_size, image_seq_len, _ = hidden_states.shape+ text_seq_len = encoder_hidden_states.shape[1]+ reference_seq_len = 0 if reference_hidden_states is None else reference_hidden_states.shape[1]+ expected_positions = text_seq_len + image_seq_len + reference_seq_len+ if position_ids.shape != (expected_positions, 3):+ raise ValueError(+ f"Krea-2 position_ids have shape {tuple(position_ids.shape)}, but text, target and reference tokens "+ f"need ({expected_positions}, 3)."+ )++ temb = transformer.time_embed(timestep, dtype=hidden_states.dtype)+ temb_mod = transformer.time_mod_proj(F.gelu(temb, approximate="tanh"))++ text_attention_mask = None+ attention_mask = None+ if encoder_attention_mask is not None:+ text_attention_mask = encoder_attention_mask[:, None, None, :]+ image_mask = encoder_attention_mask.new_ones((batch_size, image_seq_len + reference_seq_len))+ attention_mask = torch.cat([encoder_attention_mask, image_mask], dim=1)[:, None, None, :]++ encoder_hidden_states = transformer.text_fusion(encoder_hidden_states, attention_mask=text_attention_mask)+ encoder_hidden_states = transformer.txt_in(encoder_hidden_states)++ image_tokens = hidden_states+ if reference_hidden_states is not None:+ references = reference_hidden_states.to(dtype=hidden_states.dtype).expand(batch_size, -1, -1)+ image_tokens = torch.cat([hidden_states, references], dim=1)+ hidden_states = torch.cat([encoder_hidden_states, transformer.img_in(image_tokens)], dim=1)++ image_rotary_emb = transformer.rotary_emb(position_ids)++ target_end = text_seq_len + image_seq_len+ if reference_hidden_states is None:+ for block in transformer.transformer_blocks:+ hidden_states = block(hidden_states, temb_mod, image_rotary_emb, attention_mask)+ else:+ # The references are clean latents, so they are modulated as at t=0 on every step.+ temb_ref = transformer.time_embed(torch.zeros_like(timestep), dtype=hidden_states.dtype)+ temb_mod_ref = transformer.time_mod_proj(F.gelu(temb_ref, approximate="tanh"))+ for block in transformer.transformer_blocks:+ hidden_states = block_forward_split(+ block, hidden_states, temb_mod, temb_mod_ref, target_end, image_rotary_emb, attention_mask+ )++ # The final layer is modulated with the real timestep: it only ever sees the target tokens.+ return transformer.final_layer(hidden_states[:, text_seq_len:target_end], temb)+++class Krea2ReferenceKVMode(Enum):+ OFF = "off"+ CAPTURE = "capture"+ APPEND = "append"+++@dataclass+class Krea2ReferenceKVCache:+ """Per-block reference K/V shared between ``precompute_reference_kv`` and the blocks' attention processors.++ Tensors are ``[B, kv_heads, reference_len, head_dim]``, post-RoPE and pre GQA expansion. The processors+ stay installed on the cached transformer after the invocation, so :meth:`clear` belongs on the denoise+ node's exit stack.+ """++ mode: Krea2ReferenceKVMode = Krea2ReferenceKVMode.OFF+ _cache: dict[int, tuple[torch.Tensor, torch.Tensor]] = field(default_factory=dict, repr=False)++ def __len__(self) -> int:+ return len(self._cache)++ def store(self, block_index: int, key: torch.Tensor, value: torch.Tensor) -> None:+ self._cache[block_index] = (key, value)++ def extend(+ self, block_index: int, key: torch.Tensor, value: torch.Tensor, attention_mask: torch.Tensor | None+ ) -> tuple[torch.Tensor, torch.Tensor]:+ """Append this block's cached reference K/V to the live keys/values along the token axis."""+ if attention_mask is not None:+ # A mask sized for the live keys would not cover the appended ones. The denoise node never passes+ # one with references (no text padding mask; regional prompts are refused).+ raise ValueError("The Krea-2 reference K/V cache does not support attention masks.")+ try:+ cached_key, cached_value = self._cache[block_index]+ except KeyError as e:+ raise RuntimeError(f"Krea-2 reference K/V cache holds nothing for block {block_index}.") from e+ batch_size = key.shape[0]+ return (+ torch.cat([key, cached_key.expand(batch_size, -1, -1, -1)], dim=2),+ torch.cat([value, cached_value.expand(batch_size, -1, -1, -1)], dim=2),+ )++ def clear(self) -> None:+ """Drop every retained tensor. Wired to the denoise node's exit stack."""+ self.mode = Krea2ReferenceKVMode.OFF+ self._cache.clear()+++def precompute_reference_kv(+ transformer: torch.nn.Module,+ reference_hidden_states: torch.Tensor,+ reference_position_ids: torch.Tensor,+ cache: Krea2ReferenceKVCache,+) -> None:+ """Fill ``cache`` from one pass of the references alone, then switch it to appending.++ The references are modulated at t=0 and positioned by their own ids ``(i, h, w)``; each block's attention+ processor records its K/V, and the reference hidden states continue into the next block. Run it once per+ generation, with the LoRA patches already applied: they change the reference K/V.+ """+ hidden_states = transformer.img_in(reference_hidden_states)+ zero_timestep = torch.zeros(hidden_states.shape[0], device=hidden_states.device, dtype=hidden_states.dtype)+ temb_ref = transformer.time_embed(zero_timestep, dtype=hidden_states.dtype)+ temb_mod_ref = transformer.time_mod_proj(F.gelu(temb_ref, approximate="tanh"))+ image_rotary_emb = transformer.rotary_emb(reference_position_ids)++ cache.clear()+ cache.mode = Krea2ReferenceKVMode.CAPTURE+ try:+ for block in transformer.transformer_blocks:+ hidden_states = block(hidden_states, temb_mod_ref, image_rotary_emb, None)+ except BaseException:+ cache.clear()+ raise+ if len(cache) != len(transformer.transformer_blocks):+ cache.clear()+ raise RuntimeError(+ "The Krea-2 attention processors did not record the reference K/V of every block; the reference K/V "+ "cache needs the processors built with it."+ )+ cache.mode = Krea2ReferenceKVMode.APPEND+++def reference_kv_cache_bytes(+ *, num_layers: int, num_heads: int, num_kv_heads: int, head_dim: int, reference_seq_len: int, element_size: int+) -> int:+ """Memory the reference K/V cache adds to a denoise step.++ The retained cache (one key and one value per block, at the KV head count) plus one block's transient+ reference keys/values as attention sees them: concatenated to the live ones and, on builds without a+ fused grouped-query kernel, expanded to the query head count.+ """+ retained = num_layers * 2 * num_kv_heads * head_dim * reference_seq_len * element_size+ transient = 2 * num_heads * head_dim * reference_seq_len * element_size+ return retained + transientdiff --git a/invokeai/backend/krea2/sampling_utils.py b/invokeai/backend/krea2/sampling_utils.pyindex 875c7cefd4..0d74e7666a 100644--- a/invokeai/backend/krea2/sampling_utils.py+++ b/invokeai/backend/krea2/sampling_utils.py@@ -7,7 +7,7 @@ diffusers pipeline ``__call__``. These helpers replicate the Krea-2 sampling matReference: ``diffusers/pipelines/krea2/pipeline_krea2.py`` (diffusers main / 0.39.0.dev0)."""-from typing import List+from typing import List, Sequenceimport numpy as npimport torch@@ -61,6 +61,15 @@ def unpack_latents(latents: torch.Tensor, height: int, width: int) -> torch.Tensreturn latents+def _grid_position_ids(index: int, grid_height: int, grid_width: int, device: torch.device) -> torch.Tensor:+ """(grid_h*grid_w, 3) rotary coordinates (index, h, w) of one latent grid, row-major."""+ ids = torch.zeros(grid_height, grid_width, 3, device=device)+ ids[..., 0] = index+ ids[..., 1] = torch.arange(grid_height, device=device)[:, None]+ ids[..., 2] = torch.arange(grid_width, device=device)[None, :]+ return ids.reshape(grid_height * grid_width, 3)++def prepare_position_ids(text_seq_len: int, grid_height: int, grid_width: int, device: torch.device) -> torch.Tensor:"""Build the (text_seq_len + grid_h*grid_w, 3) rotary coordinates.@@ -68,11 +77,40 @@ def prepare_position_ids(text_seq_len: int, grid_height: int, grid_width: int, dcoordinates. Matches diffusers ``Krea2Pipeline.prepare_position_ids``."""text_ids = torch.zeros(text_seq_len, 3, device=device)- image_ids = torch.zeros(grid_height, grid_width, 3, device=device)- image_ids[..., 1] = torch.arange(grid_height, device=device)[:, None]- image_ids[..., 2] = torch.arange(grid_width, device=device)[None, :]- image_ids = image_ids.reshape(grid_height * grid_width, 3)- return torch.cat([text_ids, image_ids], dim=0)+ return torch.cat([text_ids, _grid_position_ids(0, grid_height, grid_width, device)], dim=0)+++def prepare_reference_position_ids(reference_grids: Sequence[tuple[int, int]], device: torch.device) -> torch.Tensor:+ """Rotary coordinates of the reference tokens alone: reference ``i`` (1-based) carries ``(i, h, w)`` over its+ own ``(grid_h, grid_w)``, starting from 0."""+ reference_ids = [+ _grid_position_ids(index, ref_height, ref_width, device)+ for index, (ref_height, ref_width) in enumerate(reference_grids, start=1)+ ]+ return torch.cat(reference_ids, dim=0) if reference_ids else torch.zeros(0, 3, device=device)+++def prepare_position_ids_with_references(+ text_seq_len: int,+ grid_height: int,+ grid_width: int,+ reference_grids: Sequence[tuple[int, int]],+ device: torch.device,+) -> torch.Tensor:+ """Rotary coordinates for ``[text | target | reference 1 | reference 2 | ...]``.++ Text and target are laid out as in ``prepare_position_ids``. Reference ``i`` (1-based) carries+ ``(i, h, w)`` over its own ``(grid_h, grid_w)``, starting from 0: the first axis is what tells the+ transformer the reference tokens apart from the target and from each other. This is the layout the+ ai-toolkit edit LoRAs were trained with (ComfyUI's "index_timestep_zero" reference method).+ """+ return torch.cat(+ [+ prepare_position_ids(text_seq_len, grid_height, grid_width, device),+ prepare_reference_position_ids(reference_grids, device),+ ],+ dim=0,+ )def calculate_shift(diff --git a/invokeai/backend/krea2/text_encoding.py b/invokeai/backend/krea2/text_encoding.pyindex 5f7640e32d..e0c0dd2b97 100644--- a/invokeai/backend/krea2/text_encoding.py+++ b/invokeai/backend/krea2/text_encoding.py@@ -5,13 +5,22 @@ token layout instead of restating it. The prompt template is copied from diffuse``Krea2Pipeline.get_text_hidden_states``: the prefix is a system turn instructing the model to describean image (the same "generate" template Qwen-Image uses), which is why the first ``KREA2_START_IDX``tokens are dropped from the encoder output.++Edit mode (reference images read by the Qwen3-VL vision tower) follows ai-toolkit, which trains Krea-2 edit+LoRAs with ``model_kwargs.edit: true``, and ``ostris/ComfyUI-Krea2-Ostris-Edit``, which runs them:+``extensions_built_in/diffusion_models/krea2/src/text_encoder.py::encode_krea_prompt`` and+``krea2.py::_prep_vlm_images``. It encodes at natural length, so its conditioning is not 512 tokens long."""from __future__ import annotations+import math+from collections.abc import Sequencefrom typing import Callable+import numpy as npimport torch+from PIL import Imagefrom invokeai.backend.krea2.sampling_utils import (KREA2_MAX_SEQ_LEN,@@ -20,6 +29,7 @@ from invokeai.backend.krea2.sampling_utils import (KREA2_START_IDX,)from invokeai.backend.model_manager.load.model_cache.utils import get_effective_device+from invokeai.backend.model_manager.util.qwen3_vl import attach_qwen3vl_visual_towerfrom invokeai.backend.util.devices import TorchDeviceKREA2_PREFIX = (@@ -31,6 +41,26 @@ KREA2_SUFFIX = "<|im_end|>\n<|im_start|>assistant\n"# Reserve room for the suffix (diffusers: max_sequence_length + start_idx - num_suffix_tokens).KREA2_BODY_MAX_LENGTH = KREA2_MAX_SEQ_LEN + KREA2_START_IDX - KREA2_NUM_SUFFIX_TOKENS+# Reference images: as many as the ComfyUI edit node takes, and the vision-pass budget ai-toolkit trains with+# (`vlm_max_pixels`, 384^2, the TextEncodeQwenImageEditPlus budget). The VLM only needs a coarse view; detail+# reaches the transformer through the VAE reference latents.+KREA2_MAX_REFERENCE_IMAGES = 3+KREA2_VLM_MAX_PIXELS = 384 * 384+KREA2_VLM_MIN_SIDE = 28++# Device memory an image encode needs above the weights, for T tokens. The attention and per-token terms are+# Qwen-Image-2.1's measurement on its Qwen3-VL-8B (RTX 4090, torch 2.13, transformers 5.10: ~286 B * T^2 ++# 224 KiB * T at peak, the allocator reserving about a fifth more), used here pending a calibration on the 4B+# (same 32 heads, narrower layers: 2560 hidden against 4096). Krea-2 also keeps every hidden state+# (`output_hidden_states`: embeddings + 36 layers) and stacks 12 of them, which that measurement did not+# include: 49 * 2560 bf16 values per token. With up to three references at 384^2 (~600 tokens) this comes to+# ~0.5 GB, which normally sits below the cache's `device_working_mem_gb` floor; it decides the reservation only+# with a lowered setting or a very long prompt. Still an estimate on 8B constants until measured on the 4B.+_BYTES_PER_TOKEN_PAIR = 286+_BYTES_PER_TOKEN = 224 * 1024+_RETAINED_HIDDEN_BYTES_PER_TOKEN = (37 + len(KREA2_SELECT_LAYERS)) * 2560 * 2+_RESERVED_OVER_ALLOCATED = 1.25+BuildTokenValues = Callable[[torch.Tensor], "torch.Tensor | None"]"""Callback receiving the body's ``(body_len, 2)`` offset mapping and returning a ``(body_len,)`` vector."""@@ -91,26 +121,9 @@ def encode_krea2_prompt(use_cache=False,return_dict=True,)-- # Some VL models nest the language-model output; fall back to that if needed.- hidden_states_tuple = getattr(outputs, "hidden_states", None)- if hidden_states_tuple is None:- lm_output = getattr(outputs, "language_model_outputs", None)- hidden_states_tuple = getattr(lm_output, "hidden_states", None)- if hidden_states_tuple is None:- raise RuntimeError("Qwen3-VL encoder did not return hidden_states; cannot build Krea-2 conditioning.")-- # Stack the selected layers along a new layer axis: (B, seq, 12, hidden).- stacked = torch.stack([hidden_states_tuple[i] for i in KREA2_SELECT_LAYERS], dim=2)-- # Drop the system-prompt prefix tokens.- prompt_embeds = stacked[:, KREA2_START_IDX:]+ prompt_embeds = _stacked_conditioning(outputs, device)prompt_mask = attention_mask[:, KREA2_START_IDX:].bool()- # Match the device-safe compute dtype used by the denoise loop (falls back from bf16 to fp16/fp32 on- # devices without bf16 support) rather than forcing bfloat16.- prompt_embeds = prompt_embeds.to(dtype=TorchDevice.choose_bfloat16_safe_dtype(device))-token_values = Noneif want_values:assert build_token_values is not None@@ -124,3 +137,129 @@ def encode_krea2_prompt(token_values = torch.cat([body_values, suffix_values])[KREA2_START_IDX:].unsqueeze(0)return prompt_embeds, prompt_mask, token_values+++def _stacked_conditioning(outputs, device: torch.device) -> torch.Tensor:+ """The selected hidden layers stacked per token, ``(1, seq, 12, hidden)``, the system prefix dropped."""+ # Some VL models nest the language-model output; fall back to that if needed.+ hidden_states_tuple = getattr(outputs, "hidden_states", None)+ if hidden_states_tuple is None:+ lm_output = getattr(outputs, "language_model_outputs", None)+ hidden_states_tuple = getattr(lm_output, "hidden_states", None)+ if hidden_states_tuple is None:+ raise RuntimeError("Qwen3-VL encoder did not return hidden_states; cannot build Krea-2 conditioning.")++ # Stack the selected layers along a new layer axis: (B, seq, 12, hidden).+ stacked = torch.stack([hidden_states_tuple[i] for i in KREA2_SELECT_LAYERS], dim=2)++ # Drop the system-prompt prefix tokens, and match the device-safe compute dtype used by the denoise loop+ # (falls back from bf16 to fp16/fp32 on devices without bf16 support) rather than forcing bfloat16.+ return stacked[:, KREA2_START_IDX:].to(dtype=TorchDevice.choose_bfloat16_safe_dtype(device))+++def prepare_vlm_reference(image: Image.Image) -> torch.Tensor:+ """A reference image as the Qwen3-VL vision pass reads it: ``(3, H, W)`` float32 in ``[0, 1]``.++ ai-toolkit's ``_prep_vlm_images``: alpha is dropped rather than composited (as ai-toolkit and ComfyUI's+ LoadImage both do), and the image is downscaled -- never upscaled, aspect kept -- to fit+ `KREA2_VLM_MAX_PIXELS`, each side at least `KREA2_VLM_MIN_SIDE`, bicubic with antialiasing on the float+ image. A tensor rather than a resized PIL image, because a uint8 round trip after the resize would round+ what the trained path keeps in float; the processor then gets it with ``do_rescale=False``.+ """+ rgb = np.asarray(image.convert("RGB"), dtype=np.float32) / 255.0+ pixels = torch.from_numpy(rgb).permute(2, 0, 1).contiguous()+ height, width = pixels.shape[1:]+ scale = min(1.0, math.sqrt(KREA2_VLM_MAX_PIXELS / (height * width)))+ size = (max(round(height * scale), KREA2_VLM_MIN_SIDE), max(round(width * scale), KREA2_VLM_MIN_SIDE))+ if size == (height, width):+ return pixels+ resized = torch.nn.functional.interpolate(pixels.unsqueeze(0), size=size, mode="bicubic", antialias=True)+ return resized.squeeze(0).clamp(0, 1)+++def image_placeholders(num_images: int) -> str:+ """One named vision placeholder per reference, the ComfyUI ``TextEncodeQwenImageEditPlus`` layout."""+ return "".join(f"Picture {i + 1}: <|vision_start|><|image_pad|><|vision_end|>" for i in range(num_images))+++def tokenize_krea2_prompt_with_images(+ prompt: str, images: Sequence[torch.Tensor], processor, tokenizer+) -> dict[str, torch.Tensor]:+ """The encoder inputs for a prompt with reference images, at natural length, on the CPU.++ `images` come from `prepare_vlm_reference`. The processor expands each ``<|image_pad|>`` into the image's+ token grid (``image_grid_thw.prod() / merge_size**2`` pads) and is called without truncation or padding,+ which would cut those runs apart. The suffix is tokenized separately and appended, as in the text-only+ path, and the processor's ``mm_token_type_ids`` -- what the 3-D M-RoPE is built from -- are extended over+ it as text. The 34-token system prefix is unchanged, so the prefix drop still keeps every image token.++ ``input_ids.shape[1]`` is the sequence length `working_memory_bytes` takes.+ """+ if not images:+ raise ValueError("tokenize_krea2_prompt_with_images needs at least one reference image.")+ try:+ body = processor(+ text=[KREA2_PREFIX + image_placeholders(len(images)) + prompt],+ images=list(images),+ return_tensors="pt",+ do_rescale=False,+ )+ except ValueError as error:+ raise ValueError(_reference_rejection(processor, images, error)) from error+ suffix = tokenizer(KREA2_SUFFIX, return_tensors="pt")+ return {+ "input_ids": torch.cat([body["input_ids"], suffix.input_ids], dim=1),+ "attention_mask": torch.cat([body["attention_mask"], suffix.attention_mask], dim=1).bool(),+ "mm_token_type_ids": torch.cat(+ [body["mm_token_type_ids"], torch.zeros_like(suffix.input_ids, dtype=body["mm_token_type_ids"].dtype)],+ dim=1,+ ),+ "pixel_values": body["pixel_values"],+ "image_grid_thw": body["image_grid_thw"],+ }+++def _reference_rejection(processor, images: Sequence[torch.Tensor], error: ValueError) -> str:+ """Name the reference the image processor refused, and why. Only runs once the joint call has failed."""+ for index, image in enumerate(images, start=1):+ try:+ processor.image_processor(images=[image], return_tensors="pt", do_rescale=False)+ except ValueError as own_error:+ height, width = image.shape[1:]+ return (+ f"Krea-2 reference image {index} cannot be read by the Qwen3-VL vision tower "+ f"({width}x{height} px after the 384x384 downscale): {own_error}. Crop it to a less extreme shape."+ )+ return f"The Qwen3-VL processor refused the Krea-2 reference images: {error}"+++def working_memory_bytes(num_tokens: int) -> int:+ """Device memory an image encode of `num_tokens` tokens needs above the encoder's weights (an estimate)."""+ per_token = _BYTES_PER_TOKEN + _RETAINED_HIDDEN_BYTES_PER_TOKEN+ return int((_BYTES_PER_TOKEN_PAIR * num_tokens**2 + per_token * num_tokens) * _RESERVED_OVER_ALLOCATED)+++def encode_krea2_prompt_with_images(+ inputs: dict[str, torch.Tensor], text_encoder: torch.nn.Module, vision_tower: torch.nn.Module+) -> tuple[torch.Tensor, torch.Tensor]:+ """Encode `tokenize_krea2_prompt_with_images` output into Krea-2 conditioning.++ Returns ``(prompt_embeds, prompt_mask)`` of shapes ``(1, L, 12, hidden)`` and ``(1, L)``, ``L`` the natural+ length less the system prefix, the mask all True.++ `vision_tower` is lent to `text_encoder` for this one forward (see `attach_qwen3vl_visual_tower`); both+ must already be locked on the device and stay locked until this returns. No ``position_ids`` are passed:+ the model builds its 3-D M-RoPE from ``image_grid_thw`` and ``mm_token_type_ids``, where the text-only path+ passes explicit 1-D positions because its padding sits inside the sequence.+ """+ device = get_effective_device(text_encoder)+ with attach_qwen3vl_visual_tower(text_encoder, vision_tower):+ outputs = text_encoder(+ **{name: tensor.to(device) for name, tensor in inputs.items()},+ output_hidden_states=True,+ use_cache=False,+ return_dict=True,+ )+ prompt_embeds = _stacked_conditioning(outputs, device)+ prompt_mask = inputs["attention_mask"][:, KREA2_START_IDX:].to(device)+ return prompt_embeds, prompt_maskdiff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.pyindex 5f68261da3..41b87c2573 100644--- a/invokeai/backend/model_manager/load/load_default.py+++ b/invokeai/backend/model_manager/load/load_default.py@@ -58,6 +58,7 @@ _FP8_EXCLUDED_SUBMODEL_TYPES: frozenset[SubModelType] = frozenset(SubModelType.TextEncoder,SubModelType.TextEncoder2,SubModelType.TextEncoder3,+ SubModelType.VisionEncoder,SubModelType.Tokenizer,SubModelType.Tokenizer2,SubModelType.Tokenizer3,@@ -341,8 +342,14 @@ class ModelLoader(ModelLoaderBase):# Check if this is a text encoder submodel of a main model with cpu_only settingif 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]:+ # Only apply CPU execution to text encoder submodels. The vision encoder is the text encoder's own+ # tower, run inside its forward, so it has to execute on the same device.+ if submodel_type in [+ SubModelType.TextEncoder,+ SubModelType.TextEncoder2,+ SubModelType.TextEncoder3,+ SubModelType.VisionEncoder,+ ]: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/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.pyindex 9f4a9a82ba..37d5d35156 100644--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py@@ -1,6 +1,7 @@"""Class for Krea-2 model loading in InvokeAI."""from abc import abstractmethod+from collections.abc import Callablefrom pathlib import Pathfrom typing import Any, Generic, Optional, TypeVar@@ -38,6 +39,9 @@ from invokeai.backend.model_manager.util.qwen3_vl import (drop_qwen3vl_visual_tower_keys,normalize_qwen3vl_rope_config,qwen3vl_target_key,+ qwen3vl_visual_tower_files,+ qwen3vl_visual_tower_nbytes,+ read_qwen3vl_visual_tower_tensors,)from invokeai.backend.quantization.fp8_scaled import (INPUT_SCALE_SUFFIXES,@@ -74,6 +78,7 @@ from invokeai.backend.quantization.nvfp4 import (predict_nvfp4_install_size,)from invokeai.backend.qwen3_vl.qwen3_vl_assets import (+ build_qwen3_vl_processor,load_bundled_qwen3_vl_config_dict,load_bundled_qwen3_vl_tokenizer,)@@ -290,6 +295,75 @@ KREA2_TRANSFORMER_CONFIG = {}+def _qwen3vl_tower_key(key: str) -> str:+ """A visual-tower checkpoint key relative to the tower (``model.visual.blocks.0...`` -> ``blocks.0...``)."""+ return qwen3vl_target_key(key)[len("visual.") :]+++def _load_qwen3vl_visual_tower(+ files: list[Path],+ vision_config: Any,+ dtype: torch.dtype,+ *,+ reserve: Callable[[int], None],+) -> torch.nn.Module:+ """Build a Qwen3-VL vision tower from the ``visual.*`` tensors of `files`, reading nothing else.++ Serves `SubModelType.VisionEncoder`: the encoders here drop their tower (see `drop_qwen3vl_visual_tower`),+ and Krea-2's edit mode loads it as its own cache entry, only when a prompt has reference images.++ The tower ends up at the compute dtype whatever the container. Every single file seen so far stores it in+ BF16, the fp8_scaled ones included; a ComfyUI ``int8_tensorwise`` repack quantizes its Linears too, and+ those stay int8 as `Int8ConvrotLinear`, as on the encoder path. A scaled-fp8 tower would be folded to the+ compute dtype: at ~0.8 GiB it does not earn an fp8 matmul path of its own.+ """+ from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLVisionModel++ what = "Qwen3-VL vision tower"+ sd: dict[str, Any] = dict(read_qwen3vl_visual_tower_tensors(files))+ if not sd:+ raise RuntimeError(+ f"{', '.join(str(f) for f in files) or 'This encoder'} carries no Qwen3-VL vision tower weights, so it "+ "cannot read Krea-2 edit reference images. Use the Krea-2 Diffusers model's own encoder, or a Qwen3-VL "+ "single file or folder that includes the vision weights (e.g. qwen3vl_4b_bf16 or qwen3vl_4b_fp8_scaled)."+ )+ # Markers are read in the checkpoint's key space, before the rename, as on the encoder path.+ int8_markers = extract_int8_convrot_markers(sd)+ reject_unmarked_int8_weights(sd, int8_markers, what)+ sd = drop_unconsumed_quantization_sidecars(sd)+ key_map: dict[str, str] = {}+ renamed: dict[str, Any] = {}+ source_of: dict[Any, Any] = {}+ for key, value in sd.items():+ key_map[key] = _qwen3vl_tower_key(key)+ _put_unique_key(renamed, key_map[key], value, source=key, source_of=source_of, what=what)+ sd = renamed++ with accelerate.init_empty_weights():+ tower = Qwen3VLVisionModel._from_config(vision_config)++ if int8_markers:+ install_int8_convrot_layers(+ tower,+ sd,+ resolve_quantized_module_paths(int8_markers, key_map),+ dtype,+ architecture=what,+ reserve=reserve,+ skip_patterns=_model_declared_skip_patterns(tower),+ )+ else:+ # Whole keys were renamed, so each `.weight_scale` still sits beside its `.weight`.+ fp8_layers = extract_fp8_scaled_layers(sd)+ reserve_for_load(reserve, sd, dtype, keep_fp8=False, model=tower, fp8_layers=fp8_layers, nvfp4_payloads={})+ dequantize_fp8_scaled(sd, fp8_layers, dtype)+ cast_state_dict(sd, dtype, keep_fp8=False, model=tower)++ load_state_dict_ignoring_extras(tower, sd, source=what, assign=True, allow_missing=True)+ _reject_incomplete_load(tower, what=what)+ return tower++@ModelLoaderRegistry.register(base=BaseModelType.Krea2, type=ModelType.Main, format=ModelFormat.Diffusers)class Krea2DiffusersModel(GenericDiffusersLoader):"""Class to load Krea-2 main models (Krea-2-Turbo) in diffusers format.@@ -298,8 +372,21 @@ class Krea2DiffusersModel(GenericDiffusersLoader):pipeline folder via the class names declared in model_index.json. The transformer resolves todiffusers' ``Krea2Transformer2DModel`` (only available in diffusers main / >=0.39); the VAE to``AutoencoderKLQwenImage`` and the text encoder to ``Qwen3VLModel``.++ Two submodels are not in model_index.json: ``vision_encoder``, the Qwen3-VL vision tower read from the+ ``visual.*`` tensors of ``text_encoder/`` (the text encoder drops it), and ``processor``, which wraps the+ pipeline's tokenizer for reference images. Krea-2's edit mode loads both only when a prompt has references."""+ def get_size_fs(+ self, config: AnyModelConfig, model_path: Path, submodel_type: Optional[SubModelType] = None+ ) -> int:+ if submodel_type is SubModelType.VisionEncoder:+ return qwen3vl_visual_tower_nbytes(qwen3vl_visual_tower_files(model_path / SubModelType.TextEncoder.value))+ if submodel_type is SubModelType.Processor:+ return 0+ return super().get_size_fs(config, model_path, submodel_type)+def _load_model(self,config: AnyModelConfig,@@ -321,9 +408,19 @@ class Krea2DiffusersModel(GenericDiffusersLoader):# are already baked into tokenizer.json as added tokens). Newer transformers expects a dict and# crashes on the list, so override it with an empty dict — the special tokens are still# recognized from tokenizer.json.- if submodel_type is SubModelType.Tokenizer:- return AutoTokenizer.from_pretrained(- model_path / submodel_type.value, local_files_only=True, extra_special_tokens={}+ if submodel_type in (SubModelType.Tokenizer, SubModelType.Processor):+ tokenizer = AutoTokenizer.from_pretrained(+ model_path / SubModelType.Tokenizer.value, local_files_only=True, extra_special_tokens={}+ )+ return tokenizer if submodel_type is SubModelType.Tokenizer else build_qwen3_vl_processor(tokenizer)++ if submodel_type is SubModelType.VisionEncoder:+ encoder_path = model_path / SubModelType.TextEncoder.value+ return _load_qwen3vl_visual_tower(+ qwen3vl_visual_tower_files(encoder_path),+ AutoConfig.from_pretrained(encoder_path, local_files_only=True).vision_config,+ TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device()),+ reserve=self._ram_cache.make_room,)load_class = self.get_hf_load_class(model_path, submodel_type)@@ -718,7 +815,28 @@ class Krea2GGUFCheckpointModel(ModelLoader):@ModelLoaderRegistry.register(base=BaseModelType.Any, type=ModelType.Qwen3VLEncoder, format=ModelFormat.Qwen3VLEncoder)class Qwen3VLEncoderLoader(ModelLoader):- """Class to load standalone Qwen3-VL text encoder models for Krea-2 (directory format)."""+ """Class to load standalone Qwen3-VL text encoder models for Krea-2 (directory format).++ Besides the tokenizer and the tower-less text encoder it serves the vision tower and a processor, which+ Krea-2's edit mode loads only when a prompt has reference images.+ """++ @staticmethod+ def _component_paths(model_path: Path) -> tuple[Path, Path]:+ """``(text_encoder, tokenizer)`` folders: a pipeline-style layout, or a standalone download at the root."""+ text_encoder_path = model_path / "text_encoder"+ if not text_encoder_path.exists() and (model_path / "config.json").exists():+ return model_path, model_path+ return text_encoder_path, model_path / "tokenizer"++ def get_size_fs(+ self, config: AnyModelConfig, model_path: Path, submodel_type: Optional[SubModelType] = None+ ) -> int:+ if submodel_type is SubModelType.VisionEncoder:+ return qwen3vl_visual_tower_nbytes(qwen3vl_visual_tower_files(self._component_paths(model_path)[0]))+ if submodel_type is SubModelType.Processor:+ return 0+ return super().get_size_fs(config, model_path, submodel_type)def _load_model(self,@@ -730,22 +848,23 @@ class Qwen3VLEncoderLoader(ModelLoader):if not isinstance(config, Qwen3VLEncoder_Qwen3VLEncoder_Config):raise ValueError("Only Qwen3VLEncoder_Qwen3VLEncoder_Config models are supported here.")- model_path = Path(config.path)-- # Support both a full pipeline-style layout (text_encoder/ + tokenizer/) and a standalone- # download where the encoder files live directly at the root.- text_encoder_path = model_path / "text_encoder"- tokenizer_path = model_path / "tokenizer"- is_standalone = not text_encoder_path.exists() and (model_path / "config.json").exists()- if is_standalone:- text_encoder_path = model_path- tokenizer_path = model_path+ text_encoder_path, tokenizer_path = self._component_paths(Path(config.path))match submodel_type:- case SubModelType.Tokenizer:+ case SubModelType.Tokenizer | SubModelType.Processor:# extra_special_tokens={} works around Krea-2's list-format tokenizer_config (see# Krea2DiffusersModel); harmless for well-formed configs.- return AutoTokenizer.from_pretrained(tokenizer_path, local_files_only=True, extra_special_tokens={})+ tokenizer = AutoTokenizer.from_pretrained(+ tokenizer_path, local_files_only=True, extra_special_tokens={}+ )+ return tokenizer if submodel_type is SubModelType.Tokenizer else build_qwen3_vl_processor(tokenizer)+ case SubModelType.VisionEncoder:+ return _load_qwen3vl_visual_tower(+ qwen3vl_visual_tower_files(text_encoder_path),+ AutoConfig.from_pretrained(text_encoder_path, local_files_only=True).vision_config,+ TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device()),+ reserve=self._ram_cache.make_room,+ )case SubModelType.TextEncoder:target_device = TorchDevice.choose_torch_device()model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)@@ -766,7 +885,7 @@ class Qwen3VLEncoderLoader(ModelLoader):return modelraise ValueError(- f"Only Tokenizer and TextEncoder submodels are supported. "+ f"Only Tokenizer, Processor, TextEncoder and VisionEncoder submodels are supported. "f"Received: {submodel_type.value if submodel_type else 'None'}")@@ -807,6 +926,13 @@ def _reject_incomplete_load(model: Any, *, what: str) -> None:reject_incomplete_load(model, what=what)+QWEN3VL_GGUF_HAS_NO_VISION_TOWER = (+ "The GGUF Qwen3-VL encoder '{name}' has no vision tower (llama.cpp keeps it in a separate mmproj file, which "+ "is not supported), so it cannot read reference images. Use a safetensors Qwen3-VL encoder or the Krea-2 "+ "Diffusers model's own encoder."+)++_Qwen3VLSingleFileConfig = TypeVar("_Qwen3VLSingleFileConfig", Qwen3VLEncoder_Checkpoint_Config, Qwen3VLEncoder_GGUF_Config)@@ -836,18 +962,39 @@ class _Qwen3VLEncoderSingleFileLoader(ModelLoader, Generic[_Qwen3VLSingleFileConmatch submodel_type:case SubModelType.Tokenizer:return load_bundled_qwen3_vl_tokenizer()+ case SubModelType.Processor:+ return build_qwen3_vl_processor(load_bundled_qwen3_vl_tokenizer())case SubModelType.TextEncoder:return self._load_text_encoder(config)+ case SubModelType.VisionEncoder:+ return self._load_vision_encoder(config)raise ValueError(- f"Only Tokenizer and TextEncoder submodels are supported. "+ f"Only Tokenizer, Processor, TextEncoder and VisionEncoder submodels are supported. "f"Received: {submodel_type.value if submodel_type else 'None'}")+ def get_size_fs(+ self, config: AnyModelConfig, model_path: Path, submodel_type: Optional[SubModelType] = None+ ) -> int:+ if submodel_type is SubModelType.Processor:+ return 0+ if submodel_type is SubModelType.VisionEncoder:+ return self._vision_encoder_nbytes(model_path)+ return super().get_size_fs(config, model_path, submodel_type)+@abstractmethoddef _load_text_encoder(self, config: _Qwen3VLSingleFileConfig) -> AnyModel:"""Decode this container's weights into the Qwen3-VL module tree."""+ @abstractmethod+ def _load_vision_encoder(self, config: _Qwen3VLSingleFileConfig) -> AnyModel:+ """Build the vision tower from this container, or refuse when it carries none."""++ @abstractmethod+ def _vision_encoder_nbytes(self, model_path: Path) -> int:+ """What loading the vision tower reads, for the cache to reserve beforehand."""+def _load_te_config(self, config: _Qwen3VLSingleFileConfig) -> Any:"""Build the architecture config for this variant from the vendored copy.@@ -873,6 +1020,18 @@ class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEncoCONFIG_CLASS = Qwen3VLEncoder_Checkpoint_Config+ def _vision_encoder_nbytes(self, model_path: Path) -> int:+ return qwen3vl_visual_tower_nbytes([model_path])++ def _load_vision_encoder(self, config: Qwen3VLEncoder_Checkpoint_Config) -> AnyModel:+ model_path = Path(config.path)+ return _load_qwen3vl_visual_tower(+ [model_path],+ self._load_te_config(config).vision_config,+ TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device()),+ reserve=self._ram_cache.make_room,+ )+def _load_text_encoder(self, config: Qwen3VLEncoder_Checkpoint_Config) -> AnyModel:import torchfrom safetensors.torch import load_file@@ -1103,6 +1262,12 @@ class Qwen3VLEncoderGGUFLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEncoder_GGCONFIG_CLASS = Qwen3VLEncoder_GGUF_Config+ def _vision_encoder_nbytes(self, model_path: Path) -> int:+ return 0++ def _load_vision_encoder(self, config: Qwen3VLEncoder_GGUF_Config) -> AnyModel:+ raise ValueError(QWEN3VL_GGUF_HAS_NO_VISION_TOWER.format(name=config.name))+def _load_text_encoder(self, config: Qwen3VLEncoder_GGUF_Config) -> AnyModel:from transformers import Qwen3VLModeldiff --git a/invokeai/backend/model_manager/taxonomy.py b/invokeai/backend/model_manager/taxonomy.pyindex 3a328b436e..eec8d97fe2 100644--- a/invokeai/backend/model_manager/taxonomy.py+++ b/invokeai/backend/model_manager/taxonomy.py@@ -127,6 +127,7 @@ class SubModelType(str, Enum):Tokenizer2 = "tokenizer_2"Tokenizer3 = "tokenizer_3"Processor = "processor"+ VisionEncoder = "vision_encoder"PromptEnhancer = "pe"PromptEnhancerTokenizer = "pe_tokenizer"VAE = "vae"diff --git a/invokeai/backend/model_manager/util/qwen3_vl.py b/invokeai/backend/model_manager/util/qwen3_vl.pyindex c8dd8d652a..318987e845 100644--- a/invokeai/backend/model_manager/util/qwen3_vl.py+++ b/invokeai/backend/model_manager/util/qwen3_vl.py@@ -4,8 +4,17 @@ Used by Krea-2, Ideogram 4 and MiniMax H3. The visual-tower helpers live here raone family's loader because three loaders in two files drop the tower, and because what counts asthe tower has to agree with the key mapping that sits next to it -- two definitions would drift.MiniMax H3 deliberately does not use them: it runs the tower for its reference images.++The same predicate also serves the opposite direction: Krea-2's edit mode loads the tower on its own, as a+separate model-cache entry, and lends it to the text encoder for the forwards that read reference images+(`read_qwen3vl_visual_tower_tensors`, `attach_qwen3vl_visual_tower`). Keeping both directions here is what+guarantees the tower that is lent back is exactly the one that was dropped."""+import json+from collections.abc import Iterable, Iterator+from contextlib import contextmanager+from pathlib import Pathfrom typing import Anyimport torch@@ -102,4 +111,96 @@ def drop_qwen3vl_visual_tower_keys(sd: dict[str, Any]) -> dict[str, Any]:does not enumerate (``scale_weight``/``scale_input`` as well as ``weight_scale``/``input_scale``,and ``comfy_quant``). Enumerating suffixes instead would silently start leaving orphans behind."""- return {k: v for k, v in sd.items() if not (isinstance(k, str) and qwen3vl_target_key(k).startswith("visual."))}+ return {k: v for k, v in sd.items() if not is_qwen3vl_visual_key(k)}+++def is_qwen3vl_visual_key(key: Any) -> bool:+ """Whether a checkpoint key (in either spelling) belongs to the visual tower, sidecars included."""+ return isinstance(key, str) and qwen3vl_target_key(key).startswith("visual.")+++def qwen3vl_visual_tower_files(folder: Path) -> list[Path]:+ """The safetensors files of a transformers-layout Qwen3-VL folder that hold visual-tower tensors.++ A sharded folder names, per key, the shard holding it, so only the shards with tower keys are+ returned; an unsharded folder returns its weight files.+ """+ index = folder / "model.safetensors.index.json"+ if index.is_file():+ weight_map: dict[str, str] = json.loads(index.read_text(encoding="utf-8"))["weight_map"]+ return sorted({folder / name for key, name in weight_map.items() if is_qwen3vl_visual_key(key)})+ # Assumes one weight set per folder: no Krea-2/Qwen3-VL folder ships variant duplicates (``*.fp16.safetensors``).+ return sorted(folder.glob("*.safetensors"))+++def qwen3vl_visual_tower_nbytes(files: Iterable[Path]) -> int:+ """Bytes the visual tower's tensors occupy in `files`, read from the headers alone.++ What the model cache should reserve before loading the tower on its own: sizing that load by the whole+ file would evict ten times what the tower needs.+ """+ from invokeai.backend.model_manager.model_on_disk import read_safetensors_header++ total = 0+ for path in files:+ for key, entry in read_safetensors_header(path).items():+ if is_qwen3vl_visual_key(key):+ start, end = entry["data_offsets"]+ total += end - start+ return total+++def read_qwen3vl_visual_tower_tensors(files: Iterable[Path]) -> dict[str, torch.Tensor]:+ """Read only the visual tower's tensors from `files`, keyed as the checkpoint spells them.++ Filtered by key before anything is read, so the peak is the tower's size and not the encoder's: the+ language tower of a 4B single file is ten times larger and is never touched.+ """+ from safetensors import safe_open++ tensors: dict[str, torch.Tensor] = {}+ for path in files:+ with safe_open(str(path), framework="pt", device="cpu") as handle:+ for key in handle.keys():+ if is_qwen3vl_visual_key(key):+ tensors[key] = handle.get_tensor(key)+ return tensors+++@contextmanager+def attach_qwen3vl_visual_tower(model: torch.nn.Module, tower: torch.nn.Module) -> Iterator[torch.nn.Module]:+ """Lend `tower` to a `Qwen3VLModel` whose own tower `drop_qwen3vl_visual_tower` replaced, for one forward.++ Restores the parameter-free stub on exit, on success and on an exception alike, together with the 3-D rope+ deltas the multimodal forward caches on the model, so the encoder leaves exactly as it came.++ Invariant for the caller: both `model` and `tower` are separate model-cache entries, and both must be+ locked on the device *before* entering and unlocked only *after* exiting. The cache sizes, moves and+ offloads a model by walking its parameters; while attached, the tower's parameters are also the+ encoder's, so an offload or VRAM accounting of either entry inside this window would count or move the+ other's weights.++ Refuses a model that still has a real tower (attaching would discard it, silently) and a tower whose+ output width is not the language model's hidden size (its embeddings could not be scattered into the+ token sequence).+ """+ existing = getattr(model, "visual", None)+ if not isinstance(existing, torch.nn.Identity):+ raise RuntimeError(+ f"{type(model).__name__} has no dropped visual tower to replace (found {type(existing).__name__}); "+ "attaching another would discard it."+ )+ text_hidden = getattr(getattr(model.config, "text_config", None), "hidden_size", None)+ tower_out = getattr(getattr(tower, "config", None), "out_hidden_size", None)+ if text_hidden is None or tower_out != text_hidden:+ raise ValueError(+ f"This Qwen3-VL vision tower emits {tower_out}-wide embeddings, but the text encoder's hidden size is "+ f"{text_hidden}; the tower belongs to a different Qwen3-VL."+ )+ prior_rope_deltas = getattr(model, "rope_deltas", None)+ model.visual = tower+ try:+ yield model+ finally:+ model.visual = existing+ model.rope_deltas = prior_rope_deltasdiff --git a/invokeai/backend/qwen3_vl/config/qwen3_vl_instruct_preprocessor_config.json b/invokeai/backend/qwen3_vl/config/qwen3_vl_instruct_preprocessor_config.jsonnew file mode 100644index 0000000000..e8de78a270--- /dev/null+++ b/invokeai/backend/qwen3_vl/config/qwen3_vl_instruct_preprocessor_config.json@@ -0,0 +1,21 @@+{+ "size": {+ "longest_edge": 16777216,+ "shortest_edge": 65536+ },+ "patch_size": 16,+ "temporal_patch_size": 2,+ "merge_size": 2,+ "image_mean": [+ 0.5,+ 0.5,+ 0.5+ ],+ "image_std": [+ 0.5,+ 0.5,+ 0.5+ ],+ "processor_class": "Qwen3VLProcessor",+ "image_processor_type": "Qwen2VLImageProcessorFast"+}diff --git a/invokeai/backend/qwen3_vl/qwen3_vl_assets.py b/invokeai/backend/qwen3_vl/qwen3_vl_assets.pyindex 7f0b0fbe85..030b2750b8 100644--- a/invokeai/backend/qwen3_vl/qwen3_vl_assets.py+++ b/invokeai/backend/qwen3_vl/qwen3_vl_assets.py@@ -18,7 +18,8 @@ The tokenizer is byte-identical across the 4B and 8B releases — verified by mdsnapshots when it was vendored, which is why one copy serves both, in both container formats. Thatidentity cannot be re-checked here without the hub, so what the tests pin instead is the behaviourthat depends on it: the exact token ids and the single-id vision markers. Configs differ per-variant and are vendored per variant.+variant and are vendored per variant. The image preprocessor config is identical in the 4B and 8B+releases (compared byte for byte when it was vendored) and is vendored once.Everything here is vendored verbatim from the Apache-2.0 ``Qwen/Qwen3-VL-{4B,8B}-Instruct``releases. The configs are deliberately *not* normalized on the way in: whether ``rope_parameters``@@ -41,6 +42,8 @@ _ASSET_DIR = Path(__file__).parent_TOKENIZER_DIR = _ASSET_DIR / "tokenizer"_CONFIG_DIR = _ASSET_DIR / "config"+_PREPROCESSOR_CONFIG_PATH = _CONFIG_DIR / "qwen3_vl_instruct_preprocessor_config.json"+_CONFIG_BY_VARIANT: dict[Qwen3VLVariantType, str] = {Qwen3VLVariantType.Qwen3VL_4B: "qwen3_vl_4b_instruct.json",Qwen3VLVariantType.Qwen3VL_8B: "qwen3_vl_8b_instruct.json",@@ -72,3 +75,30 @@ def load_bundled_qwen3_vl_config_dict(variant: Qwen3VLVariantType) -> dict[str,)config_dict: dict[str, Any] = json.loads((_CONFIG_DIR / filename).read_text(encoding="utf-8"))return config_dict+++def load_bundled_qwen3_vl_preprocessor_config_dict() -> dict[str, Any]:+ """The vendored ``preprocessor_config.json`` of ``Qwen/Qwen3-VL-{4B,8B}-Instruct``, as published, fresh per call."""+ config_dict: dict[str, Any] = json.loads(_PREPROCESSOR_CONFIG_PATH.read_text(encoding="utf-8"))+ return config_dict+++def build_qwen3_vl_processor(tokenizer: PreTrainedTokenizerBase) -> Any:+ """Wrap `tokenizer` in the Qwen3-VL processor that turns reference images into patches and image-pad runs.++ Built in code because neither container can supply one: a single-file encoder ships weights only, and+ the Krea-2 pipeline folder ships a tokenizer but no processor config. The image processor comes from the+ vendored release config, never from a bare constructor -- transformers' class defaults (patch 14,+ CLIP mean/std, a 1,003,520-pixel cap) are Qwen2-VL's, not Qwen3-VL's. transformers 5.10 has no separate+ fast class; `Qwen2VLImageProcessor` is the torchvision one the release's ``Qwen2VLImageProcessorFast``+ resolves to. The processor refuses to be built without a video processor, so a default one is given;+ it is never used.+ """+ from transformers import Qwen3VLProcessor+ from transformers.models.qwen2_vl.image_processing_qwen2_vl import Qwen2VLImageProcessor+ from transformers.models.qwen3_vl.video_processing_qwen3_vl import Qwen3VLVideoProcessor++ image_processor = Qwen2VLImageProcessor.from_dict(load_bundled_qwen3_vl_preprocessor_config_dict())+ return Qwen3VLProcessor(+ image_processor=image_processor, tokenizer=tokenizer, video_processor=Qwen3VLVideoProcessor()+ )diff --git a/invokeai/backend/stable_diffusion/diffusion/conditioning_data.py b/invokeai/backend/stable_diffusion/diffusion/conditioning_data.pyindex 04591b0f23..90cfad37fe 100644--- a/invokeai/backend/stable_diffusion/diffusion/conditioning_data.py+++ b/invokeai/backend/stable_diffusion/diffusion/conditioning_data.py@@ -149,6 +149,13 @@ class Krea2ConditioningInfo:prompt_embeds_mask: torch.Tensor | None = None"""Attention mask for prompt_embeds. Shape: (batch_size, seq_len). 1/True for valid, 0/False for padding."""+ num_reference_images: int = 0+ """How many reference images the prompt was encoded with (edit mode), as ``Picture 1..N`` in that order.++ 0 for a text-only prompt. A denoise that receives reference latents needs as many, in the same order: the+ encoder and the transformer must see the same references, or the LoRA reads one image and edits another.+ """+def to(self, device: torch.device | None = None, dtype: torch.dtype | None = None):self.prompt_embeds = self.prompt_embeds.to(device=device, dtype=dtype)if self.prompt_embeds_mask is not None:diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex 683424ebbf..159e2f2891 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -62316,6 +62316,39 @@"orig_required": false,"title": "Style Reference Prompt"},+ "reference_latents": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/LatentsField"+ },+ {+ "items": {+ "$ref": "#/components/schemas/LatentsField"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Edit references for Krea-2 edit LoRAs, encoded by 'Image to Latents - Qwen Image' with 'reference' enabled. Up to 3. They join every transformer pass as clean (t=0) image tokens, about 4096 tokens per megapixel each; with Reference K/V Cache on they run once instead of in every pass. Not combinable with style reference or regional prompts.",+ "field_kind": "input",+ "input": "connection",+ "orig_default": null,+ "orig_required": false,+ "title": "Reference Latents"+ },+ "reference_kv_cache": {+ "default": false,+ "description": "For edit LoRAs trained with ai-toolkit's 'kv_cache' option, where reference tokens attend only to each other. The references then run through the transformer once per generation instead of in every pass, which is faster. Leave off for normal edit LoRAs. The LoRA file does not say which kind it is; check its model card. No effect without reference latents.",+ "field_kind": "input",+ "input": "any",+ "orig_default": false,+ "orig_required": false,+ "title": "Reference K/V Cache",+ "type": "boolean"+ },"type": {"const": "krea2_denoise","default": "krea2_denoise",@@ -62328,7 +62361,7 @@"tags": ["image", "krea2", "krea-2"],"title": "Denoise - Krea-2","type": "object",- "version": "1.3.0",+ "version": "1.4.0","output": {"$ref": "#/components/schemas/LatentsOutput"}@@ -63205,7 +63238,7 @@"category": "conditioning","class": "invocation","classification": "prototype",- "description": "Encodes a text prompt for Krea-2 using the Qwen3-VL text encoder.\n\nThe encoder taps 12 decoder hidden-state layers and stacks them per token, producing a 4D\nconditioning tensor (B, seq, 12, hidden) that the Krea-2 transformer's text-fusion stage consumes.",+ "description": "Encodes a text prompt for Krea-2 using the Qwen3-VL text encoder.\n\nThe encoder taps 12 decoder hidden-state layers and stacks them per token, producing a 4D\nconditioning tensor (B, seq, 12, hidden) that the Krea-2 transformer's text-fusion stage consumes.\n\nWith reference images (edit mode, for edit LoRAs) the Qwen3-VL vision tower reads them into the prompt,\nahead of the text, and the conditioning has the prompt's natural length rather than 512 tokens.","node_pack": "invokeai","properties": {"id": {@@ -63281,6 +63314,20 @@"orig_required": true,"title": "Qwen3-VL Encoder"},+ "reference_images": {+ "default": [],+ "description": "Up to three reference images for an edit LoRA, read by the Qwen3-VL vision tower in this order (Picture 1, 2, 3). Needs a safetensors or Diffusers encoder: a GGUF encoder has no vision tower.",+ "field_kind": "input",+ "input": "any",+ "items": {+ "$ref": "#/components/schemas/ImageField"+ },+ "maxItems": 3,+ "orig_default": [],+ "orig_required": false,+ "title": "Reference Images",+ "type": "array"+ },"type": {"const": "krea2_text_encoder","default": "krea2_text_encoder",@@ -63293,7 +63340,7 @@"tags": ["prompt", "conditioning", "krea2", "krea-2"],"title": "Prompt - Krea-2","type": "object",- "version": "1.1.0",+ "version": "1.2.0","output": {"$ref": "#/components/schemas/Krea2ConditioningOutput"}@@ -96020,6 +96067,16 @@"orig_required": false,"title": "Height"},+ "reference": {+ "default": false,+ "description": "Encode as a Krea-2 edit reference (for 'Denoise - Krea-2' reference latents), sized as ai-toolkit trains Krea-2 edit LoRAs: RGB with alpha dropped; an image above 1 megapixel is scaled to about 1 megapixel keeping its aspect ratio; each side is rounded to a multiple of 16; resized bilinearly. Not the Qwen-Image Edit path. Width and height must be left unset.",+ "field_kind": "input",+ "input": "any",+ "orig_default": false,+ "orig_required": false,+ "title": "Reference",+ "type": "boolean"+ },"type": {"const": "qwen_image_i2l","default": "qwen_image_i2l",@@ -96032,7 +96089,7 @@"tags": ["image", "latents", "vae", "i2l", "qwen_image"],"title": "Image to Latents - Qwen Image","type": "object",- "version": "1.1.0",+ "version": "1.2.0","output": {"$ref": "#/components/schemas/LatentsOutput"}@@ -104404,6 +104461,7 @@"tokenizer_2","tokenizer_3","processor",+ "vision_encoder","pe","pe_tokenizer","vae",diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex 5e8cb07541..64a64fa769 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -24376,6 +24376,18 @@ export type components = {* @default null*/style_reference_conditioning?: components["schemas"]["Krea2ConditioningField"] | null;+ /**+ * Reference Latents+ * @description Edit references for Krea-2 edit LoRAs, encoded by 'Image to Latents - Qwen Image' with 'reference' enabled. Up to 3. They join every transformer pass as clean (t=0) image tokens, about 4096 tokens per megapixel each; with Reference K/V Cache on they run once instead of in every pass. Not combinable with style reference or regional prompts.+ * @default null+ */+ reference_latents?: components["schemas"]["LatentsField"] | components["schemas"]["LatentsField"][] | null;+ /**+ * Reference K/V Cache+ * @description For edit LoRAs trained with ai-toolkit's 'kv_cache' option, where reference tokens attend only to each other. The references then run through the transformer once per generation instead of in every pass, which is faster. Leave off for normal edit LoRAs. The LoRA file does not say which kind it is; check its model card. No effect without reference latents.+ * @default false+ */+ reference_kv_cache?: boolean;/*** type* @default krea2_denoise@@ -24908,6 +24920,9 @@ export type components = {** The encoder taps 12 decoder hidden-state layers and stacks them per token, producing a 4D* conditioning tensor (B, seq, 12, hidden) that the Krea-2 transformer's text-fusion stage consumes.+ *+ * With reference images (edit mode, for edit LoRAs) the Qwen3-VL vision tower reads them into the prompt,+ * ahead of the text, and the conditioning has the prompt's natural length rather than 512 tokens.*/Krea2TextEncoderInvocation: {/**@@ -24944,6 +24959,12 @@ export type components = {* @default null*/qwen3_vl_encoder?: components["schemas"]["Qwen3VLEncoderField"] | null;+ /**+ * Reference Images+ * @description Up to three reference images for an edit LoRA, read by the Qwen3-VL vision tower in this order (Picture 1, 2, 3). Needs a safetensors or Diffusers encoder: a GGUF encoder has no vision tower.+ * @default []+ */+ reference_images?: components["schemas"]["ImageField"][];/*** type* @default krea2_text_encoder@@ -41522,6 +41543,12 @@ export type components = {* @default null*/height?: number | null;+ /**+ * Reference+ * @description Encode as a Krea-2 edit reference (for 'Denoise - Krea-2' reference latents), sized as ai-toolkit trains Krea-2 edit LoRAs: RGB with alpha dropped; an image above 1 megapixel is scaled to about 1 megapixel keeping its aspect ratio; each side is rounded to a multiple of 16; resized bilinearly. Not the Qwen-Image Edit path. Width and height must be left unset.+ * @default false+ */+ reference?: boolean;/*** type* @default qwen_image_i2l@@ -45822,7 +45849,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" | "tokenizer" | "tokenizer_2" | "tokenizer_3" | "processor" | "vision_encoder" | "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/tests/app/invocations/test_krea2_denoise.py b/tests/app/invocations/test_krea2_denoise.pyindex a2ca338534..9a1d9e696f 100644--- a/tests/app/invocations/test_krea2_denoise.py+++ b/tests/app/invocations/test_krea2_denoise.py@@ -1,3 +1,4 @@+import dataclassesimport mathfrom contextlib import contextmanager, nullcontextfrom types import SimpleNamespace@@ -1343,3 +1344,458 @@ class TestTheAttentionScoreMatrixReachesTheReservation:assert len(set(transformer.combined_sequence_lengths)) == 2, "the passes must attend over different lengths"assert asked[0]["seq_len"] == max(transformer.combined_sequence_lengths)assert asked[0]["has_attn_mask"] is True+++# --- Edit references (reference_latents) -----------------------------------------------------------------++# width=height=16 is a 2x2 latent, i.e. one target token. The references are larger on purpose: their own+# grids, not the target's, must size their tokens and position ids.+_REFERENCE_TENSORS = {+ "ref-a": torch.ones(1, KREA2_LATENT_CHANNELS, 1, 4, 2), # 5D, as the Qwen-Image VAE emits: 2x1 grid+ "ref-b": torch.ones(1, KREA2_LATENT_CHANNELS, 2, 2), # 4D: 1x1 grid+ "ref-wrong-channels": torch.ones(1, 4, 2, 2),+ "ref-odd": torch.ones(1, KREA2_LATENT_CHANNELS, 3, 2),+ "ref-two-frames": torch.ones(1, KREA2_LATENT_CHANNELS, 2, 2, 2),+}+_REFERENCE_TOKENS = 2 + 1+++def _reference_context(+ tmp_path, transformer, positive_references: int = 0, negative_references: int | None = None, **kwargs+):+ """`_runtime_context` plus the reference tensors, with prompts encoded as having seen `*_references` images."""+ context = _runtime_context(tmp_path, transformer, **kwargs)+ base_tensors = context.tensors.load+ context.tensors.load = lambda name: _REFERENCE_TENSORS[name] if name in _REFERENCE_TENSORS else base_tensors(name)+ counts = {+ "positive": positive_references,+ "negative": positive_references if negative_references is None else negative_references,+ }+ base_conditioning = context.conditioning.load++ def load_conditioning(name: str) -> ConditioningFieldData:+ data = base_conditioning(name)+ if name not in counts:+ return data+ info = dataclasses.replace(data.conditionings[0], num_reference_images=counts[name])+ return ConditioningFieldData(conditionings=[info])++ context.conditioning.load = load_conditioning+ context.util.signal_progress = lambda *_args, **_kwargs: None+ return context+++def _references(*names: str) -> list[LatentsField]:+ return [LatentsField(latents_name=name) for name in names]+++def _tiny_krea2_transformer():+ from diffusers.models.transformers.transformer_krea2 import Krea2Transformer2DModel++ # Text width and layer count match the runtime context's (1, seq, 12, 8) prompt embeddings.+ torch.manual_seed(0)+ return Krea2Transformer2DModel(+ in_channels=64,+ num_layers=2,+ attention_head_dim=8,+ num_attention_heads=2,+ num_key_value_heads=1,+ intermediate_size=16,+ timestep_embed_dim=8,+ text_hidden_dim=8,+ num_text_layers=12,+ text_num_attention_heads=2,+ text_num_key_value_heads=2,+ text_intermediate_size=16,+ num_layerwise_text_blocks=1,+ num_refiner_text_blocks=1,+ axes_dims_rope=(2, 2, 4),+ ).eval()+++def _refusing_context(tmp_path, positive_references: int = 0, negative_references: int | None = None):+ context = _reference_context(tmp_path, _Transformer(), positive_references, negative_references)++ def load(_identifier):+ raise AssertionError("the transformer must not be loaded for a refused request")++ context.models.load = load+ return context+++ ("configure", "message"),+ [+ (+ lambda inv: setattr(inv, "reference_latents", _references("ref-b", "ref-b", "ref-b", "ref-b")),+ "at most 3 reference latents, got 4",+ ),+ (+ lambda inv: setattr(inv, "style_reference", _style_reference_field()),+ "cannot be combined with a style reference",+ ),+ (+ lambda inv: setattr(+ inv,+ "positive_conditioning",+ Krea2ConditioningField(conditioning_name="positive", mask=TensorField(tensor_name="positive-region")),+ ),+ "cannot be combined with regional",+ ),+ (+ lambda inv: setattr(+ inv,+ "negative_conditioning",+ [Krea2ConditioningField(conditioning_name="negative", mask=TensorField(tensor_name="negative-region"))],+ ),+ "cannot be combined with regional",+ ),+ (lambda inv: setattr(inv, "reference_latents", _references("ref-wrong-channels")), r"expected \(1, 16"),+ (lambda inv: setattr(inv, "reference_latents", _references("ref-two-frames")), r"expected \(1, 16"),+ (lambda inv: setattr(inv, "reference_latents", _references("ref-a", "ref-odd")), "latents 2 are 3x2"),+ ],+)+def test_run_diffusion_refuses_unusable_references_before_loading_the_transformer(+ monkeypatch, tmp_path, configure, message+) -> None:+ _patch_runtime(monkeypatch)+ invocation = _runtime_invocation(cfg_scale=4.0)+ invocation.reference_latents = _references("ref-a")+ configure(invocation)+ # The prompts agree with the references, so only the refusal under test can fire.+ encoded = len(invocation._reference_latent_fields())++ with pytest.raises(ValueError, match=message):+ invocation._run_diffusion(_refusing_context(tmp_path, positive_references=encoded))+++ ("reference_latents", "positive_references", "negative_references", "message"),+ [+ # Latents without the prompt having seen the images.+ (["ref-b"], 0, None, "positive Krea-2 prompt was encoded with 0 reference image.*has 1 reference latents"),+ # A prompt encoded with references, but no latents for the transformer.+ ([], 2, None, "positive Krea-2 prompt was encoded with 2 reference image.*has 0 reference latents"),+ # The positive prompt agrees; the negative one does not.+ (["ref-a", "ref-b"], 2, 1, "negative Krea-2 prompt was encoded with 1 reference image"),+ ],+)+def test_run_diffusion_refuses_prompts_encoded_with_a_different_reference_count(+ monkeypatch, tmp_path, reference_latents, positive_references, negative_references, message+) -> None:+ _patch_runtime(monkeypatch)+ invocation = _runtime_invocation(cfg_scale=4.0)+ invocation.reference_latents = _references(*reference_latents)++ with pytest.raises(ValueError, match=message):+ invocation._run_diffusion(_refusing_context(tmp_path, positive_references, negative_references))+++def test_a_zero_strength_style_reference_is_no_conflict_with_references() -> None:+ # Strength 0 is documented as "nothing connected".+ invocation = _runtime_invocation(cfg_scale=1.0)+ invocation.reference_latents = _references("ref-b")+ invocation.style_reference = _style_reference_field(style_strength=0.0)++ invocation._validate_inputs()++[email protected]_grad()+def test_run_diffusion_feeds_the_references_to_both_cfg_passes(monkeypatch, tmp_path) -> None:+ import invokeai.app.invocations.krea2.krea2_denoise as denoise_module++ _patch_runtime(monkeypatch)+ transformer = _tiny_krea2_transformer()+ calls: list[dict] = []+ real_forward = denoise_module.forward_with_references++ def recording_forward(model, hidden_states, encoder_hidden_states, timestep, position_ids, references):+ calls.append({"text_len": encoder_hidden_states.shape[1], "ids": position_ids, "refs": references})+ return real_forward(model, hidden_states, encoder_hidden_states, timestep, position_ids, references)++ monkeypatch.setattr(denoise_module, "forward_with_references", recording_forward)+ invocation = _runtime_invocation(cfg_scale=4.0)+ invocation.reference_latents = _references("ref-a", "ref-b")++ latents = invocation._run_diffusion(+ _reference_context(tmp_path, transformer, positive_references=2, negative_text_seq_len=3)+ )++ assert latents.shape == (1, KREA2_LATENT_CHANNELS, 1, 2, 2)+ # Two steps, conditional then unconditional, each with its own text length and the same references.+ assert [call["text_len"] for call in calls] == [2, 3, 2, 3]+ for call in calls:+ assert call["refs"].shape == (1, _REFERENCE_TOKENS, KREA2_LATENT_CHANNELS * 4)+ assert torch.equal(+ call["ids"][call["text_len"] :],+ torch.tensor([[0, 0, 0], [1, 0, 0], [1, 1, 0], [2, 0, 0]], dtype=torch.float32),+ )+++def test_run_diffusion_without_references_keeps_the_stock_transformer_call(monkeypatch, tmp_path) -> None:+ import invokeai.app.invocations.krea2.krea2_denoise as denoise_module++ _patch_runtime(monkeypatch)++ def unexpected(*_args, **_kwargs):+ pytest.fail("the reference path ran without references")++ monkeypatch.setattr(denoise_module, "forward_with_references", unexpected)+ transformer = _Transformer()+ invocation = _runtime_invocation(cfg_scale=4.0)+ invocation.reference_latents = []++ invocation._run_diffusion(_reference_context(tmp_path, transformer))++ assert transformer.position_id_lengths == [2 + 1, 2 + 1] * 2+++def test_run_diffusion_reserves_memory_for_the_reference_tokens(monkeypatch, tmp_path) -> None:+ import invokeai.app.invocations.krea2.krea2_denoise as denoise_module++ asked_seq_lens: list[int] = []++ def reservation(reference_latents) -> int:+ transformer = _Transformer()+ transformer.config = SimpleNamespace(num_attention_heads=48, attention_head_dim=128)+ info = _TransformerInfo(transformer)+ context = _reference_context(tmp_path, transformer, positive_references=len(reference_latents or []))+ context.models.load = lambda _identifier: info+ invocation = _runtime_invocation(cfg_scale=1.0)+ invocation.reference_latents = reference_latents+ invocation._run_diffusion(context)+ return info.working_mem_bytes++ def score_matrix_bytes(**kwargs) -> int:+ asked_seq_lens.append(kwargs["seq_len"])+ return 0++ _patch_runtime(monkeypatch)+ monkeypatch.setattr(+ denoise_module, "forward_with_references", lambda _model, hidden_states, *_args: torch.zeros_like(hidden_states)+ )+ monkeypatch.setattr(denoise_module, "sdpa_score_matrix_bytes", score_matrix_bytes)++ without_references = reservation(None)+ with_references = reservation(_references("ref-a", "ref-b"))++ # Every reference token is an image token to every block; 0.5 MiB per token is the estimate's own rate.+ assert with_references - without_references == _REFERENCE_TOKENS * int(0.5 * 1024**2)+ # The attention the score matrix is priced for spans text + target + references.+ assert asked_seq_lens == [2 + 1, 2 + 1 + _REFERENCE_TOKENS]++[email protected]_grad()+def test_run_diffusion_inpaints_only_the_target_next_to_references(monkeypatch, tmp_path) -> None:+ # img2img + inpaint act on the unpacked target latents. With references in the sequence the transformer+ # must still return target tokens only, and the kept region must land exactly on the init latents.+ _patch_runtime(monkeypatch)+ init = torch.randn(1, KREA2_LATENT_CHANNELS, 2, 2, generator=torch.Generator().manual_seed(3))+ keep_left_half = torch.zeros(1, 1, 16, 16)+ keep_left_half[..., :8] = 1.0 # the denoise mask marks what to keep; the node inverts it+ context = _reference_context(tmp_path, _tiny_krea2_transformer(), positive_references=2)+ tensors = {"init": init, "mask": keep_left_half}+ reference_tensors = context.tensors.load+ context.tensors.load = lambda name: tensors[name] if name in tensors else reference_tensors(name)+ invocation = _runtime_invocation(cfg_scale=1.0, with_mask=True)+ invocation.reference_latents = _references("ref-a", "ref-b")++ latents = invocation._run_diffusion(context)++ assert latents.shape == (1, KREA2_LATENT_CHANNELS, 1, 2, 2)+ torch.testing.assert_close(latents[0, :, 0, :, 0], init[0, :, :, 0])+ assert not torch.allclose(latents[0, :, 0, :, 1], init[0, :, :, 1])++[email protected](("cfg_scale", "refused"), [(1.0, False), ([1.0, 1.0], False), ([1.0, 4.0], True)])+def test_the_negative_prompt_reference_count_matters_only_when_cfg_runs(cfg_scale, refused) -> None:+ # A workflow can leave a negative prompt connected at CFG 1, where it never runs.+ invocation = _runtime_invocation(cfg_scale=cfg_scale)+ invocation.reference_latents = _references("ref-a", "ref-b")+ context = _reference_context(None, _Transformer(), positive_references=2, negative_references=0)++ if refused:+ with pytest.raises(ValueError, match="negative Krea-2 prompt was encoded with 0 reference image"):+ invocation._validate_reference_counts(context)+ else:+ invocation._validate_reference_counts(context)+++# --- Edit references in K/V-cache mode (reference_kv_cache) ----------------------------------------------+++def _main_block_kv_state(transformer):+ return transformer.attn_processors["transformer_blocks.0.attn.processor"].reference_kv_cache+++def _record_reference_kv(monkeypatch) -> list[tuple[int, torch.Tensor]]:+ from invokeai.backend.krea2.reference_edit import Krea2ReferenceKVCache++ stored: list[tuple[int, torch.Tensor]] = []+ real_store = Krea2ReferenceKVCache.store++ def store(self, block_index, key, value):+ stored.append((block_index, value.clone()))+ real_store(self, block_index, key, value)++ monkeypatch.setattr(Krea2ReferenceKVCache, "store", store)+ return stored++[email protected]_grad()+def test_the_reference_kv_cache_is_built_once_per_run_and_released(monkeypatch, tmp_path) -> None:+ import invokeai.app.invocations.krea2.krea2_denoise as denoise_module+ from invokeai.backend.krea2.reference_edit import Krea2ReferenceKVCache++ _patch_runtime(monkeypatch)+ stored = _record_reference_kv(monkeypatch)+ extended: list[int] = []+ real_extend = Krea2ReferenceKVCache.extend++ def extend(self, block_index, key, value, attention_mask):+ extended.append(block_index)+ return real_extend(self, block_index, key, value, attention_mask)++ monkeypatch.setattr(Krea2ReferenceKVCache, "extend", extend)++ def unexpected(*_args, **_kwargs):+ pytest.fail("K/V-cache mode must not put the references into the per-step sequence")++ monkeypatch.setattr(denoise_module, "forward_with_references", unexpected)+ transformer = _tiny_krea2_transformer()+ invocation = _runtime_invocation(cfg_scale=4.0)+ invocation.reference_latents = _references("ref-a", "ref-b")+ invocation.reference_kv_cache = True++ latents = invocation._run_diffusion(+ _reference_context(tmp_path, transformer, positive_references=2, negative_text_seq_len=3)+ )++ assert latents.shape == (1, KREA2_LATENT_CHANNELS, 1, 2, 2)+ # Two steps with CFG are four transformer passes, but the references ran through the blocks once.+ assert [block_index for block_index, _ in stored] == [0, 1]+ assert stored[0][1].shape[2] == _REFERENCE_TOKENS+ # ...and every block of every pass attended over the cached reference keys.+ assert extended == [0, 1] * (2 * 2)+ # The processors stay on the cached transformer; the cache must not.+ state = _main_block_kv_state(transformer)+ assert len(state) == 0+ assert state.mode.name == "OFF"++[email protected]_grad()+def test_the_reference_kv_cache_is_released_when_a_step_raises(monkeypatch, tmp_path) -> None:+ _patch_runtime(monkeypatch)+ transformer = _tiny_krea2_transformer()+ context = _reference_context(tmp_path, transformer, positive_references=1)++ def step_callback(state, _base) -> None:+ if state.step >= 1:+ raise RuntimeError("step failure")++ context.util.sd_step_callback = step_callback+ invocation = _runtime_invocation(cfg_scale=1.0)+ invocation.reference_latents = _references("ref-b")+ invocation.reference_kv_cache = True++ with pytest.raises(RuntimeError, match="step failure"):+ invocation._run_diffusion(context)++ assert len(_main_block_kv_state(transformer)) == 0++[email protected]_grad()+def test_the_reference_kv_cache_is_built_from_the_lora_patched_weights(monkeypatch, tmp_path) -> None:+ from contextlib import contextmanager++ _patch_runtime(monkeypatch)+ stored = _record_reference_kv(monkeypatch)+ transformer = _tiny_krea2_transformer()++ @contextmanager+ def doubling_patch(*, model, **_kwargs):+ # Stands in for a LoRA on block 0's value projection. V has no norm or bias, so the cached V doubles.+ weight = model.transformer_blocks[0].attn.to_v.weight+ weight.mul_(2.0)+ try:+ yield+ finally:+ weight.div_(2.0)++ def cached_block0_value(patcher) -> torch.Tensor:+ stored.clear()+ monkeypatch.setattr(+ "invokeai.app.invocations.krea2.krea2_denoise.LayerPatcher.apply_smart_model_patches", patcher+ )+ invocation = _runtime_invocation(cfg_scale=1.0)+ invocation.reference_latents = _references("ref-b")+ invocation.reference_kv_cache = True+ invocation._run_diffusion(_reference_context(tmp_path, transformer, positive_references=1))+ return next(value for block_index, value in stored if block_index == 0)++ plain = cached_block0_value(lambda **_kwargs: nullcontext())+ patched = cached_block0_value(doubling_patch)++ torch.testing.assert_close(patched, 2.0 * plain)+++def test_the_reference_kv_cache_flag_without_references_changes_nothing(monkeypatch, tmp_path) -> None:+ _patch_runtime(monkeypatch)+ transformer = _Transformer()+ invocation = _runtime_invocation(cfg_scale=4.0)+ invocation.reference_kv_cache = True++ invocation._run_diffusion(_reference_context(tmp_path, transformer))++ assert transformer.installed_processors["transformer_blocks.0.attn.processor"].reference_kv_cache is None+ assert transformer.position_id_lengths == [2 + 1, 2 + 1] * 2+++def test_the_reference_kv_cache_refuses_a_subclass_with_its_own_processors() -> None:+ invocation = _SubclassWithOwnProcessors.model_construct(+ positive_conditioning=Krea2ConditioningField(conditioning_name="positive"),+ reference_latents=_references("ref-b"),+ reference_kv_cache=True,+ )++ with pytest.raises(ValueError, match="installs its own Krea-2 attention processors"):+ invocation._validate_inputs()+++def test_the_reference_kv_cache_reserves_its_cache_instead_of_per_step_tokens(monkeypatch, tmp_path) -> None:+ import invokeai.app.invocations.krea2.krea2_denoise as denoise_module++ def reservation(reference_latents, kv_cache: bool) -> int:+ transformer = _Transformer()+ transformer.config = SimpleNamespace(num_attention_heads=48, attention_head_dim=128)+ info = _TransformerInfo(transformer)+ context = _reference_context(tmp_path, transformer, positive_references=len(reference_latents or []))+ context.models.load = lambda _identifier: info+ invocation = _runtime_invocation(cfg_scale=1.0)+ invocation.reference_latents = reference_latents+ invocation.reference_kv_cache = kv_cache+ invocation._run_diffusion(context)+ return info.working_mem_bytes++ asked_seq_lens: list[int] = []++ def score_matrix_bytes(**kwargs) -> int:+ asked_seq_lens.append(kwargs["seq_len"])+ return 0++ _patch_runtime(monkeypatch)+ # The stub transformer has no blocks to cache; the precompute itself is covered with a real model above.+ monkeypatch.setattr(denoise_module, "precompute_reference_kv", lambda *_args: None)+ monkeypatch.setattr(denoise_module, "sdpa_score_matrix_bytes", score_matrix_bytes)++ without_references = reservation(None, kv_cache=True)+ cached = reservation(_references("ref-a", "ref-b"), kv_cache=True)++ # Krea-2 defaults where the stub config is silent: 28 blocks, 12 K/V heads; fp32 under the patched runtime.+ retained = 28 * 2 * 12 * 128 * _REFERENCE_TOKENS * 4+ widest_append = 2 * 48 * 128 * _REFERENCE_TOKENS * 4+ assert cached - without_references == retained + widest_append+ # Scores: S = 2 text + 1 target queries over S + 3 reference keys is the larger area (18 > 3 * 3), priced as+ # the smallest square that holds it.+ step, references = 2 + 1, _REFERENCE_TOKENS+ assert asked_seq_lens == [step, math.ceil(math.sqrt(max(step * (step + references), references**2)))]diff --git a/tests/app/invocations/test_krea2_enhancers.py b/tests/app/invocations/test_krea2_enhancers.pyindex 1b6784d48b..ab1e510f8c 100644--- a/tests/app/invocations/test_krea2_enhancers.py+++ b/tests/app/invocations/test_krea2_enhancers.py@@ -17,10 +17,14 @@ from invokeai.app.invocations.krea2.krea2_seed_variance import Krea2SeedVariancefrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData, Krea2ConditioningInfo-def _make_context(embeds: torch.Tensor, saved: dict) -> SimpleNamespace:+def _make_context(embeds: torch.Tensor, saved: dict, num_reference_images: int = 0) -> SimpleNamespace:def load(_name: str) -> ConditioningFieldData:return ConditioningFieldData(- conditionings=[Krea2ConditioningInfo(prompt_embeds=embeds, prompt_embeds_mask=None)]+ conditionings=[+ Krea2ConditioningInfo(+ prompt_embeds=embeds, prompt_embeds_mask=None, num_reference_images=num_reference_images+ )+ ])def save(data: ConditioningFieldData) -> str:@@ -252,3 +256,29 @@ def test_seed_variance_preserves_the_regional_mask_when_enabled() -> None:output = invocation.invoke(_make_context(_ramp_embeds(), {}))assert output.conditioning.mask == regional_mask+++ "invocation",+ [+ Krea2ConditioningRebalanceInvocation.model_construct(+ conditioning=Krea2ConditioningField(conditioning_name="c"),+ per_layer_weights=",".join(["1.0"] * 12),+ multiplier=2.0,+ ),+ Krea2SeedVarianceInvocation.model_construct(+ conditioning=Krea2ConditioningField(conditioning_name="c"),+ strength=0.5,+ randomize_percent=50.0,+ variance_seed=3,+ ),+ ],+ ids=["rebalance", "seed_variance"],+)+def test_the_enhancers_keep_the_reference_image_count(invocation) -> None:+ """The denoise checks the count against its reference latents; an enhancer in between must not reset it."""+ saved: dict = {}++ invocation.invoke(_make_context(_ramp_embeds(), saved, num_reference_images=2))++ assert saved["data"].conditionings[0].num_reference_images == 2diff --git a/tests/app/invocations/test_krea2_text_encoder.py b/tests/app/invocations/test_krea2_text_encoder.pyindex 553fbc9284..1c32a2aebc 100644--- a/tests/app/invocations/test_krea2_text_encoder.py+++ b/tests/app/invocations/test_krea2_text_encoder.py@@ -395,3 +395,164 @@ def test_invoke_preserves_the_regional_mask_on_its_conditioning_output(monkeypatassert output.conditioning.conditioning_name == "conditioning-name"assert output.conditioning.mask == regional_mask+++# --- reference images (edit mode) ------------------------------------------------------------------++_INVOCATION_MODULE = "invokeai.app.invocations.text_encoder.krea2_text_encoder"+++class _RecordingInfo:+ """A LoadedModel stand-in that logs when its model is locked and released."""++ def __init__(self, name: str, model, events: list[str]) -> None:+ self.name = name+ self.model = model+ self.compute_device = torch.device("cpu")+ self._events = events+ self.working_mem_bytes: list[int | None] = []++ @contextmanager+ def model_on_device(self, working_mem_bytes=None):+ self.working_mem_bytes.append(working_mem_bytes)+ self._events.append(f"lock {self.name}")+ try:+ yield ({}, self.model)+ finally:+ self._events.append(f"unlock {self.name}")++ def __enter__(self):+ return self.model++ def __exit__(self, *_args):+ return None+++def _edit_context(events: list[str], loaded: list, infos: dict, *, refuse_tower: bool = False) -> SimpleNamespace:+ from PIL import Image++ def load(identifier):+ loaded.append(identifier)+ if refuse_tower and identifier.submodel_type is SubModelType.VisionEncoder:+ raise ValueError("The GGUF Qwen3-VL encoder 'encoder' has no vision tower")+ name = identifier.submodel_type.value+ fakes = {SubModelType.TextEncoder: _TextEncoder, SubModelType.Tokenizer: _Tokenizer}+ model = fakes.get(identifier.submodel_type, object)()+ infos[name] = _RecordingInfo(name, model, events)+ return infos[name]++ return SimpleNamespace(+ models=SimpleNamespace(load=load, get_config=lambda _identifier: _ENCODER_CONFIG),+ util=SimpleNamespace(signal_progress=lambda _message: None),+ images=SimpleNamespace(get_pil=lambda name: Image.new("RGB", (800, 600) if name == "big" else (64, 48))),+ )+++def _edit_invocation(*image_names: str) -> Krea2TextEncoderInvocation:+ from invokeai.app.invocations.fields import ImageField++ encoder = _identifier("encoder", ModelType.Qwen3VLEncoder)+ field = Qwen3VLEncoderField(+ tokenizer=encoder.model_copy(update={"submodel_type": SubModelType.Tokenizer}),+ text_encoder=encoder.model_copy(update={"submodel_type": SubModelType.TextEncoder}),+ loras=[],+ )+ return Krea2TextEncoderInvocation(+ prompt="make it red",+ qwen3_vl_encoder=field,+ reference_images=[ImageField(image_name=name) for name in image_names],+ )+++def _no_lora_patching(monkeypatch):+ monkeypatch.setattr(f"{_INVOCATION_MODULE}.LayerPatcher.apply_smart_model_patches", lambda **_kwargs: nullcontext())+ monkeypatch.setattr(f"{_INVOCATION_MODULE}.TorchDevice.choose_bfloat16_safe_dtype", lambda _device: torch.float32)+++def test_a_text_only_prompt_loads_neither_the_tower_nor_the_processor(_no_lora_patching) -> None:+ loaded: list = []+ events: list[str] = []+ infos: dict = {}++ embeds, _ = _edit_invocation()._encode(_edit_context(events, loaded, infos))++ assert {identifier.submodel_type for identifier in loaded} == {SubModelType.Tokenizer, SubModelType.TextEncoder}+ assert embeds.shape == (1, 512, 12, 4)+ assert infos["text_encoder"].working_mem_bytes == [0]+++def test_reference_images_lend_the_tower_to_the_locked_encoder(monkeypatch, _no_lora_patching) -> None:+ """The tower and processor come from the encoder's own model, the encode reserves for the longer+ sequence, and the tower is locked inside the encoder's lock and released before it: neither cache+ entry may move while the tower is part of the encoder's module tree."""+ from invokeai.backend.krea2.text_encoding import working_memory_bytes++ loaded: list = []+ events: list[str] = []+ infos: dict = {}+ captured: dict = {}++ def tokenize(prompt, images, processor, tokenizer):+ captured.update(prompt=prompt, images=images, processor=processor)+ return {"input_ids": torch.zeros(1, 300, dtype=torch.long)}++ def encode(inputs, text_encoder, vision_tower):+ events.append("encode")+ captured.update(text_encoder=text_encoder, vision_tower=vision_tower)+ return torch.zeros(1, 266, 12, 4), torch.ones(1, 266, dtype=torch.bool)++ monkeypatch.setattr(f"{_INVOCATION_MODULE}.tokenize_krea2_prompt_with_images", tokenize)+ monkeypatch.setattr(f"{_INVOCATION_MODULE}.encode_krea2_prompt_with_images", encode)++ embeds, mask = _edit_invocation("big", "small")._encode(_edit_context(events, loaded, infos))++ by_type = {identifier.submodel_type: identifier for identifier in loaded}+ assert by_type[SubModelType.VisionEncoder].key == "encoder"+ assert by_type[SubModelType.Processor].key == "encoder"+ assert captured["prompt"] == "make it red"+ # Each reference went through the 384^2 rule on the way: 800x600 shrinks, 64x48 stays.+ assert [tuple(image.shape) for image in captured["images"]] == [(3, 333, 443), (3, 48, 64)]+ assert captured["processor"] is infos["processor"].model+ assert captured["text_encoder"] is infos["text_encoder"].model+ assert captured["vision_tower"] is infos["vision_encoder"].model+ assert infos["text_encoder"].working_mem_bytes == [working_memory_bytes(300)]+ assert events == [+ "lock text_encoder",+ "lock vision_encoder",+ "encode",+ "unlock vision_encoder",+ "unlock text_encoder",+ ]+ assert embeds.shape == (1, 266, 12, 4)+ assert mask is not None and bool(mask.all())+++def test_an_encoder_without_a_tower_fails_before_the_encoder_is_read(_no_lora_patching) -> None:+ loaded: list = []++ with pytest.raises(ValueError, match="has no vision tower"):+ _edit_invocation("small")._encode(_edit_context([], loaded, {}, refuse_tower=True))++ assert SubModelType.TextEncoder not in {identifier.submodel_type for identifier in loaded}+++def test_more_than_three_reference_images_are_refused() -> None:+ from pydantic import ValidationError++ with pytest.raises(ValidationError, match="reference_images"):+ _edit_invocation("a", "b", "c", "d")++[email protected]("image_names", [(), ("big", "small")], ids=["text_only", "two_references"])+def test_the_conditioning_records_how_many_references_it_read(monkeypatch, image_names) -> None:+ saved: dict = {}+ invocation = _edit_invocation(*image_names)+ monkeypatch.setattr(+ invocation, "_encode", lambda _context: (torch.zeros(1, 2, 12, 4), torch.ones(1, 2, dtype=torch.bool))+ )+ context = SimpleNamespace(conditioning=SimpleNamespace(save=lambda data: saved.setdefault("data", data) and "c"))++ invocation.invoke(context)++ assert saved["data"].conditionings[0].num_reference_images == len(image_names)diff --git a/tests/app/invocations/test_qwen_image_i2l_reference.py b/tests/app/invocations/test_qwen_image_i2l_reference.pynew file mode 100644index 0000000000..33a7933818--- /dev/null+++ b/tests/app/invocations/test_qwen_image_i2l_reference.py@@ -0,0 +1,109 @@+"""`qwen_image_i2l` with `reference` enabled encodes an edit reference the way ai-toolkit trains edit LoRAs:+RGB without alpha, downscaled (never upscaled) to at most 1 MP, sides snapped to 16, bilinear resize."""++from types import SimpleNamespace++import numpy as np+import pytest+import torch+import torch.nn.functional as F+from PIL import Image++from invokeai.app.invocations.fields import ImageField+from invokeai.app.invocations.model import ModelIdentifierField, VAEField+from invokeai.app.invocations.vae.qwen_image_image_to_latents import QwenImageImageToLatentsInvocation+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType+++def _encode(monkeypatch, image: Image.Image, **fields) -> torch.Tensor:+ """Run the node and return the pixel tensor it hands to the VAE."""+ seen: list[torch.Tensor] = []++ def fake_vae_encode(vae_info, image_tensor, tiled=False, tile_size=0):+ seen.append(image_tensor)+ _, _, height, width = image_tensor.shape+ return torch.zeros(1, 16, 1, height // 8, width // 8)++ monkeypatch.setattr(QwenImageImageToLatentsInvocation, "vae_encode", staticmethod(fake_vae_encode))+ vae = ModelIdentifierField(key="vae", hash="h", name="vae", base=BaseModelType.QwenImage, type=ModelType.VAE)+ invocation = QwenImageImageToLatentsInvocation(image=ImageField(image_name="ref"), vae=VAEField(vae=vae), **fields)+ context = SimpleNamespace(+ images=SimpleNamespace(get_pil=lambda _name: image),+ models=SimpleNamespace(load=lambda _identifier: None),+ config=SimpleNamespace(get=lambda: SimpleNamespace(force_tiled_decode=False)),+ tensors=SimpleNamespace(save=lambda tensor: "latents"),+ )+ invocation.invoke(context)+ return seen[0]+++def _noise_image(width: int, height: int, mode: str = "RGB") -> Image.Image:+ channels = len(mode)+ pixels = np.random.default_rng(0).integers(0, 256, size=(height, width, channels), dtype=np.uint8)+ return Image.fromarray(pixels, mode=mode)+++def _as_unit_tensor(image: Image.Image) -> torch.Tensor:+ pixels = np.asarray(image.convert("RGB"), dtype=np.float32) / 255.0+ return torch.from_numpy(pixels).permute(2, 0, 1).unsqueeze(0)+++ ("width", "height", "expected_height", "expected_width"),+ [+ # 3 MP, 4:3: area 1 MP keeps 4:3 -> 886.8 x 1182.4, snapped to 880 x 1184.+ (2048, 1536, 880, 1184),+ # A tall 2:1 image at 2 MP: 1448.2 x 724.1 -> 1456 x 720.+ (1000, 2000, 1456, 720),+ # Under 1 MP is not scaled, only snapped: 300 -> 304, 500 -> 496.+ (500, 300, 304, 496),+ # Already on the grid and under budget: untouched.+ (512, 256, 256, 512),+ # Sides never snap below 16.+ (10, 6, 16, 16),+ ],+)+def test_a_reference_is_downscaled_to_one_megapixel_and_snapped_to_16(+ monkeypatch, width, height, expected_height, expected_width+) -> None:+ tensor = _encode(monkeypatch, _noise_image(width, height), reference=True)++ assert tensor.shape == (1, 3, expected_height, expected_width)+++def test_a_reference_is_resized_bilinearly_without_antialiasing(monkeypatch) -> None:+ image = _noise_image(2048, 1536)++ tensor = _encode(monkeypatch, image, reference=True)++ expected = F.interpolate(_as_unit_tensor(image), size=(880, 1184), mode="bilinear", antialias=False) * 2 - 1+ torch.testing.assert_close(tensor, expected)+++def test_a_reference_on_the_grid_is_encoded_pixel_exact(monkeypatch) -> None:+ image = _noise_image(512, 256)++ tensor = _encode(monkeypatch, image, reference=True)++ assert torch.equal(tensor, _as_unit_tensor(image) * 2 - 1)+++def test_a_reference_drops_alpha_instead_of_compositing_it(monkeypatch) -> None:+ # Fully transparent red: compositing onto white or black would change the colour, dropping alpha keeps it.+ image = Image.new("RGBA", (32, 32), (255, 0, 0, 0))++ tensor = _encode(monkeypatch, image, reference=True)++ assert torch.equal(tensor[0, :, 0, 0], torch.tensor([1.0, -1.0, -1.0]))+++def test_a_reference_refuses_an_explicit_size(monkeypatch) -> None:+ with pytest.raises(ValueError, match="sized automatically"):+ _encode(monkeypatch, _noise_image(64, 64), reference=True, width=32, height=32)+++def test_without_reference_a_large_image_is_encoded_at_its_own_size(monkeypatch) -> None:+ # The default stays the Qwen-Image / Krea-2 img2img path: no 1 MP budget.+ tensor = _encode(monkeypatch, _noise_image(2048, 1536))++ assert tensor.shape == (1, 3, 1536, 2048)diff --git a/tests/backend/krea2/test_krea2_image_text_encoding.py b/tests/backend/krea2/test_krea2_image_text_encoding.pynew file mode 100644index 0000000000..f73c2cd996--- /dev/null+++ b/tests/backend/krea2/test_krea2_image_text_encoding.py@@ -0,0 +1,376 @@+"""Krea-2 edit mode: reference images read by the Qwen3-VL vision tower into the prompt conditioning.++The reference is ai-toolkit's ``encode_krea_prompt`` / ``_prep_vlm_images``, which trains Krea-2 edit LoRAs.+Everything runs on a tiny but real ``Qwen3VLModel`` with the bundled tokenizer and processor, so the token+ids are the release's and the vision tower is the architecture's own. The vocabulary is kept at full size+for that reason; only the widths shrink.+"""++import pytest+import torch+from PIL import Image++from invokeai.backend.krea2.sampling_utils import KREA2_SELECT_LAYERS, KREA2_START_IDX+from invokeai.backend.krea2.text_encoding import (+ KREA2_BODY_MAX_LENGTH,+ KREA2_PREFIX,+ KREA2_SUFFIX,+ encode_krea2_prompt,+ encode_krea2_prompt_with_images,+ prepare_vlm_reference,+ tokenize_krea2_prompt_with_images,+ working_memory_bytes,+)+from invokeai.backend.model_manager.util.qwen3_vl import attach_qwen3vl_visual_tower, drop_qwen3vl_visual_tower+from invokeai.backend.qwen3_vl.qwen3_vl_assets import build_qwen3_vl_processor, load_bundled_qwen3_vl_tokenizer++HIDDEN = 64+++def _tiny_config(*, vision_out: int = HIDDEN):+ from transformers import Qwen3VLConfig++ return Qwen3VLConfig(+ text_config={+ "hidden_size": HIDDEN,+ "intermediate_size": 128,+ # Krea-2 taps layers up to 35, so the depth is the real one.+ "num_hidden_layers": 36,+ "num_attention_heads": 2,+ "num_key_value_heads": 1,+ "head_dim": 32,+ "vocab_size": 151936,+ "rope_scaling": {+ "mrope_interleaved": True,+ "mrope_section": [6, 5, 5],+ "rope_type": "default",+ "rope_theta": 5000000,+ },+ },+ vision_config={+ "hidden_size": HIDDEN,+ "intermediate_size": 128,+ "depth": 2,+ "num_heads": 2,+ "out_hidden_size": vision_out,+ "deepstack_visual_indexes": [0],+ },+ )+++def _tiny_encoder():+ from transformers import Qwen3VLModel++ torch.manual_seed(0)+ return Qwen3VLModel(_tiny_config()).eval()++[email protected](scope="module")+def tokenizer():+ return load_bundled_qwen3_vl_tokenizer()++[email protected](scope="module")+def processor(tokenizer):+ return build_qwen3_vl_processor(tokenizer)++[email protected](autouse=True)+def _float32_conditioning(monkeypatch):+ """The conditioning is cast to the device's bf16-safe dtype; keep it float32 so equality is exact."""+ monkeypatch.setattr(+ "invokeai.backend.krea2.text_encoding.TorchDevice.choose_bfloat16_safe_dtype", lambda _device: torch.float32+ )+++def _ids(tokenizer, text: str) -> list[int]:+ return tokenizer(text, add_special_tokens=False).input_ids+++def _image(height: int, width: int, seed: int = 0) -> torch.Tensor:+ generator = torch.Generator().manual_seed(seed)+ return torch.rand(3, height, width, generator=generator)+++# --- token layout ----------------------------------------------------------------------------------+++def test_prompt_layout_names_each_reference_after_the_system_prefix(tokenizer, processor) -> None:+ """ai-toolkit's layout, token for token: prefix, then ``Picture N: <vision_start><pad>*n<vision_end>`` per+ reference with no separator, the prompt, and the assistant suffix appended after the processor pass.+ Each pad run is one token per 2x2 merged 16px patches."""+ # Both sizes are multiples of the 32px merged patch and inside the processor's pixel budget, so the+ # processor keeps them as they are: 8 x 12 and 10 x 10 merged patches.+ images = [_image(256, 384), _image(320, 320, seed=1)]++ inputs = tokenize_krea2_prompt_with_images("a red fox", images, processor, tokenizer)++ pad = tokenizer.convert_tokens_to_ids("<|image_pad|>")+ start = tokenizer.convert_tokens_to_ids("<|vision_start|>")+ end = tokenizer.convert_tokens_to_ids("<|vision_end|>")+ expected = (+ _ids(tokenizer, KREA2_PREFIX)+ + _ids(tokenizer, "Picture 1: ")+ + [start, *[pad] * (8 * 12), end]+ + _ids(tokenizer, "Picture 2: ")+ + [start, *[pad] * (10 * 10), end]+ + _ids(tokenizer, "a red fox")+ + _ids(tokenizer, KREA2_SUFFIX)+ )+ assert inputs["input_ids"][0].tolist() == expected+ assert inputs["image_grid_thw"].tolist() == [[1, 16, 24], [1, 20, 20]]+ # The M-RoPE token types mark exactly the pads, the appended suffix included as text.+ assert torch.equal(inputs["mm_token_type_ids"][0].bool(), inputs["input_ids"][0] == pad)+ assert inputs["attention_mask"].dtype is torch.bool+ assert bool(inputs["attention_mask"].all())+++def test_the_prefix_drop_removes_the_system_turn_and_keeps_every_image_token(tokenizer, processor) -> None:+ inputs = tokenize_krea2_prompt_with_images("x", [_image(256, 256)], processor, tokenizer)+ pad = tokenizer.convert_tokens_to_ids("<|image_pad|>")++ assert len(_ids(tokenizer, KREA2_PREFIX)) == KREA2_START_IDX+ kept = inputs["input_ids"][0, KREA2_START_IDX:]+ assert int((kept == pad).sum()) == int((inputs["input_ids"] == pad).sum()) == 8 * 8+++def test_a_long_prompt_is_not_truncated_with_images(tokenizer, processor) -> None:+ """Truncating would cut a pad run apart, which the model refuses; ai-toolkit encodes at natural length."""+ prompt = " ".join(["word"] * 700)++ inputs = tokenize_krea2_prompt_with_images(prompt, [_image(256, 256)], processor, tokenizer)++ assert inputs["input_ids"].shape[1] > KREA2_BODY_MAX_LENGTH+ assert inputs["input_ids"][0, -5:].tolist() == _ids(tokenizer, KREA2_SUFFIX)+++# --- the 384^2 vision budget -----------------------------------------------------------------------+++def test_a_large_reference_is_downscaled_to_the_vision_budget_keeping_its_aspect() -> None:+ # scale = sqrt(384^2 / (1024 * 768)) = 0.4330; 768 -> 332.55 -> 333, 1024 -> 443.4 -> 443.+ pixels = prepare_vlm_reference(Image.new("RGB", (1024, 768), (255, 0, 0)))++ assert pixels.shape == (3, 333, 443)+ assert pixels.dtype is torch.float32+ assert torch.allclose(pixels[0], torch.ones(333, 443))+ assert torch.allclose(pixels[1:], torch.zeros(2, 333, 443))+++def test_a_small_reference_is_never_upscaled() -> None:+ image = Image.new("RGB", (200, 100), (51, 102, 204))++ pixels = prepare_vlm_reference(image)++ assert pixels.shape == (3, 100, 200)+ assert pixels[:, 0, 0].tolist() == pytest.approx([0.2, 0.4, 0.8])+++def test_a_thin_reference_is_held_at_the_minimum_side() -> None:+ pixels = prepare_vlm_reference(Image.new("RGB", (1000, 10)))++ assert pixels.shape == (3, 28, 1000)+++def test_alpha_is_dropped_rather_than_composited() -> None:+ """ai-toolkit and ComfyUI's LoadImage both discard alpha; compositing over white would brighten a+ transparent reference into something the LoRA never saw."""+ pixels = prepare_vlm_reference(Image.new("RGBA", (64, 64), (0, 0, 0, 0)))++ assert torch.equal(pixels, torch.zeros(3, 64, 64))+++def test_the_downscaled_reference_stays_in_range() -> None:+ """Bicubic overshoots at hard edges; the pass expects pixels in [0, 1], as ai-toolkit clamps them."""+ checker = Image.new("L", (1200, 1200))+ checker.putdata([255 * ((x // 3 + y // 3) % 2) for y in range(1200) for x in range(1200)])++ pixels = prepare_vlm_reference(checker)++ assert pixels.shape == (3, 384, 384)+ assert float(pixels.min()) >= 0.0+ assert float(pixels.max()) <= 1.0+++# --- the encode ------------------------------------------------------------------------------------+++def test_the_image_encode_matches_a_model_that_never_lost_its_tower(tokenizer, processor) -> None:+ """The lent tower must make the encoder behave exactly as if it had kept it: the same call ai-toolkit+ makes (no position ids, so Qwen3-VL builds its 3-D M-RoPE) on the intact model is the reference."""+ model = _tiny_encoder()+ inputs = tokenize_krea2_prompt_with_images(+ "a red fox", [_image(256, 384), _image(320, 320, seed=1)], processor, tokenizer+ )+ with torch.no_grad():+ hidden = model(**inputs, output_hidden_states=True, use_cache=False).hidden_states+ expected = torch.stack([hidden[i] for i in KREA2_SELECT_LAYERS], dim=2)[:, KREA2_START_IDX:]++ tower = model.visual+ drop_qwen3vl_visual_tower(model)+ with torch.no_grad():+ embeds, mask = encode_krea2_prompt_with_images(inputs, model, tower)++ length = inputs["input_ids"].shape[1] - KREA2_START_IDX+ assert embeds.shape == (1, length, 12, HIDDEN)+ assert torch.equal(embeds, expected)+ assert mask.shape == (1, length)+ assert bool(mask.all())+ assert isinstance(model.visual, torch.nn.Identity)+++def test_the_references_change_the_conditioning(tokenizer, processor) -> None:+ """Guards the test above against passing vacuously: with another image the prompt tokens read differently."""+ model = _tiny_encoder()+ tower = model.visual+ drop_qwen3vl_visual_tower(model)++ with torch.no_grad():+ first, _ = encode_krea2_prompt_with_images(+ tokenize_krea2_prompt_with_images("a fox", [_image(256, 256)], processor, tokenizer), model, tower+ )+ second, _ = encode_krea2_prompt_with_images(+ tokenize_krea2_prompt_with_images("a fox", [_image(256, 256, seed=7)], processor, tokenizer), model, tower+ )++ assert first.shape == second.shape+ assert not torch.equal(first[:, -8:], second[:, -8:])+++def _expected_text_only(model, tokenizer, prompt: str) -> torch.Tensor:+ """diffusers' text-only layout restated: prefix + prompt padded to 541, the suffix after, 1-D positions."""+ body = _ids(tokenizer, KREA2_PREFIX + prompt)+ pad_id = tokenizer.pad_token_id+ suffix = _ids(tokenizer, KREA2_SUFFIX)+ input_ids = torch.tensor([body + [pad_id] * (KREA2_BODY_MAX_LENGTH - len(body)) + suffix])+ mask = torch.tensor([[True] * len(body) + [False] * (KREA2_BODY_MAX_LENGTH - len(body)) + [True] * len(suffix)])+ positions = (mask.long().cumsum(-1) - 1).clamp(min=0).unsqueeze(0).expand(3, -1, -1)+ with torch.no_grad():+ hidden = model(+ input_ids=input_ids, attention_mask=mask, position_ids=positions, output_hidden_states=True, use_cache=False+ ).hidden_states+ return torch.stack([hidden[i] for i in KREA2_SELECT_LAYERS], dim=2)[:, KREA2_START_IDX:]+++def test_the_text_only_conditioning_is_unchanged_and_untouched_by_an_image_encode(tokenizer, processor) -> None:+ """Text-only prompts keep the diffusers-parity path, and an image encode on the same encoder leaves no+ trace: the 3-D rope deltas the multimodal forward caches on the model must not leak into it."""+ model = _tiny_encoder()+ tower = model.visual+ drop_qwen3vl_visual_tower(model)+ expected = _expected_text_only(model, tokenizer, "a red fox")++ with torch.no_grad():+ before, before_mask, _ = encode_krea2_prompt("a red fox", tokenizer, model)+ encode_krea2_prompt_with_images(+ tokenize_krea2_prompt_with_images("a red fox", [_image(256, 256)], processor, tokenizer), model, tower+ )+ after, _, _ = encode_krea2_prompt("a red fox", tokenizer, model)++ assert before.shape == (1, 512, 12, HIDDEN)+ assert torch.equal(before, expected)+ assert torch.equal(after, before)+ assert int(before_mask.sum()) == len(_ids(tokenizer, KREA2_PREFIX + "a red fox")) - KREA2_START_IDX + 5+++# --- the swap --------------------------------------------------------------------------------------+++def test_the_stub_is_restored_when_the_forward_raises() -> None:+ model = _tiny_encoder()+ tower = model.visual+ drop_qwen3vl_visual_tower(model)+ stub = model.visual++ with pytest.raises(RuntimeError, match="boom"):+ with attach_qwen3vl_visual_tower(model, tower):+ assert model.visual is tower+ raise RuntimeError("boom")++ assert model.visual is stub+ assert list(model.visual.parameters()) == []+++def test_a_model_that_still_has_its_tower_is_refused() -> None:+ model = _tiny_encoder()+ own = model.visual++ with pytest.raises(RuntimeError, match="no dropped visual tower"):+ with attach_qwen3vl_visual_tower(model, own):+ pass++ assert model.visual is own+++def test_a_tower_of_another_width_is_refused() -> None:+ from transformers import Qwen3VLModel++ model = _tiny_encoder()+ drop_qwen3vl_visual_tower(model)+ foreign = Qwen3VLModel(_tiny_config(vision_out=2 * HIDDEN)).visual++ with pytest.raises(ValueError, match="different Qwen3-VL"):+ with attach_qwen3vl_visual_tower(model, foreign):+ pass++ assert isinstance(model.visual, torch.nn.Identity)+++def test_working_memory_grows_with_the_square_of_the_sequence() -> None:+ """The attention term dominates long sequences: doubling the tokens must more than double the reserve."""+ assert working_memory_bytes(2000) > 2 * working_memory_bytes(1000) > 0+++def test_conditioning_dtype_follows_the_device(monkeypatch, tokenizer, processor) -> None:+ """The denoise loop reads the conditioning in the device's bf16-safe dtype, as on the text-only path."""+ monkeypatch.setattr(+ "invokeai.backend.krea2.text_encoding.TorchDevice.choose_bfloat16_safe_dtype", lambda _device: torch.float16+ )+ model = _tiny_encoder()+ tower = model.visual+ drop_qwen3vl_visual_tower(model)++ with torch.no_grad():+ embeds, _ = encode_krea2_prompt_with_images(+ tokenize_krea2_prompt_with_images("a fox", [_image(256, 256)], processor, tokenizer), model, tower+ )++ assert embeds.dtype is torch.float16+++def test_the_rope_deltas_are_restored_after_an_image_forward(tokenizer, processor) -> None:+ """The multimodal forward caches 3-D rope deltas on the model; the encoder must leave with its own."""+ model = _tiny_encoder()+ tower = model.visual+ drop_qwen3vl_visual_tower(model)+ sentinel = torch.tensor([[7]])+ model.rope_deltas = sentinel+ inputs = tokenize_krea2_prompt_with_images("a fox", [_image(256, 256)], processor, tokenizer)++ with torch.no_grad(), attach_qwen3vl_visual_tower(model, tower):+ model(**inputs, use_cache=False)+ assert model.rope_deltas is not sentinel++ assert model.rope_deltas is sentinel+++def test_the_rope_deltas_are_restored_when_the_forward_raises() -> None:+ model = _tiny_encoder()+ tower = model.visual+ drop_qwen3vl_visual_tower(model)+ model.rope_deltas = None++ with pytest.raises(RuntimeError, match="boom"):+ with attach_qwen3vl_visual_tower(model, tower):+ model.rope_deltas = torch.tensor([[3]])+ raise RuntimeError("boom")++ assert model.rope_deltas is None+++def test_a_reference_the_processor_refuses_is_named(tokenizer, processor) -> None:+ """A 6000x20 strip keeps its width and is held at 28 px tall: an aspect ratio over the processor's 200."""+ strip = prepare_vlm_reference(Image.new("RGB", (6000, 20)))++ with pytest.raises(ValueError, match=r"reference image 2 .*6000x28 px.*aspect ratio"):+ tokenize_krea2_prompt_with_images("x", [_image(256, 256), strip], processor, tokenizer)diff --git a/tests/backend/krea2/test_reference_edit.py b/tests/backend/krea2/test_reference_edit.pynew file mode 100644index 0000000000..9b8ca61100--- /dev/null+++ b/tests/backend/krea2/test_reference_edit.py@@ -0,0 +1,328 @@+"""Krea-2 edit references: clean reference tokens ride along in the sequence and are modulated at t=0.++`forward_with_references` restates the diffusers forward to give the reference span its own modulation,+so these tests pin it against the stock modules (drift guard) and against an independent formulation of+the reference method (ComfyUI `timestep_zero_index`, ostris `_forward_with_refs`). The K/V-cache mode is+pinned against the same joint pass with ai-toolkit's isolating mask written out.+"""++import pytest+import torch+import torch.nn.functional as F+from diffusers.models.transformers.transformer_krea2 import (+ Krea2AttnProcessor,+ Krea2RotaryPosEmbed,+ Krea2Transformer2DModel,+ Krea2TransformerBlock,+)++from invokeai.backend.krea2.attention import Krea2RegionalPromptingState, build_krea2_attention_processors+from invokeai.backend.krea2.reference_edit import (+ Krea2ReferenceKVCache,+ block_forward_split,+ forward_with_references,+ precompute_reference_kv,+)+from invokeai.backend.krea2.sampling_utils import (+ prepare_position_ids,+ prepare_position_ids_with_references,+ prepare_reference_position_ids,+)++TEXT_LEN = 3+TARGET_GRID = (2, 3)+# Two references with grids that differ from the target and from each other.+REFERENCE_GRIDS = [(2, 2), (1, 3)]+++def _randomize(module: torch.nn.Module, seed: int = 0) -> None:+ # diffusers zero-initializes the modulation tables and the zero-centered RMSNorm scales, under which+ # every block shares one modulation and a per-span bug can hide. Random weights everywhere.+ generator = torch.Generator().manual_seed(seed)+ with torch.no_grad():+ for parameter in module.parameters():+ parameter.copy_(torch.randn(parameter.shape, generator=generator) * 0.3)+++def _tiny_transformer() -> Krea2Transformer2DModel:+ model = Krea2Transformer2DModel(+ in_channels=64,+ num_layers=2,+ attention_head_dim=8,+ num_attention_heads=2,+ num_key_value_heads=1,+ intermediate_size=16,+ timestep_embed_dim=8,+ text_hidden_dim=8,+ num_text_layers=3,+ text_num_attention_heads=2,+ text_num_key_value_heads=2,+ text_intermediate_size=16,+ num_layerwise_text_blocks=1,+ num_refiner_text_blocks=1,+ axes_dims_rope=(2, 2, 4),+ ).eval()+ _randomize(model)+ return model+++def _inputs(seed: int = 1) -> dict[str, torch.Tensor]:+ generator = torch.Generator().manual_seed(seed)+ target_len = TARGET_GRID[0] * TARGET_GRID[1]+ reference_len = sum(h * w for h, w in REFERENCE_GRIDS)+ return {+ "hidden_states": torch.randn(1, target_len, 64, generator=generator),+ "encoder_hidden_states": torch.randn(1, TEXT_LEN, 3, 8, generator=generator),+ "references": torch.randn(1, reference_len, 64, generator=generator),+ }+++def _reference_position_ids() -> torch.Tensor:+ return prepare_position_ids_with_references(TEXT_LEN, *TARGET_GRID, REFERENCE_GRIDS, torch.device("cpu"))+++def _per_token_reference_forward(+ model: Krea2Transformer2DModel,+ hidden_states: torch.Tensor,+ encoder_hidden_states: torch.Tensor,+ timestep: torch.Tensor,+ position_ids: torch.Tensor,+ references: torch.Tensor,+ isolate_references: bool = False,+) -> torch.Tensor:+ """The reference method written per token: every token picks its modulation by a mask, no slicing.++ ``isolate_references`` adds ai-toolkit's ``isolate_refs`` mask: reference queries see only reference keys,+ every other query sees everything.+ """+ text = model.txt_in(model.text_fusion(encoder_hidden_states))+ sequence = torch.cat([text, model.img_in(hidden_states), model.img_in(references)], dim=1)+ target_end = text.shape[1] + hidden_states.shape[1]+ is_reference = (torch.arange(sequence.shape[1]) >= target_end)[None, :, None, None]++ temb = model.time_embed(timestep, dtype=sequence.dtype)+ real_vec = model.time_mod_proj(F.gelu(temb, approximate="tanh"))+ zero_vec = model.time_mod_proj(+ F.gelu(model.time_embed(torch.zeros_like(timestep), dtype=sequence.dtype), approximate="tanh")+ )+ rotary = model.rotary_emb(position_ids)+ mask = None+ if isolate_references:+ query_is_reference = is_reference[0, :, 0, 0][:, None]+ key_is_reference = is_reference[0, :, 0, 0][None, :]+ mask = (~query_is_reference | key_is_reference)[None, None]++ for block in model.transformer_blocks:+ real = real_vec.unflatten(-1, (6, -1)) + block.scale_shift_table+ zero = zero_vec.unflatten(-1, (6, -1)) + block.scale_shift_table+ prescale, preshift, pregate, postscale, postshift, postgate = torch.where(is_reference, zero, real).unbind(-2)+ attn = block.attn(+ (1 + prescale) * block.norm1(sequence) + preshift, attention_mask=mask, image_rotary_emb=rotary+ )+ sequence = sequence + pregate * attn+ sequence = sequence + postgate * block.ff((1 + postscale) * block.norm2(sequence) + postshift)++ return model.final_layer(sequence, temb)[:, text.shape[1] : target_end]++[email protected]_grad()+def test_split_block_with_one_modulation_is_the_stock_block() -> None:+ # Pins block_forward_split to the diffusers block it restates: a diffusers change to the block+ # (a new modulation term, a reordered gate) must fail here rather than silently diverge.+ block = Krea2TransformerBlock(hidden_size=16, intermediate_size=32, num_heads=2, num_kv_heads=1, norm_eps=1e-5)+ _randomize(block)+ generator = torch.Generator().manual_seed(2)+ hidden_states = torch.randn(1, 10, 16, generator=generator)+ temb_mod = torch.randn(1, 1, 6 * 16, generator=generator)+ position_ids = prepare_position_ids(4, 2, 3, torch.device("cpu"))+ rotary = Krea2RotaryPosEmbed(theta=1000, axes_dim=[2, 2, 4])(position_ids)+ attention_mask = torch.ones(1, 1, 1, 10, dtype=torch.bool)+ attention_mask[..., 1] = False++ expected = block(hidden_states, temb_mod, rotary, attention_mask)+ actual = block_forward_split(block, hidden_states, temb_mod, temb_mod, 6, rotary, attention_mask)++ assert torch.equal(actual, expected)++[email protected]_grad()+def test_without_references_the_forward_is_the_stock_forward() -> None:+ model = _tiny_transformer()+ inputs = _inputs()+ timestep = torch.tensor([0.7])+ position_ids = prepare_position_ids(TEXT_LEN, *TARGET_GRID, torch.device("cpu"))+ encoder_attention_mask = torch.tensor([[True, True, False]])++ expected = model(+ hidden_states=inputs["hidden_states"],+ encoder_hidden_states=inputs["encoder_hidden_states"],+ timestep=timestep,+ position_ids=position_ids,+ encoder_attention_mask=encoder_attention_mask,+ return_dict=False,+ )[0]+ actual = forward_with_references(+ model,+ inputs["hidden_states"],+ inputs["encoder_hidden_states"],+ timestep,+ position_ids,+ None,+ encoder_attention_mask=encoder_attention_mask,+ )++ assert torch.equal(actual, expected)++[email protected]_grad()+def test_with_references_the_forward_matches_the_per_token_formulation() -> None:+ model = _tiny_transformer()+ inputs = _inputs()+ timestep = torch.tensor([0.7])+ position_ids = _reference_position_ids()++ expected = _per_token_reference_forward(+ model, inputs["hidden_states"], inputs["encoder_hidden_states"], timestep, position_ids, inputs["references"]+ )+ # The production path runs under InvokeAI's own attention processors; the expectation under diffusers'.+ model.set_attn_processor(build_krea2_attention_processors(model, Krea2RegionalPromptingState()))+ actual = forward_with_references(+ model, inputs["hidden_states"], inputs["encoder_hidden_states"], timestep, position_ids, inputs["references"]+ )+ model.set_attn_processor(Krea2AttnProcessor())++ assert actual.shape == inputs["hidden_states"].shape+ torch.testing.assert_close(actual, expected)++[email protected]_grad()+def test_at_t0_references_are_ordinary_appended_image_tokens() -> None:+ """At t=0 the two modulations coincide, so the reference method collapses to the stock forward over+ [target | references] with the output cut back to the target. Anywhere else they must differ: the+ references are always presented as clean, whatever the step."""+ model = _tiny_transformer()+ inputs = _inputs()+ position_ids = _reference_position_ids()+ target_len = inputs["hidden_states"].shape[1]++ def stock_over_the_whole_sequence(timestep: torch.Tensor) -> torch.Tensor:+ return model(+ hidden_states=torch.cat([inputs["hidden_states"], inputs["references"]], dim=1),+ encoder_hidden_states=inputs["encoder_hidden_states"],+ timestep=timestep,+ position_ids=position_ids,+ return_dict=False,+ )[0][:, :target_len]++ def with_references(timestep: torch.Tensor) -> torch.Tensor:+ return forward_with_references(+ model,+ inputs["hidden_states"],+ inputs["encoder_hidden_states"],+ timestep,+ position_ids,+ inputs["references"],+ )++ torch.testing.assert_close(with_references(torch.tensor([0.0])), stock_over_the_whole_sequence(torch.tensor([0.0])))+ assert not torch.allclose(+ with_references(torch.tensor([0.7])), stock_over_the_whole_sequence(torch.tensor([0.7])), atol=1e-3+ )+++def test_a_position_id_count_that_omits_the_references_is_refused() -> None:+ model = _tiny_transformer()+ inputs = _inputs()++ with pytest.raises(ValueError, match="text, target and reference tokens"):+ forward_with_references(+ model,+ inputs["hidden_states"],+ inputs["encoder_hidden_states"],+ torch.tensor([0.5]),+ prepare_position_ids(TEXT_LEN, *TARGET_GRID, torch.device("cpu")),+ inputs["references"],+ )+++def test_reference_position_ids_number_each_reference_on_its_own_grid() -> None:+ ids = prepare_position_ids_with_references(2, 1, 2, [(1, 2), (2, 1)], torch.device("cpu"))++ expected = torch.tensor(+ [+ # text+ [0, 0, 0],+ [0, 0, 0],+ # target, 1x2+ [0, 0, 0],+ [0, 0, 1],+ # reference 1, 1x2+ [1, 0, 0],+ [1, 0, 1],+ # reference 2, 2x1+ [2, 0, 0],+ [2, 1, 0],+ ],+ dtype=torch.float32,+ )+ assert torch.equal(ids, expected)+ assert torch.equal(+ prepare_position_ids_with_references(2, 1, 2, [], torch.device("cpu")),+ prepare_position_ids(2, 1, 2, torch.device("cpu")),+ )++[email protected]("reference_grids", [REFERENCE_GRIDS[:1], REFERENCE_GRIDS], ids=["one", "two"])[email protected]_grad()+def test_the_kv_cache_is_the_joint_pass_with_isolated_references(reference_grids) -> None:+ """Precomputed reference K/V appended to the stock [text | target] pass reproduce the joint pass in which+ reference queries see only reference keys -- what ai-toolkit's kv_cache LoRAs are trained with."""+ model = _tiny_transformer()+ inputs = _inputs()+ references = inputs["references"][:, : sum(h * w for h, w in reference_grids)]+ timestep = torch.tensor([0.7])+ cpu = torch.device("cpu")++ expected = _per_token_reference_forward(+ model,+ inputs["hidden_states"],+ inputs["encoder_hidden_states"],+ timestep,+ prepare_position_ids_with_references(TEXT_LEN, *TARGET_GRID, reference_grids, cpu),+ references,+ isolate_references=True,+ )+ cache = Krea2ReferenceKVCache()+ model.set_attn_processor(+ build_krea2_attention_processors(model, Krea2RegionalPromptingState(), reference_kv_cache=cache)+ )+ precompute_reference_kv(model, references, prepare_reference_position_ids(reference_grids, cpu), cache)+ actual = model(+ hidden_states=inputs["hidden_states"],+ encoder_hidden_states=inputs["encoder_hidden_states"],+ timestep=timestep,+ position_ids=prepare_position_ids(TEXT_LEN, *TARGET_GRID, cpu),+ return_dict=False,+ )[0]++ assert len(cache) == len(model.transformer_blocks)+ torch.testing.assert_close(actual, expected)++[email protected]_grad()+def test_isolated_references_differ_from_joint_references() -> None:+ # Guards the comparison above: if isolation changed nothing on this model, it would prove nothing.+ model = _tiny_transformer()+ inputs = _inputs()+ args = (+ model,+ inputs["hidden_states"],+ inputs["encoder_hidden_states"],+ torch.tensor([0.7]),+ _reference_position_ids(),+ inputs["references"],+ )++ assert not torch.allclose(+ _per_token_reference_forward(*args), _per_token_reference_forward(*args, isolate_references=True), atol=1e-3+ )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.pyindex d99eb5466d..5c3b35c0a9 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@@ -9,6 +9,7 @@ never occupy VRAM. The loader signals this by returning `torch.device("cpu")` frfrom types import SimpleNamespacefrom typing import Optional+import pytestimport torchfrom invokeai.backend.model_manager.load.load_default import ModelLoader@@ -47,3 +48,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++[email protected]("submodel_type", [SubModelType.TextEncoder, SubModelType.VisionEncoder])+def test_a_main_models_cpu_only_setting_moves_its_encoders_to_the_cpu(submodel_type):+ # The vision encoder runs inside the text encoder's forward (Krea-2 edit mode), so `cpu_only` has to put+ # both on the same device.+ config = SimpleNamespace(default_settings=SimpleNamespace(cpu_only=True))++ assert _loader()._get_execution_device(config, submodel_type) == torch.device("cpu")+ assert _loader()._get_execution_device(config, SubModelType.Transformer) is Nonediff --git a/tests/backend/model_manager/load/test_load_default_fp8.py b/tests/backend/model_manager/load/test_load_default_fp8.pyindex 0ac15ed4ca..3f53e80bb1 100644--- a/tests/backend/model_manager/load/test_load_default_fp8.py+++ b/tests/backend/model_manager/load/test_load_default_fp8.py@@ -1212,3 +1212,15 @@ class TestSkippedModulesNeverKeepCheckpointFp8:assert out.dtype is torch.bfloat16assert torch.equal(out, reference(inp))++[email protected]("submodel", [SubModelType.TextEncoder, SubModelType.VisionEncoder])+def test_a_krea2_pipelines_encoders_never_take_fp8_storage(submodel):+ """FP8 Storage on a Krea-2 pipeline casts its transformer, never its Qwen3-VL text encoder or the vision+ tower edit mode loads from it: both condition the image."""+ loader = _make_loader("cuda")+ config = _make_config(ModelType.Main, fp8=True, base=BaseModelType.Krea2)++ with _device_holds_fp8():+ assert loader._should_use_fp8(config, SubModelType.Transformer) is True+ assert loader._should_use_fp8(config, submodel) is Falsediff --git a/tests/backend/model_manager/load/test_qwen3_vl_vision_encoder.py b/tests/backend/model_manager/load/test_qwen3_vl_vision_encoder.pynew file mode 100644index 0000000000..661d4671fb--- /dev/null+++ b/tests/backend/model_manager/load/test_qwen3_vl_vision_encoder.py@@ -0,0 +1,294 @@+"""Serving the Qwen3-VL vision tower and processor as their own submodels, for Krea-2's edit mode.++The encoders drop their tower (see `test_qwen3_vl_visual_tower.py`); `SubModelType.VisionEncoder` loads it+back as a separate cache entry, from the same files, reading only the ``visual.*`` tensors. A real tiny+`Qwen3VLModel` supplies both the files and the reference tower every load is compared against.+"""++import json+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest+import torch+from safetensors.torch import save_file++from invokeai.backend.model_manager.configs.main import Main_Diffusers_Krea2_Config+from invokeai.backend.model_manager.configs.qwen3_vl_encoder import (+ Qwen3VLEncoder_Checkpoint_Config,+ Qwen3VLEncoder_GGUF_Config,+ Qwen3VLEncoder_Qwen3VLEncoder_Config,+)+from invokeai.backend.model_manager.load.model_loaders.krea2 import (+ Krea2DiffusersModel,+ Qwen3VLEncoderCheckpointLoader,+ Qwen3VLEncoderGGUFLoader,+ Qwen3VLEncoderLoader,+)+from invokeai.backend.model_manager.load.model_util import calc_model_size_by_data+from invokeai.backend.model_manager.taxonomy import Qwen3VLVariantType, SubModelType+from invokeai.backend.model_manager.util.qwen3_vl import (+ qwen3vl_visual_tower_files,+ qwen3vl_visual_tower_nbytes,+ read_qwen3vl_visual_tower_tensors,+)+from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, Int8ConvrotLinear, build_regular_hadamard+from invokeai.backend.qwen3_vl.qwen3_vl_assets import load_bundled_qwen3_vl_tokenizer+from tests.backend.model_manager.load.qwen3vl_gguf_fixture import tiny_qwen3vl_config++_LOADERS = "invokeai.backend.model_manager.load.model_loaders.krea2"++[email protected](autouse=True)+def _cpu_float32(monkeypatch):+ """Load at float32 on the CPU, so a loaded tower can be compared to the reference exactly."""+ monkeypatch.setattr(f"{_LOADERS}.TorchDevice.choose_torch_device", lambda: torch.device("cpu"))+ monkeypatch.setattr(f"{_LOADERS}.TorchDevice.choose_bfloat16_safe_dtype", lambda _device: torch.float32)+++def _tiny_encoder(te_config=None):+ from transformers import Qwen3VLModel++ torch.manual_seed(0)+ return Qwen3VLModel(te_config or tiny_qwen3vl_config()).eval()+++def _tower_bytes(encoder) -> int:+ return sum(t.nelement() * t.element_size() for t in encoder.visual.state_dict().values())+++def _assert_same_tower(tower, reference) -> None:+ from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLVisionModel++ assert isinstance(tower, Qwen3VLVisionModel)+ loaded, expected = tower.state_dict(), reference.visual.state_dict()+ assert loaded.keys() == expected.keys()+ for key, value in expected.items():+ assert torch.equal(loaded[key], value), key+ # The cache sizes an entry by what it holds: the tower alone, not the encoder it came from.+ resident = [*reference.visual.parameters(), *reference.visual.buffers()]+ assert calc_model_size_by_data(MagicMock(), tower) == sum(t.nelement() * t.element_size() for t in resident)+++def _loader(cls):+ loader = object.__new__(cls)+ loader._ram_cache = SimpleNamespace(make_room=MagicMock())+ loader._logger = MagicMock()+ loader._torch_device = torch.device("cpu")+ return loader+++def _single_file(path: Path, state_dict: dict[str, torch.Tensor], te_config) -> Qwen3VLEncoderCheckpointLoader:+ save_file({k: v.contiguous() for k, v in state_dict.items()}, str(path))+ loader = _loader(Qwen3VLEncoderCheckpointLoader)+ loader._load_te_config = lambda _config: te_config+ return loader+++def _checkpoint_config(path: Path) -> Qwen3VLEncoder_Checkpoint_Config:+ return Qwen3VLEncoder_Checkpoint_Config.model_construct(+ path=str(path), variant=Qwen3VLVariantType.Qwen3VL_4B, name="tiny"+ )+++# --- single file -----------------------------------------------------------------------------------++[email protected]("prefixed", [False, True], ids=["transformers_layout", "comfyui_layout"])+def test_the_single_file_serves_the_tower_it_carries(tmp_path: Path, prefixed: bool) -> None:+ reference = _tiny_encoder()+ state_dict = dict(reference.state_dict())+ if prefixed:+ state_dict = {f"model.{k}": v for k, v in state_dict.items()}+ path = tmp_path / "qwen3vl_tiny.safetensors"+ loader = _single_file(path, state_dict, tiny_qwen3vl_config())++ tower = loader._load_model(_checkpoint_config(path), SubModelType.VisionEncoder)++ _assert_same_tower(tower, reference)+++def test_only_the_tower_tensors_are_read(tmp_path: Path) -> None:+ reference = _tiny_encoder()+ state_dict = {f"model.{k}": v for k, v in reference.state_dict().items()}+ path = tmp_path / "qwen3vl_tiny.safetensors"+ save_file({k: v.contiguous() for k, v in state_dict.items()}, str(path))++ tensors = read_qwen3vl_visual_tower_tensors([path])++ assert set(tensors) == {k for k in state_dict if k.startswith("model.visual.")}+++def test_the_cache_reserves_the_tower_not_the_file(tmp_path: Path) -> None:+ """`_load_and_cache` reserves `get_size_fs` before the load. Sized by the file, a tower load would evict+ ten times what it needs on the real 4B (0.77 of 8.27 GiB)."""+ reference = _tiny_encoder()+ path = tmp_path / "qwen3vl_tiny.safetensors"+ loader = _single_file(path, dict(reference.state_dict()), tiny_qwen3vl_config())+ config = _checkpoint_config(path)++ assert loader.get_size_fs(config, path, SubModelType.VisionEncoder) == _tower_bytes(reference)+ assert loader.get_size_fs(config, path, SubModelType.Processor) == 0+ assert loader.get_size_fs(config, path, SubModelType.TextEncoder) == path.stat().st_size > _tower_bytes(reference)+++def test_an_int8_tower_stays_int8(tmp_path: Path) -> None:+ """ComfyUI's int8_tensorwise repacks of the 4B quantize the tower's Linears as well (105 of them). Those+ have to come back as `Int8ConvrotLinear` -- cast to the compute dtype instead, the raw codes would load+ clean and see noise."""+ te_config = tiny_qwen3vl_config()+ te_config.text_config.hidden_size = CONVROT_GROUP_SIZE+ te_config.vision_config.hidden_size = CONVROT_GROUP_SIZE+ te_config.vision_config.out_hidden_size = CONVROT_GROUP_SIZE+ reference = _tiny_encoder(te_config)+ state_dict = {f"model.{k}": v for k, v in reference.state_dict().items()}++ layer = "model.visual.blocks.0.attn.proj"+ original = state_dict[f"{layer}.weight"].float()+ hadamard = build_regular_hadamard(CONVROT_GROUP_SIZE)+ rows = original.shape[0]+ rotated = (original.view(rows, -1, CONVROT_GROUP_SIZE) @ hadamard.T).view(rows, -1)+ scale = rotated.abs().amax(dim=1, keepdim=True) / 127.0+ marker = json.dumps({"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE})+ state_dict[f"{layer}.weight"] = torch.clamp(torch.round(rotated / scale), -128, 127).to(torch.int8)+ state_dict[f"{layer}.weight_scale"] = scale.to(torch.float32)+ state_dict[f"{layer}.comfy_quant"] = torch.frombuffer(bytearray(marker.encode("utf-8")), dtype=torch.uint8)+ path = tmp_path / "qwen3vl_int8.safetensors"+ loader = _single_file(path, state_dict, te_config)++ tower = loader._load_model(_checkpoint_config(path), SubModelType.VisionEncoder)++ assert isinstance(tower.blocks[0].attn.proj, Int8ConvrotLinear)+ x = torch.randn(4, CONVROT_GROUP_SIZE)+ torch.testing.assert_close(tower.blocks[0].attn.proj(x), reference.visual.blocks[0].attn.proj(x), atol=0.05, rtol=0)+ assert torch.equal(tower.blocks[1].attn.proj.weight, reference.visual.blocks[1].attn.proj.weight)+++def test_a_file_without_a_tower_is_refused(tmp_path: Path) -> None:+ reference = _tiny_encoder()+ language_only = {k: v for k, v in reference.state_dict().items() if not k.startswith("visual.")}+ path = tmp_path / "language_only.safetensors"+ loader = _single_file(path, language_only, tiny_qwen3vl_config())++ with pytest.raises(RuntimeError, match="no Qwen3-VL vision tower"):+ loader._load_model(_checkpoint_config(path), SubModelType.VisionEncoder)+++def test_a_gguf_encoder_refuses_the_tower_by_name(tmp_path: Path) -> None:+ """llama.cpp keeps the tower in a separate mmproj file, which identification rejects."""+ config = Qwen3VLEncoder_GGUF_Config.model_construct(+ path=str(tmp_path / "enc.gguf"), variant=Qwen3VLVariantType.Qwen3VL_4B, name="tiny-gguf"+ )++ with pytest.raises(ValueError, match="'tiny-gguf' has no vision tower"):+ _loader(Qwen3VLEncoderGGUFLoader)._load_model(config, SubModelType.VisionEncoder)+++def test_the_single_file_processor_wraps_the_bundled_tokenizer(tmp_path: Path) -> None:+ from transformers import Qwen3VLProcessor++ processor = _loader(Qwen3VLEncoderCheckpointLoader)._load_model(+ _checkpoint_config(tmp_path / "unused.safetensors"), SubModelType.Processor+ )++ assert isinstance(processor, Qwen3VLProcessor)+ assert processor.tokenizer is load_bundled_qwen3_vl_tokenizer()+ assert processor.image_processor.patch_size == 16+++# --- folders ---------------------------------------------------------------------------------------+++def test_the_folder_encoder_serves_its_tower_and_processor(tmp_path: Path) -> None:+ from transformers import Qwen3VLProcessor++ reference = _tiny_encoder()+ reference.save_pretrained(tmp_path)+ load_bundled_qwen3_vl_tokenizer().save_pretrained(tmp_path)+ config = Qwen3VLEncoder_Qwen3VLEncoder_Config.model_construct(+ path=str(tmp_path), variant=Qwen3VLVariantType.Qwen3VL_4B, name="tiny"+ )+ loader = _loader(Qwen3VLEncoderLoader)++ _assert_same_tower(loader._load_model(config, SubModelType.VisionEncoder), reference)+ assert isinstance(loader._load_model(config, SubModelType.Processor), Qwen3VLProcessor)+ assert loader.get_size_fs(config, tmp_path, SubModelType.VisionEncoder) == _tower_bytes(reference)+++def test_the_krea2_pipeline_serves_its_encoders_tower_and_processor(tmp_path: Path) -> None:+ """The path the "Krea-2 Turbo" starter model takes: the tower lives in ``text_encoder/``, which+ model_index.json names, but has no folder or index entry of its own."""+ from transformers import Qwen3VLProcessor++ reference = _tiny_encoder()+ reference.save_pretrained(tmp_path / "text_encoder")+ load_bundled_qwen3_vl_tokenizer().save_pretrained(tmp_path / "tokenizer")+ (tmp_path / "model_index.json").write_text("{}", encoding="utf-8")+ config = Main_Diffusers_Krea2_Config.model_construct(path=str(tmp_path), repo_variant=None)+ loader = _loader(Krea2DiffusersModel)++ _assert_same_tower(loader._load_model(config, SubModelType.VisionEncoder), reference)+ processor = loader._load_model(config, SubModelType.Processor)+ assert isinstance(processor, Qwen3VLProcessor)+ assert processor.tokenizer("a cat").input_ids == load_bundled_qwen3_vl_tokenizer()("a cat").input_ids+ assert loader.get_size_fs(config, tmp_path, SubModelType.VisionEncoder) == _tower_bytes(reference)+ assert loader.get_size_fs(config, tmp_path, SubModelType.Processor) == 0+++def test_a_sharded_folder_reads_only_the_shards_holding_the_tower(tmp_path: Path) -> None:+ reference = _tiny_encoder()+ reference.save_pretrained(tmp_path, max_shard_size="100KB")+ weight_map = json.loads((tmp_path / "model.safetensors.index.json").read_text(encoding="utf-8"))["weight_map"]+ tower_shards = {tmp_path / name for key, name in weight_map.items() if key.startswith("visual.")}++ files = qwen3vl_visual_tower_files(tmp_path)++ assert set(files) == tower_shards+ # The fixture has to put the language tower in shards of its own, or this shows nothing.+ assert tower_shards < {tmp_path / name for name in weight_map.values()}+ assert qwen3vl_visual_tower_nbytes(files) == _tower_bytes(reference)+++def test_a_loaded_tower_lent_to_a_towerless_encoder_matches_the_intact_model(tmp_path: Path) -> None:+ """Pins what a state-dict comparison cannot: the tower is built under `init_empty_weights`, so its+ non-persistent buffers (the rotary `inv_freq`) come from construction, not from the file."""+ import copy++ from invokeai.backend.model_manager.util.qwen3_vl import attach_qwen3vl_visual_tower, drop_qwen3vl_visual_tower+ from invokeai.backend.qwen3_vl.qwen3_vl_assets import build_qwen3_vl_processor++ te_config = tiny_qwen3vl_config()+ # The tiny vocabulary cannot hold the release's image-pad id; any in-vocabulary id serves.+ te_config.image_token_id = 5+ reference = _tiny_encoder(te_config)+ towerless = copy.deepcopy(reference)+ drop_qwen3vl_visual_tower(towerless)+ path = tmp_path / "qwen3vl_tiny.safetensors"+ tower = _single_file(path, dict(reference.state_dict()), te_config)._load_model(+ _checkpoint_config(path), SubModelType.VisionEncoder+ )++ image = build_qwen3_vl_processor(load_bundled_qwen3_vl_tokenizer()).image_processor(+ images=[torch.rand(3, 64, 64, generator=torch.Generator().manual_seed(0))],+ return_tensors="pt",+ do_rescale=False,+ )+ pads = int(image["image_grid_thw"].prod()) // 4+ input_ids = torch.tensor([[1, 2, *[5] * pads, 3, 4]])+ inputs = {+ "input_ids": input_ids,+ "attention_mask": torch.ones_like(input_ids, dtype=torch.bool),+ "mm_token_type_ids": (input_ids == 5).long(),+ "pixel_values": image["pixel_values"],+ "image_grid_thw": image["image_grid_thw"],+ }++ with torch.no_grad():+ expected = reference(**inputs, output_hidden_states=True, use_cache=False).hidden_states+ with attach_qwen3vl_visual_tower(towerless, tower):+ actual = towerless(**inputs, output_hidden_states=True, use_cache=False).hidden_states++ assert len(actual) == len(expected)+ for index, (got, want) in enumerate(zip(actual, expected, strict=True)):+ assert torch.equal(got, want), f"hidden state {index} differs"diff --git a/tests/backend/qwen3_vl/test_qwen3_vl_assets.py b/tests/backend/qwen3_vl/test_qwen3_vl_assets.pyindex 26ba611d0b..2733bcce85 100644--- a/tests/backend/qwen3_vl/test_qwen3_vl_assets.py+++ b/tests/backend/qwen3_vl/test_qwen3_vl_assets.py@@ -12,7 +12,9 @@ import pytestfrom invokeai.backend.model_manager.taxonomy import Qwen3VLVariantTypefrom invokeai.backend.qwen3_vl.qwen3_vl_assets import (_CONFIG_BY_VARIANT,+ build_qwen3_vl_processor,load_bundled_qwen3_vl_config_dict,+ load_bundled_qwen3_vl_preprocessor_config_dict,load_bundled_qwen3_vl_tokenizer,)@@ -120,3 +122,62 @@ def test_an_unregistered_variant_is_refused_by_name() -> None:with pytest.raises(NotImplementedError, match="qwen3vl_99b"):load_bundled_qwen3_vl_config_dict(_Unknown()) # type: ignore[arg-type]+++def test_bundled_preprocessor_config_is_the_released_one() -> None:+ """The values a reference image is cut into patches by. Qwen3-VL's vision tower takes 16px patches with+ 0.5/0.5 normalization; transformers' class defaults are Qwen2-VL's 14px and CLIP mean/std, which run+ without error and feed the tower off-distribution pixels."""+ config = load_bundled_qwen3_vl_preprocessor_config_dict()++ assert config["patch_size"] == 16+ assert config["merge_size"] == 2+ assert config["temporal_patch_size"] == 2+ assert config["image_mean"] == [0.5, 0.5, 0.5]+ assert config["image_std"] == [0.5, 0.5, 0.5]+ assert config["size"] == {"longest_edge": 16777216, "shortest_edge": 65536}+++def test_bundled_processor_expands_one_pad_per_merged_patch() -> None:+ """Built without any processor files, it turns one ``<|image_pad|>`` into the image's token grid, one pad+ per 2x2 merged 16px patches, and marks those pads as image tokens for the 3-D M-RoPE."""+ import torch++ processor = build_qwen3_vl_processor(load_bundled_qwen3_vl_tokenizer())+ # 384x256 is already a multiple of the 32px merged patch, so the grid is 12 x 8 merged patches.+ image = torch.rand(3, 256, 384)++ inputs = processor(+ text=["<|vision_start|><|image_pad|><|vision_end|>a cat"], images=[image], return_tensors="pt", do_rescale=False+ )++ assert inputs["image_grid_thw"].tolist() == [[1, 16, 24]]+ pad_id = processor.tokenizer.convert_tokens_to_ids("<|image_pad|>")+ pads = inputs["input_ids"] == pad_id+ assert int(pads.sum()) == 16 * 24 // 4+ assert torch.equal(inputs["mm_token_type_ids"].bool(), pads)+ assert inputs["pixel_values"].shape == (16 * 24, 3 * 2 * 16 * 16)+++def test_bundled_processor_normalizes_with_the_release_mean_and_std() -> None:+ """Mean and std 0.5: a uniform mid-grey reference must come out as zeros. CLIP's statistics (the class+ defaults) would shift and scale it into values the tower never saw."""+ import torch++ processor = build_qwen3_vl_processor(load_bundled_qwen3_vl_tokenizer())++ inputs = processor.image_processor(images=[torch.full((3, 256, 256), 0.5)], return_tensors="pt", do_rescale=False)++ torch.testing.assert_close(inputs["pixel_values"], torch.zeros_like(inputs["pixel_values"]), atol=1e-6, rtol=0)+++def test_bundled_processor_raises_a_small_reference_to_the_pixel_floor() -> None:+ """The release's 65,536 px floor: a 100x100 reference is resized up to 256x256, an 8x8 merged grid."""+ import torch++ processor = build_qwen3_vl_processor(load_bundled_qwen3_vl_tokenizer())++ inputs = processor.image_processor(images=[torch.rand(3, 100, 100)], return_tensors="pt", do_rescale=False)++ assert inputs["image_grid_thw"].tolist() == [[1, 16, 16]]+ assert int(inputs["image_grid_thw"].prod()) // processor.image_processor.merge_size**2 == 8 * 8