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
fix(krea2): reserve edit-mode encoder memory for the vision tower and refuse ambiguous references
Alexander Eichhornd9dfcd67d6da
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 7bb08971ca..0253be6bbb 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@@ -180,9 +180,10 @@ 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+- **The text encoder looks at it.** The Qwen3-VL encoder sees each reference next to the prompt. A reference+ above an area of about 384×384 pixels is scaled down to that area, keeping its aspect ratio; a smaller one+ keeps its size. A side shorter than 28 pixels is stretched to 28. The Qwen3-VL processor then works on 32-pixel cells and enlarges an image below its floor+ of 65,536 pixels to that floor. This needs the encoder's vision weights. The encoder of the Krea-2Diffusers 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 imagesare connected.@@ -201,7 +202,8 @@ Reference images are set up in the workflow editor:(`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.+ negative prompt's when a step between Denoising Start and Denoising End has CFG above 1. Each of the two+ is a single prompt node, not a collection of several.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 theunconditional pass see the references.@@ -225,7 +227,11 @@ figures with reference images can mean the LoRA was trained with isolated refere:::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.+ has reference latents: the positive prompt, and the negative prompt when a step between Denoising Start+ and Denoising End has CFG above 1. Only the number is checked, not which images or their order, so give+ the prompt and the denoise node the same images in the same order.+- With references, each of those prompts must be a single prompt. The denoise node refuses a collection of+ several, because each would add the reference images to the text again.- With the K/V cache off, every reference adds about **4096 tokens per megapixel** to every transformerpass. A 1 megapixel reference doubles the image sequence of a 1024² generation, so each step takes atleast twice as long and needs more VRAM. The memory reserved for the transformer accounts for the extra tokens.diff --git a/invokeai/app/invocations/krea2/krea2_denoise.py b/invokeai/app/invocations/krea2/krea2_denoise.pyindex cee18f57ed..0f88f445b9 100644--- a/invokeai/app/invocations/krea2/krea2_denoise.py+++ b/invokeai/app/invocations/krea2/krea2_denoise.py@@ -336,6 +336,23 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):return self.cfg_scaleraise ValueError(f"Invalid CFG scale type: {type(self.cfg_scale)}")+ def _step_window(self, num_steps: int) -> tuple[int, int]:+ """The ``[start, end)`` indices of the configured steps that denoising_start/denoising_end select."""+ return int(round(self.denoising_start * num_steps)), int(round(self.denoising_end * num_steps))++ def _active_cfg_scale(self, num_steps: int) -> list[float]:+ """The CFG of each step this node runs.++ Built against the full step count, then clipped to the active window, so a caller-supplied per-step list+ (one value per configured step) survives the reduction caused by denoising_start/denoising_end.+ """+ start_idx, end_idx = self._step_window(num_steps)+ return self._prepare_cfg_scale(num_steps)[start_idx:end_idx]++ def _negative_prompt_runs(self, num_steps: int) -> bool:+ """Whether a step this node runs applies CFG, the only steps that read the negative prompt."""+ return bool(self.negative_conditioning) and any(value > 1.0 for value in self._active_cfg_scale(num_steps))+@staticmethoddef _should_apply_cfg_for_step(cfg_scale: float, *, has_negative_conditioning: bool) -> bool:return has_negative_conditioning and cfg_scale > 1.0@@ -383,42 +400,51 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):"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.+ if type(self)._install_attention_processors is not Krea2DenoiseInvocation._install_attention_processors:+ # A subclass's processors are sized for [text | target]: joint references would reach them as extra+ # image tokens, and the K/V cache lives in this node's own 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."+ f"'{type(self).__name__}' installs its own Krea-2 attention processors, which cannot take reference "+ "latents. Use the stock 'Denoise - Krea-2' node for edit references.")def _validate_reference_counts(self, context: InvocationContext) -> None:- """Each prompt must have seen exactly the references the denoise is given.+ """Each prompt that runs must be a single prompt that saw as many references as the denoise is given.The encoder numbers the references it saw ("Picture 1", ...) and the transformer numbers the referencelatents by their position ids. An edit LoRA is trained with the two agreeing; a mismatch -- a referencemissing on one side, or a prompt encoded without them -- would condition on an image the other side- never sees.+ never sees. Only the count can be checked: the denoise gets latents, not the images they came from, so+ keeping the same images in the same order on both sides is the workflow's job.++ Several prompts are concatenated into one text sequence, so each would bring the references' vision tokens+ in again, a layout no edit LoRA is trained on."""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):+ # An unused negative prompt need not match. `self.steps` is the configured step count `_run_diffusion`+ # builds its schedule against.+ if self._negative_prompt_runs(self.steps):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]:+ fields = conditioning if isinstance(conditioning, list) else [conditioning]+ if reference_count and len(fields) > 1:+ raise ValueError(+ f"The {label} Krea-2 prompt is a collection of {len(fields)} prompts. With reference latents, "+ "connect a single 'Prompt - Krea-2' node instead: each prompt would add the reference images "+ "to the text sequence again, which edit LoRAs are not trained on."+ )+ for field in fields: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."+ 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(@@ -528,10 +554,8 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):# Clip the schedule based on denoising_start/denoising_end for img2img strength.sigmas_sched = scheduler.sigmas # (N+1,) including terminal 0- total_sigmas = len(sigmas_sched) - 1 # == self.stepsis_clipped = self.denoising_start > 0 or self.denoising_end < 1- start_idx = int(round(self.denoising_start * total_sigmas))- end_idx = int(round(self.denoising_end * total_sigmas))+ start_idx, end_idx = self._step_window(self.steps)self._validate_effective_schedule(start_idx=start_idx, end_idx=end_idx)if is_clipped:sigmas_sched = sigmas_sched[start_idx : end_idx + 1]@@ -541,16 +565,11 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):total_steps = len(timesteps_sched)- # Build the CFG schedule against the FULL step count, then clip it to the active window. This way a- # caller-supplied per-step CFG list (one value per configured step) survives the reduction caused- # by denoising_start/denoising_end; a scalar is simply broadcast.- full_cfg_scale = self._prepare_cfg_scale(total_sigmas)- cfg_scale = full_cfg_scale[start_idx:end_idx] if is_clipped else full_cfg_scale+ cfg_scale = self._active_cfg_scale(self.steps)# Load negative conditioning only if at least one active step actually uses CFG. CFG is still# decided per step below so values at or below 1.0 use the conditional prediction directly.- has_negative_conditioning = bool(self.negative_conditioning)- do_cfg = has_negative_conditioning and any(value > 1.0 for value in cfg_scale)+ do_cfg = self._negative_prompt_runs(self.steps)neg_extension: Krea2RegionalPromptingExtension | None = Noneneg_prompt_embeds = Noneif do_cfg and self.negative_conditioning is not None:diff --git a/invokeai/app/invocations/text_encoder/krea2_text_encoder.py b/invokeai/app/invocations/text_encoder/krea2_text_encoder.pyindex a1e8328ac8..fd257a750e 100644--- a/invokeai/app/invocations/text_encoder/krea2_text_encoder.py+++ b/invokeai/app/invocations/text_encoder/krea2_text_encoder.py@@ -106,38 +106,40 @@ class Krea2TextEncoderInvocation(BaseInvocation):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+ tokenizer_info = context.models.load(self.qwen3_vl_encoder.tokenizer)+ image_inputs = vision_info = Noneif images:+ # The processor and tokenizer are small and run on the CPU, so a reference the processor refuses (an+ # extreme aspect ratio) fails here, before either tower is read.+ processor_info = context.models.load(+ self.qwen3_vl_encoder.tokenizer.model_copy(update={"submodel_type": SubModelType.Processor})+ )+ with processor_info as processor, tokenizer_info as tokenizer:+ image_inputs = tokenize_krea2_prompt_with_images(self.prompt, images, processor, tokenizer)# 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.+ # the far larger language tower for nothing. The tower is its own cache entry, so text-only prompts+ # never pay for it.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# An nvfp4 or GGUF build dequantizes each packed Linear per forward, a transient its resident size does# not cover. Read from the unlocked model, before the lock the reservation applies to; zero for# other builds.- dequant_bytes = peak_dequant_transient_bytes(+ working_mem_bytes = peak_dequant_transient_bytes(text_encoder_info.model, TorchDevice.choose_bfloat16_safe_dtype(text_encoder_info.compute_device))+ if image_inputs is not None:+ # The references lengthen the sequence, and attention grows with its square. The image path does not+ # truncate, so this is the prompt's natural length.+ working_mem_bytes += working_memory_bytes(image_inputs["input_ids"].shape[1])context.util.signal_progress("Running Qwen3-VL text encoder")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])+ # The image path has tokenized already.+ text_tokenizer = exit_stack.enter_context(tokenizer_info) if image_inputs is None else None(cached_weights, text_encoder) = exit_stack.enter_context(text_encoder_info.model_on_device(working_mem_bytes=working_mem_bytes))@@ -165,14 +167,19 @@ class Krea2TextEncoderInvocation(BaseInvocation):))- if image_inputs is None:- prompt_embeds, prompt_mask, _ = encode_krea2_prompt(self.prompt, tokenizer, text_encoder)+ if text_tokenizer is not None:+ prompt_embeds, prompt_mask, _ = encode_krea2_prompt(self.prompt, text_tokenizer, text_encoder)else:- assert vision_info is not None+ assert image_inputs is not None and 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())+ # part of the encoder's module tree. With the encoder's reservation: the cache counts the locked+ # encoder as in use, so the tower is placed only in VRAM beyond the room the encoder's forward+ # needs (the default reservation would let it take that room). Adding the tower's size to the+ # encoder's reservation instead would count a tower that is already resident twice.+ (_, vision_tower) = exit_stack.enter_context(+ vision_info.model_on_device(working_mem_bytes=working_mem_bytes)+ )prompt_embeds, prompt_mask = encode_krea2_prompt_with_images(image_inputs, text_encoder, vision_tower)return prompt_embeds, prompt_maskdiff --git a/invokeai/backend/krea2/text_encoding.py b/invokeai/backend/krea2/text_encoding.pyindex e0c0dd2b97..005cf56aa1 100644--- a/invokeai/backend/krea2/text_encoding.py+++ b/invokeai/backend/krea2/text_encoding.py@@ -228,7 +228,7 @@ def _reference_rejection(processor, images: Sequence[torch.Tensor], error: Valueheight, 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."+ f"({width}x{height} px as prepared for it): {own_error}. Crop it to a less extreme shape.")return f"The Qwen3-VL processor refused the Krea-2 reference images: {error}"diff --git a/tests/app/invocations/test_krea2_denoise.py b/tests/app/invocations/test_krea2_denoise.pyindex 68c28f4493..4ed40e4cc7 100644--- a/tests/app/invocations/test_krea2_denoise.py+++ b/tests/app/invocations/test_krea2_denoise.py@@ -156,18 +156,16 @@ def test_cfg_scale_list_is_built_against_full_step_count_then_clipped() -> None:# must be prepared against the full step count (``total_sigmas``) and *then* sliced to the active# window — preparing it against the already-reduced count would reject the user's full-length list.steps = 8- invocation = Krea2DenoiseInvocation.model_construct(cfg_scale=[float(i) for i in range(steps)])-- full_cfg_scale = invocation._prepare_cfg_scale(steps) # built against the FULL step count -> ok- assert len(full_cfg_scale) == steps+ invocation = Krea2DenoiseInvocation.model_construct(+ cfg_scale=[float(i) for i in range(steps)], denoising_start=0.25, denoising_end=0.75+ )- # Slicing to the active window [start_idx:end_idx] (as _run_diffusion does) keeps the right per-step values.- start_idx, end_idx = 2, 6- assert full_cfg_scale[start_idx:end_idx] == [2.0, 3.0, 4.0, 5.0]+ # Steps 2..5 of 8 run, each with its own configured value.+ assert invocation._active_cfg_scale(steps) == [2.0, 3.0, 4.0, 5.0]# Preparing against the reduced (clipped) count instead would have raised — the bug this guards against.with pytest.raises(ValueError):- invocation._prepare_cfg_scale(end_idx - start_idx)+ invocation._prepare_cfg_scale(4)def test_get_noise_is_deterministic_and_correctly_shaped() -> None:@@ -1489,7 +1487,12 @@ def test_run_diffusion_refuses_unusable_references_before_loading_the_transforme("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"),+ (+ ["ref-b"],+ 0,+ None,+ "positive Krea-2 prompt was encoded with 0 reference image.*has 1 reference latents. Connect the same reference images, in the same order",+ ),# 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.@@ -1637,6 +1640,109 @@ def test_the_negative_prompt_reference_count_matters_only_when_cfg_runs(cfg_scalinvocation._validate_reference_counts(context)+ ("cfg_scale", "denoising_start", "denoising_end", "refused"),+ [+ # CFG only in steps the window skips: the negative prompt never runs.+ ([4.0, 4.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], 0.5, 1.0, False),+ ([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 4.0, 4.0], 0.0, 0.5, False),+ # A CFG step inside the window: it runs and must match.+ ([4.0, 4.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], 0.0, 1.0, True),+ ([1.0, 1.0, 1.0, 1.0, 4.0, 1.0, 1.0, 1.0], 0.5, 1.0, True),+ ],+)+def test_the_negative_prompt_reference_count_follows_the_clipped_cfg_schedule(+ cfg_scale, denoising_start, denoising_end, refused+) -> None:+ invocation = _runtime_invocation(cfg_scale=cfg_scale)+ invocation.steps = 8+ invocation.denoising_start = denoising_start+ invocation.denoising_end = denoising_end+ invocation.reference_latents = _references("ref-b")+ context = _reference_context(None, _Transformer(), positive_references=1, 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)+++def test_run_diffusion_never_loads_a_negative_prompt_whose_cfg_steps_are_skipped(monkeypatch, tmp_path) -> None:+ # CFG only in steps 0-1, which denoising_start=0.5 skips: validation and the run must agree that the negative+ # prompt does not run, so its mismatched reference count is no obstacle and it is never read.+ import invokeai.app.invocations.krea2.krea2_denoise as denoise_module++ _patch_runtime(monkeypatch)+ monkeypatch.setattr(+ denoise_module, "forward_with_references", lambda _model, hidden_states, *_args: torch.zeros_like(hidden_states)+ )+ invocation = _runtime_invocation(cfg_scale=[4.0, 4.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0])+ invocation.steps = 8+ invocation.denoising_start = 0.5+ invocation.latents = LatentsField(latents_name="init")+ invocation.reference_latents = _references("ref-b")+ context = _reference_context(tmp_path, _Transformer(), positive_references=1, negative_references=0)+ loaded: list[str] = []+ load_conditioning = context.conditioning.load+ context.conditioning.load = lambda name: loaded.append(name) or load_conditioning(name)++ latents = invocation._run_diffusion(context)++ assert latents.shape == (1, KREA2_LATENT_CHANNELS, 1, 2, 2)+ assert "negative" not in loaded+++ ("denoising_start", "denoising_end", "window"),+ [+ # 0.45 * 8 = 3.6 and 0.95 * 8 = 7.6 round up; truncating would give (3, 7).+ (0.45, 0.95, (4, 8)),+ # 0.3 * 8 = 2.4 and 0.8 * 8 = 6.4 round down.+ (0.3, 0.8, (2, 6)),+ ],+)+def test_the_step_window_rounds_to_the_nearest_step(denoising_start, denoising_end, window) -> None:+ invocation = Krea2DenoiseInvocation.model_construct(denoising_start=denoising_start, denoising_end=denoising_end)++ assert invocation._step_window(8) == window++[email protected]("prompt", ["positive", "negative"])+def test_run_diffusion_refuses_a_collection_of_prompts_with_references(monkeypatch, tmp_path, prompt: str) -> None:+ # Several prompts are concatenated, so each would bring the references' vision tokens into the text again.+ _patch_runtime(monkeypatch)+ invocation = _runtime_invocation(cfg_scale=4.0)+ invocation.reference_latents = _references("ref-b")+ setattr(invocation, f"{prompt}_conditioning", [Krea2ConditioningField(conditioning_name=prompt)] * 2)++ with pytest.raises(+ ValueError,+ match=f"The {prompt} Krea-2 prompt is a collection of 2 prompts.*connect a single 'Prompt - Krea-2' node",+ ):+ invocation._run_diffusion(_refusing_context(tmp_path, positive_references=1))+++ ("references", "positive_prompts", "negative_prompts", "cfg_scale"),+ [+ (1, 1, 1, 4.0), # a collection of one is a single prompt+ (1, 1, 2, 1.0), # the negative collection never runs at CFG 1+ (0, 2, 2, 4.0), # without references, several prompts are ordinary+ ],+ ids=["single_prompts", "unused_negative_collection", "no_references"],+)+def test_prompt_collections_are_refused_only_where_references_meet_them(+ references, positive_prompts, negative_prompts, cfg_scale+) -> None:+ invocation = _runtime_invocation(cfg_scale=cfg_scale)+ invocation.reference_latents = _references(*["ref-b"] * references)+ invocation.positive_conditioning = [Krea2ConditioningField(conditioning_name="positive")] * positive_prompts+ invocation.negative_conditioning = [Krea2ConditioningField(conditioning_name="negative")] * negative_prompts++ invocation._validate_reference_counts(_reference_context(None, _Transformer(), positive_references=references))++# --- Edit references in K/V-cache mode (reference_kv_cache) ----------------------------------------------@@ -1767,14 +1873,17 @@ def test_the_reference_kv_cache_flag_without_references_changes_nothing(monkeypaassert transformer.position_id_lengths == [2 + 1, 2 + 1] * 2-def test_the_reference_kv_cache_refuses_a_subclass_with_its_own_processors() -> None:[email protected]("reference_kv_cache", [False, True], ids=["joint", "kv_cache"])+def test_references_refuse_a_subclass_with_its_own_processors(reference_kv_cache: bool) -> None:+ # Its processors are sized for [text | target]: joint references would reach them as extra image tokens, and the+ # K/V cache lives in the stock processors it replaces. Without references it runs (see the seam regression test).invocation = _SubclassWithOwnProcessors.model_construct(positive_conditioning=Krea2ConditioningField(conditioning_name="positive"),reference_latents=_references("ref-b"),- reference_kv_cache=True,+ reference_kv_cache=reference_kv_cache,)- with pytest.raises(ValueError, match="installs its own Krea-2 attention processors"):+ with pytest.raises(ValueError, match="installs its own Krea-2 attention processors, which cannot take reference"):invocation._validate_inputs()diff --git a/tests/app/invocations/test_krea2_text_encoder.py b/tests/app/invocations/test_krea2_text_encoder.pyindex 1c32a2aebc..f5638a773f 100644--- a/tests/app/invocations/test_krea2_text_encoder.py+++ b/tests/app/invocations/test_krea2_text_encoder.py@@ -428,7 +428,23 @@ class _RecordingInfo:return None-def _edit_context(events: list[str], loaded: list, infos: dict, *, refuse_tower: bool = False) -> SimpleNamespace:+# "strip" keeps its 6000 px width and is held at 28 px tall: an aspect ratio over the Qwen3-VL processor's 200.+_IMAGE_SIZES = {"big": (800, 600), "small": (64, 48), "strip": (6000, 20)}++[email protected](scope="module")+def processing() -> dict:+ """The bundled Qwen3-VL tokenizer and processor, the small CPU-side models an image encode loads first."""+ from invokeai.backend.qwen3_vl.qwen3_vl_assets import build_qwen3_vl_processor, load_bundled_qwen3_vl_tokenizer++ tokenizer = load_bundled_qwen3_vl_tokenizer()+ return {SubModelType.Tokenizer: tokenizer, SubModelType.Processor: build_qwen3_vl_processor(tokenizer)}+++def _edit_context(+ events: list[str], loaded: list, infos: dict, *, refuse_tower: bool = False, processing: dict | None = None+) -> SimpleNamespace:+ """Records every model loaded, in order. `processing` swaps in real models by submodel type."""from PIL import Imagedef load(identifier):@@ -437,14 +453,17 @@ def _edit_context(events: list[str], loaded: list, infos: dict, *, refuse_tower:raise ValueError("The GGUF Qwen3-VL encoder 'encoder' has no vision tower")name = identifier.submodel_type.valuefakes = {SubModelType.TextEncoder: _TextEncoder, SubModelType.Tokenizer: _Tokenizer}- model = fakes.get(identifier.submodel_type, object)()+ if processing is not None and identifier.submodel_type in processing:+ model = processing[identifier.submodel_type]+ else:+ 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))),+ images=SimpleNamespace(get_pil=lambda name: Image.new("RGB", _IMAGE_SIZES.get(name, (64, 48)))),)@@ -528,11 +547,47 @@ def test_reference_images_lend_the_tower_to_the_locked_encoder(monkeypatch, _no_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:+def test_the_tower_is_locked_with_the_encoders_reservation(monkeypatch, _no_lora_patching) -> None:+ """The cache keeps a lock's reservation free beyond everything resident, the locked encoder included. The+ tower is locked second: with the default reservation its weights could take the room reserved for the+ encoder's forward. A dequant transient is part of that room, so it must reach the tower's lock as well."""+ from invokeai.backend.krea2.text_encoding import working_memory_bytes++ infos: dict = {}+ dequant_bytes = 7 * 2**20+ monkeypatch.setattr(f"{_INVOCATION_MODULE}.peak_dequant_transient_bytes", lambda _model, _dtype: dequant_bytes)+ monkeypatch.setattr(+ f"{_INVOCATION_MODULE}.tokenize_krea2_prompt_with_images",+ lambda *_args: {"input_ids": torch.zeros(1, 300, dtype=torch.long)},+ )+ monkeypatch.setattr(+ f"{_INVOCATION_MODULE}.encode_krea2_prompt_with_images",+ lambda *_args: (torch.zeros(1, 266, 12, 4), torch.ones(1, 266, dtype=torch.bool)),+ )++ _edit_invocation("small")._encode(_edit_context([], [], infos))++ reservation = dequant_bytes + working_memory_bytes(300)+ assert infos["text_encoder"].working_mem_bytes == [reservation]+ assert infos["vision_encoder"].working_mem_bytes == [reservation]+++def test_a_reference_the_processor_refuses_fails_before_either_tower_is_read(_no_lora_patching, processing) -> None:+ """Only the processor and tokenizer are needed to find out: the ~8 GB language tower, and the vision+ tower, are not read for a prompt that cannot run."""+ loaded: list = []++ with pytest.raises(ValueError, match="reference image 2 cannot be read by the Qwen3-VL vision tower"):+ _edit_invocation("small", "strip")._encode(_edit_context([], loaded, {}, processing=processing))++ assert [identifier.submodel_type for identifier in loaded] == [SubModelType.Tokenizer, SubModelType.Processor]+++def test_an_encoder_without_a_tower_fails_before_the_encoder_is_read(_no_lora_patching, processing) -> None:loaded: list = []with pytest.raises(ValueError, match="has no vision tower"):- _edit_invocation("small")._encode(_edit_context([], loaded, {}, refuse_tower=True))+ _edit_invocation("small")._encode(_edit_context([], loaded, {}, refuse_tower=True, processing=processing))assert SubModelType.TextEncoder not in {identifier.submodel_type for identifier in loaded}diff --git a/tests/backend/krea2/test_krea2_image_text_encoding.py b/tests/backend/krea2/test_krea2_image_text_encoding.pyindex f73c2cd996..1ceddfa7d5 100644--- a/tests/backend/krea2/test_krea2_image_text_encoding.py+++ b/tests/backend/krea2/test_krea2_image_text_encoding.py@@ -6,6 +6,7 @@ ids are the release's and the vision tower is the architecture's own. The vocabufor that reason; only the widths shrink."""+import numpy as npimport pytestimport torchfrom PIL import Image@@ -180,6 +181,23 @@ def test_alpha_is_dropped_rather_than_composited() -> None:assert torch.equal(pixels, torch.zeros(3, 64, 64))+def test_the_downscale_is_an_antialiased_bicubic_on_the_float_image() -> None:+ """Pinned by its pixels, not its size. A one-pixel checkerboard is all detail the smaller grid cannot hold:+ an antialiased resize averages it to mid-grey, a plain bicubic samples it into near black and white, and a+ uint8 round trip rounds what the trained path keeps in float."""+ checker = ((np.indices((480, 640)).sum(axis=0) % 2) * 255).astype(np.uint8)+ float_image = torch.from_numpy(checker.astype(np.float32) / 255.0).expand(1, 3, -1, -1)+ # sqrt(384^2 / (640 * 480)) = 0.6928: 480 -> 332.55 -> 333, 640 -> 443.4 -> 443.+ expected = torch.nn.functional.interpolate(float_image, size=(333, 443), mode="bicubic", antialias=True)+ expected = expected.squeeze(0).clamp(0, 1)+ # The pattern only tells the resizes apart if antialiasing really flattens it.+ assert float((expected - 0.5).abs().max()) < 0.05++ pixels = prepare_vlm_reference(Image.fromarray(checker))++ torch.testing.assert_close(pixels, expected, rtol=0, atol=1e-6)++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))