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.

perf(krea2): drop the Qwen3-VL visual tower on the safetensors paths

Alexander Eichhorn7c68424caaa2
diff --git a/invokeai/app/invocations/text_encoder/krea2_text_encoder.py b/invokeai/app/invocations/text_encoder/krea2_text_encoder.py
index 640d92e218..0eea7dc2c1 100644
--- a/invokeai/app/invocations/text_encoder/krea2_text_encoder.py
+++ b/invokeai/app/invocations/text_encoder/krea2_text_encoder.py
@@ -1,3 +1,4 @@
+import re
from contextlib import ExitStack
from typing import Iterator
@@ -40,6 +41,15 @@ _KREA2_PREFIX = (
)
_KREA2_SUFFIX = "<|im_end|>\n<|im_start|>assistant\n"
+# The loader drops the Qwen3-VL visual tower: conditioning never executes it, so its weights would be
+# dead resident bytes. An adapter can still carry layers for it -- a Krea-2 LoRA's encoder keys are
+# whatever followed `text_encoder.`, and the converter does emit `lora_qwen3vl-visual.*` -- and those
+# 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.
+_VISUAL_TOWER_LORA_LAYERS = re.compile(rf"^{re.escape(KREA2_LORA_QWEN3VL_PREFIX)}visual\.")
+
@invocation(
"krea2_text_encoder",
@@ -127,6 +137,7 @@ class Krea2TextEncoderInvocation(BaseInvocation):
dtype=TorchDevice.choose_bfloat16_safe_dtype(device),
cached_weights=cached_weights,
force_sidecar_patching=requires_sidecar_patching(text_encoder, text_encoder_format),
+ suppress_warning_layers=_VISUAL_TOWER_LORA_LAYERS,
)
)
diff --git a/invokeai/backend/model_manager/load/model_loaders/ideogram4.py b/invokeai/backend/model_manager/load/model_loaders/ideogram4.py
index 50c171c3ea..e13ef549dd 100644
--- a/invokeai/backend/model_manager/load/model_loaders/ideogram4.py
+++ b/invokeai/backend/model_manager/load/model_loaders/ideogram4.py
@@ -34,6 +34,10 @@ from invokeai.backend.model_manager.taxonomy import (
ModelType,
SubModelType,
)
+from invokeai.backend.model_manager.util.qwen3_vl import (
+ drop_qwen3vl_visual_tower,
+ drop_qwen3vl_visual_tower_keys,
+)
from invokeai.backend.quantization.fp8_scaled import (
Fp8ScaledLayer,
attach_fp8_scales,
@@ -228,6 +232,10 @@ class Ideogram4DiffusersModel(ModelLoader):
cfg.quantization_config = None
sd = _load_local_state_dict(encoder_path, "model")
+ # Ideogram 4 conditions on the Qwen3-VL language tower only -- `ideogram4/text_encoding.py`
+ # drives `text_encoder.language_model` directly and never calls `forward`, so the visual tower
+ # is never executed. Dropped before the reservation below, which is sized from this dict.
+ sd = drop_qwen3vl_visual_tower_keys(sd)
# Ahead of the reservation, which evicts other resident models to make space: a refusal below
# it would flush the cache for a load that cannot finish.
@@ -253,6 +261,9 @@ class Ideogram4DiffusersModel(ModelLoader):
# assign=True fills the meta params directly.
with accelerate.init_empty_weights():
model: torch.nn.Module = AutoModel.from_config(cfg)
+ # `required=False`: the architecture comes from the folder's config.json, so an
+ # encoder without a vision tower is a shape this loader may legitimately meet.
+ drop_qwen3vl_visual_tower(model, required=False)
swap_linears_to_fp8(model, sd, compute_dtype=compute_dtype)
load_fp8_state_dict(model, sd, device=torch.device("cpu"), dtype=compute_dtype, assign=True, strict=False)
_verify_encoder_fully_materialized(model, context="Ideogram 4 fp8 text encoder")
@@ -263,6 +274,7 @@ class Ideogram4DiffusersModel(ModelLoader):
with accelerate.init_empty_weights():
model = AutoModel.from_config(cfg)
+ drop_qwen3vl_visual_tower(model, required=False) # see the fp8 branch above
if is_bnb_nf4:
# Only this branch needs bitsandbytes, which macOS does not have; see the transformer.
from invokeai.backend.quantization.bnb_nf4 import quantize_model_nf4
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.py
index f6a34af153..af61ebf456 100644
--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py
+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py
@@ -8,6 +8,7 @@ from pathlib import Path
from typing import Any, Generic, Optional, TypeVar
import accelerate
+import torch
from transformers import AutoConfig, AutoTokenizer
from invokeai.backend.model_manager.configs.base import Checkpoint_Config_Base, Diffusers_Config_Base
@@ -35,7 +36,12 @@ from invokeai.backend.model_manager.taxonomy import (
SubModelType,
)
from invokeai.backend.model_manager.util.llamacpp_keys import convert_llamacpp_decoder_keys
-from invokeai.backend.model_manager.util.qwen3_vl import normalize_qwen3vl_rope_config
+from invokeai.backend.model_manager.util.qwen3_vl import (
+ drop_qwen3vl_visual_tower,
+ drop_qwen3vl_visual_tower_keys,
+ normalize_qwen3vl_rope_config,
+ qwen3vl_target_key,
+)
from invokeai.backend.quantization.fp8_scaled import (
INPUT_SCALE_SUFFIXES,
attach_fp8_scales,
@@ -140,8 +146,6 @@ def _remap_native_layer_paths(layer_names: Any) -> dict[str, str]:
modulation tables (``lin``). A caller that also has norms to place reads the conversion's own
``key_map`` instead of probing it; see the fp8 branch of ``_load_from_singlefile``.
"""
- import torch
-
mapping: dict[str, str] = {}
for name in layer_names:
if not isinstance(name, str):
@@ -205,8 +209,6 @@ def _convert_krea2_native_to_diffusers(sd: dict[str, Any], *, key_map: dict[str,
The original final-block ``last.down``/``last.up`` projections have no counterpart in the diffusers
``Krea2FinalLayer`` (a clean AdaLN + linear) and are dropped.
"""
- import torch
-
new_sd: dict[str, Any] = {}
source_of: dict[Any, Any] = {}
for key, value in sd.items():
@@ -367,6 +369,13 @@ class Krea2DiffusersModel(GenericDiffusersLoader):
else:
raise e
+ if submodel_type is SubModelType.TextEncoder:
+ # The bundled encoder is the same Qwen3-VL as the standalone one, and this is the path a
+ # user gets by default: the loader node falls back to the pipeline's encoder whenever no
+ # standalone one is wired up, which is how the "Krea-2 Turbo" starter model is used.
+ # Without this, that install keeps the ~0.8 GiB the standalone install no longer pays.
+ drop_qwen3vl_visual_tower(result)
+
result = self._apply_fp8_layerwise_casting(result, config, submodel_type)
return result
@@ -724,13 +733,18 @@ class Qwen3VLEncoderLoader(ModelLoader):
te_config = _normalize_qwen3vl_rope_config(
AutoConfig.from_pretrained(text_encoder_path, local_files_only=True)
)
- return Qwen3VLModel.from_pretrained(
+ model = Qwen3VLModel.from_pretrained(
text_encoder_path,
config=te_config,
torch_dtype=model_dtype,
low_cpu_mem_usage=True,
local_files_only=True,
)
+ # After the load rather than before it: `from_pretrained` builds the module tree
+ # itself, so there is no point to intervene at. The tower's weights are therefore
+ # read and then freed -- resident size drops, load peak does not.
+ drop_qwen3vl_visual_tower(model)
+ return model
raise ValueError(
f"Only Tokenizer and TextEncoder submodels are supported. "
@@ -738,24 +752,6 @@ class Qwen3VLEncoderLoader(ModelLoader):
)
-def _qwen3vl_target_key(key: str) -> str:
- """Map one ComfyUI single-file Qwen3-VL key (or module path) to the transformers layout.
-
- ComfyUI/native layout uses a single ``model.`` prefix for both towers; transformers splits them:
- ``model.visual.*`` -> ``visual.*`` and ``model.<rest>`` (layers/embed_tokens/norm) -> ``language_model.<rest>``.
-
- Shared by the state-dict remap and the fp8 layer-hint remap so the two cannot drift apart: a hint
- keyed by a path the model does not have matches nothing and is silently ignored.
- """
- # Strip a leading "model." (some checkpoints prefix everything with it), then route by tower.
- key = key[len("model.") :] if key.startswith("model.") else key
- if key.startswith("visual.") or key.startswith("language_model."):
- # Already the transformers layout (e.g. "model.language_model.*" / "model.visual.*").
- return key
- # Bare language-model keys (layers.* / embed_tokens / norm) belong under language_model.
- return "language_model." + key
-
-
def _remap_qwen3vl_singlefile_keys(
sd: dict[str, Any],
*,
@@ -774,7 +770,7 @@ def _remap_qwen3vl_singlefile_keys(
if not isinstance(k, str):
_put_unique_key(out, k, v, source=k, source_of=source_of, what=what)
continue
- new_key = _qwen3vl_target_key(k)
+ new_key = qwen3vl_target_key(k)
_put_unique_key(out, new_key, v, source=k, source_of=source_of, what=what)
if key_map is not None:
key_map[k] = new_key
@@ -902,8 +898,9 @@ class _Qwen3VLEncoderSingleFileLoader(ModelLoader, Generic[_Qwen3VLSingleFileCon
class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEncoder_Checkpoint_Config]):
"""Loads a single-file Qwen3-VL encoder checkpoint (e.g. ComfyUI ``qwen3vl_4b_bf16`` / ``_fp8_scaled``).
- The checkpoint bundles the language model + visual tower. ComfyUI 'scaled fp8' weights are
- dequantized to the compute dtype on load.
+ The checkpoint bundles the language model + visual tower; the tower is dropped on the way in (see
+ ``drop_qwen3vl_visual_tower_keys``). ComfyUI 'scaled fp8' weights are dequantized to the compute
+ dtype on load.
"""
CONFIG_CLASS = Qwen3VLEncoder_Checkpoint_Config
@@ -918,6 +915,10 @@ class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEnco
model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
sd = load_file(str(model_path))
+ # Ahead of every pass that reads tensors, so the tower is never dequantized, cast, copied or
+ # reserved for. (The file *header* is still read below for quantization metadata, which can
+ # therefore still name visual layers; those hints match no surviving key and are ignored.)
+ sd = drop_qwen3vl_visual_tower_keys(sd)
# Same one-or-the-other split as the transformer above, and here it also guards the fp8
# *detection*: an int8 layer ships a `.weight_scale` too, so probing for scales without
# ruling out int8 first would keep the encoder "fp8-resident" over weights that were never
@@ -953,10 +954,10 @@ class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEnco
# ".weight_scale" travels with its ".weight" and the recovered layer paths already match the
# model's module paths — which is what attach_fp8_scales() resolves them against.
sd = _remap_qwen3vl_singlefile_keys(sd)
- layer_hints = {_qwen3vl_target_key(path): hints for path, hints in layer_hints.items()}
+ layer_hints = {qwen3vl_target_key(path): hints for path, hints in layer_hints.items()}
# ComfyUI 'scaled fp8' (fp8 weight + .weight_scale). Only the language-model linears are
- # quantized in the checkpoints seen so far; the visual tower stays bf16 either way.
+ # quantized in the checkpoints seen so far.
fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)
source_is_fp8 = bool(fp8_layers) or any(
getattr(t, "dtype", None) in (torch.float8_e4m3fn, torch.float8_e5m2) for t in sd.values()
@@ -980,6 +981,9 @@ class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEnco
te_config = self._load_hf_config(config)
with accelerate.init_empty_weights():
model = Qwen3VLModel._from_config(te_config)
+ # Its weights were dropped from the state dict above, so the module has to go too -- left in
+ # place it would stay on the meta device and `_reject_incomplete_load` would rightly refuse.
+ drop_qwen3vl_visual_tower(model)
if int8_markers:
# `Qwen3VLModel` declares no precision-sensitive modules, but read them rather than
@@ -1043,10 +1047,21 @@ class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEnco
# fp8->bf16 round trip on every forward.
attached = attach_fp8_scales(model, fp8_layers)
warn_on_unattached_scales(self._logger, f"Qwen3-VL encoder '{config.name}'", attached, fp8_layers)
- # The checkpoint quantizes only the language-model linears; the visual tower ships bf16
- # and would make the encoder ~0.4GB larger resident than the plain fp8_storage path. On a
- # GPU already holding a ~12GB transformer that is enough to push the transformer into
- # partial loading, so cast the rest to fp8 storage. Two exclusions:
+ # This pass was originally here to cast the bf16 visual tower, worth ~0.4GB resident. The
+ # tower is now dropped before the load, and on qwen3vl_4b_fp8_scaled -- where every Linear
+ # is already scaled -- what is left for it to cast is nothing: measured 0.000 GiB saved,
+ # conditioning identical (cosine 1.000000).
+ #
+ # It stays for two reasons that survive the tower, and one that is weaker than it looks.
+ # The weak one first: a build that scales only *some* of its Linears would still shrink --
+ # but this pass quantizes those to *unscaled* fp8, and per the `nn.Embedding` note below
+ # that costs real accuracy, so on such a build it is a trade, not a free win. The two that
+ # hold: this is the only call on this branch that records the real compute dtype via
+ # `set_fp8_compute_dtype`, without which `get_model_compute_dtype` falls back to scanning
+ # for a non-fp8 float parameter -- which happens to work only because the embedding is
+ # excluded here and stays bf16. And it installs the backstop that restores the compute
+ # dtype on Linears its skip list and the default one both name, which is the documented
+ # guard against those two lists ever overlapping. Two exclusions:
#
# - anything carrying a `weight_scale`: those keep their scale and go through
# _scaled_mm; the cast hooks would upcast them without it, i.e. a wrong weight.
@@ -1063,9 +1078,9 @@ class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEnco
or isinstance(module, torch.nn.Embedding),
)
self._logger.info(
- f"Qwen3-VL encoder '{config.name}': kept {attached} scaled layer(s) quantized "
- f"({self._fp8_kept_reason()}, storage=float8_e4m3fn, compute={model_dtype}); "
- "remaining layers cast to fp8 storage."
+ f"Qwen3-VL encoder '{config.name}': visual tower dropped; kept {attached} scaled "
+ f"layer(s) quantized ({self._fp8_kept_reason()}, storage=float8_e4m3fn, "
+ f"compute={model_dtype})."
)
# The layerwise-casting path below exists to *produce* fp8 weights from full-precision
# ones. These already are fp8, and its hooks would cast them to the compute dtype without
@@ -1085,6 +1100,10 @@ class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEnco
f"FP8 layerwise casting enabled for Qwen3-VL encoder '{config.name}' "
f"(storage=float8_e4m3fn, compute={model_dtype})."
)
+ else:
+ # Otherwise nothing above has said anything, and an encoder that just became ~0.8GiB
+ # smaller than its file should say why.
+ self._logger.info(f"Qwen3-VL encoder '{config.name}': visual tower dropped (never used for text).")
return model
@@ -1106,7 +1125,6 @@ class Qwen3VLEncoderGGUFLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEncoder_GG
CONFIG_CLASS = Qwen3VLEncoder_GGUF_Config
def _load_text_encoder(self, config: Qwen3VLEncoder_GGUF_Config) -> AnyModel:
- import torch
from transformers import Qwen3VLModel
target_device = TorchDevice.choose_torch_device()
@@ -1126,12 +1144,8 @@ class Qwen3VLEncoderGGUFLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEncoder_GG
with accelerate.init_empty_weights():
model = Qwen3VLModel._from_config(te_config)
- # The visual tower's weights live in the companion mmproj file, so there is nothing to load
- # into it. Dropping the module keeps it off the meta device (where the completeness sweep
- # below would rightly reject it) and out of the cache's size accounting. Krea-2 and
- # Ideogram 4 never reach it: `Qwen3VLModel.forward` touches `self.visual` only for
- # `pixel_values`, which neither passes.
- model.visual = torch.nn.Identity()
+ # Nothing to load into it: llama.cpp keeps the visual tower in a companion mmproj file.
+ drop_qwen3vl_visual_tower(model)
load_state_dict_ignoring_extras(model, sd, source="Qwen3-VL encoder GGUF", assign=True, allow_missing=True)
diff --git a/invokeai/backend/model_manager/util/qwen3_vl.py b/invokeai/backend/model_manager/util/qwen3_vl.py
index a524fbc4f9..c8dd8d652a 100644
--- a/invokeai/backend/model_manager/util/qwen3_vl.py
+++ b/invokeai/backend/model_manager/util/qwen3_vl.py
@@ -1,7 +1,15 @@
-"""Shared helpers for loading Qwen3-VL encoder checkpoints (used by Krea-2 and MiniMax H3)."""
+"""Shared helpers for loading Qwen3-VL encoder checkpoints.
+
+Used by Krea-2, Ideogram 4 and MiniMax H3. The visual-tower helpers live here rather than beside
+one family's loader because three loaders in two files drop the tower, and because what counts as
+the 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.
+"""
from typing import Any
+import torch
+
def normalize_qwen3vl_rope_config(config: Any) -> Any:
"""Mirror Qwen3-VL rope_parameters into rope_scaling for Transformers compatibility.
@@ -15,3 +23,83 @@ def normalize_qwen3vl_rope_config(config: Any) -> Any:
if getattr(text_config, "rope_scaling", None) is None and rope_params is not None:
text_config.rope_scaling = rope_params
return config
+
+
+def qwen3vl_target_key(key: str) -> str:
+ """Map one ComfyUI single-file Qwen3-VL key (or module path) to the transformers layout.
+
+ ComfyUI/native layout uses a single ``model.`` prefix for both towers; transformers splits them:
+ ``model.visual.*`` -> ``visual.*`` and ``model.<rest>`` (layers/embed_tokens/norm) -> ``language_model.<rest>``.
+
+ Shared by the state-dict remap and the fp8 layer-hint remap so the two cannot drift apart: a hint
+ keyed by a path the model does not have matches nothing and is silently ignored.
+ """
+ # Strip a leading "model." (some checkpoints prefix everything with it), then route by tower.
+ key = key[len("model.") :] if key.startswith("model.") else key
+ if key.startswith("visual.") or key.startswith("language_model."):
+ # Already the transformers layout (e.g. "model.language_model.*" / "model.visual.*").
+ return key
+ # Bare language-model keys (layers.* / embed_tokens / norm) belong under language_model.
+ return "language_model." + key
+
+
+def drop_qwen3vl_visual_tower(model: torch.nn.Module, *, required: bool = True) -> bool:
+ """Replace the Qwen3-VL visual tower with a parameter-free stub. Returns whether one was found.
+
+ Krea-2 and Ideogram 4 condition on the language tower's hidden states alone.
+ ``Qwen3VLModel.forward`` reaches ``self.visual`` only for ``pixel_values``/``pixel_values_videos``,
+ which neither invocation passes, and Ideogram 4 does not go through ``forward`` at all -- it drives
+ ``model.language_model`` directly. Removing the tower was measured to leave Krea-2's conditioning
+ bit-identical (max abs diff 0.0). Measured resident saving on the 4B: 0.774 GiB from the bf16
+ checkpoint (8.266 -> 7.492) and 0.390 GiB from the fp8_scaled one (4.499 -> 4.109), the smaller
+ figure because that path was already casting the tower to fp8 storage to blunt its cost.
+
+ With ``required`` (the default), raises when there is no tower to replace rather than letting
+ ``setattr`` invent the attribute. On the single-file path a renamed tower would be caught anyway
+ -- its weights would stay on meta and the completeness sweep would refuse the load -- but on the
+ ``from_pretrained`` paths nothing else would notice: the renamed tower would load, a dead
+ ``visual`` attribute would be added beside it, and the encoder would keep every byte this is
+ meant to save, silently.
+
+ Ideogram 4 passes ``required=False``, and that is not the same hazard: it builds whatever the
+ folder's ``config.json`` declares, so an encoder without a vision tower is a shape this loader
+ legitimately meets rather than a sign the architecture moved underneath us. Such a build fails
+ later and on its own terms, when the caption encoder reaches for ``language_model``.
+
+ MiniMax H3 genuinely runs this tower for its reference images, and loads through its own loaders in
+ ``model_loaders/minimax_h3.py``; nothing here is reachable from them.
+
+ A LoRA layer addressed at ``visual.*`` is skipped instead of applied -- possible in principle, and
+ in fact produced by the converter (see ``test_krea2_lora_conversion_utils``). It could not have
+ changed an image before either, for the same reason the tower can go, so the callers suppress the
+ per-layer warning rather than letting it read as an adapter failure.
+ """
+ existing = getattr(model, "visual", None)
+ if not isinstance(existing, torch.nn.Module) or isinstance(existing, torch.nn.Identity):
+ if required:
+ raise RuntimeError(
+ f"{type(model).__name__} has no Qwen3-VL visual tower to drop. The architecture has "
+ "changed shape; the tower would otherwise stay resident with nothing reporting it."
+ )
+ return False
+ model.visual = torch.nn.Identity()
+ return True
+
+
+def drop_qwen3vl_visual_tower_keys(sd: dict[str, Any]) -> dict[str, Any]:
+ """Drop the visual tower's tensors from a single-file Qwen3-VL state dict.
+
+ Dropping them here rather than after the load is what makes the saving a *peak* one and not only a
+ resident one. ``safetensors.torch.load_file`` is mmap-backed, so on arrival these tensors are
+ file-backed views costing no committed memory; what used to commit them was the work downstream --
+ on the fp8 branch ``_apply_fp8_to_nn_module`` allocated a fresh fp8 copy of the whole tower, and on
+ the bf16 branch the pages were faulted in at the device move. Neither happens to tensors that are
+ no longer in the dict.
+
+ The predicate routes through ``qwen3vl_target_key`` so "what counts as the visual tower" is
+ defined in one place, and it matches on the module path prefix rather than a list of suffixes --
+ which is what makes it take *every* sidecar a visual weight carries, including spellings this file
+ 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."))}
diff --git a/tests/app/invocations/test_krea2_text_encoder.py b/tests/app/invocations/test_krea2_text_encoder.py
index e22c6d3b67..5819bbe1d7 100644
--- a/tests/app/invocations/test_krea2_text_encoder.py
+++ b/tests/app/invocations/test_krea2_text_encoder.py
@@ -349,6 +349,38 @@ def test_encode_uses_reference_fixed_length_layout_and_position_ids(monkeypatch)
assert captured["position_ids"][0, 0, -5:].tolist() == [4, 5, 6, 7, 8]
+def test_visual_tower_lora_layers_are_skipped_without_blaming_the_adapter(monkeypatch) -> None:
+ """The loader drops the Qwen3-VL visual tower, so an adapter carrying layers for it finds no
+ module. The converter really does emit these keys (see `test_krea2_lora_conversion_utils`), and
+ the 4B's vision tower has 27 blocks, so left to the patcher this is ~108 "Failed to find module
+ for LoRA layer key" lines per generation -- reading as an adapter failure for layers that never
+ affected an image.
+
+ Asserted on the pattern handed to the patcher, since the suppression is the patcher's to apply.
+ """
+ import re
+
+ captured: dict = {}
+
+ def capture(**kwargs):
+ captured.update(kwargs)
+ return nullcontext()
+
+ monkeypatch.setattr(
+ "invokeai.app.invocations.text_encoder.krea2_text_encoder.LayerPatcher.apply_smart_model_patches",
+ capture,
+ )
+
+ _invocation()._encode(_context(ModelPatchRaw(layers={})))
+
+ pattern = captured["suppress_warning_layers"]
+ assert isinstance(pattern, re.Pattern)
+ assert pattern.search(f"{KREA2_LORA_QWEN3VL_PREFIX}visual.blocks.0.attn.qkv")
+ # The language tower is what the adapter is for; a miss there is a real problem and must still
+ # be reported.
+ assert not pattern.search(f"{KREA2_LORA_QWEN3VL_PREFIX}layers.0.self_attn.q_proj")
+
+
def test_invoke_preserves_the_regional_mask_on_its_conditioning_output(monkeypatch) -> None:
regional_mask = TensorField(tensor_name="regional-mask")
invocation = _invocation().model_copy(update={"mask": regional_mask})
diff --git a/tests/backend/model_manager/load/test_ideogram4_diffusers_loader.py b/tests/backend/model_manager/load/test_ideogram4_diffusers_loader.py
index 0760352852..540dfcc90f 100644
--- a/tests/backend/model_manager/load/test_ideogram4_diffusers_loader.py
+++ b/tests/backend/model_manager/load/test_ideogram4_diffusers_loader.py
@@ -253,6 +253,40 @@ def test_the_other_spelling_is_refused_in_the_flagged_branch_too(
assert run.reserved == []
+def test_a_qwen3_vl_text_encoder_loses_its_visual_tower(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ """The encoder Ideogram 4 actually ships is a Qwen3-VL, and `backend/ideogram4/text_encoding.py`
+ drives its `language_model` directly -- the vision tower is never executed. It is dropped here
+ both from the state dict, ahead of the reservation that is sized from it, and from the built
+ module, so nothing is left on the meta device.
+
+ The other encoder fixtures in this file are `model_type: "qwen3"`, which has no tower at all and
+ therefore only exercises the tolerated case.
+ """
+ from transformers import Qwen3VLModel
+
+ from tests.backend.model_manager.load.qwen3vl_gguf_fixture import tiny_qwen3vl_config
+
+ te_config = tiny_qwen3vl_config()
+ torch.manual_seed(0)
+ state_dict = {k: v.contiguous() for k, v in Qwen3VLModel(te_config).state_dict().items()}
+
+ encoder = tmp_path / "text_encoder"
+ encoder.mkdir(parents=True, exist_ok=True)
+ (encoder / "config.json").write_text(json.dumps(te_config.to_dict()), encoding="utf-8")
+ save_file(state_dict, encoder / "model.safetensors")
+
+ run = prepare(ENCODER_SEAM, monkeypatch)
+ model = run.load(tmp_path)
+
+ assert isinstance(model.visual, torch.nn.Identity)
+ assert not any(tensor.is_meta for tensor in model.state_dict().values())
+ assert any(name.startswith("language_model.layers.") for name, _ in model.named_parameters())
+ # Sized from the filtered dict, so the tower is not reserved for either.
+ language_bytes = sum(v.nelement() * v.element_size() for k, v in state_dict.items() if not k.startswith("visual."))
+ assert run.reserved and max(run.reserved) <= language_bytes
+ assert language_bytes < sum(v.nelement() * v.element_size() for v in state_dict.values())
+
+
def test_a_dense_text_encoder_still_loads(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
"""The other half, and the only end-to-end coverage this branch has: an ordinary encoder is
built, filled, and passes the meta-device check."""
diff --git a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py
index 19aff41fba..2c828de4f7 100644
--- a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py
+++ b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py
@@ -24,6 +24,22 @@ from invokeai.backend.model_manager.taxonomy import Krea2VariantType, Qwen3VLVar
from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
+class _TinyVisionTowerHost(torch.nn.Module):
+ """A model whose only relevant feature is that it has a tower to drop."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.visual = _TinyVisionTower()
+
+
+class _TinyVisionTower(torch.nn.Module):
+ """Stands in for `Qwen3VLModel.visual`, which the encoder loaders drop before loading."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.proj = torch.nn.Linear(2, 2, bias=False)
+
+
class _TinyKrea2Transformer(torch.nn.Module):
def __init__(self, **_kwargs) -> None:
super().__init__()
@@ -248,6 +264,7 @@ def test_checkpoint_encoder_loader_decodes_int8_and_does_not_call_it_fp8(monkeyp
def __init__(self) -> None:
super().__init__()
self.language_model = _TinyLanguageModel()
+ self.visual = _TinyVisionTower()
@classmethod
def _from_config(cls, _config):
@@ -297,7 +314,8 @@ def test_directory_encoder_loader_reaches_transformers_from_pretrained(monkeypat
loader = object.__new__(Qwen3VLEncoderLoader)
text_config = SimpleNamespace(rope_parameters={"rope_type": "default"}, rope_scaling=None)
encoder_config = SimpleNamespace(text_config=text_config)
- loaded_model = object()
+ # Carries a vision tower, because the loader drops it on what `from_pretrained` returns.
+ loaded_model = _TinyVisionTowerHost()
from_pretrained = MagicMock(return_value=loaded_model)
monkeypatch.setattr(
@@ -520,6 +538,10 @@ def test_the_encoder_names_itself_when_refusing_an_unmarked_int8_weight(monkeypa
state_dict = {"model.layers.0.self_attn.q_proj.weight": torch.zeros(4, CONVROT_GROUP_SIZE, dtype=torch.int8)}
class _TinyEncoder(torch.nn.Module):
+ def __init__(self) -> None:
+ super().__init__()
+ self.visual = _TinyVisionTower()
+
@classmethod
def _from_config(cls, _config):
return cls()
@@ -592,6 +614,7 @@ def test_a_merged_encoder_checkpoint_is_not_mistaken_for_a_mixed_format_one(
def __init__(self) -> None:
super().__init__()
self.language_model = _TinyLanguageModel()
+ self.visual = _TinyVisionTower()
@classmethod
def _from_config(cls, _config):
diff --git a/tests/backend/model_manager/load/test_qwen3_vl_visual_tower.py b/tests/backend/model_manager/load/test_qwen3_vl_visual_tower.py
new file mode 100644
index 0000000000..091d9cf9b3
--- /dev/null
+++ b/tests/backend/model_manager/load/test_qwen3_vl_visual_tower.py
@@ -0,0 +1,302 @@
+"""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.
+
+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
+`model_loaders/minimax_h3.py`; nothing here is reachable from it.
+"""
+
+import json
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+import torch
+
+from invokeai.backend.model_manager.configs.qwen3_vl_encoder import (
+ Qwen3VLEncoder_Checkpoint_Config,
+ Qwen3VLEncoder_Qwen3VLEncoder_Config,
+)
+from invokeai.backend.model_manager.load.model_loaders.krea2 import (
+ Qwen3VLEncoderCheckpointLoader,
+ Qwen3VLEncoderLoader,
+)
+from invokeai.backend.model_manager.taxonomy import Qwen3VLVariantType, SubModelType
+from invokeai.backend.model_manager.util.qwen3_vl import (
+ drop_qwen3vl_visual_tower,
+ drop_qwen3vl_visual_tower_keys,
+)
+from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, build_regular_hadamard
+from tests.backend.model_manager.load.qwen3vl_gguf_fixture import tiny_qwen3vl_config
+
+# --- the key filter -------------------------------------------------------------------------------
+
+
+ "key",
+ [
+ "visual.blocks.0.attn.qkv.weight",
+ "model.visual.blocks.0.attn.qkv.weight",
+ "model.visual.pos_embed.weight",
+ # A sidecar has to leave with its weight. The sharp case is the int8 branch, which is selected
+ # purely by surviving `.comfy_quant` markers: an orphaned visual marker would route the whole
+ # checkpoint into int8 handling for a module path the model no longer has.
+ "model.visual.blocks.0.attn.qkv.comfy_quant",
+ "model.visual.blocks.0.attn.qkv.weight_scale",
+ # ComfyUI writes the reversed spelling too, which is why the filter matches on the module
+ # path prefix rather than on a list of known suffixes.
+ "model.visual.blocks.0.attn.qkv.scale_weight",
+ ],
+)
+def test_visual_tower_keys_are_dropped(key: str) -> None:
+ assert drop_qwen3vl_visual_tower_keys({key: "t"}) == {}
+
+
+ "key",
+ [
+ "model.layers.0.self_attn.q_proj.weight",
+ "language_model.layers.0.self_attn.q_proj.weight",
+ "model.embed_tokens.weight",
+ "model.norm.weight",
+ # Not the vision tower: a language-model module that merely contains the substring.
+ "model.layers.0.visualization.weight",
+ ],
+)
+def test_language_tower_keys_survive(key: str) -> None:
+ assert drop_qwen3vl_visual_tower_keys({key: "t"}) == {key: "t"}
+
+
+def test_non_string_keys_survive() -> None:
+ assert drop_qwen3vl_visual_tower_keys({0: "t"}) == {0: "t"}
+
+
+def test_a_model_without_a_tower_is_refused_rather_than_given_a_dead_attribute(tmp_path: Path) -> None:
+ """`setattr` would happily invent `visual` on anything. On the `from_pretrained` paths nothing
+ else would notice a renamed tower: it would load, a dead stub would sit beside it, and the
+ encoder would keep every byte this is meant to save."""
+ with pytest.raises(RuntimeError, match="no Qwen3-VL visual tower"):
+ drop_qwen3vl_visual_tower(torch.nn.Module())
+
+
+def test_a_model_without_a_tower_is_tolerated_when_the_caller_says_so() -> None:
+ """Ideogram 4 builds whatever its folder's config declares, so a tower-less encoder is a shape it
+ may legitimately meet rather than a sign the architecture moved."""
+ assert drop_qwen3vl_visual_tower(torch.nn.Module(), required=False) is False
+
+
+# --- the claim the whole change rests on ----------------------------------------------------------
+
+
+def test_the_conditioning_is_unchanged_without_the_tower() -> None:
+ """The justification for dropping the tower is a property of `Qwen3VLModel.forward` that a
+ transformers upgrade can quietly take away. This is the only path that can hold both towers, so
+ it is the only place the before/after comparison can be made at all.
+
+ Run through the exact call the Krea-2 invocation makes, including the 3-way expanded mRoPE
+ position ids.
+ """
+ model = _tiny_encoder().eval()
+ input_ids = torch.tensor([[1, 2, 3, 4]])
+ attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
+ position_ids = (attention_mask.long().cumsum(dim=-1) - 1).clamp(min=0).unsqueeze(0).expand(3, -1, -1)
+
+ def encode():
+ with torch.no_grad():
+ return model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ output_hidden_states=True,
+ use_cache=False,
+ return_dict=True,
+ ).hidden_states
+
+ with_tower = encode()
+ drop_qwen3vl_visual_tower(model)
+ without_tower = encode()
+
+ assert len(with_tower) == len(without_tower)
+ for index, (before, after) in enumerate(zip(with_tower, without_tower, strict=True)):
+ assert torch.equal(before, after), f"hidden state {index} changed when the tower was dropped"
+
+
+# --- the load paths -------------------------------------------------------------------------------
+
+
+def _tiny_encoder(**config_kwargs):
+ """A materialized tiny Qwen3-VL, small enough to save and reload in a test."""
+ from transformers import Qwen3VLModel
+
+ torch.manual_seed(0)
+ return Qwen3VLModel(tiny_qwen3vl_config(**config_kwargs))
+
+
+def _assert_tower_gone(model) -> None:
+ assert isinstance(model.visual, torch.nn.Identity)
+ assert list(model.visual.parameters()) == []
+ # The language tower is untouched and complete -- the point is to drop the tower, not to lose
+ # weights with it.
+ assert [name for name, p in model.named_parameters() if p.is_meta] == []
+ assert any(name.startswith("language_model.layers.") for name, _ in model.named_parameters())
+
+
+def _checkpoint_loader(monkeypatch, te_config) -> Qwen3VLEncoderCheckpointLoader:
+ loader = object.__new__(Qwen3VLEncoderCheckpointLoader)
+ loader._ram_cache = SimpleNamespace(make_room=MagicMock())
+ loader._torch_device = torch.device("cpu")
+ loader._logger = MagicMock()
+ loader._load_hf_config = lambda _config: te_config
+ loader._apply_fp8_to_nn_module = lambda *a, **k: None
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_torch_device",
+ lambda: torch.device("cpu"),
+ )
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_bfloat16_safe_dtype",
+ lambda _device: torch.float32,
+ )
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.krea2._device_supports_fp8_storage",
+ lambda _device, _logger: False,
+ )
+ return loader
+
+
+def _write_checkpoint(path: Path, state_dict: dict[str, torch.Tensor]) -> Qwen3VLEncoder_Checkpoint_Config:
+ from safetensors.torch import save_file
+
+ save_file({k: v.contiguous() for k, v in state_dict.items()}, str(path))
+ return Qwen3VLEncoder_Checkpoint_Config.model_construct(
+ path=str(path), variant=Qwen3VLVariantType.Qwen3VL_4B, name="tiny"
+ )
+
+
[email protected]("prefixed", [False, True], ids=["transformers_layout", "comfyui_layout"])
+def test_the_single_file_loader_drops_the_tower(monkeypatch, tmp_path: Path, prefixed: bool) -> None:
+ """ComfyUI single-file checkpoints bundle both towers under one ``model.`` prefix; the
+ transformers spelling keeps them apart. Both spellings must lose the tower."""
+ reference = _tiny_encoder()
+ state_dict = dict(reference.state_dict())
+ if prefixed:
+ state_dict = {f"model.{k}": v for k, v in state_dict.items()}
+ config = _write_checkpoint(tmp_path / "qwen3vl_tiny.safetensors", state_dict)
+
+ model = _checkpoint_loader(monkeypatch, tiny_qwen3vl_config())._load_text_encoder(config)
+
+ _assert_tower_gone(model)
+ # The language weights are the ones the file carried, not re-initialised ones.
+ torch.testing.assert_close(model.language_model.embed_tokens.weight, reference.language_model.embed_tokens.weight)
+
+
+def test_the_single_file_loader_reserves_only_for_what_it_keeps(monkeypatch, tmp_path: Path) -> None:
+ """Asserted on the bytes the loader asks the cache to free, which is the observable contract --
+ the cache evicts other resident models to honour it.
+
+ Note this is the loader's own reservation. `ModelLoader._load_and_cache` separately reserves the
+ file's on-disk size before `_load_model` runs, and that one still counts the tower; over-
+ reserving is safe and pre-existing, but it means this saving is not the whole story.
+ """
+ reference = _tiny_encoder()
+ state_dict = dict(reference.state_dict())
+ config = _write_checkpoint(tmp_path / "qwen3vl_tiny.safetensors", state_dict)
+ language_bytes = sum(v.nelement() * v.element_size() for k, v in state_dict.items() if not k.startswith("visual."))
+ total_bytes = sum(v.nelement() * v.element_size() for v in state_dict.values())
+
+ loader = _checkpoint_loader(monkeypatch, tiny_qwen3vl_config())
+ loader._load_text_encoder(config)
+
+ reserved = [call.args[0] for call in loader._ram_cache.make_room.call_args_list]
+ assert reserved, "the loader no longer reserves; this test no longer covers what it claims"
+ assert max(reserved) <= language_bytes
+ # The fixture has to make the difference visible, or the assertion above proves nothing.
+ assert language_bytes < total_bytes
+
+
+def test_the_int8_branch_drops_the_tower_too(monkeypatch, tmp_path: Path) -> None:
+ """The drop sits before the int8/dense split, and it has to stay there. Moved into the dense
+ branch, an int8-convrot encoder would refuse to load at all: its visual tensors are gone from the
+ state dict, so the tower would stay on the meta device and the completeness sweep would reject
+ it -- a hard load failure on a supported container, with the dense tests still green.
+ """
+ from transformers import Qwen3VLModel
+
+ te_config = tiny_qwen3vl_config()
+ # `install_int8_convrot_layers` rotates in groups, so the quantized Linear's input width has to be
+ # the group size. Everything else stays at the fixture's dimensions.
+ 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
+
+ torch.manual_seed(0)
+ state_dict = dict(Qwen3VLModel(te_config).state_dict())
+
+ # One language Linear carries the int8-convrot payload; that is all it takes to select the branch.
+ layer = "language_model.layers.0.self_attn.q_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)
+
+ config = _write_checkpoint(tmp_path / "qwen3vl_int8.safetensors", state_dict)
+
+ model = _checkpoint_loader(monkeypatch, te_config)._load_text_encoder(config)
+
+ _assert_tower_gone(model)
+
+
+def test_the_bundled_pipeline_encoder_drops_the_tower(monkeypatch, tmp_path: Path) -> None:
+ """The path a starter model actually takes. Both loader nodes fall back to the pipeline's own
+ encoder when no standalone one is wired up, so without this the headline saving never reaches
+ the users who install "Krea-2 Turbo" and press Invoke.
+ """
+ from invokeai.backend.model_manager.configs.main import Main_Diffusers_Krea2_Config
+ from invokeai.backend.model_manager.load.model_loaders.krea2 import Krea2DiffusersModel
+
+ encoder = _tiny_encoder()
+ config = Main_Diffusers_Krea2_Config.model_construct(path=str(tmp_path), repo_variant=None)
+ loader = object.__new__(Krea2DiffusersModel)
+ loader.get_hf_load_class = lambda _path, _submodel: SimpleNamespace(from_pretrained=MagicMock(return_value=encoder))
+ loader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: model
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.krea2.AutoConfig.from_pretrained",
+ lambda *_a, **_k: encoder.config,
+ )
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_torch_device",
+ lambda: torch.device("cpu"),
+ )
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_bfloat16_safe_dtype",
+ lambda _device: torch.float32,
+ )
+
+ model = loader._load_model(config, SubModelType.TextEncoder)
+
+ _assert_tower_gone(model)
+
+
+def test_the_folder_loader_drops_the_tower(tmp_path: Path) -> None:
+ """The diffusers-directory path loads through `from_pretrained`, which builds the module tree
+ itself, so the tower is read and then freed rather than skipped."""
+ _tiny_encoder().save_pretrained(tmp_path)
+ config = Qwen3VLEncoder_Qwen3VLEncoder_Config.model_construct(
+ path=str(tmp_path), variant=Qwen3VLVariantType.Qwen3VL_4B, name="tiny"
+ )
+
+ loader = object.__new__(Qwen3VLEncoderLoader)
+ loader._logger = MagicMock()
+
+ model = loader._load_model(config, SubModelType.TextEncoder)
+
+ _assert_tower_gone(model)
diff --git a/tests/backend/quantization/test_fp8_scaled.py b/tests/backend/quantization/test_fp8_scaled.py
index 6d8b28a49b..364d4dcfc6 100644
--- a/tests/backend/quantization/test_fp8_scaled.py
+++ b/tests/backend/quantization/test_fp8_scaled.py
@@ -332,10 +332,8 @@ class TestQwen3VLKeyRemap:
def test_scale_keys_and_hint_paths_land_on_the_same_module(self):
"""attach_fp8_scales resolves hint paths against the *model*, so the state-dict remap and the
hint remap must agree - otherwise every recovered scale silently matches nothing."""
- from invokeai.backend.model_manager.load.model_loaders.krea2 import (
- _qwen3vl_target_key,
- _remap_qwen3vl_singlefile_keys,
- )
+ from invokeai.backend.model_manager.load.model_loaders.krea2 import _remap_qwen3vl_singlefile_keys
+ from invokeai.backend.model_manager.util.qwen3_vl import qwen3vl_target_key as _qwen3vl_target_key
q, scale = _fp8_weight(32, 16)
sd = _remap_qwen3vl_singlefile_keys(