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): skip the unused Qwen2.5-VL lm_head in all encoder loaders (#10392)
Rahul selvaraj78eded1a5899
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 91e68b5b33..fe8cdd69cb 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@@ -105,8 +105,8 @@ weights packed; only its dequantized embeddings and the per-layer dequantizationSingle-file Qwen3 and Qwen2.5-VL (`qwen_2.5_vl_7b_fp8_scaled`) encoders in ComfyUI's scaled fp8 layout also keep theirLinear layers in fp8, with the file's own scales, on a GPU that can hold fp8: about 4.4 GB instead of about 8.0 GB for-Qwen3 4B, about 8.2 GB instead of about 15.1 GB for Qwen3 8B, and about the size of the file (9.4 GB) instead of about-16.6 GB for Qwen2.5-VL. They are dequantized layer by layer on each forward and never multiplied in fp8, whatever+Qwen3 4B, about 8.2 GB instead of about 15.1 GB for Qwen3 8B, and about 8.3 GB (the file less its unused LM head) instead+of about 15.5 GB for Qwen2.5-VL. They are dequantized layer by layer on each forward and never multiplied in fp8, whatever`fp8_compute` says. Token embeddings are always widened to the compute dtype. On a CPU, and for a Qwen3 encoder set torun on the CPU, everything is widened to the dtype the encoder computes in. An MXFP8 encoder file that names its layersin its markers or header loads too, decoded to bf16; MX scales that nothing names are refused, as is any scaled fp8 filediff --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 3b5f2f67bb..833e97c83e 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@@ -83,10 +83,10 @@ Qwen Image needs three components:free system RAM, because it is widened to bf16 before FP8 Storage casts it back.Four Qwen2.5-VL encoder builds are available as starter models: **fp8 scaled** (~9.4 GB, the one the-bundle installs), **NVFP4** (~5.7 GB download, about 6.7 GB once loaded), **GGUF Q4_K_M** (~4.7 GB, text+bundle installs), **NVFP4** (~5.7 GB download, about 6.1 GB once loaded), **GGUF Q4_K_M** (~4.7 GB, textonly) and **Diffusers** (~16 GB, full precision). The single-file and GGUF encoders ship with theirtokenizer and config inside InvokeAI. The fp8 scaled encoder stays fp8 in memory on a GPU that can hold it, about-the size of the file instead of the about 16.6 GB it takes widened to bf16; on a CPU it is widened.+8.3 GB instead of the about 15.5 GB it takes widened to bf16; on a CPU it is widened.The **GGUF** encoders are llama.cpp builds of Qwen2.5-VL-7B-Instruct (e.g. from`unsloth/Qwen2.5-VL-7B-Instruct-GGUF`) and hold only the language model. They encode text prompts, but cannotdiff --git a/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py b/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.pyindex 0202c83e36..268a759234 100644--- a/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py+++ b/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py@@ -63,10 +63,10 @@ _GENERATE_SYSTEM_PROMPT = (_GENERATE_DROP_IDX = 34# Fraction of the on-disk (bf16) encoder that stays resident after BitsAndBytes quantization. Linear weights-# shrink to 8 or 4 bits, but embeddings, norms, biases and the (excluded) lm_head stay in bf16, and nf4 carries-# per-block absmax scales, so the ratios sit above the pure 1/2 and 1/4. Over-estimating only offloads a little-# more of the cached models to RAM, whereas under-estimating leaves the encoder without enough VRAM, so both-# values are deliberately conservative.+# shrink to 8 or 4 bits, but embeddings, norms and biases stay in bf16, and nf4 carries per-block absmax scales, so+# the ratios sit above the pure 1/2 and 1/4. The folder's size also counts the lm_head, which is never loaded.+# Over-estimating only offloads a little more of the cached models to RAM, whereas under-estimating leaves the+# encoder without enough VRAM, so both values are deliberately conservative._QUANTIZED_SIZE_RATIO: dict[str, float] = {"int8": 0.6, "nf4": 0.4}_IMAGE_PLACEHOLDER = "<|vision_start|><|image_pad|><|vision_end|>"@@ -80,8 +80,8 @@ 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.+ converted (the layers share state with the originals), and any Linear BnB left unconverted comes 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 customlayer reads them."""@@ -113,6 +113,8 @@ def _read_checkpoint(encoder_path: Path) -> dict[str, torch.Tensor] | None:state_dict: dict[str, torch.Tensor] = {}for shard_name in shard_names:state_dict.update(load_file(encoder_path / shard_name))+ # The encoder is built without the LM head, so there is no point reading its pages from disk.+ state_dict.pop("lm_head.weight", None)for tensor in state_dict.values():# A strided read of one byte per page faults the whole tensor in through the very mapping transformers will# read from; the sum itself is discarded.@@ -486,7 +488,9 @@ class QwenImageTextEncoderInvocation(BaseInvocation):layers to the CPU, which BnB int8 refuses with "Some modules are dispatched onthe CPU or the disk" (issue #9147)."""- from transformers import BitsAndBytesConfig, Qwen2_5_VLConfig, Qwen2_5_VLForConditionalGeneration+ from transformers import BitsAndBytesConfig, Qwen2_5_VLConfig++ from invokeai.backend.qwen2_5_vl.headless import HeadlessQwen2_5_VLForConditionalGenerationencoder_config = context.models.get_config(self.qwen_vl_encoder.text_encoder)model_root = context.models.get_absolute_path(encoder_config)@@ -556,7 +560,7 @@ class QwenImageTextEncoderInvocation(BaseInvocation):state_dict = _read_checkpoint(encoder_path)with MODEL_LOAD_LOCK.write_lock():- text_encoder = Qwen2_5_VLForConditionalGeneration.from_pretrained(+ text_encoder = HeadlessQwen2_5_VLForConditionalGeneration.from_pretrained(None if state_dict is not None else str(encoder_path),config=model_config,state_dict=state_dict,diff --git a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py b/invokeai/backend/model_manager/load/model_loaders/qwen_image.pyindex e6e9a05e7a..04b030a057 100644--- a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/qwen_image.py@@ -105,6 +105,11 @@ def _remap_qwen_vl_checkpoint_keys(sd: dict) -> dict:return remapped_sd+def _is_lm_head_name(name: object) -> bool:+ """Whether a single-file key or module path belongs to the LM head, in either spelling, sidecars included."""+ return isinstance(name, str) and name.removeprefix("model.").split(".", 1)[0] == "lm_head"++def _build_qwen_image_transformer_config(sd: dict, is_edit: bool) -> dict:"""Auto-detect Qwen Image transformer architecture parameters from the state dict.@@ -179,6 +184,13 @@ class QwenImageDiffusersModel(GenericDiffusersLoader):model_path = Path(config.path)load_class = self.get_hf_load_class(model_path, submodel_type)+ if submodel_type is SubModelType.TextEncoder:+ from transformers import Qwen2_5_VLForConditionalGeneration++ from invokeai.backend.qwen2_5_vl.headless import HeadlessQwen2_5_VLForConditionalGeneration++ if load_class is Qwen2_5_VLForConditionalGeneration:+ load_class = HeadlessQwen2_5_VLForConditionalGenerationrepo_variant = config.repo_variant if isinstance(config, Diffusers_Config_Base) else Nonevariant = repo_variant.value if repo_variant else Nonemodel_path = model_path / submodel_type.value@@ -437,7 +449,9 @@ class QwenVLEncoderLoader(ModelLoader):if not isinstance(config, QwenVLEncoder_Diffusers_Config):raise TypeError(f"Expected QwenVLEncoder_Diffusers_Config, got {type(config).__name__}.")- from transformers import AutoTokenizer, Qwen2_5_VLForConditionalGeneration+ from transformers import AutoTokenizer++ from invokeai.backend.qwen2_5_vl.headless import HeadlessQwen2_5_VLForConditionalGenerationmodel_path = Path(config.path)@@ -450,7 +464,7 @@ class QwenVLEncoderLoader(ModelLoader):return AutoTokenizer.from_pretrained(str(tokenizer_path), local_files_only=True)case SubModelType.TextEncoder:encoder_path = model_path / "text_encoder"- return Qwen2_5_VLForConditionalGeneration.from_pretrained(+ return HeadlessQwen2_5_VLForConditionalGeneration.from_pretrained(str(encoder_path),torch_dtype=model_dtype,low_cpu_mem_usage=True,@@ -518,6 +532,7 @@ class QwenVLEncoderCheckpointLoader(ModelLoader):def _load_text_encoder_from_singlefile(self, config: QwenVLEncoder_Checkpoint_Config) -> AnyModel:from transformers import Qwen2_5_VLConfig, Qwen2_5_VLForConditionalGeneration+ from invokeai.backend.qwen2_5_vl.headless import OmittedLMHeadfrom invokeai.backend.util.logging import InvokeAILoggerlogger = InvokeAILogger.get_logger(self.__class__.__name__)@@ -527,11 +542,15 @@ class QwenVLEncoderCheckpointLoader(ModelLoader):device_keeps_fp8, model_dtype = self._storage_format(config)sd = load_safetensors_checkpoint(str(model_path))+ header_layers = parse_quantization_metadata(read_safetensors_metadata(model_path, logger))+ # The LM head is not loaded. Its weight, quantization sidecars and header entry go first, so that nothing below+ # folds, installs or reserves room for them.+ sd = {key: value for key, value in sd.items() if not _is_lm_head_name(key)}+ header_layers = {path: hint for path, hint in header_layers.items() if not _is_lm_head_name(path)}# Comfy's nvfp4 build keeps the language model's projections in nvfp4, beside scaled fp8 embeddings. Take those# layers out before the fp8 extraction: it pops every `.weight_scale`, nvfp4's block scales included.# `install_nvfp4_layers` puts them back, packed.- header_layers = parse_quantization_metadata(read_safetensors_metadata(model_path, logger))nvfp4_payloads = pop_nvfp4_layers(sd, header_layers=header_layers)# ComfyUI 'int8_tensorwise' (+convrot) shares the fp8 key layout, and the fp8 extraction below treats@@ -553,6 +572,7 @@ class QwenVLEncoderCheckpointLoader(ModelLoader):# Built before the reservation, which depends on its modules: they decide which nvfp4 layers stay packed.with accelerate.init_empty_weights():model = Qwen2_5_VLForConditionalGeneration(qwen_config)+ model.lm_head = OmittedLMHead()skip_patterns = _model_declared_skip_patterns(model)# The packed and int8 layers are named in the same legacy layout as the keys.nvfp4_payloads = _remap_qwen_vl_checkpoint_keys(nvfp4_payloads)@@ -621,20 +641,10 @@ class QwenVLEncoderCheckpointLoader(ModelLoader):packed = install_nvfp4_layers(model, sd, nvfp4_payloads, model_dtype, skip_patterns)logger.info(f"Qwen VL encoder: kept {packed} of {len(nvfp4_payloads)} nvfp4 layer(s) packed.")- # Load weights; allow missing keys for tied lm_head and re-initialised buffers.+ # Load weights; allow missing keys for re-initialised buffers.load_result = model.load_state_dict(sd, strict=False, assign=True)log_unexpected_keys("Qwen2.5-VL text encoder checkpoint", load_result.unexpected_keys)- # Tie lm_head ↔ embed_tokens if config requires it and lm_head wasn't loaded- if getattr(qwen_config, "tie_word_embeddings", False):- try:- if hasattr(model, "lm_head") and model.lm_head.weight.is_meta:- model.lm_head.weight = model.model.embed_tokens.weight- else:- model.tie_weights()- except AttributeError:- model.tie_weights()-# Re-initialise any leftover meta buffers (RoPE inv_freq etc.)for name, buffer in list(model.named_buffers()):if not buffer.is_meta:@@ -680,19 +690,6 @@ class QwenVLEncoderCheckpointLoader(ModelLoader):_GGUF_LM_HEAD_KEY = "output.weight"-class _OmittedLMHead(torch.nn.Module):- """Stands in for the LM head of an encoder loaded without it.-- The encoder's consumers take hidden states from the inner model, so nothing runs the head. A caller that runs- the full forward gets this error rather than logits from an uninitialized weight.- """-- def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:- raise RuntimeError(- "This Qwen2.5-VL encoder was loaded from GGUF without its LM head; call `.model(...)` for hidden states."- )--@ModelLoaderRegistry.register(base=BaseModelType.Any, type=ModelType.QwenVLEncoder, format=ModelFormat.GGUFQuantized)class QwenVLEncoderGGUFLoader(ModelLoader):"""Loads a llama.cpp GGUF of the Qwen2.5-VL-7B language model as a text-only Qwen-Image encoder.@@ -734,6 +731,8 @@ class QwenVLEncoderGGUFLoader(ModelLoader):def _load_text_encoder(self, config: QwenVLEncoder_GGUF_Config) -> AnyModel:from transformers import Qwen2_5_VLConfig, Qwen2_5_VLForConditionalGeneration+ from invokeai.backend.qwen2_5_vl.headless import OmittedLMHead+compute_dtype = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device())qwen_config = Qwen2_5_VLConfig.from_dict(load_bundled_qwen2_5_vl_config_dict())@@ -745,7 +744,7 @@ class QwenVLEncoderGGUFLoader(ModelLoader):with accelerate.init_empty_weights():model = Qwen2_5_VLForConditionalGeneration(qwen_config)drop_qwen3vl_visual_tower(model.model)- model.lm_head = _OmittedLMHead()+ model.lm_head = OmittedLMHead()unpacked = unpack_ggml_at_load(sd, model, _model_declared_skip_patterns(model), self._ram_cache.make_room)diff --git a/invokeai/backend/model_manager/starter_models/common.py b/invokeai/backend/model_manager/starter_models/common.pyindex f13100ea17..39d4acc6ac 100644--- a/invokeai/backend/model_manager/starter_models/common.py+++ b/invokeai/backend/model_manager/starter_models/common.py@@ -193,7 +193,7 @@ qwen_vl_encoder_nvfp4 = StarterModel(base=BaseModelType.Any,source="https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI/resolve/main/split_files/text_encoders/qwen_2.5_vl_7b_nvfp4.safetensors",description="ComfyUI's single-file nvfp4/fp8-mixed Qwen2.5-VL 7B encoder. Bundles the language model and visual "- "tower; its tokenizer and config ship with InvokeAI. Its nvfp4 layers stay packed, about 6.7GB "+ "tower; its tokenizer and config ship with InvokeAI. Its nvfp4 layers stay packed, about 6.1GB ""once loaded. ~5.7GB download",type=ModelType.QwenVLEncoder,format=ModelFormat.Checkpoint,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 344edaf287..c5dab8ffe6 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@@ -49,7 +49,8 @@ _DIFFUSERS_TEXT_ENCODER_PREFIXES = (_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.+# underscores, and some module names contain underscores themselves, so the tree is what tells them apart. `lm_head` is+# left out: the encoder is loaded without it, so its LoRA layers have nothing to patch._KOHYA_TEXT_ENCODER_TREE: ParsingTree = {"model": {"language_model": {@@ -65,7 +66,6 @@ _KOHYA_TEXT_ENCODER_TREE: ParsingTree = {"merger": {"mlp": {"0": {}, "2": {}}},},},- "lm_head": {},}# Prefixes of the flattened (Kohya-style) spellings: Kohya's, LyCORIS' own, and ai-toolkit's.diff --git a/invokeai/backend/qwen2_5_vl/headless.py b/invokeai/backend/qwen2_5_vl/headless.pynew file mode 100644index 0000000000..008d1031a9--- /dev/null+++ b/invokeai/backend/qwen2_5_vl/headless.py@@ -0,0 +1,38 @@+"""The Qwen2.5-VL encoder without its LM head, as every Qwen-Image encoder loader builds it.++Conditioning reads the inner model's hidden states, so nothing runs the head. Its untied weight (152064 x 3584 on the+7B, about 1.09 GB in bf16) would only be held in RAM and moved to VRAM.+"""++import torch+from transformers import Qwen2_5_VLConfig, Qwen2_5_VLForConditionalGeneration+++class OmittedLMHead(torch.nn.Module):+ """Stands in for the LM head of an encoder loaded without it.++ The encoder's consumers take hidden states from the inner model, so nothing runs the head. A caller that runs+ the full forward gets this error rather than logits from an uninitialized weight.+ """++ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:+ raise RuntimeError(+ "This Qwen2.5-VL encoder was loaded without its LM head; call `.model(...)` for hidden states."+ )+++class HeadlessQwen2_5_VLForConditionalGeneration(Qwen2_5_VLForConditionalGeneration):+ """`Qwen2_5_VLForConditionalGeneration` whose `from_pretrained` leaves `lm_head.weight` unread."""++ # A config that ties the head to the embeddings has nothing to tie it to.+ _tied_weights_keys: dict[str, str] = {}+ _keys_to_ignore_on_load_unexpected = [r"^lm_head\."]++ def __init__(self, config: Qwen2_5_VLConfig):+ super().__init__(config)+ self.lm_head = OmittedLMHead()+++# transformers picks the key conversion for the legacy checkpoint layout (`model.layers.*`, `visual.*`) by class name,+# so under its own name this class would load none of those weights.+HeadlessQwen2_5_VLForConditionalGeneration.__name__ = Qwen2_5_VLForConditionalGeneration.__name__diff --git a/tests/app/invocations/test_qwen_image_text_encoder.py b/tests/app/invocations/test_qwen_image_text_encoder.pyindex b60f114748..1f5dcc3cbb 100644--- a/tests/app/invocations/test_qwen_image_text_encoder.py+++ b/tests/app/invocations/test_qwen_image_text_encoder.py@@ -26,6 +26,7 @@ from invokeai.app.invocations.text_encoder.qwen_image_text_encoder import ()from invokeai.backend.model_manager.load.model_cache.model_cache import MB, MODEL_LOAD_LOCKfrom invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType+from invokeai.backend.qwen2_5_vl.headless import HeadlessQwen2_5_VLForConditionalGenerationfrom invokeai.backend.util.devices import TorchDevice@@ -429,6 +430,43 @@ class TestQuantizedEncoderLoad:assert f"{int(self.TOTAL_SIZE * 0.6) / MB:.0f} MB" in messageassert "cuda:0" in message+ def test_neither_reads_nor_builds_the_lm_head(self, tmp_path: Path):+ """A real read and `from_pretrained`, with only the quantization (which needs a GPU in practice) switched+ off: the head's 1.09 GB would otherwise go to VRAM with the encoder, and nothing runs it."""+ torch.manual_seed(0)+ reference = Qwen2_5_VLForConditionalGeneration(_tiny_config()).to(torch.bfloat16)+ reference.save_pretrained(tmp_path / "qwen-vl" / "text_encoder")+ context = MagicMock()+ context.models.get_absolute_path.return_value = tmp_path / "qwen-vl"+ invocation = self._make_invocation("nf4")+ invocation.qwen_vl_encoder.loras = []+ read: list[str] = []++ def recording_read(encoder_path: Path):+ state_dict = _read_checkpoint(encoder_path)+ read.extend(state_dict)+ return state_dict++ with (+ patch(+ "invokeai.app.invocations.text_encoder.qwen_image_text_encoder._read_checkpoint",+ side_effect=recording_read,+ ),+ patch("transformers.BitsAndBytesConfig", return_value=None),+ patch.object(TorchDevice, "choose_torch_device", return_value=torch.device("cpu")),+ ):+ text_encoder, _, cleanup = invocation._load_quantized_encoder(context)++ assert "lm_head.weight" not in read+ assert list(text_encoder.lm_head.parameters()) == []+ expected = reference.state_dict()+ del expected["lm_head.weight"]+ loaded = text_encoder.state_dict()+ assert loaded.keys() == expected.keys()+ assert all(torch.equal(loaded[key], expected[key]) for key in loaded)+ del text_encoder+ cleanup()+@pytest.mark.parametrize(("error_type", "error_message"), [(torch.OutOfMemoryError, "CUDA out of memory"), (ValueError, "bad shard")])@@ -575,7 +613,7 @@ class TestTransformersLoadPathAssumptions:@staticmethoddef _load(path: Path) -> Qwen2_5_VLForConditionalGeneration:# The exact call shape production uses (minus the device map and quantization, which need a GPU).- return Qwen2_5_VLForConditionalGeneration.from_pretrained(+ return HeadlessQwen2_5_VLForConditionalGeneration.from_pretrained(None,config=Qwen2_5_VLConfig.from_pretrained(str(path), local_files_only=True),state_dict=_read_checkpoint(path),@@ -644,6 +682,7 @@ class TestTransformersLoadPathAssumptions:loaded = self._load(tmp_path).state_dict()+ del source["lm_head.weight"]assert set(loaded) == set(source)assert all(torch.equal(loaded[name], source[name]) for name in source)diff --git a/tests/backend/model_manager/load/test_qwen_image_encoder_fp8.py b/tests/backend/model_manager/load/test_qwen_image_encoder_fp8.pyindex 3e291ae464..a7f8394fcd 100644--- a/tests/backend/model_manager/load/test_qwen_image_encoder_fp8.py+++ b/tests/backend/model_manager/load/test_qwen_image_encoder_fp8.py@@ -3,10 +3,10 @@The real `Qwen2_5_VLForConditionalGeneration` is built at toy width from the vendored config (two language-modellayers, two vision blocks), and the file is written in the legacy key layout with that build's `scale_weight` /`scale_input` spellings: every Linear (language model, vision tower, untied LM head) is float8 beside its scale, the-token table is scaled too, and the patch-embedding convolution and norms are dense. On a device that can hold float8-the Linears stay float8 with the file's own scale on their module; the token table is folded; elsewhere everything is-folded. Expected values come from the codes and scales written, run through a second, plain model. Forwards run in-float32: CPU bf16 matmuls fault on part of the hosted Windows fleet.+token table is scaled too, and the patch-embedding convolution and norms are dense. The LM head stays in the file. On a+device that can hold float8 the Linears stay float8 with the file's own scale on their module; the token table is+folded; elsewhere everything is folded. Expected values come from the codes and scales written, run through a second,+plain model. Forwards run in float32: CPU bf16 matmuls fault on part of the hosted Windows fleet."""import json@@ -16,6 +16,7 @@ from unittest.mock import MagicMockimport pytestimport torch+from safetensors import safe_openfrom safetensors.torch import save_filefrom transformers import Qwen2_5_VLConfig, Qwen2_5_VLForConditionalGeneration@@ -108,6 +109,8 @@ def _write(module = reference.get_submodule(module_path)legacy_key, legacy_module = _legacy(key), _legacy(module_path)is_linear = leaf == "weight" and isinstance(module, torch.nn.Linear)+ # The file carries the LM head, but the loaded encoder does not, so no expectation about the model counts it.+ loaded = module_path != "lm_head"is_table = leaf == "weight" and module_path == "model.language_model.embed_tokens"if not (is_linear or is_table):value = torch.rand(param.shape) + 0.5 if "norm" in key else torch.randn(param.shape) * 0.3@@ -133,9 +136,12 @@ def _write(# The placeholder this build writes beside every scale; 1.0 is not a calibration.tensors[f"{legacy_module}.scale_input"] = torch.tensor(1.0)checkpoint.dense[key] = codes * (scale[:, None] if per_row else scale)- checkpoint.scales[module_path] = scale- checkpoint.scale_bytes += 4 * scale.numel()+ if loaded:+ checkpoint.scales[module_path] = scale+ checkpoint.scale_bytes += 4 * scale.numel()hints[legacy_module] = {"format": "float8_e4m3fn"}+ if not loaded:+ continueif is_linear:checkpoint.linear_modules.append(module_path)checkpoint.linear_elements += param.numel()@@ -191,13 +197,13 @@ PIXELS = torch.randn(16, 3 * 2 * 14 * 14, generator=torch.Generator().manual_seedef _run(model: Qwen2_5_VLForConditionalGeneration) -> tuple[torch.Tensor, torch.Tensor]:with torch.no_grad():- return model(input_ids=IDS).logits, model.model.visual(PIXELS, grid_thw=GRID)+ return model.model(input_ids=IDS).last_hidden_state, model.model.visual(PIXELS, grid_thw=GRID)def _assert_encodes_like(model, dense: dict[str, torch.Tensor]) -> None:- logits, vision = _run(model)- expected_logits, expected_vision = _run(_plain_reference(dense))- torch.testing.assert_close(logits, expected_logits, rtol=1e-4, atol=1e-4)+ hidden, vision = _run(model)+ expected_hidden, expected_vision = _run(_plain_reference(dense))+ torch.testing.assert_close(hidden, expected_hidden, rtol=1e-4, atol=1e-4)torch.testing.assert_close(vision, expected_vision, rtol=1e-4, atol=1e-4)@@ -218,8 +224,7 @@ def test_a_device_that_holds_float8_keeps_every_scaled_linear_with_its_scale_andmodel = _load(checkpoint)- # Language model, vision tower (qkv, proj, mlp, merger) and the untied LM head alike.- assert "lm_head" in checkpoint.linear_modules+ # Language model and vision tower (qkv, proj, mlp, merger) alike.assert any(path.startswith("model.visual.blocks.0.attn") for path in checkpoint.linear_modules)assert any(path.startswith("model.visual.merger") for path in checkpoint.linear_modules)for path in checkpoint.linear_modules:@@ -309,7 +314,8 @@ def test_a_mxfp8_layer_named_by_its_marker_or_the_header_is_decoded_and_the_rest# Block-wise scales never reach the matmul, so this layer is folded even where the others stay float8.assert model.get_submodule(MX_MODULE).weight.dtype is torch.float32assert torch.equal(model.get_submodule(MX_MODULE).weight, checkpoint.dense[f"{MX_MODULE}.weight"])- assert model.get_submodule("lm_head").weight.dtype is (FP8 if device == "cuda:0" else torch.float32)+ untouched = model.get_submodule("model.language_model.layers.1.self_attn.q_proj")+ assert untouched.weight.dtype is (FP8 if device == "cuda:0" else torch.float32)if device == "cuda:0":apply_custom_layers_to_model(model)_assert_encodes_like(model, checkpoint.dense)@@ -347,11 +353,34 @@ def test_the_reservation_counts_float8_weights_one_byte_and_everything_else_at_tassert reserved["cpu"] == 4 * checkpoint.linear_elements + widened[email protected]("evidence", ["none", "marker", "header"])+def test_the_lm_head_in_the_file_is_neither_loaded_nor_reserved_for(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, evidence: str+) -> None:+ """The head's weight, its scale and whatever names it quantized (marker or header entry) all stay behind."""+ checkpoint = _write(tmp_path, evidence=evidence)+ with safe_open(checkpoint.path, framework="pt") as saved:+ assert {"lm_head.weight", "lm_head.scale_weight"} <= set(saved.keys())+ _decide(monkeypatch, device="cpu")+ loader = _loader()+ unexpected: list[str] = []+ monkeypatch.setattr(qwen_image, "log_unexpected_keys", lambda _source, keys: unexpected.extend(keys))++ model = _load(checkpoint, loader)++ assert list(model.lm_head.parameters()) == [] and list(model.lm_head.buffers()) == []+ assert not any("lm_head" in key for key in unexpected)+ widened = 4 * (checkpoint.linear_elements + checkpoint.other_elements) + checkpoint.scale_bytes+ loader._ram_cache.make_room.assert_called_once_with(widened)+ with pytest.raises(RuntimeError, match="without its LM head"):+ model(input_ids=IDS)++@pytest.mark.parametrize("device", ["cuda:0", "cpu"])def test_a_scale_spelling_the_loader_does_not_read_is_refused_rather_than_cast_unscaled(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, device: str) -> None:- checkpoint = _write(tmp_path, extra={"lm_head.weight_scale_inv": torch.tensor(2.0)})+ checkpoint = _write(tmp_path, extra={"model.layers.0.self_attn.q_proj.weight_scale_inv": torch.tensor(2.0)})_decide(monkeypatch, device=device, storage=True)loader = _loader()diff --git a/tests/backend/model_manager/load/test_qwen_image_encoder_lm_head.py b/tests/backend/model_manager/load/test_qwen_image_encoder_lm_head.pynew file mode 100644index 0000000000..c82a216751--- /dev/null+++ b/tests/backend/model_manager/load/test_qwen_image_encoder_lm_head.py@@ -0,0 +1,102 @@+"""The Diffusers-layout Qwen2.5-VL encoder loaders leave the LM head in the file.++Conditioning reads the inner model's hidden states, so the head's weights would only take RAM and VRAM. A toy encoder+is saved with `save_pretrained`, which writes the legacy `model.layers.*` key layout the released encoders ship in, and+read back through both loaders. The single-file and GGUF loaders are covered beside their own formats.+"""++import json+from pathlib import Path+from unittest.mock import MagicMock++import pytest+import torch+from safetensors import safe_open+from transformers import Qwen2_5_VLConfig, Qwen2_5_VLForConditionalGeneration++from invokeai.backend.model_manager.configs.main import Main_Diffusers_QwenImage_Config+from invokeai.backend.model_manager.configs.qwen_vl_encoder import QwenVLEncoder_Diffusers_Config+from invokeai.backend.model_manager.load.model_loaders import qwen_image+from invokeai.backend.model_manager.load.model_loaders.qwen_image import QwenImageDiffusersModel, QwenVLEncoderLoader+from invokeai.backend.model_manager.taxonomy import SubModelType+++def _tiny_config() -> Qwen2_5_VLConfig:+ return 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,+ "bos_token_id": 0,+ "eos_token_id": 1,+ "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],+ },+ )+++def reference(tmp_path: Path) -> Qwen2_5_VLForConditionalGeneration:+ """The full encoder, saved as `tmp_path / "text_encoder"`."""+ torch.manual_seed(0)+ model = Qwen2_5_VLForConditionalGeneration(_tiny_config()).eval()+ model.save_pretrained(tmp_path / "text_encoder")+ return model+++def _load_standalone(root: Path) -> torch.nn.Module:+ loader = object.__new__(QwenVLEncoderLoader)+ config = QwenVLEncoder_Diffusers_Config.model_construct(path=str(root))+ return loader._load_model(config, SubModelType.TextEncoder)+++def _load_from_main_model(root: Path) -> torch.nn.Module:+ index = {"text_encoder": ["transformers", "Qwen2_5_VLForConditionalGeneration"]}+ (root / "model_index.json").write_text(json.dumps(index))+ loader = object.__new__(QwenImageDiffusersModel)+ loader._logger = MagicMock()+ config = Main_Diffusers_QwenImage_Config.model_construct(path=str(root), repo_variant=None)+ return loader._load_model(config, SubModelType.TextEncoder)++[email protected]("load", [_load_standalone, _load_from_main_model], ids=["standalone", "main_model"])+def test_the_encoder_loads_every_weight_but_the_lm_head(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, reference: Qwen2_5_VLForConditionalGeneration, load+) -> None:+ monkeypatch.setattr(qwen_image.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: torch.float32)+ with safe_open(tmp_path / "text_encoder" / "model.safetensors", framework="pt") as saved:+ assert {"lm_head.weight", "model.layers.0.self_attn.q_proj.weight"} <= set(saved.keys())++ encoder = load(tmp_path)++ # Prompt nodes and the LoRA patcher expect the causal-LM class.+ assert isinstance(encoder, Qwen2_5_VLForConditionalGeneration)+ assert list(encoder.lm_head.parameters()) == []+ expected = reference.state_dict()+ del expected["lm_head.weight"]+ loaded = encoder.state_dict()+ assert loaded.keys() == expected.keys()+ for key, value in loaded.items():+ assert torch.equal(value, expected[key].to(value.dtype)), key+ assert not any(tensor.is_meta for tensor in (*encoder.parameters(), *encoder.buffers()))+++def test_a_caller_of_the_full_forward_is_told_the_lm_head_was_not_loaded(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, reference: Qwen2_5_VLForConditionalGeneration+) -> None:+ monkeypatch.setattr(qwen_image.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: torch.float32)++ encoder = _load_standalone(tmp_path)++ with pytest.raises(RuntimeError, match="without its LM head"):+ encoder(input_ids=torch.tensor([[1, 2]]))diff --git a/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.py b/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.pyindex 8fc052b596..65c315c81e 100644--- a/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.py+++ b/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.py@@ -247,14 +247,15 @@ def test_the_encoder_keeps_marker_named_nvfp4_layers_packed_under_their_transforstate_dict[f"{legacy}.comfy_quant"] = _marker("nvfp4")expected[legacy.replace("model.", "model.language_model.", 1)] = weightstate_dict["model.layers.0.self_attn.q_proj.bias"] = torch.randn(128)- fp8_values = torch.randint(-8, 9, (32, 64)).float()fp8_marker = _marker("float8_e4m3fn")- # The fp8_scaled encoder's own scale spelling, beside the marker the nvfp4 build adds.- state_dict["lm_head.weight"] = fp8_values.to(torch.float8_e4m3fn)- state_dict["lm_head.scale_weight"] = torch.tensor(0.5)- state_dict["lm_head.scale_input"] = torch.tensor(1.0)- state_dict["lm_head.comfy_quant"] = fp8_marker- state_dict["visual.proj.weight"] = torch.randn(4, 8)+ # The fp8_scaled encoder's own scale spelling, beside the marker the nvfp4 build adds. The released nvfp4 file ships+ # the LM head in scaled fp8; it is not loaded.+ fp8_values = torch.randint(-8, 9, (4, 8)).float()+ for legacy, weight in (("visual.proj", fp8_values), ("lm_head", torch.randint(-8, 9, (32, 64)).float())):+ state_dict[f"{legacy}.weight"] = weight.to(torch.float8_e4m3fn)+ state_dict[f"{legacy}.scale_weight"] = torch.tensor(0.5)+ state_dict[f"{legacy}.scale_input"] = torch.tensor(1.0)+ state_dict[f"{legacy}.comfy_quant"] = fp8_markerstate_dict["visual.proj.bias"] = torch.randn(4)log = _patch_common(monkeypatch, state_dict, {})@@ -271,7 +272,6 @@ def test_the_encoder_keeps_marker_named_nvfp4_layers_packed_under_their_transforloader._torch_device, loader._logger = torch.device("cpu"), MagicMock()_record_fold(monkeypatch, loader, log)q_bias = state_dict["model.layers.0.self_attn.q_proj.bias"]- visual_weight = state_dict["visual.proj.weight"]model = loader._load_text_encoder_from_singlefile(QwenVLEncoder_Checkpoint_Config.model_construct(path=str(checkpoint))@@ -286,15 +286,15 @@ def test_the_encoder_keeps_marker_named_nvfp4_layers_packed_under_their_transforx = torch.randn(3, module.in_features, dtype=torch.float32)bias = q_bias.to(COMPUTE_DTYPE).float() if module.bias is not None else Nonetorch.testing.assert_close(module(x), torch.nn.functional.linear(x, weight, bias))- assert torch.equal(model.lm_head.weight, (fp8_values * 0.5).to(COMPUTE_DTYPE))- assert torch.equal(model.model.visual.proj.weight, visual_weight.to(COMPUTE_DTYPE))+ assert list(model.lm_head.parameters()) == []+ assert torch.equal(model.model.visual.proj.weight, (fp8_values * 0.5).to(COMPUTE_DTYPE))assert log == [True]- # Counted by hand: the packed layers as stored, the q_proj bias, the folded LM head and the vision projection at- # bf16, and the LM head's recovered scale (the 1.0 `scale_input` is an uncalibrated placeholder, charged nothing).- # Its marker is consumed by the extraction before the reservation.+ # Counted by hand: the packed layers as stored, the q_proj bias and the folded vision projection at bf16, and that+ # projection's recovered scale (the 1.0 `scale_input` is an uncalibrated placeholder, charged nothing). Its marker+ # is consumed by the extraction before the reservation. The LM head, scales and marker included, costs nothing.packed = 2 * _packed_bytes(128, 64)- widened = 128 + 32 * 64 + (4 * 8 + 4)+ widened = 128 + (4 * 8 + 4)recovered_scale = torch.tensor(0.5).element_size()loader._ram_cache.make_room.assert_called_once_with(packed + widened * COMPUTE_DTYPE.itemsize + recovered_scale)@@ -373,13 +373,13 @@ def test_the_encoder_keeps_int8_layers_int8_under_their_transformers_paths(monketorch.testing.assert_close(layer(x), torch.nn.functional.linear(x, weight, bias), rtol=1e-4, atol=1e-4)# The W8A8 activation scale has nothing to attach to.assert not hasattr(layer, "input_scale")- assert model.lm_head.weight.dtype is COMPUTE_DTYPE+ assert list(model.lm_head.parameters()) == []assert model.model.visual.proj.weight.dtype is COMPUTE_DTYPE- # Counted by hand: the int8 weights as stored, their fp32 scales, and the bias, `lm_head` and vision projection at+ # Counted by hand: the int8 weights as stored, their fp32 scales, and the bias and vision projection at# bf16. Markers and activation scales are dropped and cost nothing.int8 = 2 * 128 * 64scales = (2 * 128 * 4) if rotated else 2 * 4- dense = 128 + 32 * 64 + (4 * 8 + 4)+ dense = 128 + (4 * 8 + 4)assert run.reserved == [int8 + scales + dense * COMPUTE_DTYPE.itemsize]@@ -452,9 +452,9 @@ def test_an_encoder_file_mixing_int8_and_nvfp4_layers_loads_both_under_one_reserassert isinstance(packed, NVFP4Linear)x = torch.randn(3, 64)torch.testing.assert_close(packed(x), torch.nn.functional.linear(x, nvfp4_weight))- # The int8 q_proj with its fp32 scale, the packed layer as stored, and the dense bias, `lm_head` and vision- # projection at bf16: one call that covers both schemes.- dense = 128 + 32 * 64 + (4 * 8 + 4)+ # The int8 q_proj with its fp32 scale, the packed layer as stored, and the dense bias and vision projection at+ # bf16: one call that covers both schemes.+ dense = 128 + (4 * 8 + 4)assert run.reserved == [128 * 64 + 128 * 4 + _packed_bytes(128, 64) + dense * COMPUTE_DTYPE.itemsize]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 44c4cf712a..c83ec43108 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@@ -6,7 +6,7 @@ import accelerateimport pytestimport torchfrom diffusers.models.transformers.transformer_qwenimage import QwenImageTransformer2DModel-from transformers import Qwen2_5_VLConfig, Qwen2_5_VLForConditionalGeneration+from transformers import Qwen2_5_VLConfigfrom invokeai.backend.patches.layer_patcher import LayerPatcherfrom invokeai.backend.patches.layers.loha_layer import LoHALayer@@ -20,6 +20,7 @@ from invokeai.backend.patches.lora_conversions.qwen_image_lora_conversion_utilsis_state_dict_likely_kohya_qwen_image,lora_model_from_qwen_image_state_dict,)+from invokeai.backend.qwen2_5_vl.headless import HeadlessQwen2_5_VLForConditionalGenerationfrom tests.backend.patches.lora_conversions.lora_state_dicts.qwen_image_lora_aitoolkit_loha_format import (state_dict_keys as aitoolkit_loha_state_dict_keys,)@@ -371,8 +372,8 @@ def test_lora_scalar_scales_the_update(prefix: str, form: str):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."""+ """`lora_te_*` layers name Qwen2.5-VL modules (language tower, vision tower, merger); the transformer's layers in+ the same file keep their prefix. The file's `lora_te_lm_head` is dropped: encoders are loaded without that head."""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)@@ -393,7 +394,6 @@ def test_kohya_text_encoder_layers_are_routed_to_the_qwen_vl_prefix():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",}@@ -444,7 +444,7 @@ def test_unmapped_kohya_layers_produce_one_warning_with_the_count(caplog: pytestdef 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+ """The Kohya key of each Linear in the loaded module tree converts to a path the patcher resolves to that verymodule. Built from the model's own names, so a module missing from the parsing tree fails here."""config = Qwen2_5_VLConfig(text_config={@@ -466,7 +466,7 @@ def test_every_linear_of_a_qwen2_5_vl_encoder_is_reachable_from_its_onetrainer_k},)with torch.device("meta"):- encoder = Qwen2_5_VLForConditionalGeneration(config)+ encoder = HeadlessQwen2_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)@@ -494,8 +494,9 @@ def test_every_linear_of_a_qwen2_5_vl_encoder_is_reachable_from_its_onetrainer_kdef 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."""+ """A Conv3d (`patch_embed`) cannot hold a patch and would crash the patcher, as would the weightless stand-in for+ `lm_head`; the transformers < 4.52 layout (`model.layers.N`) names nothing in the current encoder. All 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),@@ -505,6 +506,8 @@ def test_diffusers_text_encoder_layers_that_are_not_encoder_linears_are_skipped_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),+ f"{prefix}lm_head.lora_A.weight": torch.empty(8, 3584),+ f"{prefix}lm_head.lora_B.weight": torch.empty(152064, 8),}with caplog.at_level(logging.WARNING):@@ -513,7 +516,7 @@ def test_diffusers_text_encoder_layers_that_are_not_encoder_linears_are_skipped_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]+ assert "Skipped 4 " in warnings[0]def test_onetrainer_comfy_text_encoder_keys_are_routed_beside_diffusion_model_transformer_keys(@@ -542,6 +545,7 @@ def test_onetrainer_comfy_text_encoder_keys_are_routed_beside_diffusion_model_trf"{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]+ warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]+ assert len(warnings) == 1+ assert "Skipped 1 " in warnings[0]diff --git a/tests/backend/quantization/test_qwen_vl_bnb_lora.py b/tests/backend/quantization/test_qwen_vl_bnb_lora.pyindex 5f20dd5f3e..840672aff3 100644--- a/tests/backend/quantization/test_qwen_vl_bnb_lora.py+++ b/tests/backend/quantization/test_qwen_vl_bnb_lora.py@@ -55,13 +55,15 @@ def checkpoint(tmp_path_factory: pytest.TempPathFactory) -> Path:def _load(checkpoint: Path, quantization: str):"""As `_load_quantized_encoder` loads it."""- from transformers import BitsAndBytesConfig, Qwen2_5_VLForConditionalGeneration+ from transformers import BitsAndBytesConfig++ from invokeai.backend.qwen2_5_vl.headless import HeadlessQwen2_5_VLForConditionalGenerationif 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(+ return HeadlessQwen2_5_VLForConditionalGeneration.from_pretrained(str(checkpoint), quantization_config=config, device_map={"": DEVICE}, dtype=torch.bfloat16)@@ -86,7 +88,6 @@ def _patch_for(layer_name: str, in_features: int, out_features: int):[("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(@@ -110,8 +111,7 @@ def test_sidecar_lora_on_a_bnb_quantized_encoder(_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 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)