Skip to content

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

Merge remote-tracking branch 'upstream/main' into feat/qwen-image-2-1-edit

Alexander Eichhorn362e18e3f41b
diff --cc docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx
index b5f3de5a4c,5bb08d7b22..3a9b3845d8
--- a/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx
+++ b/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx
@@@ -119,11 -125,12 +125,12 @@@ What a reference does, and what option
|---|---|---|
| **SD 1.5, SDXL** | An IP-Adapter model carries the reference's look into the image. | **Mode**: **Style**, **Composition** or **Both**. **Weight**. Under **Advanced**: the IP-Adapter model, a **Style variant** and the **Active steps** range. |
| **FLUX.1** | An IP-Adapter, or a **FLUX Redux** model, which transfers the reference's content. | IP-Adapter options as above, or **Image influence** (Lowest to Highest) for Redux. |
+ | **Anima** (not Anima-3.8B) | An Anima IP-Adapter carries a character's appearance (hair, outfit, accessories) into the image. Up to four references (experimental); images of one character combine well, different characters blend. | **Strength** (0 to 2; 0 turns it off), per reference. Under **Advanced**: the IP-Adapter model and the **Active steps** range. |
| **FLUX.1 Kontext** | Kontext edits or recombines the reference images according to your prompt. | None beyond the model. |
-| **FLUX.2, Qwen Image Edit** | The model reads the references directly and uses them as your prompt instructs, for example *put the jacket from the first image on the person in the second*. | None. |
+| **FLUX.2, Qwen Image Edit, Qwen-Image-2.1** | The model reads the references directly and uses them as your prompt instructs, for example *put the jacket from the first image on the person in the second*. | None. |
| **Krea-2** | One reference's look — palette, texture, rendering — is transferred into the image while the prompt keeps driving the content; see [Krea-2](/users-guide/models/local-models/krea-2/#style-reference). | **Style strength** (0–2; 0 turns the reference off). |
- Reference images require an extra model for SD 1.5, SDXL and FLUX.1 (an IP-Adapter or FLUX Redux model). These are available as starter models in the Model Manager, and an installed IP-Adapter is selected automatically.
+ Reference images require an extra model for SD 1.5, SDXL, FLUX.1 and Anima (an IP-Adapter or FLUX Redux model). These are available as starter models in the Model Manager, and an installed IP-Adapter is selected automatically.
## Prompt tools
diff --cc invokeai/app/invocations/text_encoder/qwen_image_2_1_text_encoder.py
index 31b5384f4b,0bea270aa4..c3b2103e7c
--- a/invokeai/app/invocations/text_encoder/qwen_image_2_1_text_encoder.py
+++ b/invokeai/app/invocations/text_encoder/qwen_image_2_1_text_encoder.py
@@@ -90,54 -42,15 +90,54 @@@ class QwenImage21TextEncoderInvocation(
)
context.util.signal_progress("Running Qwen3-VL text encoder")
- with (
- tokenizer_info as tokenizer,
- text_encoder_info.model_on_device(working_mem_bytes=dequant_bytes) as (
- _,
- text_encoder,
- ),
- ):
- embeds = encode_prompt(text_encoder, tokenizer, self.prompt, get_effective_device(text_encoder))
-
- conditioning = QwenImage21ConditioningInfo(prompt_embeds=embeds.detach().cpu())
+ with tokenizer_info as tokenizer:
+ # Reference images make the sequence long, and its attention grows with the square of it: room the
+ # model cache has to make, or the driver spills the encode to system memory and it crawls.
+ num_tokens = sequence_length(tokenizer, self.prompt, images)
+ working_memory = dequant_bytes + working_memory_bytes(num_tokens, compute_dtype.itemsize, vision_bytes)
+ # The tower locks before the encoder, so the room the encoder reserves is still free once both are on
+ # the device.
+ with (
+ processor_info.model_on_device() if processor_info is not None else nullcontext((None, None)) as (
+ _,
+ processor,
+ ),
+ tower_info.model_on_device() if tower_info is not None else nullcontext((None, None)) as (_, tower),
+ text_encoder_info.model_on_device(working_mem_bytes=working_memory) as (_, text_encoder),
+ attached_vision_tower(text_encoder, tower) if tower is not None else nullcontext(),
+ ):
+ encoding = encode_prompt(
+ text_encoder,
+ tokenizer,
+ self.prompt,
+ get_effective_device(text_encoder),
+ processor=processor,
+ images=images,
+ )
+
+ conditioning = QwenImage21ConditioningInfo(
+ prompt_embeds=encoding.embeds.detach().cpu(),
+ image_pad_mask=None if encoding.image_pad_mask is None else encoding.image_pad_mask.cpu(),
+ reference_grids=encoding.reference_grids,
+ )
name = context.conditioning.save(ConditioningFieldData(conditionings=[conditioning]))
return QwenImage21ConditioningOutput.build(name)
+
+ def _edit_identifiers(self, context: InvocationContext) -> tuple[ModelIdentifierField, ModelIdentifierField]:
+ """The vision tower and the image processor an edit adds, which only a Qwen-Image-2.1 pipeline brings.
+
+ Checked on the configs, before anything loads: a graph can pair a standalone encoder with this pipeline's
+ tokenizer, or the other way round.
+ """
+ for identifier in (self.qwen3_vl_encoder.tokenizer, self.qwen3_vl_encoder.text_encoder):
+ config = context.models.get_config(identifier)
+ if (
+ config.base is not BaseModelType.QwenImage21
+ or config.type is not ModelType.Main
+ or config.format is not ModelFormat.Diffusers
+ ):
+ raise ValueError(_NO_VISION_TOWER)
+ return (
- self.qwen3_vl_encoder.text_encoder.model_copy(update={"submodel_type": SubModelType.VisionTower}),
++ self.qwen3_vl_encoder.text_encoder.model_copy(update={"submodel_type": SubModelType.VisionEncoder}),
+ self.qwen3_vl_encoder.tokenizer.model_copy(update={"submodel_type": SubModelType.Processor}),
+ )
diff --cc invokeai/backend/architectures/capabilities.py
index e72665da0d,5e2cb651af..423816b768
--- a/invokeai/backend/architectures/capabilities.py
+++ b/invokeai/backend/architectures/capabilities.py
@@@ -176,8 -171,7 +176,8 @@@ def architecture_capabilities() -> list
is rendered in full, so a client never has to know which fields a variant row is allowed to omit.
Differences too small to have earned a mapping are expressed on the base row instead, by
- `features.reference_images_require_variant` (Qwen-Image) and
- `features.reference_images_require_variant` (Qwen-Image and Anima).
++ `features.reference_images_require_variant` (Qwen-Image and Anima) and
+ `features.reference_images_require_format` (Qwen-Image-2.1).
Sorted by base value, then variant, so the response is stable and diffable.
"""
diff --cc invokeai/backend/architectures/facets/features.py
index 027f27ad3b,3677131fb2..1386f63d14
--- a/invokeai/backend/architectures/facets/features.py
+++ b/invokeai/backend/architectures/facets/features.py
@@@ -121,11 -121,8 +121,11 @@@ class FeaturesFacet(Facet)
control_kinds: frozenset[ControlKind] = frozenset()
max_reference_images: int = 0
reference_images_require_variant: str | None = None
- """Qwen-Image accepts reference images only as the `edit` variant — one of the two features in this
- table that a base alone cannot answer."""
+ """The one variant that accepts reference images, where a base alone cannot answer: Qwen-Image
+ takes them only as `edit`, Anima only on its Qwen3-conditioned releases."""
+ reference_images_require_format: str | None = None
- """The other: Qwen-Image-2.1 reads reference images only as a Diffusers pipeline, whose encoder is
- the only one that keeps the vision tower."""
++ """The one format that accepts reference images: Qwen-Image-2.1 reads them only as a Diffusers
++ pipeline, whose encoder is the only one that keeps the vision tower."""
supports_regional_guidance: bool = False
regional_negative: bool = False
diff --cc invokeai/backend/model_manager/load/model_loaders/qwen_image_2_1.py
index 549ee7f5be,f94637da23..a26d788731
--- a/invokeai/backend/model_manager/load/model_loaders/qwen_image_2_1.py
+++ b/invokeai/backend/model_manager/load/model_loaders/qwen_image_2_1.py
@@@ -64,29 -62,12 +64,29 @@@ def _build_transformer(sd: dict[str, An
class QwenImage21DiffusersModel(GenericDiffusersLoader):
"""Loads the submodels of a Qwen-Image-2.1 diffusers pipeline.
- The tokenizer lives in `processor/` (the pipeline declares a `Qwen3VLProcessor`, of which text prompts
- need only the tokenizer). The text encoder loads as `Qwen3VLModel` rather than the declared
- `Qwen3VLForConditionalGeneration`: the LM head is ~1.2 GiB the encoder never runs, and `Qwen3VLModel` is
- what the standalone Qwen3-VL loaders return, so the text encoder node sees one class.
+ The tokenizer lives in `processor/` (the pipeline declares a `Qwen3VLProcessor`); the processor itself, which
+ also cuts reference images into patches, loads only for an edit. The text encoder loads as `Qwen3VLModel`
+ rather than the declared `Qwen3VLForConditionalGeneration`: the LM head is ~1.2 GiB the encoder never runs,
+ and `Qwen3VLModel` is what the standalone Qwen3-VL loaders return, so the text encoder node sees one class.
+
+ `TextEncoder` drops the vision tower, as the standalone loaders do: text prompts never reach it.
- `VisionTower` is that tower alone (~1.1 GiB), read from the same folder for edits, which attach it to the
++ `VisionEncoder` is that tower alone (~1.1 GiB), read from the same folder for edits, which attach it to the
+ cached encoder while they encode. The language model's weights are cached once for both.
"""
+ def get_size_fs(
+ self, config: AnyModelConfig, model_path: Path, submodel_type: Optional[SubModelType] = None
+ ) -> int:
- if submodel_type is SubModelType.VisionTower:
++ if submodel_type is SubModelType.VisionEncoder:
+ # A few hundred tensors of the encoder's folder, not the folder: reserving its ~17 GB for the tower
+ # would evict models for nothing. Sized at the dtype they load in, whatever the file stores.
+ element_size = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device()).itemsize
+ return sum(
+ math.prod(shape) * element_size
+ for _shard, _key, shape in _vision_tower_tensors(model_path / SubModelType.TextEncoder.value)
+ )
+ return super().get_size_fs(config, model_path, submodel_type)
+
def _load_model(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> AnyModel:
if isinstance(config, Checkpoint_Config_Base):
raise NotImplementedError(
@@@ -109,11 -86,6 +109,11 @@@
dtype = self._torch_dtype_avoiding_float16()
else:
dtype = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device())
+
- if submodel_type is SubModelType.VisionTower:
++ if submodel_type is SubModelType.VisionEncoder:
+ tower = _load_vision_tower(model_path / SubModelType.TextEncoder.value, dtype)
+ return self._apply_fp8_layerwise_casting(tower, config, submodel_type)
+
repo_variant = config.repo_variant if isinstance(config, Diffusers_Config_Base) else None
variant = repo_variant.value if repo_variant else None
if submodel_type is SubModelType.TextEncoder:
@@@ -137,8 -109,7 +137,8 @@@
raise
if submodel_type is SubModelType.TextEncoder:
- # Text prompts never reach the vision tower; edits load it as `VisionTower` and attach it while they
- # Text prompts never reach the vision tower; reference images (which would) are not wired up.
++ # Text prompts never reach the vision tower; edits load it as `VisionEncoder` and attach it while they
+ # encode.
drop_qwen3vl_visual_tower(result)
return self._apply_fp8_layerwise_casting(result, config, submodel_type)
diff --cc invokeai/backend/model_manager/taxonomy.py
index 4a45c175c5,eec8d97fe2..56a52fe07b
--- a/invokeai/backend/model_manager/taxonomy.py
+++ b/invokeai/backend/model_manager/taxonomy.py
@@@ -130,6 -127,7 +127,9 @@@ class SubModelType(str, Enum)
Tokenizer2 = "tokenizer_2"
Tokenizer3 = "tokenizer_3"
Processor = "processor"
++ # A vision-language encoder's vision tower alone, which the text encoder is loaded without; edits attach it
++ # while they encode, so the language model is cached once. Krea-2 and Qwen-Image-2.1.
+ VisionEncoder = "vision_encoder"
PromptEnhancer = "pe"
PromptEnhancerTokenizer = "pe_tokenizer"
VAE = "vae"
diff --cc invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json
index 8d13ff2f46,8112d93f0b..9b514e7b5b
--- a/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json
+++ b/invokeai/frontend/webv2/src/features/generation/core/__fixtures__/architectureCapabilities.json
@@@ -16,9 -16,8 +16,9 @@@
"control_kinds": [
"anima_lllite"
],
- "max_reference_images": 0,
- "reference_images_require_variant": null,
+ "max_reference_images": 4,
+ "reference_images_require_variant": "anima_qwen3",
+ "reference_images_require_format": null,
"supports_regional_guidance": true,
"regional_negative": false,
"clip_skip_max": null,
@@@ -75,9 -74,8 +75,9 @@@
"control_kinds": [
"anima_lllite"
],
- "max_reference_images": 0,
- "reference_images_require_variant": null,
+ "max_reference_images": 4,
+ "reference_images_require_variant": "anima_qwen3",
+ "reference_images_require_format": null,
"supports_regional_guidance": true,
"regional_negative": false,
"clip_skip_max": null,
diff --cc invokeai/frontend/webv2/src/features/generation/core/graph.test.ts
index 679b87ffac,b259760436..df7b2d55a0
--- a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts
@@@ -3,8 -3,8 +3,9 @@@ import { afterEach, describe, expect, i
import type {
ComponentModelConfig,
+ ExternalImageGeneratorModelConfig,
GenerateModelConfig,
+ GenerateReferenceImage,
GenerateSettings,
LoraModelConfig,
MainModelConfig,
diff --cc tests/app/invocations/test_qwen_image_2_1_nodes.py
index 4de2d880fa,20e7fa0ad0..a5d2e53f7d
--- a/tests/app/invocations/test_qwen_image_2_1_nodes.py
+++ b/tests/app/invocations/test_qwen_image_2_1_nodes.py
@@@ -399,475 -349,3 +399,475 @@@ def test_the_4b_encoder_is_refused() -
loader = _loader(qwen3_vl_encoder_model=("encoder", BaseModelType.Any, ModelType.Qwen3VLEncoder))
with pytest.raises(ValueError, match="8B"):
loader.invoke(_loader_context(ModelFormat.Diffusers, encoder_variant=Qwen3VLVariantType.Qwen3VL_4B))
+
+
+def _edit_prompt(sign: float, grids: list[tuple[int, int]]) -> QwenImage21ConditioningInfo:
+ """A prompt encoded with references: a token, then one run of image slots per reference, then a token."""
+ mask = [False]
+ for rows, columns in grids:
+ mask += [True] * (rows * columns) + [False]
+ return QwenImage21ConditioningInfo(
+ prompt_embeds=sign * torch.ones(1, len(mask), 8),
+ image_pad_mask=torch.tensor([mask]),
+ reference_grids=tuple(grids),
+ )
+
+
+def _edit_context(transformer, prompt_grids, references: dict[str, torch.Tensor], negative=None):
+ infos = {"pos": _edit_prompt(1.0, prompt_grids), "neg": negative or _edit_prompt(-1.0, prompt_grids)}
+ return _context(transformer, QwenImage21VariantType.Base, infos=infos, tensors=references)
+
+
+def test_references_lead_the_image_tokens_and_fill_the_prompts_slots() -> None:
+ transformer = _Transformer()
+ # A 4x8 reference is 32 latent tokens in 2x4 slots; the 64x64 target is 4x4.
+ reference = torch.randn(1, LATENT_CHANNELS, 4, 8)
+ _denoise(reference_latents=[LatentsField(latents_name="ref")], steps=1)._run_diffusion(
+ _edit_context(transformer, [(2, 4)], {"ref": reference})
+ )
+
+ seen = transformer.inputs[0]
+ assert seen.img_shapes == [[(1, 4, 8), (1, 4, 4)]]
+ assert seen.hidden_states.shape[1] == 32 + 16
+ assert torch.equal(seen.hidden_states[:, :32], pack_latents(reference))
+ # The prompt's own mask, then one slot per 2x2 group of the target's 4x4 latents.
+ assert seen.img_mask.tolist() == [[False] + [True] * 8 + [False] + [True] * 4]
+
+
+def test_references_that_do_not_fill_the_slots_are_refused() -> None:
+ context = _edit_context(_Transformer(), [(2, 2)], {"ref": torch.zeros(1, LATENT_CHANNELS, 4, 8)})
+ with pytest.raises(ValueError, match=r"positive prompt was encoded with 1 reference image\(s\) \(64x64\)"):
+ _denoise(reference_latents=LatentsField(latents_name="ref"))._run_diffusion(context)
+
+
+def test_two_references_of_one_size_in_swapped_order_are_refused() -> None:
+ # Landscape then portrait in the prompt; portrait then landscape as latents. The slot counts agree.
+ context = _edit_context(
+ _Transformer(),
+ [(2, 4), (4, 2)],
+ {"portrait": torch.zeros(1, LATENT_CHANNELS, 8, 4), "landscape": torch.zeros(1, LATENT_CHANNELS, 4, 8)},
+ )
+ latents = [LatentsField(latents_name="portrait"), LatentsField(latents_name="landscape")]
+ with pytest.raises(ValueError, match="in reference mode, from the same images and in the same order"):
+ _denoise(reference_latents=latents)._run_diffusion(context)
+
+
+def test_latents_from_another_vae_are_refused() -> None:
+ context = _edit_context(_Transformer(), [(2, 4)], {"ref": torch.zeros(1, 16, 4, 8)})
+ with pytest.raises(ValueError, match="64 channels"):
+ _denoise(reference_latents=LatentsField(latents_name="ref"))._run_diffusion(context)
+
+
+def test_a_negative_prompt_encoded_without_the_references_is_refused() -> None:
+ context = _edit_context(
+ _Transformer(),
+ [(2, 4)],
+ {"ref": torch.zeros(1, LATENT_CHANNELS, 4, 8)},
+ negative=QwenImage21ConditioningInfo(prompt_embeds=-torch.ones(1, 2, 8)),
+ )
+ with pytest.raises(ValueError, match="negative prompt was encoded with 0"):
+ _denoise(reference_latents=LatentsField(latents_name="ref"), cfg_scale=4.0)._run_diffusion(context)
+
+
+def test_the_prefix_counts_each_reference_slot_as_four_latent_tokens() -> None:
+ # A 1 MP reference is 32x32 slots: 1024 slots in the prompt, 4096 tokens in the joint sequence.
+ info = _edit_prompt(1.0, [(32, 32)])
+ assert prefix_length(info) == info.prompt_embeds.shape[1] + 3 * 1024
+
+
+def test_the_prefix_caches_are_reserved_only_when_they_are_kept() -> None:
+ estimate = QwenImage21DenoiseInvocation._estimate_working_memory
+ prefix = 4200
+ cached = estimate(4096, prefix, prefix, True, True, 2, RELEASED_KV_BYTES)
+ recomputed = estimate(4096, prefix, prefix, True, False, 2, RELEASED_KV_BYTES)
+ # K and V of every prefix token in all 32 blocks, per guidance branch: ~2 GiB per 1 MP reference.
+ assert cached - recomputed == 2 * prefix * RELEASED_KV_BYTES
+
+
+def test_caches_larger_than_half_the_card_are_not_kept(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(torch.cuda, "get_device_properties", lambda _device: SimpleNamespace(total_memory=24 * 2**30))
+ cuda = torch.device("cuda")
+ # Two references at CFG fit a 24 GB card; four do not.
+ assert prefix_cache_fits(2 * 2 * 4200 * RELEASED_KV_BYTES, cuda)
+ assert not prefix_cache_fits(2 * 4 * 4200 * RELEASED_KV_BYTES, cuda)
+
+
[email protected](("integrated", "fits"), [(False, False), (True, True)], ids=["discrete", "integrated"])
+def test_a_discrete_xpu_card_is_limited_like_any_dedicated_card(
+ monkeypatch: pytest.MonkeyPatch, integrated: bool, fits: bool
+) -> None:
+ # Four references at CFG hold ~16 GiB: more than half a 16 GB Arc card. An integrated GPU shares system RAM,
+ # which the cache does not budget as a card.
+ monkeypatch.setattr("invokeai.backend.util.devices.xpu_device_is_integrated", lambda _device: integrated)
+ monkeypatch.setattr(torch.xpu, "get_device_properties", lambda _device: SimpleNamespace(total_memory=16 * 2**30))
+ assert prefix_cache_fits(2 * 4 * 4200 * RELEASED_KV_BYTES, torch.device("xpu")) is fits
+ assert prefix_cache_fits(2 * 4 * 4200 * RELEASED_KV_BYTES, torch.device("cpu"))
+
+
+def test_without_room_for_the_caches_every_step_runs_the_whole_prefix(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(f"{DENOISE}.prefix_cache_fits", lambda _bytes, _device: False)
+ transformer = _Transformer()
+ _denoise(reference_latents=LatentsField(latents_name="ref"), cfg_scale=4.0)._run_diffusion(
+ _edit_context(transformer, [(2, 4)], {"ref": torch.zeros(1, LATENT_CHANNELS, 4, 8)})
+ )
+ assert {(cache, mode) for _prompt, cache, mode, _t in transformer.calls} == {(id(None), None)}
+
+
+def test_a_later_step_decodes_from_the_cache_its_prefill_filled_with_the_references() -> None:
+ transformer = _Transformer()
+ reference = torch.randn(1, LATENT_CHANNELS, 4, 8)
+ _denoise(reference_latents=[LatentsField(latents_name="ref")], steps=2)._run_diffusion(
+ _edit_context(transformer, [(2, 4)], {"ref": reference})
+ )
+
+ assert [(prompt, mode) for prompt, _cache, mode, _t in transformer.calls] == [("pos", "extract"), ("pos", "cached")]
+ # One cache for the run: the cached step reads what the prefill wrote.
+ assert len({cache for _prompt, cache, _mode, _t in transformer.calls}) == 1
+ # The transformer rebuilds the joint sequence on every step, so the cached step still needs the references in
+ # front of the target, and the same layout.
+ for seen in transformer.inputs:
+ assert seen.img_shapes == [[(1, 4, 8), (1, 4, 4)]]
+ assert torch.equal(seen.hidden_states[:, :32], pack_latents(reference))
+ assert seen.img_mask.tolist() == [[False] + [True] * 8 + [False] + [True] * 4]
+
+
+def test_large_references_before_a_small_target_price_the_last_references_attention(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ sides: list[int] = []
+
+ def score_bytes(*, seq_len: int, **_kwargs) -> int:
+ sides.append(seq_len)
+ return 0
+
+ monkeypatch.setattr(f"{DENOISE}.sdpa_score_matrix_bytes", score_bytes)
+ # Four 1 MP references (32x32 slots, 64x64 latents each) before a 256x256 target (16x16 latents).
+ grids = [(32, 32)] * 4
+ references = {f"ref{i}": torch.zeros(1, LATENT_CHANNELS, 64, 64) for i in range(4)}
+ _denoise(
+ reference_latents=[LatentsField(latents_name=name) for name in references], width=256, height=256, steps=1
+ )._run_diffusion(_edit_context(_Transformer(), grids, references))
+
+ # The prompt's layout: one text token, then each reference's 4096 latent tokens and one text token. The last
+ # reference's 4096 queries attend over every key up to its end: 4 * 4096 + 4 of them. The target's call is
+ # 256 x (16389 + 256), a sixteenth of that.
+ largest = 4096 * (4 * 4096 + 4)
+ assert len(sides) == 1
+ assert (sides[0] - 1) ** 2 < largest <= sides[0] ** 2
+
+
[email protected]("cache_fits", [True, False], ids=["cached", "recomputed"])
+def test_the_metadata_records_whether_the_prefix_was_cached(cache_fits: bool, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(f"{DENOISE}.prefix_cache_fits", lambda _bytes, _device: cache_fits)
+ context = _edit_context(_Transformer(), [(2, 4)], {"ref": torch.zeros(1, LATENT_CHANNELS, 4, 8)})
+ context.tensors.save = lambda tensor: "out"
+ node = _denoise(
+ reference_latents=LatentsField(latents_name="ref"),
+ cfg_scale=4.0,
+ metadata=MetadataField.model_validate({"seed": 7, "steps": 3}),
+ )
+
+ output = node.invoke(context)
+
+ # What the graph recorded passes through, with the mode this run took beside it.
+ assert output.metadata.root == {"seed": 7, "steps": 3, PREFIX_CACHE_METADATA_KEY: cache_fits}
+ assert (output.latents.latents_name, output.width, output.height) == ("out", 64, 64)
+
+
+def test_a_standalone_encoder_cannot_read_references() -> None:
+ encoder = ModelIdentifierField(
+ key="enc", hash="h", name="qwen3vl_8b", base=BaseModelType.Any, type=ModelType.Qwen3VLEncoder
+ )
+ node = QwenImage21TextEncoderInvocation.model_construct(
+ prompt="swap them",
+ qwen3_vl_encoder=Qwen3VLEncoderField(tokenizer=encoder, text_encoder=encoder, loras=[]),
+ reference_images=[ImageField(image_name="ref.png")],
+ )
+ context = SimpleNamespace(
+ images=SimpleNamespace(get_pil=lambda _name: Image.new("RGB", (64, 64))),
+ models=SimpleNamespace(
+ get_config=lambda _identifier: SimpleNamespace(
+ base=BaseModelType.Any, type=ModelType.Qwen3VLEncoder, format=ModelFormat.Checkpoint
+ )
+ ),
+ )
+ with pytest.raises(ValueError, match="vision tower"):
+ node.invoke(context)
+
+
+def _pipeline_encoder_node(num_references: int) -> QwenImage21TextEncoderInvocation:
+ main = ModelIdentifierField(
+ key="qwen21", hash="h", name="Qwen-Image-2.1", base=BaseModelType.QwenImage21, type=ModelType.Main
+ )
+ return QwenImage21TextEncoderInvocation.model_construct(
+ prompt="Combine the subjects of all reference images.",
+ qwen3_vl_encoder=Qwen3VLEncoderField(
+ tokenizer=main.model_copy(update={"submodel_type": SubModelType.Tokenizer}),
+ text_encoder=main.model_copy(update={"submodel_type": SubModelType.TextEncoder}),
+ loras=[],
+ ),
+ reference_images=[ImageField(image_name=f"ref{i}.png") for i in range(num_references)],
+ )
+
+
+def test_the_processor_comes_from_the_qwen_image_2_1_pipeline_the_tokenizer_is_from() -> None:
+ context = SimpleNamespace(
+ models=SimpleNamespace(
+ get_config=lambda _identifier: SimpleNamespace(
+ base=BaseModelType.QwenImage21, type=ModelType.Main, format=ModelFormat.Diffusers
+ )
+ )
+ )
+ tower, processor = _pipeline_encoder_node(1)._edit_identifiers(context)
- assert (tower.key, tower.submodel_type) == ("qwen21", SubModelType.VisionTower)
++ assert (tower.key, tower.submodel_type) == ("qwen21", SubModelType.VisionEncoder)
+ assert (processor.key, processor.submodel_type) == ("qwen21", SubModelType.Processor)
+
+
+def test_a_standalone_encoder_beside_the_pipelines_tokenizer_cannot_read_references() -> None:
+ # The tokenizer passes; the encoder, whose pipeline would have to bring the vision tower, does not.
+ def get_config(identifier):
+ if identifier.submodel_type is SubModelType.Tokenizer:
+ return SimpleNamespace(base=BaseModelType.QwenImage21, type=ModelType.Main, format=ModelFormat.Diffusers)
+ return SimpleNamespace(base=BaseModelType.Any, type=ModelType.Qwen3VLEncoder, format=ModelFormat.Checkpoint)
+
+ with pytest.raises(ValueError, match="vision tower"):
+ _pipeline_encoder_node(1)._edit_identifiers(SimpleNamespace(models=SimpleNamespace(get_config=get_config)))
+
+
+def test_more_references_than_the_architecture_reads_are_refused_before_anything_loads() -> None:
+ # The context has no images or models: reaching either would fail with another error.
+ with pytest.raises(ValueError, match="at most 4 reference images; this prompt has 5"):
+ _pipeline_encoder_node(5).invoke(SimpleNamespace())
+
+
+class _ReservationRecorded(Exception):
+ pass
+
+
+def _encode_until_reservation(num_references: int, image_size: int = 1024) -> tuple[list[int], list[SubModelType]]:
+ """Runs the node until the encoder would move to the device; returns what it reserved and what it loaded."""
+ from invokeai.backend.qwen3_vl.qwen3_vl_assets import load_bundled_qwen3_vl_tokenizer
+
+ reserved: list[int] = []
+ loaded: list[SubModelType] = []
+
+ @contextmanager
+ def on_device(*, working_mem_bytes: int):
+ reserved.append(working_mem_bytes)
+ raise _ReservationRecorded
+ yield # pragma: no cover
+
+ text_encoder = torch.nn.Module()
+ text_encoder.language_model = torch.nn.Linear(2, 2)
+ text_encoder.visual = torch.nn.Identity()
+ tower = torch.nn.Linear(2, 2)
+ # The released tower's attention geometry.
+ tower.config = SimpleNamespace(num_heads=16, hidden_size=1152)
+ infos = {
+ SubModelType.TextEncoder: SimpleNamespace(
+ model=text_encoder, compute_device=torch.device("cpu"), model_on_device=on_device
+ ),
- SubModelType.VisionTower: SimpleNamespace(
++ SubModelType.VisionEncoder: SimpleNamespace(
+ model=tower, compute_device=torch.device("cpu"), model_on_device=lambda: nullcontext((None, tower))
+ ),
+ SubModelType.Tokenizer: nullcontext(load_bundled_qwen3_vl_tokenizer()),
+ SubModelType.Processor: SimpleNamespace(model_on_device=lambda: nullcontext((None, None))),
+ }
+
+ def load(identifier):
+ loaded.append(identifier.submodel_type)
+ return infos[identifier.submodel_type]
+
+ context = SimpleNamespace(
+ images=SimpleNamespace(get_pil=lambda _name: Image.new("RGB", (image_size, image_size))),
+ models=SimpleNamespace(
+ get_config=lambda _identifier: SimpleNamespace(
+ base=BaseModelType.QwenImage21, type=ModelType.Main, format=ModelFormat.Diffusers
+ ),
+ load=load,
+ ),
+ util=SimpleNamespace(signal_progress=lambda _message: None),
+ )
+ with pytest.raises(_ReservationRecorded):
+ _pipeline_encoder_node(num_references).invoke(context)
+ return reserved, loaded
+
+
[email protected]("num_references", [0, 2], ids=["text-only", "edit"])
+def test_only_an_edit_loads_the_vision_tower(num_references: int) -> None:
+ _, loaded = _encode_until_reservation(num_references, image_size=64)
+ # The encoder is the tower-less one either way: its language model is cached once for both.
+ assert loaded[0] is SubModelType.TextEncoder and SubModelType.TextEncoder not in loaded[1:]
- assert (SubModelType.VisionTower in loaded) is bool(num_references)
++ assert (SubModelType.VisionEncoder in loaded) is bool(num_references)
+ assert (SubModelType.Processor in loaded) is bool(num_references)
+
+
+class _EncodeFailed(Exception):
+ pass
+
+
[email protected]("fail", [False, True], ids=["encoded", "failed"])
+def test_an_edit_encodes_with_the_tower_attached_and_detaches_it(fail: bool, monkeypatch: pytest.MonkeyPatch) -> None:
+ """End to end through the node with a tiny Qwen3-VL split the way the pipeline loader caches it."""
+ import copy
+
+ from transformers import Qwen2VLImageProcessor, Qwen3VLModel, Qwen3VLProcessor
+ from transformers.models.qwen3_vl.video_processing_qwen3_vl import Qwen3VLVideoProcessor
+
+ from invokeai.app.invocations.text_encoder import qwen_image_2_1_text_encoder as node_module
+ from invokeai.backend.model_manager.util.qwen3_vl import drop_qwen3vl_visual_tower
+ from invokeai.backend.qwen3_vl.qwen3_vl_assets import load_bundled_qwen3_vl_tokenizer
+ from invokeai.backend.qwen_image_2_1.text_encoding import encode_prompt
+ from invokeai.backend.qwen_image_2_1.vae import to_reference
+ from tests.backend.model_manager.load.qwen3vl_gguf_fixture import tiny_qwen3vl_config
+
+ monkeypatch.setattr(f"{node_module.__name__}.TorchDevice.choose_bfloat16_safe_dtype", lambda _d: torch.float32)
+ tokenizer = load_bundled_qwen3_vl_tokenizer()
+ processor = Qwen3VLProcessor(
+ image_processor=Qwen2VLImageProcessor(patch_size=16, merge_size=2, temporal_patch_size=2),
+ tokenizer=tokenizer,
+ video_processor=Qwen3VLVideoProcessor(),
+ )
+ config = tiny_qwen3vl_config()
+ config.text_config.vocab_size = len(tokenizer)
+ torch.manual_seed(0)
+ built_in = Qwen3VLModel(config).float().eval()
+ tower = copy.deepcopy(built_in.visual)
+ encoder = copy.deepcopy(built_in)
+ drop_qwen3vl_visual_tower(encoder)
+
+ def info(model):
+ return SimpleNamespace(
+ model=model, compute_device=torch.device("cpu"), model_on_device=lambda **_kw: nullcontext((None, model))
+ )
+
+ infos = {
+ SubModelType.TextEncoder: info(encoder),
- SubModelType.VisionTower: info(tower),
++ SubModelType.VisionEncoder: info(tower),
+ SubModelType.Tokenizer: nullcontext(tokenizer),
+ SubModelType.Processor: info(processor),
+ }
+ saved: list[ConditioningFieldData] = []
+ reference = Image.new("RGB", (64, 64), (200, 30, 30))
+ context = SimpleNamespace(
+ images=SimpleNamespace(get_pil=lambda _name: reference),
+ models=SimpleNamespace(
+ get_config=lambda _identifier: SimpleNamespace(
+ base=BaseModelType.QwenImage21, type=ModelType.Main, format=ModelFormat.Diffusers
+ ),
+ load=lambda identifier: infos[identifier.submodel_type],
+ ),
+ conditioning=SimpleNamespace(save=lambda data: saved.append(data) or "cond"),
+ util=SimpleNamespace(signal_progress=lambda _message: None),
+ )
+ node = _pipeline_encoder_node(1)
+ if fail:
+
+ def failing_encode(*_args, **_kwargs):
+ raise _EncodeFailed
+
+ monkeypatch.setattr(node_module, "encode_prompt", failing_encode)
+ with pytest.raises(_EncodeFailed):
+ node.invoke(context)
+ else:
+ node.invoke(context)
+ expected = encode_prompt(
+ built_in, tokenizer, node.prompt, torch.device("cpu"), processor=processor, images=[to_reference(reference)]
+ )
+ info_out = saved[0].conditionings[0]
+ assert torch.equal(info_out.prompt_embeds, expected.embeds)
+ assert torch.equal(info_out.image_pad_mask, expected.image_pad_mask)
+
+ # The cached encoder is left as it was loaded, whether the encode finished or not.
+ assert isinstance(encoder.visual, torch.nn.Identity)
+
+
[email protected]("num_references", [0, 4])
+def test_the_encoder_reserves_room_for_the_attention_its_references_need(
+ num_references: int, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # The measurement below is a bf16 one; on a CPU without bf16 the node would price float32, twice as much.
+ monkeypatch.setattr(
+ "invokeai.app.invocations.text_encoder.qwen_image_2_1_text_encoder.TorchDevice.choose_bfloat16_safe_dtype",
+ lambda _device: torch.bfloat16,
+ )
+ reserved, _ = _encode_until_reservation(num_references)
+
+ if num_references:
+ # Measured on an RTX 4090: four 1-megapixel references peak 5.44 GiB above the weights, and the allocator
+ # reserves about a fifth more. Less than that and the driver spills the encode to system memory.
+ assert reserved[0] >= 1.2 * 5.44 * 2**30
+ else:
+ assert reserved[0] < 2**28
+
+
+def test_a_float32_encoder_reserves_twice_the_bfloat16_room(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The encoder runs in float32 where the device has no bf16 (CPU, older MPS); its activations are twice as wide.
+ reserved = {}
+ for dtype in (torch.bfloat16, torch.float32):
+ monkeypatch.setattr(
+ "invokeai.app.invocations.text_encoder.qwen_image_2_1_text_encoder.TorchDevice.choose_bfloat16_safe_dtype",
+ lambda _device, dtype=dtype: dtype,
+ )
+ reserved[dtype] = _encode_until_reservation(4)[0][0]
+ assert reserved[torch.float32] == pytest.approx(2 * reserved[torch.bfloat16], rel=1e-6)
+
+
+class _VAE:
+ """Records what it encodes and answers with bf16 latents, as the real VAE runs in bf16."""
+
+ dtype = torch.bfloat16
+ config = SimpleNamespace(latents_mean=[0.3] * LATENT_CHANNELS, latents_std=[1.7] * LATENT_CHANNELS)
+
+ def __init__(self) -> None:
+ self.pixels: torch.Tensor | None = None
+ self.z: torch.Tensor | None = None
+
+ def parameters(self):
+ return iter([torch.zeros(1, dtype=torch.bfloat16)])
+
+ def encode(self, pixels: torch.Tensor):
+ self.pixels = pixels
+ _, _, frames, height, width = pixels.shape
+ generator = torch.Generator().manual_seed(0)
+ self.z = torch.randn(1, LATENT_CHANNELS, frames, height // 16, width // 16, generator=generator).bfloat16()
+ return SimpleNamespace(latent_dist=SimpleNamespace(mode=lambda: self.z))
+
+
+def test_a_reference_encodes_at_its_reading_size_with_its_alpha_normalized_in_bf16(monkeypatch) -> None:
+ from invokeai.app.invocations.vae import qwen_image_2_1_image_to_latents as i2l_module
+
+ monkeypatch.setattr(i2l_module, "patch_qwen_image_vae_tiling", lambda *_args: nullcontext())
+ vae = _VAE()
+ saved: dict[str, torch.Tensor] = {}
+
+ @contextmanager
+ def on_device(**_kwargs):
+ yield ({}, vae)
+
+ context = SimpleNamespace(
+ images=SimpleNamespace(get_pil=lambda _name: Image.new("RGBA", (500, 300), (255, 0, 0, 64))),
+ models=SimpleNamespace(
+ load=lambda _identifier: SimpleNamespace(
+ compute_device=torch.device("cpu"), model=vae, model_on_device=on_device
+ )
+ ),
+ config=SimpleNamespace(get=lambda: SimpleNamespace(force_tiled_decode=False, auto_tiled_decode=False)),
+ tensors=SimpleNamespace(save=lambda tensor: saved.update(latents=tensor) or "latents"),
+ )
+ vae_field = VAEField(
+ vae=ModelIdentifierField(key="v", hash="h", name="v", base=BaseModelType.QwenImage21, type=ModelType.VAE)
+ )
+ output = QwenImage21ImageToLatentsInvocation.model_construct(
+ image=ImageField(image_name="ref.png"), vae=vae_field, tiled=False, tile_size=0, reference=True
+ ).invoke(context)
+
+ # 500x300 reads at 1312x800; the alpha is the image's own (64/255), not the canvas encode's 1.
+ assert (output.width, output.height) == (1312, 800)
+ assert vae.pixels is not None and vae.pixels.shape == (1, 4, 1, 800, 1312)
+ assert vae.pixels[0, 3].unique().tolist() == [torch.tensor(64 / 255 * 2 - 1).bfloat16().item()]
+ # Normalized in bf16, as the pipeline normalizes it -- which differs from normalizing in fp32.
+ mean, std = torch.tensor(0.3).bfloat16(), torch.tensor(1.7).bfloat16()
+ expected = ((vae.z - mean) / std).float()[:, :, 0]
+ assert torch.equal(saved["latents"], expected)
+ assert not torch.equal(expected, ((vae.z.float() - 0.3) / 1.7)[:, :, 0])
diff --cc tests/backend/architectures/test_features.py
index 7bf2a45f9a,b817571157..4f1502819f
--- a/tests/backend/architectures/test_features.py
+++ b/tests/backend/architectures/test_features.py
@@@ -82,23 -82,17 +82,25 @@@ def test_control_kinds_match_the_fronte
assert declared == expected
-def test_reference_images_and_their_variant_conditions() -> None:
+def test_reference_images_and_the_conditions_on_them() -> None:
- """Qwen-Image is the only base whose answer depends on the variant, and Qwen-Image-2.1 the only one whose
- answer depends on the format."""
+ """Qwen-Image and Anima are the bases whose answer depends on the variant: Qwen-Image takes
+ reference images only as `edit`, Anima only on the Qwen3-conditioned releases the IP-Adapter was
- trained on (not Anima-3.8B's Qwen3.5 variant)."""
++ trained on (not Anima-3.8B's Qwen3.5 variant). Qwen-Image-2.1 is the only one whose answer depends
++ on the format."""
supported = {
b.value for b in generative_bases() if (f := get(b, FeaturesFacet)) is not None and f.supports_reference_images
}
- assert supported == {"flux", "flux2", "sd-1", "sdxl", "qwen-image", "krea-2", "qwen-image-2-1"}
- assert supported == {"flux", "flux2", "sd-1", "sdxl", "qwen-image", "krea-2", "anima"}
++ assert supported == {"flux", "flux2", "sd-1", "sdxl", "qwen-image", "krea-2", "anima", "qwen-image-2-1"}
+
+ by_format = {
+ b.value: f.reference_images_require_format
+ for b in generative_bases()
+ if (f := get(b, FeaturesFacet)) is not None and f.reference_images_require_format is not None
+ }
+ assert by_format == {"qwen-image-2-1": "diffusers"}
conditional = {
- b.value
+ b.value: f.reference_images_require_variant
for b in generative_bases()
if (f := get(b, FeaturesFacet)) is not None and f.reference_images_require_variant is not None
}
diff --cc tests/backend/model_manager/load/test_load_default_cpu_only.py
index 0aa27d8a04,5c3b35c0a9..6088179ad4
--- a/tests/backend/model_manager/load/test_load_default_cpu_only.py
+++ b/tests/backend/model_manager/load/test_load_default_cpu_only.py
@@@ -49,11 -50,11 +50,11 @@@ def test_config_without_cpu_only_attr_r
assert _loader()._get_execution_device(SimpleNamespace(), None) is None
- def test_a_main_models_cpu_only_puts_its_encoder_and_vision_tower_on_the_cpu():
- # Qwen-Image-2.1 attaches the tower to the encoder while it reads references, so the two must share a device;
- # the denoiser stays on the cache default.
+ @pytest.mark.parametrize("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.
++ # The vision encoder runs inside the text encoder's forward (Krea-2 and Qwen-Image-2.1 edits), so `cpu_only`
++ # has to put both on the same device.
config = SimpleNamespace(default_settings=SimpleNamespace(cpu_only=True))
- loader = _loader()
- assert loader._get_execution_device(config, SubModelType.TextEncoder) == torch.device("cpu")
- assert loader._get_execution_device(config, SubModelType.VisionTower) == torch.device("cpu")
- assert loader._get_execution_device(config, SubModelType.Transformer) is None
+
+ assert _loader()._get_execution_device(config, submodel_type) == torch.device("cpu")
+ assert _loader()._get_execution_device(config, SubModelType.Transformer) is None
diff --cc tests/backend/model_manager/load/test_load_default_fp8.py
index 236986cd00,3f53e80bb1..3f343af3c3
--- a/tests/backend/model_manager/load/test_load_default_fp8.py
+++ b/tests/backend/model_manager/load/test_load_default_fp8.py
@@@ -183,18 -183,6 +183,18 @@@ def test_should_use_fp8_excludes_prompt
assert loader._should_use_fp8(config, SubModelType.Transformer) is True
+def test_should_use_fp8_excludes_the_vision_tower():
+ """Qwen-Image-2.1's vision tower attaches to the text encoder for edits and follows its exclusion. It could
+ not take the cast either: `Qwen3VLModel` casts the pixels to `visual.dtype`, which a cast tower reports as
+ float8."""
+ loader = _make_loader(device="cuda")
+ config = _make_config(ModelType.Main, fp8=True, base=BaseModelType.QwenImage21)
+ with _device_holds_fp8():
- assert loader._should_use_fp8(config, SubModelType.VisionTower) is False
++ assert loader._should_use_fp8(config, SubModelType.VisionEncoder) is False
+ # Sanity: the same config opts the transformer in, so the assertion above is about the exclusion.
+ assert loader._should_use_fp8(config, SubModelType.Transformer) is True
+
+
class _RaisingModule(torch.nn.Module):
"""A module whose forward unconditionally raises — used to test that the FP8 wrapper's
storage-dtype cleanup runs even when forward fails."""
diff --cc tests/backend/model_manager/load/test_qwen3_vl_visual_tower.py
index bd3fb1df4f,2d377cb153..fa6c34213f
--- a/tests/backend/model_manager/load/test_qwen3_vl_visual_tower.py
+++ b/tests/backend/model_manager/load/test_qwen3_vl_visual_tower.py
@@@ -1,10 -1,11 +1,11 @@@
"""Dropping the Qwen3-VL visual tower on the safetensors load paths.
Krea-2 and Ideogram 4 condition on the language tower's hidden states; `Qwen3VLModel.forward`
- reaches `self.visual` only for `pixel_values`, which neither invocation passes, and Ideogram 4 does
- not go through `forward` at all. The tower is therefore never executed, and dropping it takes
- 0.39-0.77 GiB off the 4B encoder depending on the container. Qwen-Image-2.1 drops it for text
- prompts too, and loads the tower on its own for edits.
+ reaches `self.visual` only for `pixel_values`, which text-only encoding never passes, and Ideogram 4
-does not go through `forward` at all. Krea-2 reference images do run the tower, but a separately
-loaded one (the `VisionEncoder` submodel) attached to the encoder for that call. The encoder's own
-tower is therefore never executed, and dropping it takes 0.39-0.77 GiB off the 4B encoder depending
-on the container.
++does not go through `forward` at all. Krea-2 and Qwen-Image-2.1 reference images do run the tower,
++but a separately loaded one (the `VisionEncoder` submodel) attached to the encoder for that call. The
++encoder's own tower is therefore never executed, and dropping it takes 0.39-0.77 GiB off the 4B
++encoder depending on the container.
These tests use a real (tiny) `Qwen3VLModel`, so what disappears is the architecture's actual vision
tower rather than a stand-in. MiniMax H3 does run this tower and loads through
@@@ -301,97 -302,3 +302,97 @@@ def test_the_folder_loader_drops_the_to
model = loader._load_model(config, SubModelType.TextEncoder)
_assert_tower_gone(model)
+
+
+def _qwen_image_2_1_pipeline(
+ monkeypatch,
+ tmp_path: Path,
+ *,
+ conditional_generation: bool,
+ saved_dtype: torch.dtype = torch.float32,
+ max_shard_size: str | None = None,
+):
+ """A Qwen-Image-2.1 pipeline folder holding a tiny encoder, saved as `Qwen3VLForConditionalGeneration` (the
+ released layout, `model.visual.*`) or as `Qwen3VLModel` (`visual.*`); the loader over it, which loads in
+ float32; the saved encoder."""
+ from transformers import Qwen3VLForConditionalGeneration
+
+ from invokeai.backend.model_manager.configs.main import Main_Diffusers_QwenImage21_Config
+ from invokeai.backend.model_manager.load.model_loaders.qwen_image_2_1 import QwenImage21DiffusersModel
+
+ torch.manual_seed(0)
+ saved = Qwen3VLForConditionalGeneration(tiny_qwen3vl_config()) if conditional_generation else _tiny_encoder()
+ saved = saved.to(saved_dtype)
+ shard_kwargs = {"max_shard_size": max_shard_size} if max_shard_size else {}
+ saved.save_pretrained(tmp_path / "text_encoder", **shard_kwargs)
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.qwen_image_2_1.TorchDevice.choose_bfloat16_safe_dtype",
+ lambda _device: torch.float32,
+ )
+ config = Main_Diffusers_QwenImage21_Config.model_construct(path=str(tmp_path), repo_variant=None)
+ loader = object.__new__(QwenImage21DiffusersModel)
+ loader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: model
+ encoder = saved.model if conditional_generation else saved
+ return loader, config, encoder
+
+
+def _assert_tower_loaded(tower, saved) -> None:
+ from transformers.models.qwen3_vl.modeling_qwen3_vl import Qwen3VLVisionModel
+
+ assert isinstance(tower, Qwen3VLVisionModel)
+ expected = saved.visual.state_dict()
+ loaded = tower.state_dict()
+ assert loaded.keys() == expected.keys()
+ for key, value in expected.items():
+ assert torch.equal(loaded[key], value), key
+
+
[email protected]("conditional_generation", [True, False], ids=["model.visual", "visual"])
+def test_the_qwen_image_2_1_pipeline_loads_the_tower_on_its_own(
+ monkeypatch, tmp_path: Path, conditional_generation: bool
+) -> None:
+ """Text prompts load the encoder without the tower, as every other loader does. Edits load the tower alone,
+ from the same folder and with the weights it was saved with, and attach it while they encode."""
+ loader, config, saved = _qwen_image_2_1_pipeline(
+ monkeypatch, tmp_path, conditional_generation=conditional_generation
+ )
+
+ _assert_tower_gone(loader._load_model(config, SubModelType.TextEncoder))
- _assert_tower_loaded(loader._load_model(config, SubModelType.VisionTower), saved)
++ _assert_tower_loaded(loader._load_model(config, SubModelType.VisionEncoder), saved)
+
+
+def _shard_the_tower_and_leave_a_stray_file(tmp_path: Path) -> None:
+ """The released encoder is sharded; check the tower spans several shards, and leave a stray safetensors file
+ beside them (a leftover variant) that the index does not name, holding zeros under the tower's keys."""
+ from safetensors import safe_open
+ from safetensors.torch import save_file
+
+ folder = tmp_path / "text_encoder"
+ weight_map = json.loads((folder / "model.safetensors.index.json").read_text())["weight_map"]
+ tower_keys = [key for key in weight_map if key.startswith("model.visual.")]
+ assert len({weight_map[key] for key in tower_keys}) > 1
+ first_shard = folder / weight_map[tower_keys[0]]
+ with safe_open(first_shard, framework="pt") as f:
+ stray = {key: torch.zeros_like(f.get_tensor(key)) for key in f.keys() if key.startswith("model.visual.")}
+ save_file(stray, str(folder / "model.fp16.safetensors"))
+
+
+def test_a_sharded_tower_loads_from_the_shards_its_index_names(monkeypatch, tmp_path: Path) -> None:
+ loader, config, saved = _qwen_image_2_1_pipeline(
+ monkeypatch, tmp_path, conditional_generation=True, max_shard_size="40KB"
+ )
+ _shard_the_tower_and_leave_a_stray_file(tmp_path)
+
- _assert_tower_loaded(loader._load_model(config, SubModelType.VisionTower), saved)
++ _assert_tower_loaded(loader._load_model(config, SubModelType.VisionEncoder), saved)
+
+
+def test_the_tower_reserves_its_own_size_at_the_dtype_it_loads_in(monkeypatch, tmp_path: Path) -> None:
+ """The cache makes room for this size before the load: the encoder folder's would evict ~17 GB for ~1 GB.
+ Saved in bf16, sharded, and loaded in float32: four bytes per element, counted once, from the index's shards."""
+ loader, config, saved = _qwen_image_2_1_pipeline(
+ monkeypatch, tmp_path, conditional_generation=True, saved_dtype=torch.bfloat16, max_shard_size="40KB"
+ )
+ _shard_the_tower_and_leave_a_stray_file(tmp_path)
+
+ elements = sum(v.nelement() for v in saved.visual.state_dict().values())
- assert loader.get_size_fs(config, tmp_path, SubModelType.VisionTower) == 4 * elements
++ assert loader.get_size_fs(config, tmp_path, SubModelType.VisionEncoder) == 4 * elements