Skip to content

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

feat(quantization): keep Comfy fp4_mixed Qwen3 encoders packed

Alexander Eichhorn0b50df5f85d8
diff --git a/docs/src/content/docs/start-here/system-requirements.mdx b/docs/src/content/docs/start-here/system-requirements.mdx
index 2488357c93..2e84df4412 100644
--- a/docs/src/content/docs/start-here/system-requirements.mdx
+++ b/docs/src/content/docs/start-here/system-requirements.mdx
@@ -29,7 +29,7 @@ The requirements below are rough guidelines for best performance. GPUs with less
| FLUX.1 | 1024x1024 | Nvidia 20xx+ | 10GB | 32GB | |
| FLUX.2 Klein 4B | 1024x1024 | Nvidia 30xx+ | 12GB | 16GB | FP8 works with 8GB+; Diffusers + encoder |
| FLUX.2 Klein 9B | 1024x1024 | Nvidia 40xx | 24GB | 32GB | FP8 works with 12GB+; Diffusers + encoder |
-| Z-Image Turbo | 1024x1024 | Nvidia 20xx+ | 8GB | 16GB | Q4_K 8GB; Q8/BF16 16GB+ |
+| Z-Image Turbo | 1024x1024 | Nvidia 20xx+ | 8GB | 16GB | Q4_K / NVFP4 8GB; Q8/BF16 16GB+ |
| Krea-2 (Turbo / Raw) | 1024x1024 | Nvidia 40xx | 24GB | 32GB | FP8 works with 16GB+; GGUF Q4_K ~12GB. Diffusers ~26GB; GGUF needs a standalone VAE + Qwen3-VL encoder |
| Wan 2.2 A14B (T2V/I2V) | 1280x720 | Nvidia 30xx+ | 12GB | 32GB | Dual-expert MoE; Q4_K_M 12GB; Q8 18GB+; Diffusers requires 32GB+ |
| Wan 2.2 TI2V-5B | 1280x720 | Nvidia 20xx+ | 8GB | 16GB | Single transformer; Q4_K_M 6GB+; Q8 8GB+; Diffusers 12GB+ |
diff --git a/invokeai/app/api/routers/model_manager.py b/invokeai/app/api/routers/model_manager.py
index b29a92de64..1c5742b3f5 100644
--- a/invokeai/app/api/routers/model_manager.py
+++ b/invokeai/app/api/routers/model_manager.py
@@ -1432,11 +1432,13 @@ def get_is_installed(
# Determine expected variant from source pattern
expected_variant: Qwen3VariantType | None = None
- if "klein-9B" in starter_model.source or "qwen3_8b" in starter_model.source.lower():
+ source = starter_model.source.lower()
+ if "klein-9B" in starter_model.source or "qwen3_8b" in source or "qwen_3_8b" in source:
expected_variant = Qwen3VariantType.Qwen3_8B
elif (
"klein-4B" in starter_model.source
- or "qwen3_4b" in starter_model.source.lower()
+ or "qwen3_4b" in source
+ or "qwen_3_4b" in source
or "Z-Image" in starter_model.source
):
expected_variant = Qwen3VariantType.Qwen3_4B
diff --git a/invokeai/app/invocations/text_encoder/anima_text_encoder.py b/invokeai/app/invocations/text_encoder/anima_text_encoder.py
index ae79327f3c..7c446e17f4 100644
--- a/invokeai/app/invocations/text_encoder/anima_text_encoder.py
+++ b/invokeai/app/invocations/text_encoder/anima_text_encoder.py
@@ -34,6 +34,7 @@ from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpec
from invokeai.backend.patches.lora_conversions.anima_lora_constants import ANIMA_LORA_QWEN3_PREFIX
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
+from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes, requires_sidecar_patching
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (
AnimaConditioningInfo,
ConditioningFieldData,
@@ -121,9 +122,17 @@ class AnimaTextEncoderInvocation(BaseInvocation):
# --- Step 1: Encode with Qwen3 0.6B ---
text_encoder_info = context.models.load(self.qwen3_encoder.text_encoder)
tokenizer_info = context.models.load(self.qwen3_encoder.tokenizer)
+ text_encoder_format = context.models.get_config(self.qwen3_encoder.text_encoder).format
+ # An nvfp4 build dequantizes each packed Linear per forward, a transient its resident size does not
+ # cover. Read from the unlocked model, before the lock the reservation applies to; zero for other builds.
+ dequant_bytes = peak_dequant_transient_bytes(
+ text_encoder_info.model, TorchDevice.choose_anima_inference_dtype(text_encoder_info.compute_device)
+ )
with ExitStack() as exit_stack:
- (_, text_encoder) = exit_stack.enter_context(text_encoder_info.model_on_device())
+ (_, text_encoder) = exit_stack.enter_context(
+ text_encoder_info.model_on_device(working_mem_bytes=dequant_bytes)
+ )
(_, tokenizer) = exit_stack.enter_context(tokenizer_info.model_on_device())
# Use the encoder's intended compute device, not its current parameter residency: partial loading may
@@ -139,6 +148,9 @@ class AnimaTextEncoderInvocation(BaseInvocation):
patches=self._lora_iterator(context),
prefix=ANIMA_LORA_QWEN3_PREFIX,
dtype=lora_dtype,
+ # Quantized weights (packed nvfp4 Linears, GGUF, SDNQ) cannot take a direct patch, so
+ # their LoRAs ride as sidecars.
+ force_sidecar_patching=requires_sidecar_patching(text_encoder, text_encoder_format),
)
)
diff --git a/invokeai/app/invocations/text_encoder/flux2_klein_text_encoder.py b/invokeai/app/invocations/text_encoder/flux2_klein_text_encoder.py
index 33150c7a28..1e7f15266e 100644
--- a/invokeai/app/invocations/text_encoder/flux2_klein_text_encoder.py
+++ b/invokeai/app/invocations/text_encoder/flux2_klein_text_encoder.py
@@ -28,6 +28,7 @@ from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpec
from invokeai.backend.patches.lora_conversions.flux_lora_constants import FLUX_LORA_T5_PREFIX
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
+from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes, requires_sidecar_patching
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData, FLUXConditioningInfo
from invokeai.backend.util.devices import TorchDevice
@@ -102,7 +103,15 @@ class Flux2KleinTextEncoderInvocation(BaseInvocation):
# Reordered loading to prevent the annoying cache drop issue
# This prevents it from being evicted while we look up the tokenizer
text_encoder_info = context.models.load(self.qwen3_encoder.text_encoder)
- (cached_weights, text_encoder) = exit_stack.enter_context(text_encoder_info.model_on_device())
+ text_encoder_format = context.models.get_config(self.qwen3_encoder.text_encoder).format
+ # An nvfp4 build dequantizes each packed Linear per forward, a transient its resident size does not
+ # cover. Read from the unlocked model, before the lock the reservation applies to; zero for other builds.
+ dequant_bytes = peak_dequant_transient_bytes(
+ text_encoder_info.model, TorchDevice.choose_bfloat16_safe_dtype(text_encoder_info.compute_device)
+ )
+ (cached_weights, text_encoder) = exit_stack.enter_context(
+ text_encoder_info.model_on_device(working_mem_bytes=dequant_bytes)
+ )
# Now it is safe to load and lock the tokenizer
tokenizer_info = context.models.load(self.qwen3_encoder.tokenizer)
@@ -127,6 +136,9 @@ class Flux2KleinTextEncoderInvocation(BaseInvocation):
prefix=FLUX_LORA_T5_PREFIX,
dtype=lora_dtype,
cached_weights=cached_weights,
+ # Quantized weights (packed nvfp4 Linears, GGUF, SDNQ) cannot take a direct patch, so
+ # their LoRAs ride as sidecars.
+ force_sidecar_patching=requires_sidecar_patching(text_encoder, text_encoder_format),
)
)
diff --git a/invokeai/app/invocations/text_encoder/z_image_text_encoder.py b/invokeai/app/invocations/text_encoder/z_image_text_encoder.py
index 397ebc1ac4..9c5541627c 100644
--- a/invokeai/app/invocations/text_encoder/z_image_text_encoder.py
+++ b/invokeai/app/invocations/text_encoder/z_image_text_encoder.py
@@ -19,6 +19,7 @@ from invokeai.app.services.shared.invocation_context import InvocationContext
from invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpec
from invokeai.backend.patches.lora_conversions.z_image_lora_constants import Z_IMAGE_LORA_QWEN3_PREFIX
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
+from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes, requires_sidecar_patching
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (
ConditioningFieldData,
ZImageConditioningInfo,
@@ -75,9 +76,17 @@ class ZImageTextEncoderInvocation(BaseInvocation):
text_encoder_info = context.models.load(self.qwen3_encoder.text_encoder)
tokenizer_info = context.models.load(self.qwen3_encoder.tokenizer)
+ text_encoder_format = context.models.get_config(self.qwen3_encoder.text_encoder).format
+ # An nvfp4 build dequantizes each packed Linear per forward, a transient its resident size does not
+ # cover. Read from the unlocked model, before the lock the reservation applies to; zero for other builds.
+ dequant_bytes = peak_dequant_transient_bytes(
+ text_encoder_info.model, TorchDevice.choose_bfloat16_safe_dtype(text_encoder_info.compute_device)
+ )
with ExitStack() as exit_stack:
- (cached_weights, text_encoder) = exit_stack.enter_context(text_encoder_info.model_on_device())
+ (cached_weights, text_encoder) = exit_stack.enter_context(
+ text_encoder_info.model_on_device(working_mem_bytes=dequant_bytes)
+ )
(_, tokenizer) = exit_stack.enter_context(tokenizer_info.model_on_device())
# Repair any required tensors left on the CPU by a previous interrupted run, then run on the encoder's
@@ -99,6 +108,9 @@ class ZImageTextEncoderInvocation(BaseInvocation):
prefix=Z_IMAGE_LORA_QWEN3_PREFIX,
dtype=lora_dtype,
cached_weights=cached_weights,
+ # Quantized weights (packed nvfp4 Linears, GGUF, SDNQ) cannot take a direct patch, so
+ # their LoRAs ride as sidecars.
+ force_sidecar_patching=requires_sidecar_patching(text_encoder, text_encoder_format),
)
)
diff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.py
index 595218f8fc..9cda49bf8e 100644
--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py
@@ -1221,28 +1221,16 @@ class Qwen3EncoderCheckpointLoader(ModelLoader):
# Load the state dict from safetensors file
sd = load_file(model_path)
-
- # Handle ComfyUI quantized checkpoints
- # ComfyUI stores quantized weights with accompanying scale factors:
- # - layer.weight: quantized data (FP8)
- # - layer.weight_scale: scale factor (FP32 scalar)
- # Dequantization formula: dequantized = weight.to(dtype) * weight_scale
- # Reference: https://github.com/Comfy-Org/ComfyUI/blob/master/QUANTIZATION.md
original_key_count = len(sd)
- dequantized_count = _fold_comfy_scaled_weights(sd, model_dtype)
-
- if dequantized_count > 0:
- logger.info(f"Dequantized {dequantized_count} ComfyUI quantized weights")
-
- # Filter out ComfyUI quantization metadata keys (comfy_quant, weight_scale)
- # These are no longer needed after dequantization
- comfy_metadata_keys = [k for k in sd.keys() if is_scale_metadata_key(k)]
- for k in comfy_metadata_keys:
- del sd[k]
- if comfy_metadata_keys:
- logger.info(f"Filtered out {len(comfy_metadata_keys)} ComfyUI quantization metadata keys")
- logger.info(f"Loaded state dict with {len(sd)} keys (originally {original_key_count})")
+ # Comfy's fp4_mixed encoders keep most projections in nvfp4, beside scaled fp8. Take those out before
+ # anything below reads the side channel: the fold pairs every `weight_scale` with its weight and would
+ # stretch nvfp4's block scales over the packed codes, and the cast further down would widen them.
+ nvfp4_payloads = pop_nvfp4_layers(
+ sd, header_layers=parse_quantization_metadata(read_safetensors_metadata(model_path, logger))
+ )
+ # `lm_head` is tied to the embeddings below, which replaces the weight a packed module would hold.
+ nvfp4_payloads.pop("lm_head", None)
# Count the number of layers by looking at layer keys
layer_count = 0
@@ -1293,18 +1281,26 @@ class Qwen3EncoderCheckpointLoader(ModelLoader):
f"Unknown Qwen3 variant: embed_hidden_size={embed_hidden_size}, layers={layer_count}. "
"Attempting to detect configuration from weights..."
)
- q_proj_weight = sd.get("model.layers.0.self_attn.q_proj.weight")
- k_proj_weight = sd.get("model.layers.0.self_attn.k_proj.weight")
- gate_proj_weight = sd.get("model.layers.0.mlp.gate_proj.weight")
- if q_proj_weight is None or k_proj_weight is None or gate_proj_weight is None:
+ def output_rows(path: str) -> int | None:
+ # A packed layer's weight has left `sd`; its payload knows the rows.
+ if path in nvfp4_payloads:
+ return nvfp4_payloads[path].out_features
+ weight = sd.get(f"{path}.weight")
+ return None if weight is None else weight.shape[0]
+
+ q_rows = output_rows("model.layers.0.self_attn.q_proj")
+ k_rows = output_rows("model.layers.0.self_attn.k_proj")
+ gate_rows = output_rows("model.layers.0.mlp.gate_proj")
+
+ if q_rows is None or k_rows is None or gate_rows is None:
raise ValueError("Could not find attention/mlp weights to determine configuration")
hidden_size = embed_hidden_size
head_dim = 128
- num_attention_heads = q_proj_weight.shape[0] // head_dim
- num_kv_heads = k_proj_weight.shape[0] // head_dim
- intermediate_size = gate_proj_weight.shape[0]
+ num_attention_heads = q_rows // head_dim
+ num_kv_heads = k_rows // head_dim
+ intermediate_size = gate_rows
max_position_embeddings = 40960
logger.info(
@@ -1331,18 +1327,52 @@ class Qwen3EncoderCheckpointLoader(ModelLoader):
torch_dtype=model_dtype,
)
- # Handle memory management
- new_sd_size = sum([ten.nelement() * model_dtype.itemsize for ten in sd.values()])
- self._ram_cache.make_room(new_sd_size)
+ # Use Qwen3ForCausalLM - the correct model class for Z-Image text encoder
+ # Use init_empty_weights for fast model creation, then load weights with assign=True. Built before the
+ # reservation, which depends on its modules: they decide which nvfp4 layers stay packed.
+ with accelerate.init_empty_weights():
+ model = Qwen3ForCausalLM(qwen_config)
+ skip_patterns = _model_declared_skip_patterns(model)
+
+ # Handle memory management before anything below widens a weight: the scaled-fp8 fold turns every quantized
+ # layer into the compute dtype, and the base loader reserved only the file size. One reservation for what
+ # the state dict ends up holding -- every tensor but the scale metadata at the compute dtype, plus the nvfp4
+ # layers as they will be held -- since `make_room` makes that much room rather than adding to an earlier one.
+ new_sd_size = sum(
+ tensor.nelement() * model_dtype.itemsize for key, tensor in sd.items() if not is_scale_metadata_key(key)
+ )
+ self._ram_cache.make_room(
+ new_sd_size + predict_nvfp4_install_size(model, nvfp4_payloads, model_dtype, skip_patterns)
+ )
+
+ # Handle ComfyUI quantized checkpoints
+ # ComfyUI stores quantized weights with accompanying scale factors:
+ # - layer.weight: quantized data (FP8)
+ # - layer.weight_scale: scale factor (FP32 scalar)
+ # Dequantization formula: dequantized = weight.to(dtype) * weight_scale
+ # Reference: https://github.com/Comfy-Org/ComfyUI/blob/master/QUANTIZATION.md
+ dequantized_count = _fold_comfy_scaled_weights(sd, model_dtype)
+
+ if dequantized_count > 0:
+ logger.info(f"Dequantized {dequantized_count} ComfyUI quantized weights")
+
+ # Filter out ComfyUI quantization metadata keys (comfy_quant, weight_scale)
+ # These are no longer needed after dequantization
+ comfy_metadata_keys = [k for k in sd.keys() if is_scale_metadata_key(k)]
+ for k in comfy_metadata_keys:
+ del sd[k]
+ if comfy_metadata_keys:
+ logger.info(f"Filtered out {len(comfy_metadata_keys)} ComfyUI quantization metadata keys")
+
+ logger.info(f"Loaded state dict with {len(sd)} keys (originally {original_key_count})")
# Convert to target dtype
for k in sd.keys():
sd[k] = sd[k].to(model_dtype)
- # Use Qwen3ForCausalLM - the correct model class for Z-Image text encoder
- # Use init_empty_weights for fast model creation, then load weights with assign=True
- with accelerate.init_empty_weights():
- model = Qwen3ForCausalLM(qwen_config)
+ if nvfp4_payloads:
+ packed = install_nvfp4_layers(model, sd, nvfp4_payloads, model_dtype, skip_patterns)
+ logger.info(f"Kept {packed} of {len(nvfp4_payloads)} nvfp4 layer(s) packed.")
# Load the text model weights from checkpoint
# assign=True replaces meta tensors with real ones from state dict
diff --git a/invokeai/backend/model_manager/starter_models/__init__.py b/invokeai/backend/model_manager/starter_models/__init__.py
index a6f17efe61..741e0d6b60 100644
--- a/invokeai/backend/model_manager/starter_models/__init__.py
+++ b/invokeai/backend/model_manager/starter_models/__init__.py
@@ -52,6 +52,7 @@ from invokeai.backend.model_manager.starter_models.common import (
t5_gguf_q6_k_encoder,
wan_22_t5_encoder,
z_image_qwen3_encoder,
+ z_image_qwen3_encoder_fp4,
z_image_qwen3_encoder_quantized,
)
from invokeai.backend.model_manager.starter_models.ernie_image import (
@@ -244,6 +245,7 @@ from invokeai.backend.model_manager.starter_models.z_image import (
z_image_controlnet_tile,
z_image_controlnet_union,
z_image_turbo,
+ z_image_turbo_nvfp4,
z_image_turbo_q8,
z_image_turbo_quantized,
z_image_turbo_sdnq,
@@ -383,9 +385,11 @@ STARTER_MODELS: list[StarterModel] = [
z_image_turbo,
z_image_turbo_quantized,
z_image_turbo_q8,
+ z_image_turbo_nvfp4,
z_image_turbo_sdnq,
z_image_qwen3_encoder,
z_image_qwen3_encoder_quantized,
+ z_image_qwen3_encoder_fp4,
z_image_controlnet_union,
z_image_controlnet_tile,
ernie_image,
diff --git a/invokeai/backend/model_manager/starter_models/common.py b/invokeai/backend/model_manager/starter_models/common.py
index 7c17e199d8..edb0c15daa 100644
--- a/invokeai/backend/model_manager/starter_models/common.py
+++ b/invokeai/backend/model_manager/starter_models/common.py
@@ -314,6 +314,14 @@ z_image_qwen3_encoder_quantized = StarterModel(
format=ModelFormat.GGUFQuantized,
)
+z_image_qwen3_encoder_fp4 = StarterModel(
+ name="Z-Image Qwen3 Text Encoder (FP4 mixed)",
+ base=BaseModelType.Any,
+ source="https://huggingface.co/Comfy-Org/z_image/resolve/main/split_files/text_encoders/qwen_3_4b_fp4_mixed.safetensors",
+ description="Comfy-Org's nvfp4/fp8-mixed Qwen3 4B text encoder for Z-Image. Its nvfp4 layers stay packed, about 4.3GB once loaded. ~3.5GB download",
+ type=ModelType.Qwen3Encoder,
+)
+
# region Krea-2
# Standalone Qwen3-VL text encoder used by Krea-2 (distinct from the Qwen2.5-VL encoder above). Pair
# with single-file / GGUF Krea-2 transformers, which ship only the transformer. The Qwen-Image VAE
diff --git a/invokeai/backend/model_manager/starter_models/z_image.py b/invokeai/backend/model_manager/starter_models/z_image.py
index 8d9c1c1f68..7f7ae9a42e 100644
--- a/invokeai/backend/model_manager/starter_models/z_image.py
+++ b/invokeai/backend/model_manager/starter_models/z_image.py
@@ -1,6 +1,9 @@
"""Z-Image starter models."""
-from invokeai.backend.model_manager.starter_models.common import z_image_qwen3_encoder_quantized
+from invokeai.backend.model_manager.starter_models.common import (
+ z_image_qwen3_encoder_fp4,
+ z_image_qwen3_encoder_quantized,
+)
from invokeai.backend.model_manager.starter_models.flux import flux_vae
from invokeai.backend.model_manager.starter_models.types import StarterModel
from invokeai.backend.model_manager.taxonomy import (
@@ -37,6 +40,15 @@ z_image_turbo_q8 = StarterModel(
dependencies=[z_image_qwen3_encoder_quantized, flux_vae],
)
+z_image_turbo_nvfp4 = StarterModel(
+ name="Z-Image Turbo (NVFP4)",
+ base=BaseModelType.ZImage,
+ source="https://huggingface.co/Comfy-Org/z_image_turbo/resolve/main/split_files/diffusion_models/z_image_turbo_nvfp4.safetensors",
+ description="Z-Image Turbo in Comfy-Org's nvfp4 build. Its quantized layers stay packed, so it needs about a third of the full-precision transformer's memory. Requires standalone Qwen3 text encoder and Flux VAE. ~4.5GB",
+ type=ModelType.Main,
+ dependencies=[z_image_qwen3_encoder_fp4, flux_vae],
+)
+
z_image_turbo_sdnq = StarterModel(
name="Z-Image Turbo (SDNQ uint4 + SVD)",
base=BaseModelType.ZImage,
diff --git a/tests/app/invocations/test_anima_text_encoder.py b/tests/app/invocations/test_anima_text_encoder.py
index 8a5cf19299..215acffb0c 100644
--- a/tests/app/invocations/test_anima_text_encoder.py
+++ b/tests/app/invocations/test_anima_text_encoder.py
@@ -51,7 +51,7 @@ class FakeT5Tokenizer:
class FakeLoadedModel:
def __init__(self, model, compute_device=torch.device("cpu")):
- self._model = model
+ self.model = model
self._compute_device = compute_device
@property
@@ -59,8 +59,8 @@ class FakeLoadedModel:
return self._compute_device
@contextmanager
- def model_on_device(self):
- yield (None, self._model)
+ def model_on_device(self, working_mem_bytes=None):
+ yield (None, self.model)
def _run_encode(monkeypatch, compute_device: torch.device) -> FakeQwen3Encoder:
diff --git a/tests/app/invocations/test_qwen3_text_encoders_with_packed_layers.py b/tests/app/invocations/test_qwen3_text_encoders_with_packed_layers.py
new file mode 100644
index 0000000000..4e16809897
--- /dev/null
+++ b/tests/app/invocations/test_qwen3_text_encoders_with_packed_layers.py
@@ -0,0 +1,100 @@
+"""The Qwen3 text-encoder nodes have to treat a quantized encoder the way the denoise nodes treat a quantized
+transformer: reserve working memory for the per-forward dequantization of packed nvfp4 Linears, and apply LoRA as
+a sidecar wherever a direct patch cannot write the weights -- packed nvfp4 Linears, and GGUF or SDNQ encoders,
+which the denoise nodes already patch this way. All three nodes load through the same Qwen3 loader, so each of
+them receives a packed encoder as soon as someone installs Comfy's fp4_mixed file.
+"""
+
+from contextlib import ExitStack, contextmanager
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+import torch
+
+from invokeai.app.invocations.text_encoder.anima_text_encoder import AnimaTextEncoderInvocation
+from invokeai.app.invocations.text_encoder.flux2_klein_text_encoder import Flux2KleinTextEncoderInvocation
+from invokeai.app.invocations.text_encoder.z_image_text_encoder import ZImageTextEncoderInvocation
+from invokeai.backend.model_manager.taxonomy import ModelFormat
+from invokeai.backend.patches.layer_patcher import LayerPatcher
+from invokeai.backend.quantization.nvfp4 import NVFP4Linear
+
+
+class _StopAtPatching(Exception):
+ """Raised from the patched `apply_smart_model_patches`, so the node stops right where it has decided."""
+
+
+class _LoadedModel:
+ def __init__(self, model: object) -> None:
+ self.model = model
+ self.compute_device = torch.device("cpu")
+ self.working_mem_bytes: int | None = None
+
+ @contextmanager
+ def model_on_device(self, working_mem_bytes: int | None = None):
+ self.working_mem_bytes = working_mem_bytes
+ yield (None, self.model)
+
+ def repair_required_tensors_on_device(self) -> int:
+ return 0
+
+
+def _encoder(packed: bool) -> torch.nn.Module:
+ encoder = torch.nn.Module()
+ if packed:
+ weight = torch.zeros(128, 32, dtype=torch.uint8)
+ encoder.proj = NVFP4Linear(weight, torch.ones(128, 4).to(torch.float8_e4m3fn), torch.tensor(1.0))
+ else:
+ encoder.proj = torch.nn.Linear(64, 128)
+ return encoder
+
+
+NODES = {
+ "z_image": (ZImageTextEncoderInvocation, lambda node, context: node._encode_prompt(context, max_seq_len=512)),
+ "flux2_klein": (Flux2KleinTextEncoderInvocation, lambda node, context: node._encode_prompt(context, ExitStack())),
+ "anima": (AnimaTextEncoderInvocation, lambda node, context: node._encode_prompt(context)),
+}
+
+
+ ("packed", "model_format", "sidecar", "working_memory"),
+ [
+ (True, ModelFormat.Checkpoint, True, True),
+ (False, ModelFormat.Checkpoint, False, False),
+ (False, ModelFormat.GGUFQuantized, True, False),
+ ],
+ ids=["nvfp4_checkpoint", "dense_checkpoint", "gguf"],
+)
[email protected]("node_name", list(NODES))
+def test_the_node_reserves_the_dequant_transient_and_patches_quantized_encoders_as_sidecars(
+ monkeypatch: pytest.MonkeyPatch,
+ node_name: str,
+ packed: bool,
+ model_format: ModelFormat,
+ sidecar: bool,
+ working_memory: bool,
+) -> None:
+ invocation_class, encode = NODES[node_name]
+ encoder = _LoadedModel(_encoder(packed))
+ context = MagicMock()
+ context.models.load.side_effect = [encoder, _LoadedModel(object())]
+ context.models.get_config.return_value = SimpleNamespace(format=model_format)
+ patching: dict = {}
+
+ def stop(**kwargs):
+ patching.update(kwargs)
+ raise _StopAtPatching
+
+ monkeypatch.setattr(LayerPatcher, "apply_smart_model_patches", stop)
+ node = invocation_class.model_construct(
+ prompt="a prompt",
+ qwen3_encoder=SimpleNamespace(text_encoder=SimpleNamespace(), tokenizer=SimpleNamespace(), loras=[]),
+ mask=None,
+ max_seq_len=512,
+ )
+
+ with pytest.raises(_StopAtPatching):
+ encode(node, context)
+
+ assert patching["force_sidecar_patching"] is sidecar
+ assert bool(encoder.working_mem_bytes) is working_memory
diff --git a/tests/app/routers/test_starter_model_is_installed.py b/tests/app/routers/test_starter_model_is_installed.py
new file mode 100644
index 0000000000..c4d4816fee
--- /dev/null
+++ b/tests/app/routers/test_starter_model_is_installed.py
@@ -0,0 +1,29 @@
+"""A Qwen3 encoder starter counts as installed when any encoder of its size is.
+
+The Z-Image and FLUX.2 Klein starters depend on a Qwen3 encoder, and every such encoder of one size serves them
+alike. Recognising the size only by the source spellings BFL and Tongyi use (`qwen3_4b`, `Z-Image`) left out
+Comfy-Org's `qwen_3_4b_fp4_mixed`: installing "Z-Image Turbo (NVFP4)" beside an installed 4B encoder would queue a
+redundant 3.5GB download.
+"""
+
+from invokeai.app.api.routers.model_manager import get_is_installed
+from 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.taxonomy import Qwen3VariantType
+
+
+def _installed_encoder(variant: Qwen3VariantType) -> Qwen3Encoder_Checkpoint_Config:
+ return Qwen3Encoder_Checkpoint_Config.model_construct(
+ key="installed",
+ name=f"my {variant.value} encoder",
+ source=f"D:/models/{variant.value}.safetensors",
+ variant=variant,
+ )
+
+
+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)])
diff --git a/tests/backend/model_manager/load/test_qwen3_encoder_checkpoint_loader.py b/tests/backend/model_manager/load/test_qwen3_encoder_checkpoint_loader.py
new file mode 100644
index 0000000000..d9cbe80ede
--- /dev/null
+++ b/tests/backend/model_manager/load/test_qwen3_encoder_checkpoint_loader.py
@@ -0,0 +1,169 @@
+"""Loader-level test for single-file Qwen3 encoders in Comfy's fp4_mixed layout.
+
+Drives `Qwen3EncoderCheckpointLoader._load_from_singlefile` on a real, tiny safetensors file laid out like
+`Comfy-Org/z_image`'s `qwen_3_4b_fp4_mixed`: nvfp4 projections named by `comfy_quant` markers -- or, as another
+producer might write them, only in the `_quantization_metadata` header -- one scaled-fp8 projection, dense tensors
+for the rest. What it pins is order inside the loader: room is reserved before the scaled-fp8 fold widens anything;
+the nvfp4 layers leave the state dict before that fold, which would pair their block scales with the packed codes,
+and come back only after the blanket cast, which would widen them; and an nvfp4 `lm_head` is dropped rather than
+packed, since the loader ties `lm_head` to the embeddings. And that the returned model encodes exactly like a dense
+Qwen3 holding the same weights.
+"""
+
+import json
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+import torch
+from safetensors.torch import save_file
+from transformers import Qwen3Config, Qwen3ForCausalLM
+
+from invokeai.backend.model_manager.configs.qwen3_encoder import Qwen3Encoder_Checkpoint_Config
+from invokeai.backend.model_manager.load.model_loaders import z_image
+from invokeai.backend.model_manager.load.model_loaders.z_image import Qwen3EncoderCheckpointLoader
+from invokeai.backend.model_manager.taxonomy import Qwen3VariantType
+from invokeai.backend.quantization.nvfp4 import NVFP4Linear
+
+# Not a known Qwen3 size, so the loader reads the head counts off the projections at its fixed head_dim of 128:
+# a one-head model.
+HIDDEN = 128
+INTERMEDIATE = 256
+# A multiple of 128, so an nvfp4 `lm_head` over it is a valid block-scale grid.
+VOCAB = 128
+
+NVFP4_PROJECTIONS = {
+ "self_attn.q_proj": (HIDDEN, HIDDEN),
+ "self_attn.k_proj": (HIDDEN, HIDDEN),
+ "self_attn.o_proj": (HIDDEN, HIDDEN),
+ "mlp.gate_proj": (INTERMEDIATE, HIDDEN),
+ "mlp.up_proj": (INTERMEDIATE, HIDDEN),
+ "mlp.down_proj": (HIDDEN, INTERMEDIATE),
+}
+
+
+def _marker_blob(marker: dict) -> torch.Tensor:
+ return torch.frombuffer(bytearray(json.dumps(marker).encode("utf-8")), dtype=torch.uint8)
+
+
+def _nvfp4_layer(path: str, positive: torch.Tensor, evidence: str) -> dict[str, 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."""
+ rows, columns = positive.shape
+ codes = torch.where(positive, 2, 10).to(torch.uint8)
+ layer = {
+ f"{path}.weight": (codes[:, 0::2] << 4) | codes[:, 1::2],
+ f"{path}.weight_scale": torch.full((rows, columns // 16), 2.0).to(torch.float8_e4m3fn),
+ f"{path}.weight_scale_2": torch.tensor(0.25),
+ }
+ if evidence == "marker":
+ layer[f"{path}.comfy_quant"] = _marker_blob({"format": "nvfp4"})
+ return layer
+
+
+def _write_checkpoint(tmp_path: Path, evidence: str) -> tuple[Path, dict[str, torch.Tensor]]:
+ """Returns the file and the dense weights it has to load as."""
+ torch.manual_seed(0)
+ tensors: dict[str, torch.Tensor] = {}
+ dense: dict[str, torch.Tensor] = {}
+ nvfp4_paths = [f"model.layers.0.{name}" for name in NVFP4_PROJECTIONS] + ["lm_head"]
+ for path, shape in zip(nvfp4_paths, [*NVFP4_PROJECTIONS.values(), (VOCAB, HIDDEN)], strict=True):
+ positive = torch.randint(0, 2, shape, dtype=torch.bool)
+ tensors.update(_nvfp4_layer(path, positive, evidence))
+ if path != "lm_head":
+ dense[f"{path}.weight"] = torch.where(positive, 0.5, -0.5)
+
+ fp8_values = torch.randint(-8, 9, (HIDDEN, HIDDEN)).float()
+ tensors["model.layers.0.self_attn.v_proj.weight"] = fp8_values.to(torch.float8_e4m3fn)
+ tensors["model.layers.0.self_attn.v_proj.weight_scale"] = torch.tensor(0.5)
+ tensors["model.layers.0.self_attn.v_proj.comfy_quant"] = _marker_blob({"format": "float8_e4m3fn"})
+ dense["model.layers.0.self_attn.v_proj.weight"] = fp8_values * 0.5
+
+ for key, tensor in {
+ "model.embed_tokens.weight": torch.randn(VOCAB, HIDDEN),
+ "model.layers.0.input_layernorm.weight": torch.rand(HIDDEN) + 0.5,
+ "model.layers.0.post_attention_layernorm.weight": torch.rand(HIDDEN) + 0.5,
+ "model.layers.0.self_attn.q_norm.weight": torch.rand(128) + 0.5,
+ "model.layers.0.self_attn.k_norm.weight": torch.rand(128) + 0.5,
+ "model.norm.weight": torch.rand(HIDDEN) + 0.5,
+ }.items():
+ tensors[key] = tensor
+ dense[key] = tensor
+
+ checkpoint = tmp_path / "qwen_3_4b_fp4_mixed.safetensors"
+ header = {path: {"format": "nvfp4"} for path in nvfp4_paths}
+ metadata = {"_quantization_metadata": json.dumps({"layers": header})} if evidence == "header" else None
+ save_file(tensors, checkpoint, metadata=metadata)
+ return checkpoint, dense
+
+
+def _dense_reference(dense: dict[str, torch.Tensor]) -> Qwen3ForCausalLM:
+ """The same encoder as a plain Qwen3 holding the decoded weights, configured the way the loader does it."""
+ config = Qwen3Config(
+ vocab_size=VOCAB,
+ hidden_size=HIDDEN,
+ intermediate_size=INTERMEDIATE,
+ num_hidden_layers=1,
+ num_attention_heads=1,
+ num_key_value_heads=1,
+ head_dim=128,
+ max_position_embeddings=40960,
+ rms_norm_eps=1e-6,
+ tie_word_embeddings=True,
+ rope_theta=1000000.0,
+ use_sliding_window=False,
+ attention_bias=False,
+ attention_dropout=0.0,
+ )
+ model = Qwen3ForCausalLM(config)
+ model.load_state_dict(dense, strict=False)
+ model.tie_weights()
+ return model.eval()
+
+
[email protected]("evidence", ["marker", "header"])
+def test_an_fp4_mixed_encoder_loads_packed_and_encodes_like_its_dense_weights(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, evidence: str
+) -> None:
+ checkpoint, dense = _write_checkpoint(tmp_path, evidence)
+ monkeypatch.setattr(z_image.TorchDevice, "choose_torch_device", lambda: torch.device("cpu"))
+ monkeypatch.setattr(z_image.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: torch.float32)
+ loader = object.__new__(Qwen3EncoderCheckpointLoader)
+ loader._ram_cache = SimpleNamespace(make_room=MagicMock())
+ reserved_before_fold: list[bool] = []
+ fold = z_image._fold_comfy_scaled_weights
+
+ def recording_fold(sd: dict, dtype: torch.dtype) -> int:
+ reserved_before_fold.append(loader._ram_cache.make_room.called)
+ return fold(sd, dtype)
+
+ monkeypatch.setattr(z_image, "_fold_comfy_scaled_weights", recording_fold)
+ config = Qwen3Encoder_Checkpoint_Config.model_construct(path=str(checkpoint), variant=Qwen3VariantType.Qwen3_4B)
+
+ model = loader._load_from_singlefile(config)
+
+ layer = model.model.layers[0]
+ for name in NVFP4_PROJECTIONS:
+ module = layer.get_submodule(name)
+ assert isinstance(module, NVFP4Linear), name
+ # Still as stored: installed before the cast, the buffers would be widened.
+ assert module.weight.dtype is torch.uint8 and module.weight_scale.dtype is torch.uint8, name
+ assert type(layer.self_attn.v_proj) is torch.nn.Linear
+ assert type(model.lm_head) is torch.nn.Linear
+ assert model.lm_head.weight is model.model.embed_tokens.weight
+ assert reserved_before_fold == [True]
+
+ input_ids = torch.tensor([[1, 5, 7, 2, 30]])
+ with torch.no_grad():
+ encoded = model(input_ids=input_ids, output_hidden_states=True).hidden_states[-1]
+ expected = _dense_reference(dense)(input_ids=input_ids, output_hidden_states=True).hidden_states[-1]
+ assert torch.equal(encoded, expected)
+
+ # One reservation: the rest of the state dict at float32 plus the packed projections as stored. The dropped
+ # `lm_head` costs nothing, and the packed layers are not charged their decoded size.
+ packed_paths = {f"model.layers.0.{name}.weight" for name in NVFP4_PROJECTIONS}
+ rest = sum(tensor.nelement() * 4 for key, tensor in dense.items() if key not in packed_paths)
+ packed = sum(rows * columns // 2 + rows * columns // 16 + 4 for rows, columns in NVFP4_PROJECTIONS.values())
+ loader._ram_cache.make_room.assert_called_once()
+ (reserved,), _ = loader._ram_cache.make_room.call_args
+ assert rest + packed <= reserved < rest + packed + 1024