Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(qwen-image): apply LoRA text-encoder layers to the Qwen2.5-VL encoder (#10184)
Alexander Eichhorn2c50a098b5e5
diff --git a/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx b/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdxindex 9e42782d03..adf4b869a7 100644--- a/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx@@ -226,5 +226,7 @@ Plain Qwen-Image LoRAs also load in ComfyUI's `diffusion_model.` key layout and(`base_model.model.`) when they train the blocks' modulation or MLP layers; see the[family page](/users-guide/models/local-models/qwen-image/#lora).+Qwen-Image LoRAs also patch the Qwen2.5-VL encoder when the file has text-encoder layers; see the same page.+[PiD decoders](/users-guide/image-generation/advanced-topics/pid-decode/) load for FLUX.1, FLUX.2, SD 3, SDXL andQwen-Image (v1 and v1.5, bf16 and int8 builds). FLUX.3 and MOSS-Image use the FLUX.2 decoders.diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image.mdxindex 34cedb6b6a..8154e84908 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image.mdx@@ -153,8 +153,15 @@ Image**; connect an **Image to Latents - Qwen Image** node to the **Reference La## LoRA-Qwen Image LoRAs (diffusers PEFT, Kohya and LoKR formats) are supported and apply to the transformer.-In the workflow editor use **Apply LoRA - Qwen Image** or **Apply LoRA Collection - Qwen Image**.+Qwen Image LoRAs (diffusers PEFT, Kohya and LoKR formats) are supported and apply to the transformer and,+when the file has text-encoder layers, to the Qwen2.5-VL encoder too. This holds for every encoder build,+including the **Encoder quantization** setting. DoRA layers on the encoder need unpacked weights: they fail+with int8 or nf4 quantization and with packed nvfp4 encoders, so set **Encoder quantization** to **None** and+use a bf16 or fp8 encoder. A LoRA that holds only text-encoder layers is not recognized on install.++In the workflow editor use **Apply LoRA - Qwen Image** or **Apply LoRA Collection - Qwen Image**. Route the+encoder through the LoRA node as well as the transformer: connect the node's **Qwen VL Encoder** output to+the prompt nodes, otherwise the LoRA's text-encoder layers stay unused. The LoRA node logs a warning when it sees this.Plain LoRAs saved in ComfyUI's layout, whose keys start with `diffusion_model.`, and raw PEFT adapters(`base_model.model.`) load as well, provided they train the blocks' modulation or MLP layers (`img_mod`,diff --git a/invokeai/app/invocations/model.py b/invokeai/app/invocations/model.pyindex 02f96dd09a..f1e84fed4c 100644--- a/invokeai/app/invocations/model.py+++ b/invokeai/app/invocations/model.py@@ -118,6 +118,7 @@ class QwenVLEncoderField(BaseModel):tokenizer: ModelIdentifierField = Field(description="Info to load tokenizer submodel")text_encoder: ModelIdentifierField = Field(description="Info to load text_encoder submodel")+ loras: list[LoRAField] = Field(default_factory=list, description="LoRAs to apply on model loading")class Qwen3EncoderField(BaseModel):diff --git a/invokeai/app/invocations/qwen_image/qwen_image_lora_loader.py b/invokeai/app/invocations/qwen_image/qwen_image_lora_loader.pyindex dea5fc3df5..c644df2c1e 100644--- a/invokeai/app/invocations/qwen_image/qwen_image_lora_loader.py+++ b/invokeai/app/invocations/qwen_image/qwen_image_lora_loader.py@@ -8,9 +8,25 @@ from invokeai.app.invocations.baseinvocation import (invocation_output,)from invokeai.app.invocations.fields import FieldDescriptions, Input, InputField, OutputField-from invokeai.app.invocations.model import LoRAField, ModelIdentifierField, TransformerField+from invokeai.app.invocations.model import LoRAField, ModelIdentifierField, QwenVLEncoderField, TransformerFieldfrom invokeai.app.services.shared.invocation_context import InvocationContextfrom invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType+from invokeai.backend.patches.lora_conversions.qwen_image_lora_constants import QWEN_IMAGE_LORA_QWEN_VL_PREFIX+from invokeai.backend.patches.model_patch_raw import ModelPatchRaw+++def _warn_if_encoder_layers_are_unused(+ context: InvocationContext, lora: ModelIdentifierField, *, transformer_only: bool+) -> None:+ """Saved workflows predate the encoder connection, so a LoRA with text-encoder layers would silently lose them."""+ if not transformer_only:+ return+ patch = context.models.load(lora).model+ if isinstance(patch, ModelPatchRaw) and any(key.startswith(QWEN_IMAGE_LORA_QWEN_VL_PREFIX) for key in patch.layers):+ context.logger.warning(+ f'LoRA "{context.models.get_config(lora.key).name}" has text-encoder layers, but no Qwen VL Encoder is '+ "connected to this node, so they are not applied. Connect the Qwen VL Encoder through the LoRA node."+ )@invocation_output("qwen_image_lora_loader_output")@@ -20,6 +36,9 @@ class QwenImageLoRALoaderOutput(BaseInvocationOutput):transformer: Optional[TransformerField] = OutputField(default=None, description=FieldDescriptions.transformer, title="Transformer")+ qwen_vl_encoder: Optional[QwenVLEncoderField] = OutputField(+ default=None, description=FieldDescriptions.qwen_vl_encoder, title="Qwen VL Encoder"+ )@invocation(@@ -27,11 +46,11 @@ class QwenImageLoRALoaderOutput(BaseInvocationOutput):title="Apply LoRA - Qwen Image",tags=["lora", "model", "qwen_image"],category="model",- version="1.0.0",+ version="1.1.0",classification=Classification.Prototype,)class QwenImageLoRALoaderInvocation(BaseInvocation):- """Apply a LoRA model to a Qwen Image transformer."""+ """Apply a LoRA model to a Qwen Image transformer and/or Qwen2.5-VL text encoder."""lora: ModelIdentifierField = InputField(description=FieldDescriptions.lora_model,@@ -46,6 +65,12 @@ class QwenImageLoRALoaderInvocation(BaseInvocation):input=Input.Connection,title="Transformer",)+ qwen_vl_encoder: QwenVLEncoderField | None = InputField(+ default=None,+ description=FieldDescriptions.qwen_vl_encoder,+ input=Input.Connection,+ title="Qwen VL Encoder",+ )def invoke(self, context: InvocationContext) -> QwenImageLoRALoaderOutput:lora_key = self.lora.key@@ -55,9 +80,14 @@ class QwenImageLoRALoaderInvocation(BaseInvocation):if self.transformer and any(lora.lora.key == lora_key for lora in self.transformer.loras):raise ValueError(f'LoRA "{lora_key}" already applied to transformer.')+ if self.qwen_vl_encoder and any(lora.lora.key == lora_key for lora in self.qwen_vl_encoder.loras):+ raise ValueError(f'LoRA "{lora_key}" already applied to Qwen VL encoder.')output = QwenImageLoRALoaderOutput()+ _warn_if_encoder_layers_are_unused(+ context, self.lora, transformer_only=self.transformer is not None and self.qwen_vl_encoder is None+ )if self.transformer is not None:output.transformer = self.transformer.model_copy(deep=True)output.transformer.loras.append(@@ -66,6 +96,14 @@ class QwenImageLoRALoaderInvocation(BaseInvocation):weight=self.weight,))+ if self.qwen_vl_encoder is not None:+ output.qwen_vl_encoder = self.qwen_vl_encoder.model_copy(deep=True)+ output.qwen_vl_encoder.loras.append(+ LoRAField(+ lora=self.lora,+ weight=self.weight,+ )+ )return output@@ -75,11 +113,11 @@ class QwenImageLoRALoaderInvocation(BaseInvocation):title="Apply LoRA Collection - Qwen Image",tags=["lora", "model", "qwen_image"],category="model",- version="1.0.1",+ version="1.1.0",classification=Classification.Prototype,)class QwenImageLoRACollectionLoader(BaseInvocation):- """Applies a collection of LoRAs to a Qwen Image transformer."""+ """Applies a collection of LoRAs to a Qwen Image transformer and/or Qwen2.5-VL text encoder."""loras: Optional[LoRAField | list[LoRAField]] = InputField(default=None,@@ -94,6 +132,12 @@ class QwenImageLoRACollectionLoader(BaseInvocation):input=Input.Connection,title="Transformer",)+ qwen_vl_encoder: QwenVLEncoderField | None = InputField(+ default=None,+ description=FieldDescriptions.qwen_vl_encoder,+ input=Input.Connection,+ title="Qwen VL Encoder",+ )def invoke(self, context: InvocationContext) -> QwenImageLoRALoaderOutput:output = QwenImageLoRALoaderOutput()@@ -103,6 +147,9 @@ class QwenImageLoRACollectionLoader(BaseInvocation):if self.transformer is not None:output.transformer = self.transformer.model_copy(deep=True)+ if self.qwen_vl_encoder is not None:+ output.qwen_vl_encoder = self.qwen_vl_encoder.model_copy(deep=True)+for lora in loras:if lora is None:continue@@ -112,8 +159,13 @@ class QwenImageLoRACollectionLoader(BaseInvocation):raise Exception(f"Unknown lora: {lora.lora.key}!")added_loras.append(lora.lora.key)+ _warn_if_encoder_layers_are_unused(+ context, lora.lora, transformer_only=self.transformer is not None and self.qwen_vl_encoder is None+ )if self.transformer is not None and output.transformer is not None:output.transformer.loras.append(lora)+ if self.qwen_vl_encoder is not None and output.qwen_vl_encoder is not None:+ output.qwen_vl_encoder.loras.append(lora)return outputdiff --git a/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py b/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.pyindex c44de4662e..736c2dcf10 100644--- a/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py+++ b/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py@@ -2,8 +2,9 @@ import gcimport jsonimport mmapimport traceback+from contextlib import ExitStackfrom pathlib import Path-from typing import Any, Callable, Literal+from typing import Any, Callable, Iterator, Literalimport torchfrom PIL import Image as PILImage@@ -20,10 +21,18 @@ from invokeai.app.invocations.model import QwenVLEncoderFieldfrom invokeai.app.invocations.primitives import QwenImageConditioningOutputfrom invokeai.app.services.shared.invocation_context import InvocationContextfrom invokeai.backend.model_manager.load.model_cache.model_cache import MB, MODEL_LOAD_LOCK+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (+ AUTOCAST_MODULE_TYPE_MAPPING,+ BNB_LINEAR_TYPE_MAPPING,+ apply_custom_layers_to_model,+)from invokeai.backend.model_manager.load.model_util import calc_model_size_by_fsfrom invokeai.backend.model_manager.taxonomy import ModelFormat+from invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpec+from invokeai.backend.patches.lora_conversions.qwen_image_lora_constants import QWEN_IMAGE_LORA_QWEN_VL_PREFIX+from invokeai.backend.patches.model_patch_raw import ModelPatchRawfrom invokeai.backend.quantization.bnb_cast_notice import silence_int8_cast_notice-from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes+from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes, requires_sidecar_patchingfrom invokeai.backend.qwen2_5_vl.qwen2_5_vl_assets import (load_bundled_qwen2_5_vl_preprocessor_config_dict,tokenizer_can_encode,@@ -67,6 +76,18 @@ _IMAGE_PLACEHOLDER = "<|vision_start|><|image_pad|><|vision_end|>"_LoadedEncoder = tuple[torch.nn.Module, torch.device, Callable[[], None]]+def _make_bnb_layers_patchable(text_encoder: torch.nn.Module) -> None:+ """Give the BitsAndBytes Linears of a `from_pretrained`-built encoder the sidecar-patch API.++ transformers builds plain `bnb.nn.Linear8bitLt` / `Linear4bit` layers, which cannot hold a LoRA. Only this model is+ converted (the layers share state with the originals), and unconverted Linears such as `lm_head` come along through+ the standard mapping. Layers without a patch behave as before.+ Must run before the model's first forward: the plain int8 forward moves CB/SCB off the weight, where the custom+ layer reads them.+ """+ apply_custom_layers_to_model(text_encoder, type_mapping={**AUTOCAST_MODULE_TYPE_MAPPING, **BNB_LINEAR_TYPE_MAPPING})++def _read_checkpoint(encoder_path: Path) -> dict[str, torch.Tensor] | None:"""Map the encoder's safetensors shards and pull their pages into memory.@@ -393,18 +414,64 @@ class QwenImageTextEncoderInvocation(BaseInvocation):dequant_bytes = peak_dequant_transient_bytes(text_encoder_info.model, TorchDevice.choose_bfloat16_safe_dtype(text_encoder_info.compute_device))- ctx = text_encoder_info.model_on_device(working_mem_bytes=dequant_bytes)- _, text_encoder = ctx.__enter__()- # Use the encoder's intended compute device, not its current parameter residency: partial loading may have- # temporarily offloaded all weights to RAM, which would wrongly run the whole encode on the CPU.- device = text_encoder_info.compute_device- assert isinstance(text_encoder, Qwen2_5_VLForConditionalGeneration)-- def release() -> None:- ctx.__exit__(None, None, None)+ encoder_format = context.models.get_config(self.qwen_vl_encoder.text_encoder).format+ # The stack holds the model lock and then the patches, so closing it undoes the patches before the lock is+ # released. `pop_all` hands that over to the caller only once everything succeeded; a failure while patching+ # still releases the lock here.+ with ExitStack() as stack:+ cached_weights, text_encoder = stack.enter_context(+ text_encoder_info.model_on_device(working_mem_bytes=dequant_bytes)+ )+ # Use the encoder's intended compute device, not its current parameter residency: partial loading may have+ # temporarily offloaded all weights to RAM, which would wrongly run the whole encode on the CPU.+ device = text_encoder_info.compute_device+ assert isinstance(text_encoder, Qwen2_5_VLForConditionalGeneration)+ # A packed build (nvfp4, GGUF) cannot be patched in place, so its LoRA goes in as a sidecar.+ self._apply_lora_patches(+ context,+ stack,+ text_encoder,+ device,+ cached_weights=cached_weights,+ force_sidecar_patching=requires_sidecar_patching(text_encoder, encoder_format),+ )+ release = stack.pop_all().closereturn text_encoder, device, release+ def _lora_iterator(self, context: InvocationContext) -> Iterator[PatchSpec]:+ """Iterate over the LoRA models to apply to the Qwen2.5-VL text encoder."""+ for lora in self.qwen_vl_encoder.loras:+ lora_info = context.models.load(lora.lora)+ if not isinstance(lora_info.model, ModelPatchRaw):+ raise TypeError(+ f"Expected ModelPatchRaw for LoRA '{lora.lora.key}', got {type(lora_info.model).__name__}."+ )+ yield (lora_info.model, lora.weight, lora_info.model_in_ram())++ def _apply_lora_patches(+ self,+ context: InvocationContext,+ stack: ExitStack,+ text_encoder: torch.nn.Module,+ device: torch.device,+ *,+ cached_weights: dict[str, torch.Tensor] | None,+ force_sidecar_patching: bool,+ ) -> None:+ """Patch the encoder with the connected LoRAs until `stack` closes. The caller says whether the layers are+ quantized (`force_sidecar_patching`): the patcher does not detect that itself."""+ stack.enter_context(+ LayerPatcher.apply_smart_model_patches(+ model=text_encoder,+ patches=self._lora_iterator(context),+ prefix=QWEN_IMAGE_LORA_QWEN_VL_PREFIX,+ dtype=TorchDevice.choose_bfloat16_safe_dtype(device),+ cached_weights=cached_weights,+ force_sidecar_patching=force_sidecar_patching,+ )+ )+def _load_quantized_encoder(self, context: InvocationContext) -> _LoadedEncoder:"""Load the text encoder with BitsAndBytes quantization, bypassing the model cache.@@ -472,6 +539,8 @@ class QwenImageTextEncoderInvocation(BaseInvocation):# installed transformers.vram_available: int | None = Nonestate_dict: dict[str, torch.Tensor] | None = None+ text_encoder: torch.nn.Module | None = None+ patches = ExitStack()try:# A CPU execution device has no VRAM to make room in (recent bitsandbytes can quantize on the CPU).if quantized_bytes > 0 and device.type != "cpu":@@ -497,6 +566,13 @@ class QwenImageTextEncoderInvocation(BaseInvocation):dtype=torch.bfloat16,local_files_only=True,)++ if self.qwen_vl_encoder.loras:+ _make_bnb_layers_patchable(text_encoder)+ # Quantized layers cannot be patched in place, and there are no cached weights to restore from.+ self._apply_lora_patches(+ context, patches, text_encoder, device, cached_weights=None, force_sidecar_patching=True+ )except BaseException as exc:# A failed load (an OOM is the expected way) leaves the partially built model referenced only by the# in-flight traceback's frames. Without releasing it here its weights stay allocated until the session@@ -504,20 +580,27 @@ class QwenImageTextEncoderInvocation(BaseInvocation):# the very leak `_encode` guards against on the success path. This frame is still executing and is# skipped by `clear_frames`, hence the explicit drop of the checkpoint.traceback.clear_frames(exc.__traceback__)+ load_failed = text_encoder is Nonestate_dict = None+ text_encoder = Nonegc.collect()try:TorchDevice.empty_cache()except Exception as cache_exc:# A sick device context fails here too; the original error is the one worth reporting.context.logger.warning(f"Could not empty the device cache after the failed load: {cache_exc}")- if isinstance(exc, torch.OutOfMemoryError):+ # Only a failed load is reported as the encoder not fitting; an OOM while patching is not that.+ if load_failed and isinstance(exc, torch.OutOfMemoryError):raise torch.OutOfMemoryError(self._oom_message(device, quantized_bytes, vram_available)) from excraise+ assert text_encoder is not None+# Hand the model out without keeping a reference in this closure, so that once `_encode` drops its own the- # weights are actually free by the time empty_cache() runs.+ # weights are actually free by the time empty_cache() runs. The patches are undone first: their generators+ # hold the model, and are finished once the stack is closed.def cleanup() -> None:+ patches.close()gc.collect()TorchDevice.empty_cache()diff --git a/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/torch_module_autocast.py b/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/torch_module_autocast.pyindex cbd60e1b37..3c2ccb0c96 100644--- a/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/torch_module_autocast.py+++ b/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/torch_module_autocast.py@@ -54,8 +54,18 @@ AUTOCAST_MODULE_TYPE_MAPPING: dict[type[torch.nn.Module], type[torch.nn.Module]]NVFP4Linear: CustomNVFP4Linear,}+# The plain bitsandbytes Linear types (as built by `transformers`' `from_pretrained(quantization_config=...)`) and the+# custom layers that can wrap them. Empty when bitsandbytes is unavailable. Deliberately not part of+# AUTOCAST_MODULE_TYPE_MAPPING: the model cache would then wrap, and `remove_custom_layers_from_model` would "unwrap",+# bnb layers of every model, and the INVERSE mapping needs one original type per custom type. The custom layers read the+# same attributes as the plain ones, so a caller that owns a transformers-built bnb model (which bypasses the cache)+# opts in by passing this to `apply_custom_layers_to_model`, to give those layers `add_patch`.+BNB_LINEAR_TYPE_MAPPING: dict[type[torch.nn.Module], type[torch.nn.Module]] = {}+try:# These dependencies are not expected to be present on MacOS.+ import bitsandbytes as bnb+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_invoke_linear_8_bit_lt import (CustomInvokeLinear8bitLt,)@@ -67,6 +77,8 @@ try:AUTOCAST_MODULE_TYPE_MAPPING[InvokeLinear8bitLt] = CustomInvokeLinear8bitLtAUTOCAST_MODULE_TYPE_MAPPING[InvokeLinearNF4] = CustomInvokeLinearNF4+ BNB_LINEAR_TYPE_MAPPING[bnb.nn.Linear8bitLt] = CustomInvokeLinear8bitLt+ BNB_LINEAR_TYPE_MAPPING[bnb.nn.Linear4bit] = CustomInvokeLinearNF4except (ImportError, OSError, RuntimeError) as e: # bnb may import and then fail loading its native libraryrecord_bnb_import_failure(e)@@ -103,9 +115,17 @@ def unwrap_custom_layer(custom_layer: torch.nn.Module, original_layer_type: typereturn original_layer-def apply_custom_layers_to_model(module: torch.nn.Module, device_autocasting_enabled: bool = False):+def apply_custom_layers_to_model(+ module: torch.nn.Module,+ device_autocasting_enabled: bool = False,+ type_mapping: dict[type[torch.nn.Module], type[torch.nn.Module]] | None = None,+):+ """Replace the children of `module` that `type_mapping` knows (default: AUTOCAST_MODULE_TYPE_MAPPING) with custom+ layers, sharing their state. A custom `type_mapping` replaces the default, so merge it in to keep the defaults."""+ if type_mapping is None:+ type_mapping = AUTOCAST_MODULE_TYPE_MAPPINGfor name, submodule in module.named_children():- override_type = AUTOCAST_MODULE_TYPE_MAPPING.get(type(submodule), None)+ override_type = type_mapping.get(type(submodule), None)if override_type is not None:custom_layer = wrap_custom_layer(submodule, override_type)# TODO(ryand): In the future, we should manage this flag on a per-module basis.@@ -113,7 +133,7 @@ def apply_custom_layers_to_model(module: torch.nn.Module, device_autocasting_enasetattr(module, name, custom_layer)else:# Recursively apply to submodules- apply_custom_layers_to_model(submodule, device_autocasting_enabled)+ apply_custom_layers_to_model(submodule, device_autocasting_enabled, type_mapping)def remove_custom_layers_from_model(module: torch.nn.Module):diff --git a/invokeai/backend/patches/lora_conversions/qwen_image_lora_constants.py b/invokeai/backend/patches/lora_conversions/qwen_image_lora_constants.pyindex 727ee5a428..e1b1d5bcbd 100644--- a/invokeai/backend/patches/lora_conversions/qwen_image_lora_constants.py+++ b/invokeai/backend/patches/lora_conversions/qwen_image_lora_constants.py@@ -3,3 +3,6 @@# Prefix for Qwen Image Edit transformer LoRA layersQWEN_IMAGE_EDIT_LORA_TRANSFORMER_PREFIX = "lora_transformer-"++# Prefix for Qwen2.5-VL text encoder LoRA layers+QWEN_IMAGE_LORA_QWEN_VL_PREFIX = "lora_qwen_vl-"diff --git a/invokeai/backend/patches/lora_conversions/qwen_image_lora_conversion_utils.py b/invokeai/backend/patches/lora_conversions/qwen_image_lora_conversion_utils.pyindex 380fc2fb68..5736d30c60 100644--- a/invokeai/backend/patches/lora_conversions/qwen_image_lora_conversion_utils.py+++ b/invokeai/backend/patches/lora_conversions/qwen_image_lora_conversion_utils.py@@ -1,10 +1,15 @@"""Qwen Image LoRA conversion utilities.-Qwen Image uses QwenImageTransformer2DModel architecture.+Qwen Image uses QwenImageTransformer2DModel architecture, with a Qwen2.5-VL text encoder.Supports multiple LoRA formats:- Diffusers/PEFT: transformer_blocks.0.attn.to_k.lora_down.weight- With prefix: transformer.transformer_blocks.0.attn.to_k.lora_down.weight (also diffusion_model./base_model.model.)- Kohya: lora_unet_transformer_blocks_0_attn_to_k.lora_down.weight (underscores instead of dots)++Text-encoder layers are routed to the Qwen2.5-VL encoder under their own prefix:+- Diffusers/PEFT: text_encoder.model.language_model.layers.0.mlp.down_proj.lora_A.weight (also base_model.model.,+ and OneTrainer's ComfyUI export text_encoders.qwen25_7b.transformer.)+- Kohya: lora_te_model_language_model_layers_0_mlp_down_proj.lora_down.weight"""import re@@ -14,10 +19,49 @@ import torchfrom invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatchfrom invokeai.backend.patches.layers.utils import any_lora_layer_from_state_dict+from invokeai.backend.patches.lora_conversions.kohya_key_utils import (+ INDEX_PLACEHOLDER,+ ParsingTree,+ insert_periods_into_kohya_key,+ kohya_module_path_is_leaf,+)from invokeai.backend.patches.lora_conversions.qwen_image_lora_constants import (QWEN_IMAGE_EDIT_LORA_TRANSFORMER_PREFIX,+ QWEN_IMAGE_LORA_QWEN_VL_PREFIX,)from invokeai.backend.patches.model_patch_raw import ModelPatchRaw+from invokeai.backend.util import InvokeAILogger++_KOHYA_TEXT_ENCODER_PREFIX = "lora_te_"+# `text_encoders.qwen25_7b.transformer.` is OneTrainer's ComfyUI export (`QwenModel.lora_text_encoders`), written beside+# `diffusion_model.` transformer keys.+_DIFFUSERS_TEXT_ENCODER_PREFIXES = (+ "base_model.model.text_encoder.",+ "text_encoder.",+ "text_encoders.qwen25_7b.transformer.",+)++_MLP: ParsingTree = {"gate_proj": {}, "up_proj": {}, "down_proj": {}}++# Linear modules of Qwen2_5_VLForConditionalGeneration (transformers >= 4.52 layout). Kohya keys flatten the dots to+# underscores, and some module names contain underscores themselves, so the tree is what tells them apart.+_KOHYA_TEXT_ENCODER_TREE: ParsingTree = {+ "model": {+ "language_model": {+ "layers": {+ INDEX_PLACEHOLDER: {+ "self_attn": {"q_proj": {}, "k_proj": {}, "v_proj": {}, "o_proj": {}},+ "mlp": _MLP,+ }+ }+ },+ "visual": {+ "blocks": {INDEX_PLACEHOLDER: {"attn": {"qkv": {}, "proj": {}}, "mlp": _MLP}},+ "merger": {"mlp": {"0": {}, "2": {}}},+ },+ },+ "lm_head": {},+}# Regex for Kohya-format Qwen Image LoRA keys.# Example: lora_unet_transformer_blocks_0_attn_to_k@@ -77,12 +121,35 @@ def _convert_kohya_key(kohya_layer: str) -> str | None:return None+def _convert_kohya_text_encoder_key(kohya_layer: str) -> str | None:+ """Convert a `lora_te_*` layer name to a dotted Qwen2.5-VL module path, or None when it names no known Linear.++ Example: lora_te_model_language_model_layers_0_mlp_down_proj -> model.language_model.layers.0.mlp.down_proj+ """+ try:+ module_path = insert_periods_into_kohya_key(+ kohya_layer[len(_KOHYA_TEXT_ENCODER_PREFIX) :], _KOHYA_TEXT_ENCODER_TREE+ )+ except ValueError:+ return None+ # A prefix of a real path (e.g. ...layers.0.mlp) parses cleanly without naming a module.+ return module_path if kohya_module_path_is_leaf(module_path, _KOHYA_TEXT_ENCODER_TREE) else None+++def _warn_unmapped_layers(count: int) -> None:+ if count:+ InvokeAILogger.get_logger(__name__).warning(+ f"Skipped {count} Qwen Image LoRA layer(s) whose key does not name a known transformer or "+ "text-encoder module."+ )++def lora_model_from_qwen_image_state_dict(state_dict: Dict[str, torch.Tensor], alpha: float | None = None) -> ModelPatchRaw:"""Convert a Qwen Image LoRA state dict to a ModelPatchRaw.- Handles three key formats:+ Handles three key formats (text-encoder layers are routed to the Qwen2.5-VL prefix in each):- Diffusers/PEFT: transformer_blocks.0.attn.to_k.lora_down.weight- With prefix: transformer.transformer_blocks.0.attn.to_k.lora_down.weight(also diffusion_model., base_model.model.)@@ -110,15 +177,21 @@ def _convert_kohya_format(state_dict: Dict[str, torch.Tensor], alpha: float | Nogrouped[layer_name] = {}grouped[layer_name][param_name] = value+ unmapped = 0for kohya_layer, layer_dict in grouped.items():- model_path = _convert_kohya_key(kohya_layer)+ if kohya_layer.startswith(_KOHYA_TEXT_ENCODER_PREFIX):+ model_path = _convert_kohya_text_encoder_key(kohya_layer)+ prefix = QWEN_IMAGE_LORA_QWEN_VL_PREFIX+ else:+ model_path = _convert_kohya_key(kohya_layer)+ prefix = QWEN_IMAGE_EDIT_LORA_TRANSFORMER_PREFIXif model_path is None:- continue # Skip unrecognized layers+ unmapped += 1+ continue- layer = any_lora_layer_from_state_dict(layer_dict)- final_key = f"{QWEN_IMAGE_EDIT_LORA_TRANSFORMER_PREFIX}{model_path}"- layers[final_key] = layer+ layers[f"{prefix}{model_path}"] = any_lora_layer_from_state_dict(layer_dict)+ _warn_unmapped_layers(unmapped)return ModelPatchRaw(layers=layers)@@ -131,9 +204,21 @@ def _convert_diffusers_format(state_dict: Dict[str, torch.Tensor], alpha: floatgrouped = _group_by_layer(state_dict)+ unmapped = 0for layer_key, layer_dict in grouped.items():- values = _normalize_lora_keys(layer_dict, alpha)- layer = any_lora_layer_from_state_dict(values)+ # Text-encoder layers first: `base_model.model.` is also in the transformer strip list.+ text_encoder_prefix = next((p for p in _DIFFUSERS_TEXT_ENCODER_PREFIXES if layer_key.startswith(p)), None)+ if text_encoder_prefix is not None:+ module_path = layer_key[len(text_encoder_prefix) :]+ # Only Linears of the current transformers layout can take a patch: the patcher would otherwise reach+ # layers it cannot patch (`patch_embed` is a Conv3d) or crash on them.+ if not kohya_module_path_is_leaf(module_path, _KOHYA_TEXT_ENCODER_TREE):+ unmapped += 1+ continue+ layer = any_lora_layer_from_state_dict(_normalize_lora_keys(layer_dict, alpha))+ layers[f"{QWEN_IMAGE_LORA_QWEN_VL_PREFIX}{module_path}"] = layer+ continue+ layer = any_lora_layer_from_state_dict(_normalize_lora_keys(layer_dict, alpha))clean_key = layer_keyfor prefix in strip_prefixes:if clean_key.startswith(prefix):@@ -142,6 +227,7 @@ def _convert_diffusers_format(state_dict: Dict[str, torch.Tensor], alpha: floatfinal_key = f"{QWEN_IMAGE_EDIT_LORA_TRANSFORMER_PREFIX}{clean_key}"layers[final_key] = layer+ _warn_unmapped_layers(unmapped)return ModelPatchRaw(layers=layers)diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex 8d9b63dff2..96d5433d7a 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -104759,7 +104759,7 @@"category": "model","class": "invocation","classification": "prototype",- "description": "Applies a collection of LoRAs to a Qwen Image transformer.",+ "description": "Applies a collection of LoRAs to a Qwen Image transformer and/or Qwen2.5-VL text encoder.","node_pack": "invokeai","properties": {"id": {@@ -104828,6 +104828,23 @@"orig_required": false,"title": "Transformer"},+ "qwen_vl_encoder": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/QwenVLEncoderField"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Qwen2.5-VL tokenizer, processor and text/vision encoder",+ "field_kind": "input",+ "input": "connection",+ "orig_default": null,+ "orig_required": false,+ "title": "Qwen VL Encoder"+ },"type": {"const": "qwen_image_lora_collection_loader","default": "qwen_image_lora_collection_loader",@@ -104840,7 +104857,7 @@"tags": ["lora", "model", "qwen_image"],"title": "Apply LoRA Collection - Qwen Image","type": "object",- "version": "1.0.1",+ "version": "1.1.0","output": {"$ref": "#/components/schemas/QwenImageLoRALoaderOutput"}@@ -104849,7 +104866,7 @@"category": "model","class": "invocation","classification": "prototype",- "description": "Apply a LoRA model to a Qwen Image transformer.",+ "description": "Apply a LoRA model to a Qwen Image transformer and/or Qwen2.5-VL text encoder.","node_pack": "invokeai","properties": {"id": {@@ -104921,6 +104938,23 @@"orig_required": false,"title": "Transformer"},+ "qwen_vl_encoder": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/QwenVLEncoderField"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Qwen2.5-VL tokenizer, processor and text/vision encoder",+ "field_kind": "input",+ "input": "connection",+ "orig_default": null,+ "orig_required": false,+ "title": "Qwen VL Encoder"+ },"type": {"const": "qwen_image_lora_loader","default": "qwen_image_lora_loader",@@ -104933,7 +104967,7 @@"tags": ["lora", "model", "qwen_image"],"title": "Apply LoRA - Qwen Image","type": "object",- "version": "1.0.0",+ "version": "1.1.0","output": {"$ref": "#/components/schemas/QwenImageLoRALoaderOutput"}@@ -104957,6 +104991,21 @@"title": "Transformer","ui_hidden": false},+ "qwen_vl_encoder": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/QwenVLEncoderField"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Qwen2.5-VL tokenizer, processor and text/vision encoder",+ "field_kind": "output",+ "title": "Qwen VL Encoder",+ "ui_hidden": false+ },"type": {"const": "qwen_image_lora_loader_output","default": "qwen_image_lora_loader_output",@@ -104965,7 +105014,7 @@"type": "string"}},- "required": ["output_meta", "transformer", "type", "type"],+ "required": ["output_meta", "transformer", "qwen_vl_encoder", "type", "type"],"title": "QwenImageLoRALoaderOutput","type": "object"},@@ -105425,6 +105474,14 @@"text_encoder": {"$ref": "#/components/schemas/ModelIdentifierField","description": "Info to load text_encoder submodel"+ },+ "loras": {+ "description": "LoRAs to apply on model loading",+ "items": {+ "$ref": "#/components/schemas/LoRAField"+ },+ "title": "Loras",+ "type": "array"}},"required": ["tokenizer", "text_encoder"],diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex 4f87283bad..d01631e621 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -45369,7 +45369,7 @@ export type components = {};/*** Apply LoRA Collection - Qwen Image- * @description Applies a collection of LoRAs to a Qwen Image transformer.+ * @description Applies a collection of LoRAs to a Qwen Image transformer and/or Qwen2.5-VL text encoder.*/QwenImageLoRACollectionLoader: {/**@@ -45401,6 +45401,12 @@ export type components = {* @default null*/transformer?: components["schemas"]["TransformerField"] | null;+ /**+ * Qwen VL Encoder+ * @description Qwen2.5-VL tokenizer, processor and text/vision encoder+ * @default null+ */+ qwen_vl_encoder?: components["schemas"]["QwenVLEncoderField"] | null;/*** type* @default qwen_image_lora_collection_loader@@ -45410,7 +45416,7 @@ export type components = {};/*** Apply LoRA - Qwen Image- * @description Apply a LoRA model to a Qwen Image transformer.+ * @description Apply a LoRA model to a Qwen Image transformer and/or Qwen2.5-VL text encoder.*/QwenImageLoRALoaderInvocation: {/**@@ -45448,6 +45454,12 @@ export type components = {* @default null*/transformer?: components["schemas"]["TransformerField"] | null;+ /**+ * Qwen VL Encoder+ * @description Qwen2.5-VL tokenizer, processor and text/vision encoder+ * @default null+ */+ qwen_vl_encoder?: components["schemas"]["QwenVLEncoderField"] | null;/*** type* @default qwen_image_lora_loader@@ -45466,6 +45478,12 @@ export type components = {* @default null*/transformer: components["schemas"]["TransformerField"] | null;+ /**+ * Qwen VL Encoder+ * @description Qwen2.5-VL tokenizer, processor and text/vision encoder+ * @default null+ */+ qwen_vl_encoder: components["schemas"]["QwenVLEncoderField"] | null;/*** type* @default qwen_image_lora_loader_output@@ -45715,6 +45733,11 @@ export type components = {tokenizer: components["schemas"]["ModelIdentifierField"];/** @description Info to load text_encoder submodel */text_encoder: components["schemas"]["ModelIdentifierField"];+ /**+ * Loras+ * @description LoRAs to apply on model loading+ */+ loras?: components["schemas"]["LoRAField"][];};/*** QwenVLEncoder_Checkpoint_Configdiff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.test.tsindex 8da4a97049..7469e8d94c 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.test.ts@@ -2542,6 +2542,40 @@ describe('model-family tuning', () => {expect(getNodeByType(quantized, 'core_metadata')?.qwen_image_quantization).toBe('nf4');});+ describe('Qwen-Image LoRAs', () => {+ const qwenLora: LoraModelConfig = { base: 'qwen-image', key: 'qwen-lora', name: 'A LoRA', type: 'lora' };+ const loras = [{ isEnabled: true, model: qwenLora, weight: 0.7 }];++ it('routes the Qwen2.5-VL encoder to both prompts through the LoRA collection loader', () => {+ const graph = compile(qwenImageModel, { cfgScale: 4, loras });+ const loader = getNodeByType(graph, 'qwen_image_lora_collection_loader');++ expect(loader).toBeDefined();+ expect(getEdge(graph, loader?.id ?? '', 'qwen_vl_encoder')?.source.node_id).toBe('model_loader');+ expect(getEdge(graph, 'pos_cond', 'qwen_vl_encoder')?.source.node_id).toBe(loader?.id);+ expect(getEdge(graph, 'neg_cond', 'qwen_vl_encoder')?.source.node_id).toBe(loader?.id);+ expect(getEdge(graph, 'denoise_latents', 'transformer')?.source.node_id).toBe(loader?.id);+ });++ it('takes the encoder straight from the model loader without an active LoRA', () => {+ const graph = compile(qwenImageModel, { cfgScale: 4, loras: [{ ...loras[0]!, isEnabled: false }] });++ expect(getNodeByType(graph, 'qwen_image_lora_collection_loader')).toBeUndefined();+ expect(getEdge(graph, 'pos_cond', 'qwen_vl_encoder')?.source.node_id).toBe('model_loader');+ expect(getEdge(graph, 'neg_cond', 'qwen_vl_encoder')?.source.node_id).toBe('model_loader');+ });++ it('keeps the encoder quantization on both prompts next to the LoRA edges', () => {+ const graph = compile(qwenImageModel, { cfgScale: 4, loras, qwenImageEncoderQuantization: 'int8' });+ const loader = getNodeByType(graph, 'qwen_image_lora_collection_loader');++ expect(graph.nodes.pos_cond?.quantization).toBe('int8');+ expect(graph.nodes.neg_cond?.quantization).toBe('int8');+ expect(getEdge(graph, 'pos_cond', 'qwen_vl_encoder')?.source.node_id).toBe(loader?.id);+ expect(getEdge(graph, 'neg_cond', 'qwen_vl_encoder')?.source.node_id).toBe(loader?.id);+ });+ });+it('encodes the enabled Krea-2 style reference at the denoise size and feeds it to the denoise node', () => {// The served limit is one enabled reference; a disabled card stays out of the graph.const graph = compile(krea2Model, {diff --git a/invokeai/frontend/webv2/src/features/generation/core/graph.ts b/invokeai/frontend/webv2/src/features/generation/core/graph.tsindex fb12657538..cb57aefc27 100644--- a/invokeai/frontend/webv2/src/features/generation/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/generation/core/graph.ts@@ -1062,6 +1062,7 @@ const buildQwenImageGraph = (const loraSource = activeLoras.length? addTransformerLoraCollectionLoader(graph, activeLoras, 'qwen_image_lora_collection_loader', modelLoader, ['transformer',+ 'qwen_vl_encoder',]): modelLoader;// The encoders default to `none`, so only an actual quantization choice reaches the graph.@@ -1097,12 +1098,12 @@ const buildQwenImageGraph = (addEdge(graph, loraSource, 'transformer', denoise, 'transformer');// The denoise encodes a ControlNet's control and inpaint images with this VAE; without one the input is idle.addEdge(graph, modelLoader, 'vae', denoise, 'vae');- addEdge(graph, modelLoader, 'qwen_vl_encoder', posCond, 'qwen_vl_encoder');+ addEdge(graph, loraSource, 'qwen_vl_encoder', posCond, 'qwen_vl_encoder');addEdge(graph, positivePrompt, 'value', posCond, 'prompt');addEdge(graph, posCond, 'conditioning', denoise, 'positive_conditioning');if (negCond) {- addEdge(graph, modelLoader, 'qwen_vl_encoder', negCond, 'qwen_vl_encoder');+ addEdge(graph, loraSource, 'qwen_vl_encoder', negCond, 'qwen_vl_encoder');addEdge(graph, negativePrompt, 'value', negCond, 'prompt');addEdge(graph, negCond, 'conditioning', denoise, 'negative_conditioning');}diff --git a/invokeai/frontend/webv2/src/features/upscale/core/__snapshots__/upscaleGraphNodeTypes.json b/invokeai/frontend/webv2/src/features/upscale/core/__snapshots__/upscaleGraphNodeTypes.jsonindex 45c8d28ef5..6c8e897c36 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/__snapshots__/upscaleGraphNodeTypes.json+++ b/invokeai/frontend/webv2/src/features/upscale/core/__snapshots__/upscaleGraphNodeTypes.json@@ -106,8 +106,9 @@"qwen_image_denoise latents qwen_image_l2i latents","qwen_image_i2l latents krea2_denoise latents","qwen_image_i2l latents qwen_image_denoise latents",+ "qwen_image_lora_collection_loader qwen_vl_encoder qwen_image_text_encoder qwen_vl_encoder","qwen_image_lora_collection_loader transformer qwen_image_denoise transformer",- "qwen_image_model_loader qwen_vl_encoder qwen_image_text_encoder qwen_vl_encoder",+ "qwen_image_model_loader qwen_vl_encoder qwen_image_lora_collection_loader qwen_vl_encoder","qwen_image_model_loader transformer qwen_image_lora_collection_loader transformer","qwen_image_model_loader vae qwen_image_i2l vae","qwen_image_model_loader vae qwen_image_l2i vae",@@ -1308,6 +1309,7 @@"qwen_image_lora_collection_loader": {"inputs": ["loras",+ "qwen_vl_encoder","transformer"],"literalInputs": {@@ -1319,6 +1321,7 @@]},"outputs": [+ "qwen_vl_encoder","transformer"]},diff --git a/invokeai/frontend/webv2/src/features/upscale/core/graph.test.ts b/invokeai/frontend/webv2/src/features/upscale/core/graph.test.tsindex 8b3d592299..c6d5a99262 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/graph.test.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/graph.test.ts@@ -761,8 +761,15 @@ describe('compileUpscaleGraph for Qwen Image', () => {expect(hasEdge(edges, 'pos_cond', 'conditioning', 'denoise_latents', 'positive_conditioning')).toBe(true);expect(hasEdge(edges, 'neg_cond', 'conditioning', 'denoise_latents', 'negative_conditioning')).toBe(true);expect(nodes.pos_cond_collect).toBeUndefined();- expect(hasEdge(edges, 'model_loader', 'qwen_vl_encoder', 'neg_cond', 'qwen_vl_encoder')).toBe(true);- expect(Object.values(nodes).some((node) => node.type === 'qwen_image_lora_collection_loader')).toBe(true);+ const loraLoaderId = Object.entries(nodes).find(+ ([, node]) => node.type === 'qwen_image_lora_collection_loader'+ )?.[0];+ expect(loraLoaderId).toBeDefined();+ // The LoRAs' text-encoder layers patch the encoder, so it reaches both prompts through the loader.+ expect(hasEdge(edges, 'model_loader', 'qwen_vl_encoder', loraLoaderId ?? '', 'qwen_vl_encoder')).toBe(true);+ expect(hasEdge(edges, loraLoaderId ?? '', 'qwen_vl_encoder', 'pos_cond', 'qwen_vl_encoder')).toBe(true);+ expect(hasEdge(edges, loraLoaderId ?? '', 'qwen_vl_encoder', 'neg_cond', 'qwen_vl_encoder')).toBe(true);+ expect(hasEdge(edges, 'model_loader', 'qwen_vl_encoder', 'neg_cond', 'qwen_vl_encoder')).toBe(false);expect(nodes.core_metadata).toMatchObject({cfg_scale: 4,qwen_image_qwen_vl_encoder: { key: 'qwen-vl' },@@ -770,6 +777,16 @@ describe('compileUpscaleGraph for Qwen Image', () => {});});+ it('takes the encoder straight from the model loader without LoRAs', () => {+ const { edges, nodes } = compileUpscaleGraph({ ...createQwenImageValues(), loras: [] }, 'gallery', {+ useCpuNoise: true,+ }).backendGraph;++ expect(Object.values(nodes).some((node) => node.type === 'qwen_image_lora_collection_loader')).toBe(false);+ expect(hasEdge(edges, 'model_loader', 'qwen_vl_encoder', 'pos_cond', 'qwen_vl_encoder')).toBe(true);+ expect(hasEdge(edges, 'model_loader', 'qwen_vl_encoder', 'neg_cond', 'qwen_vl_encoder')).toBe(true);+ });+it('wires the negative prompt only above CFG 1, where the node runs an unconditional pass', () => {const { edges, nodes } = compileUpscaleGraph(createQwenImageValues({ cfgScale: 1 }), 'gallery', {useCpuNoise: true,diff --git a/invokeai/frontend/webv2/src/features/upscale/core/graph.ts b/invokeai/frontend/webv2/src/features/upscale/core/graph.tsindex f5a3cbaab0..846df7bcd8 100644--- a/invokeai/frontend/webv2/src/features/upscale/core/graph.ts+++ b/invokeai/frontend/webv2/src/features/upscale/core/graph.ts@@ -856,6 +856,7 @@ const buildQwenImageUpscalePath: UpscalePathBuilder = ({const loraSource = activeLoras.length? addTransformerLoraCollectionLoader(graph, activeLoras, 'qwen_image_lora_collection_loader', modelLoader, ['transformer',+ 'qwen_vl_encoder',]): modelLoader;const imageToLatents = addNode(graph, {@@ -886,7 +887,7 @@ const buildQwenImageUpscalePath: UpscalePathBuilder = ({addPromptConditioning(graph, {collect: false,denoise,- encoderFields: [{ field: 'qwen_vl_encoder', source: modelLoader }],+ encoderFields: [{ field: 'qwen_vl_encoder', source: loraSource }],encoderType: 'qwen_image_text_encoder',negativePrompt: wiresUpscaleNegativePrompt(model, settings.cfgScale) ? negativePrompt : null,positivePrompt,diff --git a/tests/app/invocations/test_qwen_image_lora_loader.py b/tests/app/invocations/test_qwen_image_lora_loader.pynew file mode 100644index 0000000000..467e35100f--- /dev/null+++ b/tests/app/invocations/test_qwen_image_lora_loader.py@@ -0,0 +1,194 @@+from types import SimpleNamespace++import pytest+import torch++from invokeai.app.invocations.model import LoRAField, ModelIdentifierField, QwenVLEncoderField, TransformerField+from invokeai.app.invocations.qwen_image.qwen_image_lora_loader import (+ QwenImageLoRACollectionLoader,+ QwenImageLoRALoaderInvocation,+)+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType, SubModelType+from invokeai.backend.patches.lora_conversions.qwen_image_lora_conversion_utils import (+ lora_model_from_qwen_image_state_dict,+)+++def _model(key: str, model_type: ModelType) -> ModelIdentifierField:+ return ModelIdentifierField(key=key, hash=f"hash-{key}", name=key, base=BaseModelType.QwenImage, type=model_type)+++def _lora(key: str = "lora", weight: float = 1.0) -> LoRAField:+ return LoRAField(lora=_model(key, ModelType.LoRA), weight=weight)+++def _transformer(loras: list[LoRAField]) -> TransformerField:+ return TransformerField(+ transformer=_model("main", ModelType.Main).model_copy(update={"submodel_type": SubModelType.Transformer}),+ loras=loras,+ )+++def _encoder(loras: list[LoRAField]) -> QwenVLEncoderField:+ encoder = _model("encoder", ModelType.QwenVLEncoder)+ return QwenVLEncoderField(+ tokenizer=encoder.model_copy(update={"submodel_type": SubModelType.Tokenizer}),+ text_encoder=encoder.model_copy(update={"submodel_type": SubModelType.TextEncoder}),+ loras=loras,+ )+++def _patch(*layers: str):+ state_dict = {}+ for layer in layers:+ state_dict[f"{layer}.lora_A.weight"] = torch.zeros(2, 4)+ state_dict[f"{layer}.lora_B.weight"] = torch.zeros(4, 2)+ return lora_model_from_qwen_image_state_dict(state_dict)+++TRANSFORMER_ONLY = ("transformer_blocks.0.attn.to_k",)+WITH_ENCODER_LAYERS = (*TRANSFORMER_ONLY, "text_encoder.model.language_model.layers.0.mlp.down_proj")+++def _context(layers: tuple[str, ...] = TRANSFORMER_ONLY) -> SimpleNamespace:+ warnings: list[str] = []+ return SimpleNamespace(+ models=SimpleNamespace(+ exists=lambda _key: True,+ load=lambda _identifier: SimpleNamespace(model=_patch(*layers)),+ get_config=lambda _key: SimpleNamespace(name="My LoRA"),+ ),+ logger=SimpleNamespace(warning=warnings.append),+ warnings=warnings,+ )+++def test_the_encoder_field_defaults_to_no_loras() -> None:+ """Saved graphs carry encoder fields without `loras`."""+ encoder = _model("encoder", ModelType.QwenVLEncoder)++ assert QwenVLEncoderField(tokenizer=encoder, text_encoder=encoder).loras == []+++def test_single_loader_adds_the_lora_to_transformer_and_encoder_with_the_weight() -> None:+ invocation = QwenImageLoRALoaderInvocation.model_construct(+ lora=_model("lora", ModelType.LoRA), weight=0.6, transformer=_transformer([]), qwen_vl_encoder=_encoder([])+ )++ output = invocation.invoke(_context())++ assert [(item.lora.key, item.weight) for item in output.transformer.loras] == [("lora", 0.6)]+ assert [(item.lora.key, item.weight) for item in output.qwen_vl_encoder.loras] == [("lora", 0.6)]+++def test_single_loader_leaves_its_inputs_untouched() -> None:+ transformer, encoder = _transformer([]), _encoder([])+ invocation = QwenImageLoRALoaderInvocation.model_construct(+ lora=_model("lora", ModelType.LoRA), weight=1.0, transformer=transformer, qwen_vl_encoder=encoder+ )++ invocation.invoke(_context())++ assert transformer.loras == [] and encoder.loras == []+++def test_a_transformer_only_graph_still_works() -> None:+ invocation = QwenImageLoRALoaderInvocation.model_construct(+ lora=_model("lora", ModelType.LoRA), weight=1.0, transformer=_transformer([]), qwen_vl_encoder=None+ )++ output = invocation.invoke(_context())++ assert [item.lora.key for item in output.transformer.loras] == ["lora"]+ assert output.qwen_vl_encoder is None+++def test_an_encoder_only_graph_works() -> None:+ invocation = QwenImageLoRALoaderInvocation.model_construct(+ lora=_model("lora", ModelType.LoRA), weight=1.0, transformer=None, qwen_vl_encoder=_encoder([])+ )++ output = invocation.invoke(_context())++ assert output.transformer is None+ assert [item.lora.key for item in output.qwen_vl_encoder.loras] == ["lora"]++[email protected]("applied_to", ["transformer", "encoder"])+def test_single_loader_rejects_a_lora_already_applied(applied_to: str) -> None:+ lora = _lora()+ invocation = QwenImageLoRALoaderInvocation.model_construct(+ lora=lora.lora,+ weight=1.0,+ transformer=_transformer([lora] if applied_to == "transformer" else []),+ qwen_vl_encoder=_encoder([lora] if applied_to == "encoder" else []),+ )++ with pytest.raises(ValueError, match="already applied"):+ invocation.invoke(_context())+++def test_collection_loader_adds_each_lora_once_to_both_models() -> None:+ first, second = _lora("a", 0.5), _lora("b", 0.8)+ invocation = QwenImageLoRACollectionLoader.model_construct(+ loras=[first, second, first], transformer=_transformer([]), qwen_vl_encoder=_encoder([])+ )++ output = invocation.invoke(_context())++ expected = [("a", 0.5), ("b", 0.8)]+ assert [(item.lora.key, item.weight) for item in output.transformer.loras] == expected+ assert [(item.lora.key, item.weight) for item in output.qwen_vl_encoder.loras] == expected+++def test_collection_loader_works_without_the_encoder() -> None:+ invocation = QwenImageLoRACollectionLoader.model_construct(+ loras=_lora(), transformer=_transformer([]), qwen_vl_encoder=None+ )++ output = invocation.invoke(_context())++ assert [item.lora.key for item in output.transformer.loras] == ["lora"]+ assert output.qwen_vl_encoder is None++[email protected]("loader", ["single", "collection"])+def test_a_transformer_only_connection_warns_once_when_the_lora_has_encoder_layers(loader: str) -> None:+ """Workflows saved before the encoder connection existed would otherwise lose the layers without a trace."""+ context = _context(WITH_ENCODER_LAYERS)+ if loader == "single":+ invocation = QwenImageLoRALoaderInvocation.model_construct(+ lora=_model("lora", ModelType.LoRA), weight=1.0, transformer=_transformer([]), qwen_vl_encoder=None+ )+ else:+ invocation = QwenImageLoRACollectionLoader.model_construct(+ loras=[_lora(), _lora()], transformer=_transformer([]), qwen_vl_encoder=None+ )++ invocation.invoke(context)++ assert len(context.warnings) == 1+ assert "My LoRA" in context.warnings[0] and "Qwen VL Encoder" in context.warnings[0]++[email protected]("loader", ["single", "collection"])+ ("layers", "connect_encoder"),+ [(TRANSFORMER_ONLY, False), (WITH_ENCODER_LAYERS, True)],+ ids=["transformer_only_lora", "encoder_connected"],+)+def test_no_warning_without_unused_encoder_layers(loader: str, layers: tuple[str, ...], connect_encoder: bool) -> None:+ context = _context(layers)+ encoder = _encoder([]) if connect_encoder else None+ if loader == "single":+ invocation = QwenImageLoRALoaderInvocation.model_construct(+ lora=_model("lora", ModelType.LoRA), weight=1.0, transformer=_transformer([]), qwen_vl_encoder=encoder+ )+ else:+ invocation = QwenImageLoRACollectionLoader.model_construct(+ loras=[_lora()], transformer=_transformer([]), qwen_vl_encoder=encoder+ )++ invocation.invoke(context)++ assert context.warnings == []diff --git a/tests/app/invocations/test_qwen_image_packed_models.py b/tests/app/invocations/test_qwen_image_packed_models.pyindex 37e77671a0..175c428c7a 100644--- a/tests/app/invocations/test_qwen_image_packed_models.py+++ b/tests/app/invocations/test_qwen_image_packed_models.py@@ -136,7 +136,7 @@ def test_the_text_encoder_reserves_the_dequant_transient_of_a_packed_encoder(moncontext = MagicMock()context.models.load.return_value = loadednode = QwenImageTextEncoderInvocation.model_construct(- qwen_vl_encoder=SimpleNamespace(text_encoder=SimpleNamespace(), tokenizer=SimpleNamespace())+ qwen_vl_encoder=SimpleNamespace(text_encoder=SimpleNamespace(), tokenizer=SimpleNamespace(), loras=[]))_, _, cleanup = node._load_cached_encoder(context)diff --git a/tests/app/invocations/test_qwen_image_text_encoder_lora.py b/tests/app/invocations/test_qwen_image_text_encoder_lora.pynew file mode 100644index 0000000000..579a77978f--- /dev/null+++ b/tests/app/invocations/test_qwen_image_text_encoder_lora.py@@ -0,0 +1,387 @@+"""LoRA layers aimed at the Qwen2.5-VL encoder reach it on every load path of the Qwen-Image text encoder node."""++import gc+import weakref+from contextlib import contextmanager, nullcontext+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest+import torch+from transformers import Qwen2_5_VLConfig, Qwen2_5_VLForConditionalGeneration++from invokeai.app.invocations.model import LoRAField, ModelIdentifierField, QwenVLEncoderField+from invokeai.app.invocations.text_encoder.qwen_image_text_encoder import (+ _GENERATE_DROP_IDX,+ QwenImageTextEncoderInvocation,+)+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_linear import (+ CustomLinear,+)+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (+ apply_custom_layers_to_model,+)+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType+from invokeai.backend.patches.layer_patcher import LayerPatcher+from invokeai.backend.patches.lora_conversions.qwen_image_lora_conversion_utils import (+ lora_model_from_qwen_image_state_dict,+)+from invokeai.backend.quantization.nvfp4 import NVFP4Linear+from invokeai.backend.util.devices import TorchDevice++HIDDEN = 8+RANK = 4+_PROJ_PATH = "model.language_model.layers.0.mlp.down_proj"+SEQ_LEN = _GENERATE_DROP_IDX + 3+++class _InnerModel(torch.nn.Module):+ """The encoder's inner model, which the node runs: its forward returns the Linear's output as the last hidden state."""++ def __init__(self, fail: bool) -> None:+ super().__init__()+ self.language_model = torch.nn.Module()+ self.language_model.layers = torch.nn.ModuleList([torch.nn.Module()])+ self.language_model.layers[0].mlp = torch.nn.Module()+ self.language_model.layers[0].mlp.down_proj = torch.nn.Linear(HIDDEN, HIDDEN, bias=False)+ self.fail = fail+ self.patches_during_forward: int | None = None++ def forward(self, input_ids, attention_mask, **_):+ proj = self.language_model.layers[0].mlp.down_proj+ self.patches_during_forward = proj.get_num_patches() if hasattr(proj, "get_num_patches") else None+ if self.fail:+ raise RuntimeError("forward failed (simulated)")+ x = torch.linspace(-1, 1, input_ids.numel() * HIDDEN).reshape(*input_ids.shape, HIDDEN)+ return SimpleNamespace(last_hidden_state=proj(x))+++class _Encoder(torch.nn.Module):+ """One Linear the LoRA targets, at the path of a real Qwen2.5-VL Linear, which is what a converted LoRA can address."""++ def __init__(self, fail: bool = False) -> None:+ super().__init__()+ self.model = _InnerModel(fail)++ @property+ def proj(self) -> torch.nn.Module:+ return self.model.language_model.layers[0].mlp.down_proj++ @property+ def patches_during_forward(self) -> int | None:+ return self.model.patches_during_forward+++def _encoder_module(fail: bool = False) -> _Encoder:+ torch.manual_seed(0)+ return _Encoder(fail)+++def _identifier(key: str, model_type: ModelType) -> ModelIdentifierField:+ return ModelIdentifierField(key=key, hash="h", name=key, base=BaseModelType.QwenImage, type=model_type)+++def _lora_weights() -> tuple[torch.Tensor, torch.Tensor]:+ generator = torch.Generator().manual_seed(1)+ return torch.randn(RANK, HIDDEN, generator=generator), torch.randn(HIDDEN, RANK, generator=generator)+++_PIN = nullcontext() # what `model_in_ram()` hands back: the cache pin the patcher must hold while patching+++def _lora_info() -> SimpleNamespace:+ down, up = _lora_weights()+ patch_raw = lora_model_from_qwen_image_state_dict(+ {+ f"text_encoder.{_PROJ_PATH}.lora_A.weight": down,+ f"text_encoder.{_PROJ_PATH}.lora_B.weight": up,+ }+ )+ return SimpleNamespace(model=patch_raw, model_in_ram=lambda: _PIN)+++def _node(loras: list[LoRAField], quantization: str = "none") -> QwenImageTextEncoderInvocation:+ encoder = _identifier("enc", ModelType.QwenVLEncoder)+ return QwenImageTextEncoderInvocation.model_construct(+ prompt="a cat",+ reference_images=[],+ qwen_vl_encoder=QwenVLEncoderField(tokenizer=encoder, text_encoder=encoder, loras=loras),+ quantization=quantization,+ )+++def _lora_field(weight: float) -> LoRAField:+ return LoRAField(lora=_identifier("lora", ModelType.LoRA), weight=weight)+++def _context(+ model_root: Path, text_encoder_info: object | None = None, model_format: ModelFormat = ModelFormat.Diffusers+):+ """A context whose model loads serve the LoRA, the tokenizer (opaque to the node) and the cached encoder."""+ context = MagicMock()+ context.models.get_absolute_path.return_value = model_root+ context.models.get_config.return_value = SimpleNamespace(format=model_format)++ def load(identifier):+ if identifier.type == ModelType.LoRA:+ return _lora_info()+ if identifier.submodel_type is None and text_encoder_info is not None:+ return text_encoder_info+ return SimpleNamespace(model=MagicMock())++ context.models.load.side_effect = load+ return context+++def _cached_info(encoder: torch.nn.Module, events: list, cached_weights: object = None) -> SimpleNamespace:+ @contextmanager+ def model_on_device(working_mem_bytes=None):+ events.append("lock")+ try:+ yield cached_weights, encoder+ finally:+ events.append(("release", getattr(encoder.proj, "get_num_patches", lambda: None)()))++ return SimpleNamespace(model=encoder, compute_device=torch.device("cpu"), model_on_device=model_on_device)+++def _processor() -> MagicMock:+ model_inputs = MagicMock()+ model_inputs.input_ids = torch.zeros(1, SEQ_LEN, dtype=torch.long)+ model_inputs.attention_mask = torch.ones(1, SEQ_LEN, dtype=torch.long)+ model_inputs.to.return_value = model_inputs+ return MagicMock(return_value=model_inputs)+++def _encode(node: QwenImageTextEncoderInvocation, context: MagicMock) -> torch.Tensor:+ with patch.object(QwenImageTextEncoderInvocation, "_build_processor", return_value=_processor()):+ prompt_embeds, _ = node._encode(context, images=[])+ return prompt_embeds+++def _expected_shift(weight: float) -> torch.Tensor:+ """What a LoRA adds to the encoder output: `x @ (up @ down).T * weight` (no alpha, so scale 1), in bf16."""+ down, up = _lora_weights()+ x = torch.linspace(-1, 1, SEQ_LEN * HIDDEN).reshape(1, SEQ_LEN, HIDDEN)+ return (x @ (up @ down).T * weight)[:, _GENERATE_DROP_IDX:].to(torch.bfloat16).float()++[email protected](autouse=True)+def _float32_patch_dtype(monkeypatch: pytest.MonkeyPatch):+ """The node patches in bf16; CPU bf16 matmul faults on part of the CI fleet (tests/AGENTS.md), so run float32."""+ monkeypatch.setattr(TorchDevice, "choose_bfloat16_safe_dtype", lambda device: torch.float32)+++def _tiny_encoder_class(monkeypatch: pytest.MonkeyPatch):+ """The cached loader checks its model's type; the test encoder stands in for the real class."""+ import transformers++ monkeypatch.setattr(transformers, "Qwen2_5_VLForConditionalGeneration", _Encoder, raising=False)+++class _RecordedPatching(Exception):+ pass+++ ("packed", "model_format", "sidecar"),+ [+ (True, ModelFormat.Checkpoint, True),+ (False, ModelFormat.Checkpoint, False),+ (False, ModelFormat.GGUFQuantized, True),+ ],+ ids=["nvfp4", "dense", "gguf"],+)[email protected]("_tiny_encoder_class")+def test_cached_path_hands_prefix_weights_and_cached_weights_to_the_patcher(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, packed: bool, model_format: ModelFormat, sidecar: bool+) -> None:+ encoder = _encoder_module()+ if packed:+ encoder.packed = NVFP4Linear(+ torch.zeros(128, 32, dtype=torch.uint8), torch.ones(128, 4).to(torch.float8_e4m3fn), torch.tensor(1.0)+ )+ cached_weights = {f"{_PROJ_PATH}.weight": torch.zeros(1)}+ seen: dict = {}++ def record(**kwargs):+ seen.update(kwargs)+ seen["patches"] = list(kwargs["patches"])+ raise _RecordedPatching++ monkeypatch.setattr(LayerPatcher, "apply_smart_model_patches", record)+ events: list = []+ context = _context(tmp_path, _cached_info(encoder, events, cached_weights), model_format)++ with pytest.raises(_RecordedPatching):+ _node([_lora_field(0.7)])._load_cached_encoder(context)++ assert seen["prefix"] == "lora_qwen_vl-"+ assert seen["cached_weights"] is cached_weights+ assert seen["force_sidecar_patching"] is sidecar+ assert [spec[1] for spec in seen["patches"]] == [0.7]+ assert seen["patches"][0][2] is _PIN+ # The failed patching must not leave the model locked.+ assert events[-1][0] == "release"++[email protected]("_tiny_encoder_class")+def test_cached_path_applies_the_lora_to_the_encoder_output_and_removes_it_afterwards(tmp_path: Path) -> None:+ """The encoder output moves by the LoRA contribution, the layer carries no patch once the node is done, and the+ patch is gone before the model lock is released."""+ encoder = _encoder_module()+ apply_custom_layers_to_model(encoder) # as the model cache does on `put()`+ assert isinstance(encoder.proj, CustomLinear)+ events: list = []+ context = _context(tmp_path, _cached_info(encoder, events))++ baseline = _encode(_node([]), context)+ patched = _encode(_node([_lora_field(0.5)]), context)+ patches_during_patched_forward = encoder.patches_during_forward+ again = _encode(_node([]), context)++ torch.testing.assert_close((patched - baseline).float(), _expected_shift(0.5), atol=0.1, rtol=0.05)+ assert not torch.equal(patched, baseline)+ assert torch.equal(again, baseline)+ assert patches_during_patched_forward == 1+ assert events == ["lock", ("release", 0)] * 3++[email protected]("_tiny_encoder_class")+def test_cached_path_undoes_patches_and_releases_the_lock_when_the_forward_raises(tmp_path: Path) -> None:+ encoder = _encoder_module(fail=True)+ apply_custom_layers_to_model(encoder)+ events: list = []+ context = _context(tmp_path, _cached_info(encoder, events))++ with pytest.raises(RuntimeError, match="simulated"):+ _encode(_node([_lora_field(1.0)]), context)++ assert encoder.patches_during_forward == 1+ assert events == ["lock", ("release", 0)]+++def _quantized_context(tmp_path: Path) -> MagicMock:+ model_root = tmp_path / "qwen-vl"+ (model_root / "text_encoder").mkdir(parents=True, exist_ok=True)+ Qwen2_5_VLConfig().save_pretrained(model_root / "text_encoder")+ return _context(model_root)+++@contextmanager+def _quantized_load(handoff: list):+ """`from_pretrained` serves the test encoder (a one-shot handoff, so no mock keeps it alive) on the CPU."""+ with (+ patch.object(Qwen2_5_VLForConditionalGeneration, "from_pretrained", side_effect=lambda *a, **k: handoff.pop()),+ patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cpu")),+ ):+ yield+++def test_quantized_path_without_loras_leaves_the_layers_unwrapped(tmp_path: Path) -> None:+ encoder = _encoder_module()+ with _quantized_load([encoder]):+ loaded, _, cleanup = _node([], "int8")._load_quantized_encoder(_quantized_context(tmp_path))++ assert loaded is encoder+ assert type(encoder.proj) is torch.nn.Linear+ cleanup()++[email protected]("failure", [None, "forward", "patching"], ids=["encoded", "forward_raises", "patching_raises"])+def test_quantized_path_frees_the_patched_encoder_before_the_cache_is_emptied(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, failure: str | None+) -> None:+ """The patcher's generator frames hold the model, so the patches must be closed before cleanup empties the cache+ (see `_encode`): otherwise the encoder's VRAM stays reserved by torch. A failure while patching releases it too."""+ encoder = _encoder_module(failure == "forward")+ encoder_ref = weakref.ref(encoder)+ freed_at_empty_cache: list[bool] = []+ handoff = [encoder]+ del encoder+ if failure == "patching":++ def fail(**_kwargs):+ raise RuntimeError("patching failed (simulated)")++ monkeypatch.setattr(LayerPatcher, "apply_smart_model_patches", fail)++ def empty_cache() -> None:+ gc.collect()+ freed_at_empty_cache.append(encoder_ref() is None)++ with _quantized_load(handoff), patch.object(TorchDevice, "empty_cache", side_effect=empty_cache):+ node = _node([_lora_field(0.5)], "int8")+ if failure:+ with pytest.raises(RuntimeError, match="simulated"):+ _encode(node, _quantized_context(tmp_path))+ else:+ _encode(node, _quantized_context(tmp_path))++ assert freed_at_empty_cache == [True]+++def test_an_oom_while_patching_is_not_reported_as_the_encoder_not_fitting(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ def oom(**_kwargs):+ raise torch.OutOfMemoryError("oom while moving the LoRA")++ monkeypatch.setattr(LayerPatcher, "apply_smart_model_patches", oom)++ with _quantized_load([_encoder_module()]), pytest.raises(torch.OutOfMemoryError) as excinfo:+ _node([_lora_field(0.5)], "int8")._load_quantized_encoder(_quantized_context(tmp_path))++ assert str(excinfo.value) == "oom while moving the LoRA"+++def test_quantized_path_always_patches_as_a_sidecar(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ """On the CPU the patcher picks a sidecar anyway, so only the flag itself shows that a quantized layer is never+ patched in place on a device where it would be."""+ seen: dict = {}++ def record(**kwargs):+ seen.update(kwargs)+ raise _RecordedPatching++ monkeypatch.setattr(LayerPatcher, "apply_smart_model_patches", record)++ with _quantized_load([_encoder_module()]), pytest.raises(_RecordedPatching):+ _node([_lora_field(0.5)], "int8")._load_quantized_encoder(_quantized_context(tmp_path))++ assert seen["prefix"] == "lora_qwen_vl-"+ assert seen["force_sidecar_patching"] is True+ assert seen["cached_weights"] is None+++def test_quantized_path_changes_the_output_by_the_lora_contribution(tmp_path: Path) -> None:+ results = []+ for loras in ([], [_lora_field(0.5)]):+ with _quantized_load([_encoder_module()]):+ results.append(_encode(_node(loras, "int8"), _quantized_context(tmp_path)))++ torch.testing.assert_close((results[1] - results[0]).float(), _expected_shift(0.5), atol=0.1, rtol=0.05)++[email protected]("_tiny_encoder_class")+def test_quantized_single_file_fallback_patches_once(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ """A single-file checkpoint is served by the cached loader, which already applies the LoRA."""+ single_file = tmp_path / "encoder.safetensors"+ single_file.write_bytes(b"")+ encoder = _encoder_module()+ apply_custom_layers_to_model(encoder)+ calls: list[str] = []+ original = LayerPatcher.apply_smart_model_patches++ def counting(**kwargs):+ calls.append(kwargs["prefix"])+ return original(**kwargs)++ monkeypatch.setattr(LayerPatcher, "apply_smart_model_patches", counting)+ context = _context(single_file, _cached_info(encoder, []))++ _encode(_node([_lora_field(1.0)], "int8"), context)++ assert calls == ["lora_qwen_vl-"]diff --git a/tests/backend/model_manager/configs/test_qwen_image_lora_config.py b/tests/backend/model_manager/configs/test_qwen_image_lora_config.pyindex 03c5531c96..b6be9567b3 100644--- a/tests/backend/model_manager/configs/test_qwen_image_lora_config.py+++ b/tests/backend/model_manager/configs/test_qwen_image_lora_config.py@@ -99,6 +99,84 @@ def test_only_the_qwen_image_probe_claims_a_qwen_image_lora(prefix: str, tmp_patassert accepting == [LoRA_LyCORIS_QwenImage_Config.__name__]+ ("prefix", "text_encoder_prefix"),+ [+ ("", "text_encoder."),+ ("base_model.model.", "base_model.model.text_encoder."),+ ("diffusion_model.", "text_encoders.qwen25_7b.transformer."),+ ],+)+def test_a_lora_with_text_encoder_layers_is_still_claimed_by_the_qwen_image_probe_alone(+ prefix: str, text_encoder_prefix: str, tmp_path: Path+) -> None:+ """Qwen2.5-VL layers in the file are applied to the encoder, but must not change what the file is identified as."""+ path = tmp_path / "lora.safetensors"+ sd = _qwen_image_lora(prefix)+ sd.update(+ _lora(+ {+ f"{text_encoder_prefix}model.language_model.layers.0.self_attn.q_proj": (3584, 3584),+ f"{text_encoder_prefix}model.language_model.layers.0.mlp.down_proj": (18944, 3584),+ f"{text_encoder_prefix}model.visual.blocks.0.attn.qkv": (1280, 3840),+ }+ )+ )+ mod = _make_mod(path, sd)++ accepting = []+ for cls in Config_Base.CONFIG_CLASSES:+ if getattr(cls.model_fields.get("type"), "default", None) is not ModelType.LoRA:+ continue+ try:+ cls.from_model_on_disk(mod, _overrides(path))+ except Exception:+ continue+ accepting.append(cls.__name__)++ assert accepting == [LoRA_LyCORIS_QwenImage_Config.__name__]+++def test_a_onetrainer_kohya_lora_with_text_encoder_layers_is_claimed_by_the_qwen_image_probe_alone(+ tmp_path: Path,+) -> None:+ path = tmp_path / "lora.safetensors"+ sd: dict[str, torch.Tensor] = {}+ for block in range(2):+ for module, (in_features, out_features) in {+ "attn_to_q": (3072, 3072),+ "attn_add_q_proj": (3072, 3072),+ "img_mod_1": (3072, 18432),+ "img_mlp_net_0_proj": (3072, 12288),+ "txt_mlp_net_2": (12288, 3072),+ }.items():+ layer = f"lora_unet_transformer_blocks_{block}_{module}"+ sd[f"{layer}.lora_down.weight"] = _z(16, in_features)+ sd[f"{layer}.lora_up.weight"] = _z(out_features, 16)+ sd[f"{layer}.alpha"] = torch.tensor(16.0)+ for module, (in_features, out_features) in {+ "self_attn_q_proj": (3584, 3584),+ "mlp_down_proj": (18944, 3584),+ }.items():+ layer = f"lora_te_model_language_model_layers_0_{module}"+ sd[f"{layer}.lora_down.weight"] = _z(16, in_features)+ sd[f"{layer}.lora_up.weight"] = _z(out_features, 16)+ sd[f"{layer}.alpha"] = torch.tensor(16.0)+ mod = _make_mod(path, sd)++ accepting = []+ for cls in Config_Base.CONFIG_CLASSES:+ if getattr(cls.model_fields.get("type"), "default", None) is not ModelType.LoRA:+ continue+ try:+ cls.from_model_on_disk(mod, _overrides(path))+ except Exception:+ continue+ accepting.append(cls.__name__)++ assert accepting == [LoRA_LyCORIS_QwenImage_Config.__name__]++@pytest.mark.parametrize("layers",[diff --git a/tests/backend/patches/lora_conversions/lora_state_dicts/qwen_image_lora_kohya_with_te_format.py b/tests/backend/patches/lora_conversions/lora_state_dicts/qwen_image_lora_kohya_with_te_format.pynew file mode 100644index 0000000000..3c3ff63d3a--- /dev/null+++ b/tests/backend/patches/lora_conversions/lora_state_dicts/qwen_image_lora_kohya_with_te_format.py@@ -0,0 +1,50 @@+# Kohya-format Qwen Image LoRA state dict keys with both transformer (lora_unet_) and Qwen2.5-VL text encoder+# (lora_te_) layers, as OneTrainer writes them. `lora_te_` keys flatten `model.language_model.layers.N.mlp.down_proj`+# and `model.visual.blocks.N.attn.qkv` to underscores.+state_dict_keys: dict[str, list[int]] = {+ "lora_unet_transformer_blocks_0_attn_to_k.lora_down.weight": [8, 3072],+ "lora_unet_transformer_blocks_0_attn_to_k.lora_up.weight": [3072, 8],+ "lora_unet_transformer_blocks_0_attn_to_k.alpha": [],+ "lora_unet_transformer_blocks_0_img_mlp_net_2.lora_down.weight": [8, 12288],+ "lora_unet_transformer_blocks_0_img_mlp_net_2.lora_up.weight": [3072, 8],+ "lora_unet_transformer_blocks_0_img_mlp_net_2.alpha": [],+ "lora_te_model_language_model_layers_0_self_attn_q_proj.lora_down.weight": [8, 3584],+ "lora_te_model_language_model_layers_0_self_attn_q_proj.lora_up.weight": [3584, 8],+ "lora_te_model_language_model_layers_0_self_attn_q_proj.alpha": [],+ "lora_te_model_language_model_layers_0_self_attn_k_proj.lora_down.weight": [8, 3584],+ "lora_te_model_language_model_layers_0_self_attn_k_proj.lora_up.weight": [512, 8],+ "lora_te_model_language_model_layers_0_self_attn_k_proj.alpha": [],+ "lora_te_model_language_model_layers_0_self_attn_v_proj.lora_down.weight": [8, 3584],+ "lora_te_model_language_model_layers_0_self_attn_v_proj.lora_up.weight": [512, 8],+ "lora_te_model_language_model_layers_0_self_attn_v_proj.alpha": [],+ "lora_te_model_language_model_layers_0_self_attn_o_proj.lora_down.weight": [8, 3584],+ "lora_te_model_language_model_layers_0_self_attn_o_proj.lora_up.weight": [3584, 8],+ "lora_te_model_language_model_layers_0_self_attn_o_proj.alpha": [],+ "lora_te_model_language_model_layers_0_mlp_gate_proj.lora_down.weight": [8, 3584],+ "lora_te_model_language_model_layers_0_mlp_gate_proj.lora_up.weight": [18944, 8],+ "lora_te_model_language_model_layers_0_mlp_gate_proj.alpha": [],+ "lora_te_model_language_model_layers_0_mlp_up_proj.lora_down.weight": [8, 3584],+ "lora_te_model_language_model_layers_0_mlp_up_proj.lora_up.weight": [18944, 8],+ "lora_te_model_language_model_layers_0_mlp_up_proj.alpha": [],+ "lora_te_model_language_model_layers_0_mlp_down_proj.lora_down.weight": [8, 18944],+ "lora_te_model_language_model_layers_0_mlp_down_proj.lora_up.weight": [3584, 8],+ "lora_te_model_language_model_layers_0_mlp_down_proj.alpha": [],+ "lora_te_model_visual_blocks_0_attn_qkv.lora_down.weight": [8, 1280],+ "lora_te_model_visual_blocks_0_attn_qkv.lora_up.weight": [3840, 8],+ "lora_te_model_visual_blocks_0_attn_qkv.alpha": [],+ "lora_te_model_visual_blocks_0_attn_proj.lora_down.weight": [8, 1280],+ "lora_te_model_visual_blocks_0_attn_proj.lora_up.weight": [1280, 8],+ "lora_te_model_visual_blocks_0_attn_proj.alpha": [],+ "lora_te_model_visual_blocks_0_mlp_gate_proj.lora_down.weight": [8, 1280],+ "lora_te_model_visual_blocks_0_mlp_gate_proj.lora_up.weight": [3420, 8],+ "lora_te_model_visual_blocks_0_mlp_gate_proj.alpha": [],+ "lora_te_model_visual_blocks_0_mlp_down_proj.lora_down.weight": [8, 3420],+ "lora_te_model_visual_blocks_0_mlp_down_proj.lora_up.weight": [1280, 8],+ "lora_te_model_visual_blocks_0_mlp_down_proj.alpha": [],+ "lora_te_model_visual_merger_mlp_2.lora_down.weight": [8, 5120],+ "lora_te_model_visual_merger_mlp_2.lora_up.weight": [3584, 8],+ "lora_te_model_visual_merger_mlp_2.alpha": [],+ "lora_te_lm_head.lora_down.weight": [8, 3584],+ "lora_te_lm_head.lora_up.weight": [152064, 8],+ "lora_te_lm_head.alpha": [],+}diff --git a/tests/backend/patches/lora_conversions/test_qwen_image_lora_conversion_utils.py b/tests/backend/patches/lora_conversions/test_qwen_image_lora_conversion_utils.pyindex e07471ddd3..13a729ace1 100644--- a/tests/backend/patches/lora_conversions/test_qwen_image_lora_conversion_utils.py+++ b/tests/backend/patches/lora_conversions/test_qwen_image_lora_conversion_utils.py@@ -1,10 +1,15 @@"""Tests for Qwen Image LoRA conversion utilities."""+import logging+import pytestimport torch+from transformers import Qwen2_5_VLConfig, Qwen2_5_VLForConditionalGeneration+from invokeai.backend.patches.layer_patcher import LayerPatcherfrom invokeai.backend.patches.lora_conversions.qwen_image_lora_constants import (QWEN_IMAGE_EDIT_LORA_TRANSFORMER_PREFIX,+ QWEN_IMAGE_LORA_QWEN_VL_PREFIX,)from invokeai.backend.patches.lora_conversions.qwen_image_lora_conversion_utils import (_convert_kohya_key,@@ -17,6 +22,9 @@ from tests.backend.patches.lora_conversions.lora_state_dicts.qwen_image_lora_diffrom tests.backend.patches.lora_conversions.lora_state_dicts.qwen_image_lora_kohya_format import (state_dict_keys as kohya_state_dict_keys,)+from tests.backend.patches.lora_conversions.lora_state_dicts.qwen_image_lora_kohya_with_te_format import (+ state_dict_keys as kohya_with_te_state_dict_keys,+)from tests.backend.patches.lora_conversions.lora_state_dicts.utils import keys_to_mock_state_dict# ---- Format detection tests ----@@ -122,7 +130,7 @@ def test_diffusers_key_prefix_is_stripped(prefix: str):# ---- Unknown key handling tests -----def test_kohya_unknown_submodule_is_silently_skipped():+def test_kohya_unknown_submodule_is_skipped():"""Unknown Kohya sub-modules are skipped, producing no layers for them."""state_dict = {# Known key — should produce a layer@@ -167,3 +175,183 @@ def test_peft_dora_magnitude_is_kept_as_a_dora_layer():assert isinstance(layer, DoRALayer)assert layer.magnitude_is_out_dimassert torch.equal(layer.dora_scale, magnitude)+++# ---- Text encoder layers ----+++def test_kohya_text_encoder_layers_are_routed_to_the_qwen_vl_prefix():+ """`lora_te_*` layers name Qwen2.5-VL modules (language tower, vision tower, merger, lm_head); the transformer's+ layers in the same file keep their prefix."""+ state_dict = keys_to_mock_state_dict(kohya_with_te_state_dict_keys)+ model = lora_model_from_qwen_image_state_dict(state_dict, alpha=None)++ t = QWEN_IMAGE_EDIT_LORA_TRANSFORMER_PREFIX+ te = QWEN_IMAGE_LORA_QWEN_VL_PREFIX+ assert set(model.layers) == {+ f"{t}transformer_blocks.0.attn.to_k",+ f"{t}transformer_blocks.0.img_mlp.net.2",+ f"{te}model.language_model.layers.0.self_attn.q_proj",+ f"{te}model.language_model.layers.0.self_attn.k_proj",+ f"{te}model.language_model.layers.0.self_attn.v_proj",+ f"{te}model.language_model.layers.0.self_attn.o_proj",+ f"{te}model.language_model.layers.0.mlp.gate_proj",+ f"{te}model.language_model.layers.0.mlp.up_proj",+ f"{te}model.language_model.layers.0.mlp.down_proj",+ f"{te}model.visual.blocks.0.attn.qkv",+ f"{te}model.visual.blocks.0.attn.proj",+ f"{te}model.visual.blocks.0.mlp.gate_proj",+ f"{te}model.visual.blocks.0.mlp.down_proj",+ f"{te}model.visual.merger.mlp.2",+ f"{te}lm_head",+ }++[email protected]("prefix", ["text_encoder.", "base_model.model.text_encoder."])+def test_diffusers_text_encoder_layers_are_routed_to_the_qwen_vl_prefix(prefix: str):+ """`base_model.model.` is also a transformer prefix, so it must not swallow the text-encoder layers."""+ state_dict = {+ f"{prefix}model.language_model.layers.3.mlp.down_proj.lora_A.weight": torch.empty(8, 18944),+ f"{prefix}model.language_model.layers.3.mlp.down_proj.lora_B.weight": torch.empty(3584, 8),+ f"{prefix}model.visual.blocks.1.attn.qkv.lora_A.weight": torch.empty(8, 1280),+ f"{prefix}model.visual.blocks.1.attn.qkv.lora_B.weight": torch.empty(3840, 8),+ "base_model.model.transformer_blocks.0.attn.to_k.lora_A.weight": torch.empty(8, 3072),+ "base_model.model.transformer_blocks.0.attn.to_k.lora_B.weight": torch.empty(3072, 8),+ }+ model = lora_model_from_qwen_image_state_dict(state_dict, alpha=None)++ assert set(model.layers) == {+ f"{QWEN_IMAGE_LORA_QWEN_VL_PREFIX}model.language_model.layers.3.mlp.down_proj",+ f"{QWEN_IMAGE_LORA_QWEN_VL_PREFIX}model.visual.blocks.1.attn.qkv",+ f"{QWEN_IMAGE_EDIT_LORA_TRANSFORMER_PREFIX}transformer_blocks.0.attn.to_k",+ }+++def test_unmapped_kohya_layers_produce_one_warning_with_the_count(caplog: pytest.LogCaptureFixture):+ """Layers that name no known module (an unknown transformer module, a text-encoder Linear outside the tree, a bare+ prefix of a real path) are skipped with a single warning, however many there are."""+ state_dict = {+ "lora_unet_transformer_blocks_0_attn_to_k.lora_down.weight": torch.empty(8, 3072),+ "lora_unet_transformer_blocks_0_attn_to_k.lora_up.weight": torch.empty(3072, 8),+ }+ unmapped = [+ "lora_unet_transformer_blocks_0_unknown_projection",+ "lora_te_model_visual_patch_embed_proj",+ "lora_te_model_language_model_layers_0_mlp",+ "lora_te_model_language_model_layers_0_mlp_down_proj_extra",+ ]+ for layer in unmapped:+ state_dict[f"{layer}.lora_down.weight"] = torch.empty(8, 16)+ state_dict[f"{layer}.lora_up.weight"] = torch.empty(16, 8)++ with caplog.at_level(logging.WARNING):+ model = lora_model_from_qwen_image_state_dict(state_dict, alpha=None)++ assert set(model.layers) == {f"{QWEN_IMAGE_EDIT_LORA_TRANSFORMER_PREFIX}transformer_blocks.0.attn.to_k"}+ warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]+ assert len(warnings) == 1+ assert "Skipped 4 " in warnings[0]+++def test_every_linear_of_a_qwen2_5_vl_encoder_is_reachable_from_its_onetrainer_key():+ """The Kohya key of each Linear in the real module tree converts to a path the patcher resolves to that very+ module. Built from the model's own names, so a module missing from the parsing tree fails here."""+ config = Qwen2_5_VLConfig(+ text_config={+ "hidden_size": 64,+ "intermediate_size": 128,+ "num_hidden_layers": 2,+ "num_attention_heads": 4,+ "num_key_value_heads": 2,+ "vocab_size": 512,+ "rope_scaling": {"type": "mrope", "mrope_section": [2, 3, 3]},+ },+ vision_config={+ "depth": 2,+ "hidden_size": 32,+ "intermediate_size": 64,+ "num_heads": 4,+ "out_hidden_size": 64,+ "fullatt_block_indexes": [1],+ },+ )+ with torch.device("meta"):+ encoder = Qwen2_5_VLForConditionalGeneration(config)+ linears = {name: module for name, module in encoder.named_modules() if isinstance(module, torch.nn.Linear)}+ assert any(name.startswith("model.visual.merger") for name in linears)++ state_dict = {}+ for name in linears:+ layer = "lora_te_" + name.replace(".", "_")+ state_dict[f"{layer}.lora_down.weight"] = torch.empty(4, 8)+ state_dict[f"{layer}.lora_up.weight"] = torch.empty(8, 4)+ state_dict["lora_unet_transformer_blocks_0_attn_to_k.lora_down.weight"] = torch.empty(4, 8)+ state_dict["lora_unet_transformer_blocks_0_attn_to_k.lora_up.weight"] = torch.empty(8, 4)+ model = lora_model_from_qwen_image_state_dict(state_dict, alpha=None)++ resolved = {}+ for layer_key in model.layers:+ if layer_key.startswith(QWEN_IMAGE_LORA_QWEN_VL_PREFIX):+ module_key, module = LayerPatcher._get_submodule(+ encoder, layer_key[len(QWEN_IMAGE_LORA_QWEN_VL_PREFIX) :], layer_key_is_flattened=False+ )+ resolved[module_key] = module+ assert resolved.keys() == linears.keys()+ assert all(resolved[name] is linears[name] for name in linears)++[email protected]("prefix", ["text_encoder.", "base_model.model.text_encoder."])+def test_diffusers_text_encoder_layers_that_are_not_encoder_linears_are_skipped_with_one_warning(+ prefix: str, caplog: pytest.LogCaptureFixture+):+ """A Conv3d (`patch_embed`) cannot hold a patch and would crash the patcher, and the transformers < 4.52 layout+ (`model.layers.N`) names nothing in the current encoder. Both join the single counted warning."""+ state_dict = {+ f"{prefix}model.language_model.layers.0.mlp.down_proj.lora_A.weight": torch.empty(8, 18944),+ f"{prefix}model.language_model.layers.0.mlp.down_proj.lora_B.weight": torch.empty(3584, 8),+ f"{prefix}model.visual.patch_embed.proj.lora_A.weight": torch.empty(8, 1176),+ f"{prefix}model.visual.patch_embed.proj.lora_B.weight": torch.empty(1280, 8),+ f"{prefix}model.layers.0.mlp.down_proj.lora_A.weight": torch.empty(8, 18944),+ f"{prefix}model.layers.0.mlp.down_proj.lora_B.weight": torch.empty(3584, 8),+ f"{prefix}model.language_model.layers.0.mlp.lora_A.weight": torch.empty(8, 16),+ f"{prefix}model.language_model.layers.0.mlp.lora_B.weight": torch.empty(16, 8),+ }++ with caplog.at_level(logging.WARNING):+ model = lora_model_from_qwen_image_state_dict(state_dict, alpha=None)++ assert set(model.layers) == {f"{QWEN_IMAGE_LORA_QWEN_VL_PREFIX}model.language_model.layers.0.mlp.down_proj"}+ warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]+ assert len(warnings) == 1+ assert "Skipped 3 " in warnings[0]+++def test_onetrainer_comfy_text_encoder_keys_are_routed_beside_diffusion_model_transformer_keys(+ caplog: pytest.LogCaptureFixture,+):+ """OneTrainer's COMFY_LORA export writes encoder layers as `text_encoders.qwen25_7b.transformer.<module>`."""+ te = "text_encoders.qwen25_7b.transformer."+ modules = {+ f"{te}model.language_model.layers.0.mlp.down_proj": (18944, 3584),+ f"{te}model.visual.blocks.0.attn.qkv": (1280, 3840),+ f"{te}model.visual.merger.mlp.0": (5120, 5120),+ f"{te}lm_head": (3584, 152064),+ "diffusion_model.transformer_blocks.0.attn.to_k": (3072, 3072),+ }+ state_dict = {}+ for layer, (in_features, out_features) in modules.items():+ state_dict[f"{layer}.lora_down.weight"] = torch.empty(8, in_features)+ state_dict[f"{layer}.lora_up.weight"] = torch.empty(out_features, 8)++ with caplog.at_level(logging.WARNING):+ model = lora_model_from_qwen_image_state_dict(state_dict, alpha=None)++ t, v = QWEN_IMAGE_EDIT_LORA_TRANSFORMER_PREFIX, QWEN_IMAGE_LORA_QWEN_VL_PREFIX+ assert set(model.layers) == {+ f"{t}transformer_blocks.0.attn.to_k",+ f"{v}model.language_model.layers.0.mlp.down_proj",+ f"{v}model.visual.blocks.0.attn.qkv",+ f"{v}model.visual.merger.mlp.0",+ f"{v}lm_head",+ }+ assert not [r for r in caplog.records if r.levelno == logging.WARNING]diff --git a/tests/backend/quantization/test_qwen_vl_bnb_lora.py b/tests/backend/quantization/test_qwen_vl_bnb_lora.pynew file mode 100644index 0000000000..5f20dd5f3e--- /dev/null+++ b/tests/backend/quantization/test_qwen_vl_bnb_lora.py@@ -0,0 +1,139 @@+"""LoRA on a BitsAndBytes-quantized Qwen2.5-VL encoder, loaded the way the Qwen-Image text encoder node loads it.++transformers builds plain `bnb.nn.Linear8bitLt` / `Linear4bit` layers, which cannot hold a sidecar patch; the node+converts them with `_make_bnb_layers_patchable`. Needs CUDA (bitsandbytes quantizes on the device).+"""++from pathlib import Path++import pytest+import torch++pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="BitsAndBytes quantization needs CUDA")++HIDDEN = 64+RANK = 4+WEIGHT = 0.6+DEVICE = torch.device("cuda:0")+++def _tiny_config():+ from transformers import Qwen2_5_VLConfig++ return Qwen2_5_VLConfig(+ text_config={+ "hidden_size": HIDDEN,+ "intermediate_size": 128,+ "num_hidden_layers": 2,+ "num_attention_heads": 4,+ "num_key_value_heads": 2,+ "vocab_size": 512,+ "max_position_embeddings": 256,+ "tie_word_embeddings": False,+ "rope_scaling": {"type": "mrope", "mrope_section": [2, 3, 3]},+ },+ vision_config={+ "depth": 2,+ "hidden_size": 32,+ "intermediate_size": 64,+ "num_heads": 4,+ "out_hidden_size": HIDDEN,+ "fullatt_block_indexes": [1],+ },+ )++[email protected](scope="module")+def checkpoint(tmp_path_factory: pytest.TempPathFactory) -> Path:+ from transformers import Qwen2_5_VLForConditionalGeneration++ torch.manual_seed(0)+ path = tmp_path_factory.mktemp("tiny_qwen_vl")+ Qwen2_5_VLForConditionalGeneration(_tiny_config()).to(torch.bfloat16).save_pretrained(path)+ return path+++def _load(checkpoint: Path, quantization: str):+ """As `_load_quantized_encoder` loads it."""+ from transformers import BitsAndBytesConfig, Qwen2_5_VLForConditionalGeneration++ if quantization == "nf4":+ config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_quant_type="nf4")+ else:+ config = BitsAndBytesConfig(load_in_8bit=True)+ return Qwen2_5_VLForConditionalGeneration.from_pretrained(+ str(checkpoint), quantization_config=config, device_map={"": DEVICE}, dtype=torch.bfloat16+ )+++def _patch_for(layer_name: str, in_features: int, out_features: int):+ from invokeai.backend.patches.lora_conversions.qwen_image_lora_conversion_utils import (+ lora_model_from_qwen_image_state_dict,+ )++ generator = torch.Generator().manual_seed(3)+ down = torch.randn(RANK, in_features, generator=generator) * 0.1+ up = torch.randn(out_features, RANK, generator=generator) * 0.1+ patch = lora_model_from_qwen_image_state_dict(+ {f"text_encoder.{layer_name}.lora_A.weight": down, f"text_encoder.{layer_name}.lora_B.weight": up}+ )+ return patch, down, up++[email protected]("quantization", ["int8", "nf4"])+ ("layer_name", "in_features", "out_features"),+ [+ ("model.language_model.layers.0.mlp.down_proj", 128, HIDDEN),+ ("model.language_model.layers.1.self_attn.q_proj", HIDDEN, HIDDEN),+ ("lm_head", HIDDEN, 512), # not quantized by transformers: a plain Linear+ ],+)+def test_sidecar_lora_on_a_bnb_quantized_encoder(+ checkpoint: Path, quantization: str, layer_name: str, in_features: int, out_features: int+) -> None:+ import bitsandbytes as bnb++ from invokeai.app.invocations.text_encoder.qwen_image_text_encoder import _make_bnb_layers_patchable+ from invokeai.backend.patches.layer_patcher import LayerPatcher+ from invokeai.backend.patches.lora_conversions.qwen_image_lora_constants import QWEN_IMAGE_LORA_QWEN_VL_PREFIX++ input_ids = torch.arange(16, device=DEVICE).reshape(1, 16)+ # A separate instance: the plain int8 forward moves CB/SCB off the weight, so the model under test must be wrapped+ # before its first forward, as in the node. Quantization is deterministic, so the two instances agree.+ reference = _load(checkpoint, quantization)+ with torch.no_grad():+ reference_hidden = reference(input_ids=input_ids, output_hidden_states=True).hidden_states[-1]+ del reference++ model = _load(checkpoint, quantization)+ _make_bnb_layers_patchable(model)++ layer = model.get_submodule(layer_name)+ if layer_name != "lm_head":+ assert isinstance(layer, (bnb.nn.Linear8bitLt, bnb.nn.Linear4bit)), "wrapping must keep the bnb base class"+ assert hasattr(layer, "add_patch")+ x = torch.randn(1, 5, in_features, device=DEVICE, dtype=torch.bfloat16)+ patch, down, up = _patch_for(layer_name, in_features, out_features)++ with torch.no_grad():+ # Wrapped layers without a patch compute what the unwrapped model did.+ wrapped_hidden = model(input_ids=input_ids, output_hidden_states=True).hidden_states[-1]+ assert torch.equal(wrapped_hidden, reference_hidden)++ unpatched = layer(x)+ with LayerPatcher.apply_smart_model_patches(+ model=model,+ patches=[(patch, WEIGHT)],+ prefix=QWEN_IMAGE_LORA_QWEN_VL_PREFIX,+ dtype=torch.bfloat16,+ force_sidecar_patching=True,+ ):+ assert layer.get_num_patches() == 1+ patched = layer(x)+ after = layer(x)++ expected_shift = (x.float() @ (up @ down).T.to(DEVICE) * WEIGHT).to(torch.bfloat16)+ torch.testing.assert_close((patched - unpatched).float(), expected_shift.float(), atol=0.05, rtol=0.1)+ assert layer.get_num_patches() == 0+ assert torch.equal(after, unpatched)diff --git a/tests/backend/quantization/test_qwen_vl_bnb_wrap_cpu.py b/tests/backend/quantization/test_qwen_vl_bnb_wrap_cpu.pynew file mode 100644index 0000000000..eef7c511a7--- /dev/null+++ b/tests/backend/quantization/test_qwen_vl_bnb_wrap_cpu.py@@ -0,0 +1,103 @@+"""The BitsAndBytes layers transformers builds for the Qwen-Image text encoder accept a sidecar LoRA after the node's wrap.++bitsandbytes quantizes on the CPU as well (0.50), so this guards `BNB_LINEAR_TYPE_MAPPING` and the wrap in every CI+lane; `test_qwen_vl_bnb_lora.py` covers the same on a real model with CUDA. float32 throughout: CPU bf16 matmul is+unsafe on part of the CI fleet.+"""++import pytest+import torch++bnb = pytest.importorskip("bitsandbytes")++from invokeai.app.invocations.text_encoder.qwen_image_text_encoder import _make_bnb_layers_patchable # noqa: E402+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_invoke_linear_8_bit_lt import ( # noqa: E402+ CustomInvokeLinear8bitLt,+)+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_invoke_linear_nf4 import ( # noqa: E402+ CustomInvokeLinearNF4,+)+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_linear import ( # noqa: E402+ CustomLinear,+)+from invokeai.backend.patches.layer_patcher import LayerPatcher # noqa: E402+from invokeai.backend.patches.layers.utils import any_lora_layer_from_state_dict # noqa: E402+from invokeai.backend.patches.model_patch_raw import ModelPatchRaw # noqa: E402++FEATURES = 64+RANK = 4+WEIGHT = 0.6+++class _TinyEncoder(torch.nn.Module):+ """One quantized Linear as transformers builds it, and one that transformers leaves alone (like `lm_head`)."""++ def __init__(self, quantization: str) -> None:+ super().__init__()+ torch.manual_seed(0)+ weight = torch.randn(FEATURES, FEATURES)+ if quantization == "int8":+ self.quantized = bnb.nn.Linear8bitLt(FEATURES, FEATURES, bias=False, has_fp16_weights=False)+ self.quantized.weight = bnb.nn.Int8Params(weight, requires_grad=False, has_fp16_weights=False)+ else:+ self.quantized = bnb.nn.Linear4bit(+ FEATURES, FEATURES, bias=False, compute_dtype=torch.float32, quant_type="nf4"+ )+ self.quantized.weight = bnb.nn.Params4bit(weight, requires_grad=False, quant_type="nf4")+ self.plain = torch.nn.Linear(FEATURES, FEATURES, bias=False)++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ return self.plain(self.quantized(x))+++def _build(quantization: str) -> _TinyEncoder:+ try:+ # Moving the module is what quantizes the weights.+ return _TinyEncoder(quantization).to("cpu")+ except (NotImplementedError, RuntimeError) as exc:+ pytest.skip(f"bitsandbytes {bnb.__version__} cannot quantize {quantization} on the CPU: {exc}")++[email protected]("quantization", ["int8", "nf4"])+def test_a_sidecar_lora_applies_to_wrapped_bnb_layers_and_leaves_no_trace(quantization: str) -> None:+ reference = _build(quantization)+ model = _build(quantization)+ x = torch.randn(3, FEATURES, generator=torch.Generator().manual_seed(1))+ with torch.no_grad():+ expected_output = reference(x)++ # Before the first forward, as in the node: the plain int8 forward moves CB/SCB off the weight.+ _make_bnb_layers_patchable(model)++ assert type(model.quantized) is (CustomInvokeLinear8bitLt if quantization == "int8" else CustomInvokeLinearNF4)+ assert type(model.plain) is CustomLinear++ generator = torch.Generator().manual_seed(2)+ down, up = torch.randn(RANK, FEATURES, generator=generator), torch.randn(FEATURES, RANK, generator=generator)+ patch = ModelPatchRaw(+ layers={+ f"lora_qwen_vl-{name}": any_lora_layer_from_state_dict({"lora_down.weight": down, "lora_up.weight": up})+ for name in ("quantized", "plain")+ }+ )+ with torch.no_grad():+ unpatched = model(x)+ # A wrapped layer without a patch computes what the plain one does.+ torch.testing.assert_close(unpatched, expected_output, atol=0, rtol=0)++ with LayerPatcher.apply_smart_model_patches(+ model=model,+ patches=[(patch, WEIGHT)],+ prefix="lora_qwen_vl-",+ dtype=torch.float32,+ force_sidecar_patching=True,+ ):+ patched_quantized = model.quantized(x)+ patched_plain = model.plain(x)+ restored = model(x)++ shift = x @ (up @ down).T * WEIGHT+ torch.testing.assert_close(patched_quantized - reference.quantized(x), shift, atol=1e-4, rtol=1e-4)+ torch.testing.assert_close(patched_plain - reference.plain(x), shift, atol=1e-4, rtol=1e-4)+ torch.testing.assert_close(restored, expected_output, atol=0, rtol=0)+ assert model.quantized.get_num_patches() == 0 and model.plain.get_num_patches() == 0