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
feat(quantization): keep Comfy nvfp4 Qwen-Image models packed
Alexander Eichhorn68e7d0c465e5
diff --git a/invokeai/app/invocations/qwen_image/qwen_image_denoise.py b/invokeai/app/invocations/qwen_image/qwen_image_denoise.pyindex c4e856bf4e..3cd1d89717 100644--- a/invokeai/app/invocations/qwen_image/qwen_image_denoise.py+++ b/invokeai/app/invocations/qwen_image/qwen_image_denoise.py@@ -23,12 +23,13 @@ from invokeai.app.invocations.fields import (from invokeai.app.invocations.model import TransformerFieldfrom invokeai.app.invocations.primitives import LatentsOutputfrom invokeai.app.services.shared.invocation_context import InvocationContext-from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat+from invokeai.backend.model_manager.taxonomy import BaseModelTypefrom invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpecfrom invokeai.backend.patches.lora_conversions.qwen_image_lora_constants import (QWEN_IMAGE_EDIT_LORA_TRANSFORMER_PREFIX,)from invokeai.backend.patches.model_patch_raw import ModelPatchRaw+from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes, requires_sidecar_patchingfrom invokeai.backend.rectified_flow.rectified_flow_inpaint_extension import RectifiedFlowInpaintExtensionfrom invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateStatefrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import QwenImageConditioningInfo@@ -456,13 +457,20 @@ class QwenImageDenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):noisy_seq_len = latents.shape[1]- # Determine if the model is quantized — GGUF models need sidecar patching for LoRAstransformer_config = context.models.get_config(self.transformer.transformer)- model_is_quantized = transformer_config.format in (ModelFormat.GGUFQuantized,)+ # An nvfp4 build dequantizes each packed Linear per forward, a transient its resident size does not cover. The+ # cache holds back the larger of this and its default working memory, not their sum: this node has no+ # activation estimate to add it to. Read from the unlocked model, before the lock; zero for every other build.+ dequant_bytes = peak_dequant_transient_bytes(transformer_info.model, inference_dtype)with ExitStack() as exit_stack:- (cached_weights, transformer) = exit_stack.enter_context(transformer_info.model_on_device())+ (cached_weights, transformer) = exit_stack.enter_context(+ transformer_info.model_on_device(working_mem_bytes=dequant_bytes)+ )assert isinstance(transformer, QwenImageTransformer2DModel)+ # Quantized weights (packed nvfp4 Linears, GGUF, SDNQ) cannot take a direct patch, so their LoRAs ride as+ # sidecars. Asked of the loaded module tree: a `checkpoint` build may hold packed Linears.+ model_is_quantized = requires_sidecar_patching(transformer, transformer_config.format)# Apply LoRA patches to the transformerexit_stack.enter_context(diff --git a/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py b/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.pyindex 1044826255..1f2db772e5 100644--- a/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py+++ b/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py@@ -15,6 +15,7 @@ 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 MODEL_LOAD_LOCK+from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytesfrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import (ConditioningFieldData,QwenImageConditioningInfo,@@ -260,11 +261,17 @@ class QwenImageTextEncoderInvocation(BaseInvocation):return prompt_embeds, encoder_attention_maskdef _load_cached_encoder(self, context: InvocationContext):- """Load the text encoder through the model cache (no quantization)."""+ """Load the text encoder through the model cache, without BitsAndBytes quantization."""from transformers import Qwen2_5_VLForConditionalGenerationtext_encoder_info = context.models.load(self.qwen_vl_encoder.text_encoder)- ctx = text_encoder_info.model_on_device()+ # An nvfp4 build dequantizes each packed Linear per forward, a transient its resident size does not cover. The+ # cache holds back the larger of this and its default working memory, not their sum. Read from the unlocked+ # model, before the lock; zero for every other build.+ 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.@@ -287,10 +294,8 @@ class QwenImageTextEncoderInvocation(BaseInvocation):encoder_config = context.models.get_config(self.qwen_vl_encoder.text_encoder)model_root = context.models.get_absolute_path(encoder_config)if model_root.is_file():- # Single-file checkpoint (e.g. ComfyUI fp8_scaled): BnB can't load from- # a single file, and the checkpoint is already FP8-compressed anyway.- # Fall back to the cached path; the user effectively gets fp8 instead of- # int8/nf4, which is comparable in size.+ # Single-file checkpoint (e.g. ComfyUI fp8_scaled or nvfp4): BnB can't load from a single file. Fall back+ # to the cached path, which folds fp8 layers to bf16 and keeps nvfp4 layers packed.return self._load_cached_encoder(context)encoder_path = model_root / "text_encoder"diff --git a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py b/invokeai/backend/model_manager/load/model_loaders/qwen_image.pyindex 1342cbe107..b24c8d6a15 100644--- a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/qwen_image.py@@ -14,7 +14,7 @@ from invokeai.backend.model_manager.configs.qwen_vl_encoder import (QwenVLEncoder_Checkpoint_Config,QwenVLEncoder_Diffusers_Config,)-from invokeai.backend.model_manager.load.load_default import ModelLoader+from invokeai.backend.model_manager.load.load_default import ModelLoader, _model_declared_skip_patternsfrom invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistryfrom invokeai.backend.model_manager.load.model_loaders.comfyui_state_dict_utils import (_dequantize_comfyui_fp8,@@ -30,8 +30,15 @@ from invokeai.backend.model_manager.taxonomy import (QwenImageVariantType,SubModelType,)+from invokeai.backend.quantization.fp8_scaled import (+ parse_quantization_metadata,+ predict_cast_state_dict_size,+ read_safetensors_metadata,+ strip_layer_path_prefix,+)from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensorfrom invokeai.backend.quantization.gguf.loaders import gguf_sd_loader+from invokeai.backend.quantization.nvfp4 import install_nvfp4_layers, pop_nvfp4_layers, predict_nvfp4_install_sizefrom invokeai.backend.util.devices import TorchDevice@@ -264,26 +271,43 @@ class QwenImageCheckpointModel(ModelLoader):sd = load_file(str(model_path))sd = _strip_comfyui_prefix(sd)- dequantized = _dequantize_comfyui_fp8(sd, model_dtype)- if dequantized > 0:- logger.info(f"Dequantized {dequantized} ComfyUI-quantized weights")- _strip_quantization_metadata(sd)+ # Comfy's nvfp4 build keeps the image stream's attention and MLP in nvfp4, beside scaled fp8. Take those layers+ # out before the fold: `_dequantize_comfyui_fp8` multiplies every `.weight_scale` into its weight, nvfp4's+ # block scales included. `install_nvfp4_layers` puts them back, packed.+ header_layers = strip_layer_path_prefix(+ parse_quantization_metadata(read_safetensors_metadata(model_path, logger))+ )+ nvfp4_payloads = pop_nvfp4_layers(sd, header_layers=header_layers)is_edit = getattr(config, "variant", None) == QwenImageVariantType.Editmodel_config = _build_qwen_image_transformer_config(sd, is_edit=is_edit)+ # Built before the reservation, which depends on its modules: they decide which nvfp4 layers stay packed.with accelerate.init_empty_weights():model = QwenImageTransformer2DModel(**model_config)+ skip_patterns = _model_declared_skip_patterns(model)++ # One reservation, before the fold widens a single weight: `make_room` makes that much room rather than adding+ # to an earlier one. Every fp8 layer is folded to the compute dtype.+ self._ram_cache.make_room(+ predict_cast_state_dict_size(sd, model_dtype, keep_fp8=False)+ + predict_nvfp4_install_size(model, nvfp4_payloads, model_dtype, skip_patterns)+ )++ dequantized = _dequantize_comfyui_fp8(sd, model_dtype)+ if dequantized > 0:+ logger.info(f"Dequantized {dequantized} ComfyUI-quantized weights")+ _strip_quantization_metadata(sd)# Dequantized fp8 weights are already at model_dtype; this only casts any remaining- # non-quantized float weights (e.g. a plain fp16/fp32 checkpoint) to the compute dtype- # so the cache reservation below is sized from the actual post-cast tensors.+ # non-quantized float weights (e.g. a plain fp16/fp32 checkpoint) to the compute dtype.for k in list(sd.keys()):if sd[k].is_floating_point():sd[k] = sd[k].to(model_dtype)- new_sd_size = sum(t.nelement() * t.element_size() for t in sd.values())- self._ram_cache.make_room(new_sd_size)+ if nvfp4_payloads:+ packed = install_nvfp4_layers(model, sd, nvfp4_payloads, model_dtype, skip_patterns)+ logger.info(f"Qwen Image: kept {packed} of {len(nvfp4_payloads)} nvfp4 layer(s) packed.")model.load_state_dict(sd, strict=False, assign=True)return model@@ -396,23 +420,12 @@ class QwenVLEncoderCheckpointLoader(ModelLoader):sd = load_file(str(model_path))- # Dequantize ComfyUI-style fp8 weights, then strip the now-unused quantization- # metadata (`scale_input` is the activation scale ComfyUI's fp8 matmul kernels- # use at runtime — we run the encoder in bf16 after dequantization).- dequantized_count = _dequantize_comfyui_fp8(sd, model_dtype)- if dequantized_count > 0:- logger.info(f"Dequantized {dequantized_count} ComfyUI-quantized weights")- _strip_quantization_metadata(sd)-- # ComfyUI single-file checkpoints use the legacy Qwen2.5-VL key layout- # (`visual.X`, `model.X`); remap to the `model.visual.X` / `model.language_model.X`- # layout transformers expects. See `_remap_qwen_vl_checkpoint_keys` for details.- sd = _remap_qwen_vl_checkpoint_keys(sd)-- # Cast to compute dtype (skip integer/index tensors)- for k in list(sd.keys()):- if sd[k].is_floating_point():- sd[k] = sd[k].to(model_dtype)+ # Comfy's nvfp4 build keeps the language model's projections in nvfp4, beside scaled fp8 embeddings. Take those+ # layers out before the fold: `_dequantize_comfyui_fp8` multiplies every `.weight_scale` into its weight,+ # nvfp4's block scales included. `install_nvfp4_layers` puts them back, packed.+ nvfp4_payloads = pop_nvfp4_layers(+ sd, header_layers=parse_quantization_metadata(read_safetensors_metadata(model_path, logger))+ )# Fetch the architecture config from HuggingFace (small, ~5KB).# Offline fallback: tries cache first, downloads only if missing.@@ -435,11 +448,41 @@ class QwenVLEncoderCheckpointLoader(ModelLoader):) from eqwen_config.torch_dtype = model_dtype- new_sd_size = sum(t.nelement() * t.element_size() for t in sd.values())- self._ram_cache.make_room(new_sd_size)-+ # 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)+ skip_patterns = _model_declared_skip_patterns(model)+ # The packed layers are named in the same legacy layout as the keys.+ nvfp4_payloads = _remap_qwen_vl_checkpoint_keys(nvfp4_payloads)++ # One reservation, before the fold widens a single weight: `make_room` makes that much room rather than adding+ # to an earlier one. Every fp8 layer is folded to the compute dtype.+ self._ram_cache.make_room(+ predict_cast_state_dict_size(sd, model_dtype, keep_fp8=False)+ + predict_nvfp4_install_size(model, nvfp4_payloads, model_dtype, skip_patterns)+ )++ # Dequantize ComfyUI-style fp8 weights, then strip the now-unused quantization+ # metadata (`scale_input` is the activation scale ComfyUI's fp8 matmul kernels+ # use at runtime — we run the encoder in bf16 after dequantization).+ dequantized_count = _dequantize_comfyui_fp8(sd, model_dtype)+ if dequantized_count > 0:+ logger.info(f"Dequantized {dequantized_count} ComfyUI-quantized weights")+ _strip_quantization_metadata(sd)++ # ComfyUI single-file checkpoints use the legacy Qwen2.5-VL key layout+ # (`visual.X`, `model.X`); remap to the `model.visual.X` / `model.language_model.X`+ # layout transformers expects. See `_remap_qwen_vl_checkpoint_keys` for details.+ sd = _remap_qwen_vl_checkpoint_keys(sd)++ # Cast to compute dtype (skip integer/index tensors)+ for k in list(sd.keys()):+ if sd[k].is_floating_point():+ sd[k] = sd[k].to(model_dtype)++ if nvfp4_payloads:+ 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_result = model.load_state_dict(sd, strict=False, assign=True)diff --git a/invokeai/backend/model_manager/starter_models/__init__.py b/invokeai/backend/model_manager/starter_models/__init__.pyindex 54813b09c2..a40e9c59de 100644--- a/invokeai/backend/model_manager/starter_models/__init__.py+++ b/invokeai/backend/model_manager/starter_models/__init__.py@@ -32,7 +32,9 @@ from invokeai.backend.model_manager.starter_models.common import (flux2_dev_cow_mistral_q4,flux2_dev_cow_mistral_q8,flux2_klein_qwen3_4b_encoder,+ flux2_klein_qwen3_4b_encoder_fp4,flux2_klein_qwen3_8b_encoder,+ flux2_klein_qwen3_8b_encoder_fp4,gemma2_2b_encoder,llava_onevision,llava_onevision_7b,@@ -41,6 +43,7 @@ from invokeai.backend.model_manager.starter_models.common import (qwen3_vl_encoder_4b,qwen_vl_encoder_diffusers,qwen_vl_encoder_fp8,+ qwen_vl_encoder_nvfp4,realesrgan_x2,realesrgan_x4,siglip,@@ -350,6 +353,8 @@ STARTER_MODELS: list[StarterModel] = [flux2_klein_9b_gguf_q8,flux2_klein_qwen3_4b_encoder,flux2_klein_qwen3_8b_encoder,+ flux2_klein_qwen3_4b_encoder_fp4,+ flux2_klein_qwen3_8b_encoder_fp4,flux2_dev_comfy_mistral_bf16,flux2_dev_comfy_mistral_fp4,flux2_dev_comfy_mistral_fp8,@@ -366,6 +371,7 @@ STARTER_MODELS: list[StarterModel] = [cogview4,qwen_image_vae,qwen_vl_encoder_fp8,+ qwen_vl_encoder_nvfp4,qwen_vl_encoder_diffusers,qwen_image_edit,qwen_image_edit_gguf_q2_k,diff --git a/invokeai/backend/model_manager/starter_models/common.py b/invokeai/backend/model_manager/starter_models/common.pyindex 5910c722ae..afdd9206e7 100644--- a/invokeai/backend/model_manager/starter_models/common.py+++ b/invokeai/backend/model_manager/starter_models/common.py@@ -164,6 +164,17 @@ qwen_vl_encoder_fp8 = StarterModel(format=ModelFormat.Checkpoint,)+qwen_vl_encoder_nvfp4 = StarterModel(+ name="Qwen2.5-VL Encoder (NVFP4)",+ 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; tokenizer/processor are fetched from HuggingFace on first use. Its nvfp4 layers stay packed, about 6.7GB "+ "once loaded. ~5.7GB download",+ type=ModelType.QwenVLEncoder,+ format=ModelFormat.Checkpoint,+)+qwen_vl_encoder_diffusers = StarterModel(name="Qwen2.5-VL Encoder (Diffusers)",base=BaseModelType.Any,@@ -241,6 +252,22 @@ flux2_klein_qwen3_8b_encoder = StarterModel(type=ModelType.Qwen3Encoder,)+flux2_klein_qwen3_4b_encoder_fp4 = StarterModel(+ name="FLUX.2 Klein Qwen3 4B Encoder (FP4 mixed)",+ base=BaseModelType.Any,+ source="https://huggingface.co/Comfy-Org/vae-text-encorder-for-flux-klein-4b/resolve/main/split_files/text_encoders/qwen_3_4b_fp4_flux2.safetensors",+ description="Comfy-Org's nvfp4/fp8-mixed Qwen3 4B text encoder for FLUX.2 Klein 4B. Its nvfp4 layers stay packed, about 5.2GB once loaded. ~3.6GB download",+ type=ModelType.Qwen3Encoder,+)++flux2_klein_qwen3_8b_encoder_fp4 = StarterModel(+ name="FLUX.2 Klein Qwen3 8B Encoder (FP4 mixed)",+ base=BaseModelType.Any,+ source="https://huggingface.co/Comfy-Org/vae-text-encorder-for-flux-klein-9b/resolve/main/split_files/text_encoders/qwen_3_8b_fp4mixed.safetensors",+ description="Comfy-Org's nvfp4/fp8-mixed Qwen3 8B text encoder for FLUX.2 Klein 9B. Its nvfp4 layers stay packed, about 9.4GB once loaded. ~6.3GB download",+ type=ModelType.Qwen3Encoder,+)+# Comfy-Org safetensors (single-file, 30-layer cow, with embedded Tekken tokenizer).# Higher precision than the cow GGUFs and avoids the Tekken-via-HF-Hub fetch.flux2_dev_comfy_mistral_fp8 = StarterModel(diff --git a/tests/app/invocations/test_qwen_image_packed_models.py b/tests/app/invocations/test_qwen_image_packed_models.pynew file mode 100644index 0000000000..73273ec148--- /dev/null+++ b/tests/app/invocations/test_qwen_image_packed_models.py@@ -0,0 +1,142 @@+"""The Qwen-Image nodes have to treat a packed nvfp4 model like the other nodes treat one.++The denoise node reserves the per-forward dequantization transient of packed Linears and applies LoRA to them as+sidecars, which it used to decide from the format alone -- GGUF only -- so a `checkpoint` build holding packed Linears+would have been patched directly. The text encoder node reserves the same transient.+"""++from contextlib import contextmanager, nullcontext+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest+import torch++from invokeai.app.invocations.qwen_image import qwen_image_denoise+from invokeai.app.invocations.qwen_image.qwen_image_denoise import QwenImageDenoiseInvocation+from invokeai.app.invocations.text_encoder.qwen_image_text_encoder import QwenImageTextEncoderInvocation+from invokeai.backend.model_manager.taxonomy import ModelFormat+from invokeai.backend.patches.layer_patcher import LayerPatcher+from invokeai.backend.quantization.nvfp4 import NVFP4Linear++# One packed 128x64 Linear at bf16: the weight (2 bytes), its int32 byte index (4 bytes per packed byte, so 2 per+# element) and the 16-element block scale grid (2 bytes per block).+PACKED_TRANSIENT_BYTES = 128 * 64 * (2 + 2) + (128 * 64 // 16) * 2+++class _Stop(Exception):+ """Raised where the node has made the decision a test looks at."""+++def _module(packed: bool) -> torch.nn.Module:+ module = torch.nn.Module()+ if packed:+ module.proj = NVFP4Linear(+ torch.zeros(128, 32, dtype=torch.uint8), torch.ones(128, 4).to(torch.float8_e4m3fn), torch.tensor(1.0)+ )+ else:+ module.proj = torch.nn.Linear(64, 128)+ return module+++class _TinyQwenImageTransformer(torch.nn.Module):+ """Stands in for `QwenImageTransformer2DModel`: the config the node reads before the lock, and one Linear."""++ def __init__(self, packed: bool) -> None:+ super().__init__()+ self.config = SimpleNamespace(patch_size=2, out_channels=16, zero_cond_t=False)+ self.inner = _module(packed)+++def _denoise_node() -> QwenImageDenoiseInvocation:+ return QwenImageDenoiseInvocation.model_construct(+ latents=None,+ reference_latents=None,+ denoise_mask=None,+ denoising_start=0.0,+ denoising_end=1.0,+ transformer=SimpleNamespace(transformer=SimpleNamespace(), loras=[]),+ positive_conditioning=SimpleNamespace(conditioning_name="pos"),+ negative_conditioning=None,+ cfg_scale=1.0,+ width=64,+ height=64,+ steps=2,+ seed=0,+ shift=None,+ )+++ ("packed", "model_format", "transient", "sidecar"),+ [+ (True, ModelFormat.Checkpoint, PACKED_TRANSIENT_BYTES, True),+ (False, ModelFormat.Checkpoint, 0, False),+ (False, ModelFormat.GGUFQuantized, 0, True),+ ],+ ids=["nvfp4_checkpoint", "dense_checkpoint", "gguf"],+)+def test_the_denoise_node_reserves_the_transient_and_patches_quantized_weights_as_sidecars(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+ packed: bool,+ model_format: ModelFormat,+ transient: int,+ sidecar: bool,+) -> None:+ transformer = _TinyQwenImageTransformer(packed=packed)+ monkeypatch.setattr(qwen_image_denoise, "QwenImageTransformer2DModel", _TinyQwenImageTransformer)+ monkeypatch.setattr(qwen_image_denoise.TorchDevice, "choose_torch_device", lambda: torch.device("cpu"))+ monkeypatch.setattr(+ QwenImageDenoiseInvocation, "_load_text_conditioning", lambda self, **_kwargs: (torch.zeros(1, 4, 8), None)+ )+ loaded = MagicMock()+ loaded.model = transformer+ loaded.model_on_device = MagicMock(return_value=nullcontext((None, transformer)))+ context = MagicMock()+ context.models.load.return_value = loaded+ context.models.get_config.return_value = SimpleNamespace(format=model_format)+ context.models.get_absolute_path.return_value = tmp_path / "qwen_image.safetensors"+ patching: dict = {}++ def stop(**kwargs):+ patching.update(kwargs)+ raise _Stop++ monkeypatch.setattr(LayerPatcher, "apply_smart_model_patches", stop)++ with pytest.raises(_Stop):+ _denoise_node()._run_diffusion(context)++ assert loaded.model_on_device.call_args.kwargs["working_mem_bytes"] == transient+ assert patching["force_sidecar_patching"] is sidecar+++def test_the_text_encoder_reserves_the_dequant_transient_of_a_packed_encoder(monkeypatch: pytest.MonkeyPatch) -> None:+ import transformers++ class _TinyQwenVL(torch.nn.Module):+ def __init__(self) -> None:+ super().__init__()+ self.inner = _module(packed=True)++ monkeypatch.setattr(transformers, "Qwen2_5_VLForConditionalGeneration", _TinyQwenVL, raising=False)+ encoder = _TinyQwenVL()+ reserved: dict = {}++ @contextmanager+ def model_on_device(working_mem_bytes=None):+ reserved["working_mem_bytes"] = working_mem_bytes+ yield (None, encoder)++ loaded = SimpleNamespace(model=encoder, compute_device=torch.device("cpu"), model_on_device=model_on_device)+ context = MagicMock()+ context.models.load.return_value = loaded+ node = QwenImageTextEncoderInvocation.model_construct(+ qwen_vl_encoder=SimpleNamespace(text_encoder=SimpleNamespace(), tokenizer=SimpleNamespace())+ )++ _, _, cleanup = node._load_cached_encoder(context)+ cleanup()++ assert reserved["working_mem_bytes"] == PACKED_TRANSIENT_BYTESdiff --git a/tests/app/routers/test_starter_model_is_installed.py b/tests/app/routers/test_starter_model_is_installed.pyindex c4d4816fee..d43507a3c1 100644--- a/tests/app/routers/test_starter_model_is_installed.py+++ b/tests/app/routers/test_starter_model_is_installed.py@@ -3,14 +3,28 @@The Z-Image and FLUX.2 Klein starters depend on a Qwen3 encoder, and every such encoder of one size serves themalike. Recognising the size only by the source spellings BFL and Tongyi use (`qwen3_4b`, `Z-Image`) left outComfy-Org's `qwen_3_4b_fp4_mixed`: installing "Z-Image Turbo (NVFP4)" beside an installed 4B encoder would queue a-redundant 3.5GB download.+redundant 3.5GB download. Comfy's Klein repos spell the size in lower case (`flux-klein-9b`), so their encoders are+recognised by the file name alone."""+import pytest+from invokeai.app.api.routers.model_manager import get_is_installedfrom invokeai.backend.model_manager.configs.qwen3_encoder import Qwen3Encoder_Checkpoint_Config-from invokeai.backend.model_manager.starter_models.common import z_image_qwen3_encoder_fp4+from invokeai.backend.model_manager.starter_models.common import (+ flux2_klein_qwen3_4b_encoder_fp4,+ flux2_klein_qwen3_8b_encoder_fp4,+ z_image_qwen3_encoder_fp4,+)+from invokeai.backend.model_manager.starter_models.types import StarterModelfrom invokeai.backend.model_manager.taxonomy import Qwen3VariantType+FP4_ENCODER_STARTERS = [+ (z_image_qwen3_encoder_fp4, Qwen3VariantType.Qwen3_4B, Qwen3VariantType.Qwen3_8B),+ (flux2_klein_qwen3_4b_encoder_fp4, Qwen3VariantType.Qwen3_4B, Qwen3VariantType.Qwen3_8B),+ (flux2_klein_qwen3_8b_encoder_fp4, Qwen3VariantType.Qwen3_8B, Qwen3VariantType.Qwen3_4B),+]+def _installed_encoder(variant: Qwen3VariantType) -> Qwen3Encoder_Checkpoint_Config:return Qwen3Encoder_Checkpoint_Config.model_construct(@@ -21,9 +35,11 @@ def _installed_encoder(variant: Qwen3VariantType) -> Qwen3Encoder_Checkpoint_Con)-def test_the_fp4_encoder_starter_is_satisfied_by_an_installed_4b_encoder() -> None:- assert get_is_installed(z_image_qwen3_encoder_fp4, [_installed_encoder(Qwen3VariantType.Qwen3_4B)])---def test_an_installed_8b_encoder_does_not_satisfy_the_4b_starter() -> None:- assert not get_is_installed(z_image_qwen3_encoder_fp4, [_installed_encoder(Qwen3VariantType.Qwen3_8B)])+ ("starter", "size", "other_size"), FP4_ENCODER_STARTERS, ids=["z_image_4b", "klein_4b", "klein_8b"]+)+def test_an_fp4_encoder_starter_is_satisfied_by_an_installed_encoder_of_its_size_only(+ starter: StarterModel, size: Qwen3VariantType, other_size: Qwen3VariantType+) -> None:+ assert get_is_installed(starter, [_installed_encoder(size)])+ assert not get_is_installed(starter, [_installed_encoder(other_size)])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.pynew file mode 100644index 0000000000..9c574a579b--- /dev/null+++ b/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.py@@ -0,0 +1,229 @@+"""Qwen-Image's single-file loaders keep Comfy's nvfp4 builds packed.++Both Comfy files mix nvfp4 with scaled fp8, and both loaders fold ComfyUI fp8 with `_dequantize_comfyui_fp8`, which+multiplies every `.weight_scale` into its weight -- nvfp4's block scales included. So what these tests pin is the order:+the nvfp4 layers leave the state dict before the fold, come back packed under the paths the model uses (the encoder's+legacy `model.X` keys become `model.language_model.X`), the fp8 layers are still folded, and one reservation is made+before the fold widens anything. The compute dtype is bf16, as in production: the packed global scale must not be cast.+"""++import json+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest+import torch++from invokeai.backend.model_manager.configs.main import Main_Checkpoint_QwenImage_Config+from invokeai.backend.model_manager.configs.qwen_vl_encoder import QwenVLEncoder_Checkpoint_Config+from invokeai.backend.model_manager.load.model_loaders import qwen_image+from invokeai.backend.model_manager.load.model_loaders.qwen_image import (+ QwenImageCheckpointModel,+ QwenVLEncoderCheckpointLoader,+)+from invokeai.backend.quantization.nvfp4 import NVFP4Linear++COMPUTE_DTYPE = torch.bfloat16+++def _nvfp4_tensors(path: str, shape: tuple[int, int]) -> tuple[dict[str, torch.Tensor], torch.Tensor]:+ """Codes 2 and 10 are +1.0 and -1.0; with a block scale of 2 and a global scale of 0.25 the weight is +-0.5. Comfy+ ships an activation scale beside each layer, which the loader has no use for."""+ positive = torch.randint(0, 2, shape, dtype=torch.bool)+ codes = torch.where(positive, 2, 10).to(torch.uint8)+ tensors = {+ f"{path}.weight": (codes[:, 0::2] << 4) | codes[:, 1::2],+ f"{path}.weight_scale": torch.full((shape[0], shape[1] // 16), 2.0).to(torch.float8_e4m3fn),+ f"{path}.weight_scale_2": torch.tensor(0.25),+ f"{path}.input_scale": torch.tensor(1.0),+ }+ return tensors, torch.where(positive, 0.5, -0.5)+++def _packed_bytes(rows: int, columns: int) -> int:+ return rows * columns // 2 + rows * (columns // 16) + 4+++def _marker(fmt: str) -> torch.Tensor:+ return torch.frombuffer(bytearray(json.dumps({"format": fmt}).encode("utf-8")), dtype=torch.uint8).clone()+++def _patch_common(monkeypatch: pytest.MonkeyPatch, state_dict: dict, metadata: dict) -> list[bool]:+ """Patch file access and devices; return a log of whether room had been made when the fp8 fold ran."""+ import safetensors.torch++ monkeypatch.setattr(safetensors.torch, "load_file", lambda _path: state_dict)+ monkeypatch.setattr(qwen_image, "read_safetensors_metadata", lambda _path, _logger: metadata)+ monkeypatch.setattr(qwen_image.TorchDevice, "choose_torch_device", lambda: torch.device("cpu"))+ monkeypatch.setattr(qwen_image.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: COMPUTE_DTYPE)+ return []+++def _record_fold(monkeypatch: pytest.MonkeyPatch, loader, log: list[bool]) -> None:+ fold = qwen_image._dequantize_comfyui_fp8++ def recording_fold(*args, **kwargs):+ log.append(loader._ram_cache.make_room.called)+ return fold(*args, **kwargs)++ monkeypatch.setattr(qwen_image, "_dequantize_comfyui_fp8", recording_fold)+++class _TinyQwenImageTransformer(torch.nn.Module):+ """The diffusers module names Comfy's Qwen-Image build uses, at toy width."""++ _skip_layerwise_casting_patterns = ["pos_embed", "norm"]++ def __init__(self, **_kwargs) -> None:+ super().__init__()+ block = torch.nn.Module()+ block.attn = torch.nn.Module()+ block.attn.to_q = torch.nn.Linear(64, 128)+ block.img_mlp = torch.nn.Module()+ block.img_mlp.net = torch.nn.ModuleList([torch.nn.Module()])+ block.img_mlp.net[0].proj = torch.nn.Linear(64, 256)+ block.txt_mlp = torch.nn.Module()+ block.txt_mlp.net = torch.nn.ModuleList([torch.nn.Identity(), torch.nn.Identity(), torch.nn.Linear(64, 128)])+ self.transformer_blocks = torch.nn.ModuleList([block])+ self.img_in = torch.nn.Linear(64, 128)+++def test_the_transformer_keeps_header_named_nvfp4_layers_packed_beside_folded_fp8(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ import diffusers++ torch.manual_seed(0)+ state_dict: dict[str, torch.Tensor] = {}+ expected: dict[str, torch.Tensor] = {}+ header: dict[str, dict[str, str]] = {}+ for path, shape in (+ ("transformer_blocks.0.attn.to_q", (128, 64)),+ ("transformer_blocks.0.img_mlp.net.0.proj", (256, 64)),+ ):+ tensors, weight = _nvfp4_tensors(path, shape)+ state_dict.update(tensors)+ state_dict[f"{path}.bias"] = torch.randn(shape[0])+ expected[path] = weight+ header[path] = {"format": "nvfp4"}+ fp8_values = torch.randint(-8, 9, (128, 64)).float()+ fp8 = "transformer_blocks.0.txt_mlp.net.2"+ state_dict[f"{fp8}.weight"] = fp8_values.to(torch.float8_e4m3fn)+ state_dict[f"{fp8}.weight_scale"] = torch.tensor(0.5)+ state_dict[f"{fp8}.input_scale"] = torch.tensor(1.0)+ state_dict[f"{fp8}.bias"] = torch.randn(128)+ header[fp8] = {"format": "float8_e4m3fn"}+ state_dict["img_in.weight"] = torch.randn(128, 64)+ state_dict["img_in.bias"] = torch.randn(128)++ log = _patch_common(monkeypatch, state_dict, {"_quantization_metadata": json.dumps({"layers": header})})+ monkeypatch.setattr(diffusers, "QwenImageTransformer2DModel", _TinyQwenImageTransformer, raising=False)+ checkpoint = tmp_path / "qwen_image_nvfp4.safetensors"+ checkpoint.touch()+ loader = object.__new__(QwenImageCheckpointModel)+ loader._ram_cache = SimpleNamespace(make_room=MagicMock())+ _record_fold(monkeypatch, loader, log)+ biases = {path: state_dict[f"{path}.bias"] for path in expected}++ model = loader._load_from_singlefile(Main_Checkpoint_QwenImage_Config.model_construct(path=str(checkpoint)))++ for path, weight in expected.items():+ module = model.get_submodule(path)+ assert isinstance(module, NVFP4Linear), path+ assert module.weight.dtype is torch.uint8, path+ assert module.weight_scale_2.dtype is torch.float32, path+ x = torch.randn(3, module.in_features, dtype=COMPUTE_DTYPE)+ expected_out = torch.nn.functional.linear(x, weight.to(COMPUTE_DTYPE), biases[path].to(COMPUTE_DTYPE))+ torch.testing.assert_close(module(x), expected_out)+ folded = model.transformer_blocks[0].txt_mlp.net[2]+ assert type(folded) is torch.nn.Linear+ assert torch.equal(folded.weight, (fp8_values * 0.5).to(COMPUTE_DTYPE))+ assert log == [True]++ # Counted by hand: the packed layers as stored; their biases, the folded fp8 weight and its bias, its two scale+ # scalars, and the dense input projection at bf16. The packed layers' scales are part of their stored size.+ packed = _packed_bytes(128, 64) + _packed_bytes(256, 64)+ widened = (128 + 256) + (128 * 64 + 128 + 2) + (128 * 64 + 128)+ loader._ram_cache.make_room.assert_called_once_with(packed + widened * COMPUTE_DTYPE.itemsize)+++class _TinyQwenVL(torch.nn.Module):+ """transformers' `Qwen2_5_VLForConditionalGeneration` layout at toy width: the language model and the vision tower+ under `model.`, the LM head at the top."""++ _checkpoint_conversion_mapping: dict = {}++ def __init__(self, _config) -> None:+ super().__init__()+ layer = torch.nn.Module()+ layer.self_attn = torch.nn.Module()+ layer.self_attn.q_proj = torch.nn.Linear(64, 128)+ layer.mlp = torch.nn.Module()+ layer.mlp.down_proj = torch.nn.Linear(64, 128, bias=False)+ self.model = torch.nn.Module()+ self.model.language_model = torch.nn.Module()+ self.model.language_model.layers = torch.nn.ModuleList([layer])+ self.model.visual = torch.nn.Module()+ self.model.visual.proj = torch.nn.Linear(8, 4)+ self.lm_head = torch.nn.Linear(64, 32, bias=False)+++def test_the_encoder_keeps_marker_named_nvfp4_layers_packed_under_their_transformers_paths(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ import transformers++ torch.manual_seed(1)+ state_dict: dict[str, torch.Tensor] = {}+ expected: dict[str, torch.Tensor] = {}+ for legacy, shape in (("model.layers.0.self_attn.q_proj", (128, 64)), ("model.layers.0.mlp.down_proj", (128, 64))):+ tensors, weight = _nvfp4_tensors(legacy, shape)+ state_dict.update(tensors)+ state_dict[f"{legacy}.comfy_quant"] = _marker("nvfp4")+ expected[legacy.replace("model.", "model.language_model.", 1)] = weight+ state_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)+ state_dict["visual.proj.bias"] = torch.randn(4)++ log = _patch_common(monkeypatch, state_dict, {})+ monkeypatch.setattr(transformers, "Qwen2_5_VLForConditionalGeneration", _TinyQwenVL, raising=False)+ monkeypatch.setattr(+ transformers.AutoConfig,+ "from_pretrained",+ lambda *_args, **_kwargs: SimpleNamespace(torch_dtype=None, tie_word_embeddings=False),+ )+ checkpoint = tmp_path / "qwen_2.5_vl_7b_nvfp4.safetensors"+ checkpoint.touch()+ loader = object.__new__(QwenVLEncoderCheckpointLoader)+ loader._ram_cache = SimpleNamespace(make_room=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))+ )++ for path, weight in expected.items():+ module = model.get_submodule(path)+ assert isinstance(module, NVFP4Linear), path+ assert module.weight_scale_2.dtype is torch.float32, path+ x = torch.randn(3, module.in_features, dtype=COMPUTE_DTYPE)+ bias = q_bias.to(COMPUTE_DTYPE) if module.bias is not None else None+ torch.testing.assert_close(module(x), torch.nn.functional.linear(x, weight.to(COMPUTE_DTYPE), 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 log == [True]++ # Counted by hand: the packed layers as stored, the q_proj bias, the folded LM head with its two scale scalars and+ # the vision projection at bf16, and the LM head's 27-byte marker as stored.+ packed = 2 * _packed_bytes(128, 64)+ widened = 128 + (32 * 64 + 2) + (4 * 8 + 4)+ loader._ram_cache.make_room.assert_called_once_with(packed + widened * COMPUTE_DTYPE.itemsize + fp8_marker.numel())