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.

fix(models): keep ComfyUI fp8_scaled Qwen3 and Qwen2.5-VL encoders packed (#10291)

Alexander Eichhorn920760997188
diff --git a/docs/src/content/docs/Users Guide/03.Models/02.model-families.mdx b/docs/src/content/docs/Users Guide/03.Models/02.model-families.mdx
index ddaa50fcf1..118f51ef84 100644
--- a/docs/src/content/docs/Users Guide/03.Models/02.model-families.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/02.model-families.mdx
@@ -50,7 +50,7 @@ InvokeAI recognizes the format from the file's contents, so you install them lik
- **int8** (`int8_convrot`, from ComfyUI repackages): the weights stay int8 in memory on every device, including Apple Silicon, and need no setting to turn on. Supported for FLUX.1, FLUX.2 Klein, FLUX.3, Z-Image, Anima, Krea-2, Qwen-Image, Qwen-Image-2.1, Ideogram 4, MiniMax H3, LTX-2, Wan 2.2 and the PiD decoders, and for the Qwen3 4B and 8B, Qwen3-VL, Qwen2.5-VL and LTX-2 Gemma encoders.
- **int4** (`convrot_w4a4` or `int4_tensorwise`, ComfyUI repackages that usually keep some layers int8): the weights stay packed in memory at half a byte each and are unpacked per layer, on every device. This saves memory, not time: InvokeAI unpacks the weights for every step rather than running 4-bit matrix kernels, and 4-bit weights keep less detail than int8. Supported for the Krea-2 transformer.
- **nvfp4** (4-bit, in ComfyUI's checkpoint format, such as Comfy-Org's builds; other nvfp4 exports such as AWQ are refused): the weights stay packed in memory and are unpacked per layer, so no special GPU is needed. Supported for the FLUX.3, Z-Image, Krea-2, Qwen-Image and LTX-2 transformers and for the Qwen3, Qwen3-VL 4B/8B, Qwen2.5-VL and FLUX.2 Mistral encoders; for FLUX.3 also Black Forest Labs' own nvfp4 build, in NVIDIA ModelOpt's layout. The Ideogram 4 and Qwen-Image-2.1 nvfp4 transformer files are refused at install.
-- **fp8** (plain or `fp8_scaled`): InvokeAI keeps the weights in fp8 when [FP8 Storage](/configuration/optimization/fp8-storage/) is on, which installation does for you, or when `fp8_compute` is enabled.
+- **fp8** (plain or `fp8_scaled`): a transformer keeps its weights in fp8 when [FP8 Storage](/configuration/optimization/fp8-storage/) is on, which installation does for you, or when `fp8_compute` is enabled. The single-file T5, Qwen3, Qwen3-VL, Qwen2.5-VL and FLUX.2 Mistral text encoders have neither setting: they keep their fp8 layers on their own on a GPU that can store fp8, and are widened elsewhere.
- **MXFP8** (fp8 with one scale per block of 32 weights): loaded by unpacking to BF16. Turn FP8 Storage off for these, except on Wan 2.2; see the [FP8 Storage caution](/configuration/optimization/fp8-storage/).
Text encoders for T5, Qwen-Image, Z-Image, Krea-2, FLUX.3, Ideogram 4, Qwen-Image-2.1 and MOSS-Image bring their tokenizer and configuration with InvokeAI, so single-file and GGUF encoders load without network access.
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.mdx
index 408600fee4..d58619d1ba 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
@@ -101,6 +101,16 @@ slowly where the CPU has no native bf16 support. That takes about 19 GB of RAM f
if the RAM cache (`max_cache_ram_gb`) is smaller than that, raise it or use a GGUF T5. A GGUF T5 keeps its quantized
weights packed; only its dequantized embeddings and the per-layer dequantization transients are float32.
+Single-file Qwen3 and Qwen2.5-VL (`qwen_2.5_vl_7b_fp8_scaled`) encoders in ComfyUI's scaled fp8 layout also keep their
+Linear 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
+`fp8_compute` says. Token embeddings are always widened to the compute dtype. On a CPU, and for a Qwen3 encoder set to
+run on the CPU, everything is widened to the dtype the encoder computes in. An MXFP8 encoder file that names its layers
+in its markers or header loads too, decoded to bf16; MX scales that nothing names are refused, as is any scaled fp8 file
+whose scales use a spelling InvokeAI does not read (such as `weight_scale_inv`), with a message rather than a load of
+unscaled weights.
+
The single-file CLIP builds are ComfyUI's `clip_l` and `clip_g`, as used by FLUX.1 and SD 3. SD and SDXL take their
CLIP encoders from the main model only, so a separate CLIP file does not change them. A CLIP-G file needs its
`text_projection` for SD 3 and is refused without it, as are extended-context CLIP-L variants such as Long-CLIP.
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-2.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-2.mdx
index 57bec93cb4..0b60eee05c 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-2.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-2.mdx
@@ -98,7 +98,8 @@ FLUX.2 pipeline automatically, so you don't need standalone ones:
Standalone Qwen3 encoders are available as starter models too: *FLUX.2 Klein Qwen3 4B Encoder* (~8 GB) and
its *FP4 mixed* build (~3.6 GB download), and *FLUX.2 Klein Qwen3 8B Encoder* (~16 GB) with *FP4 mixed*
(~6.3 GB download) and *int8* (~9.4 GB) builds. A 4B encoder only works with Klein 4B models, an 8B encoder
-only with Klein 9B.
+only with Klein 9B. A scaled-fp8 Qwen3 encoder file stays fp8 in memory on a GPU that can hold it, about 4.4 GB for
+4B and about 8.2 GB for 8B, instead of being widened to bf16 (about 8.0 GB and 15.1 GB).
When you install an FP8 checkpoint, FP8 Storage is switched on for it automatically, which keeps the file's
fp8 weights instead of expanding them.
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image.mdx
index aa7564aff1..3b5f2f67bb 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
@@ -41,9 +41,9 @@ consumer GPU, use a **GGUF** or **fp8** transformer together with the standalone
| fp8 (Qwen Image 2512) | ~20.4 GB |
| fp8 mixed (Qwen Image Edit 2511) | ~20.5 GB |
-The Qwen2.5-VL encoder is loaded in addition to the transformer (~7 GB for the fp8 build). If your GPU
+The Qwen2.5-VL encoder is loaded in addition to the transformer (~9.4 GB for the fp8 build). If your GPU
cannot hold both, enable [Low-VRAM mode](/configuration/optimization/low-vram-mode/). Single-file
-checkpoints that ship fp8 weights are kept in fp8 with
+transformer checkpoints that ship fp8 weights are kept in fp8 with
[FP8 Storage](/configuration/optimization/fp8-storage/), which is switched on for them when they are installed.
ComfyUI's `int8_tensorwise` builds, rotated (`int8_convrot`) or not, load for the transformer and for the Qwen2.5-VL
@@ -73,7 +73,7 @@ Qwen Image needs three components:
includes everything.
- **GGUF** (from `unsloth/Qwen-Image-2512-GGUF` and `unsloth/Qwen-Image-Edit-2511-GGUF`): the file
contains only the transformer. The GGUF starter models install the **Qwen Image VAE** (~250 MB) and
- the **Qwen2.5-VL Encoder (fp8 scaled)** (~7 GB) as dependencies, so you never need the full pipeline.
+ the **Qwen2.5-VL Encoder (fp8 scaled)** (~9.4 GB) as dependencies, so you never need the full pipeline.
- **Single-file `.safetensors`** checkpoints (bf16/fp16, and ComfyUI-style plain fp8, fp8-scaled or nvfp4
builds) can be installed by path or URL; like GGUF, they need a standalone VAE and encoder. The two fp8
starter models (from `Comfy-Org/Qwen-Image` and `Comfy-Org/Qwen-Image-Edit`) install the same VAE and
@@ -82,10 +82,11 @@ Qwen Image needs three components:
keep part of it in RAM. The 2512 file is plain fp8 without scales: loading it briefly needs about 41 GB of
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** (~7 GB, the one the
+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
only) and **Diffusers** (~16 GB, full precision). The single-file and GGUF encoders ship with their
-tokenizer and config inside InvokeAI.
+tokenizer 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.
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 cannot
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/z-image.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/z-image.mdx
index ff74fecc19..208be7ef25 100644
--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/z-image.mdx
+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/z-image.mdx
@@ -64,7 +64,8 @@ The starter models:
| Z-Image Turbo (SDNQ uint4 + SVD) | SDNQ Diffusers pipeline | ~5 GB | nothing, everything is bundled |
A full-precision **Z-Image Qwen3 Text Encoder** (~8 GB) and its community **int8** build (~4.4 GB download,
-about 4.4 GB once loaded) are also available as separate starters.
+about 4.4 GB once loaded) are also available as separate starters. A scaled-fp8 Qwen3 4B encoder file
+also stays fp8 in memory on a GPU that can hold it, about 4.4 GB instead of about 8.0 GB.
The NVFP4 build keeps its quantized layers packed in memory and decodes them on the fly, so it needs about
a third of the full-precision transformer's memory. The int8 build keeps its int8 layers as well, about 6.2 GB
diff --git a/docs/src/content/docs/configuration/Optimization/fp8-storage.mdx b/docs/src/content/docs/configuration/Optimization/fp8-storage.mdx
index 29ace3e58b..9f751a6cdf 100644
--- a/docs/src/content/docs/configuration/Optimization/fp8-storage.mdx
+++ b/docs/src/content/docs/configuration/Optimization/fp8-storage.mdx
@@ -57,7 +57,7 @@ If your model is quantized, its full-precision variant gets the full effect of F
| Wan (checkpoint and Diffusers) | Yes |
| ControlNet (SD1, SD2, SDXL), T2I-Adapter | Yes |
| VAE | No: visible decode-quality regression |
-| Text encoders, tokenizers | No: small models, and FP8 rounding costs text quality. The FLUX.2 Mistral encoder keeps its scaled fp8 weights packed on any GPU that passes the FP8 test, with no setting. |
+| Text encoders, tokenizers | No: small models, and FP8 rounding costs text quality. Scaled fp8 single-file encoders (T5-XXL, Qwen3, Qwen3-VL, Qwen2.5-VL, and the FLUX.2 Mistral encoder) keep their fp8 Linear weights packed, with their scales, on any GPU that passes the FP8 test, with no setting. |
| Anima ControlNet-LLLite | No: the adapter is only tens of MB |
| FLUX.1, FLUX.2, Z-Image and Qwen-Image ControlNets | No: not implemented yet |
| MiniMax H3 | No: not implemented yet |
diff --git a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py b/invokeai/backend/model_manager/load/model_loaders/qwen_image.py
index 927efb33e7..9aebe71f48 100644
--- a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/qwen_image.py
@@ -16,12 +16,12 @@ from invokeai.backend.model_manager.configs.qwen_vl_encoder import (
QwenVLEncoder_Diffusers_Config,
QwenVLEncoder_GGUF_Config,
)
-from invokeai.backend.model_manager.load.load_default import ModelLoader, _model_declared_skip_patterns
-from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistry
-from invokeai.backend.model_manager.load.model_loaders.comfyui_state_dict_utils import (
- _dequantize_comfyui_fp8,
- _strip_quantization_metadata,
+from invokeai.backend.model_manager.load.load_default import (
+ ModelLoader,
+ _device_supports_fp8_storage,
+ _model_declared_skip_patterns,
)
+from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistry
from invokeai.backend.model_manager.load.model_loaders.generic_diffusers import GenericDiffusersLoader
from invokeai.backend.model_manager.qwen_image_controlnet_keys import is_qwen_image_instantx_controlnet
from invokeai.backend.model_manager.taxonomy import (
@@ -35,6 +35,8 @@ from invokeai.backend.model_manager.taxonomy import (
from invokeai.backend.model_manager.util.llamacpp_keys import convert_llamacpp_decoder_keys
from invokeai.backend.model_manager.util.qwen3_vl import drop_qwen3vl_visual_tower
from invokeai.backend.quantization.fp8_scaled import (
+ FP8_WEIGHT_DTYPES,
+ Fp8ScaledLayer,
attach_fp8_scales,
cast_state_dict,
dequantize_fp8_scaled,
@@ -470,6 +472,30 @@ class QwenVLEncoderCheckpointLoader(ModelLoader):
`invokeai.backend.qwen2_5_vl`, so this encoder loads with no network access.
"""
+ def _storage_format(self, config: AnyModelConfig) -> tuple[bool, torch.dtype]:
+ """Whether float8 Linear weights stay float8, and the compute dtype everything else is held in.
+
+ Decided once per loader (a fresh one serves each load): the cache key and the built weights must agree, and the
+ capability probes can flip between the key computation and the build under the load lock. Float8 follows the
+ execution device, because a CPU-only encoder reads its weights on the CPU whatever the session's device is.
+ """
+ device = self._get_execution_device(config, SubModelType.TextEncoder) or self._torch_device
+ decisions = self.__dict__.setdefault("_storage_format_decisions", {})
+ if device not in decisions:
+ keep_fp8 = should_keep_fp8_weights(device) or _device_supports_fp8_storage(device, self._logger)
+ decisions[device] = (keep_fp8, TorchDevice.choose_bfloat16_safe_dtype(self._torch_device))
+ return decisions[device]
+
+ def _cache_key_variant(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> str:
+ # Device caches share one canonical CPU copy per key: a device must not adopt float8 it cannot hold, nor folded
+ # weights that throw away a capable device's saving. The visual tower is part of the text encoder's module, so
+ # it is covered too. Keyed by the device's decision, not the file's contents, which would take a header read
+ # on every cache lookup.
+ if submodel_type == SubModelType.TextEncoder:
+ keep_fp8, dtype = self._storage_format(config)
+ return f"{'fp8-' if keep_fp8 else ''}{str(dtype).removeprefix('torch.')}"
+ return ""
+
def _load_model(
self,
config: AnyModelConfig,
@@ -499,20 +525,19 @@ class QwenVLEncoderCheckpointLoader(ModelLoader):
model_path = Path(config.path)
- target_device = TorchDevice.choose_torch_device()
- model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
+ device_keeps_fp8, model_dtype = self._storage_format(config)
sd = load_file(str(model_path))
# 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.
+ # 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 fold below multiplies every
- # `.weight_scale` into its weight, which for a rotated layer leaves a weight of the right shape and no
- # relation to the one stored. The int8 layers are claimed first and stay int8. Ahead of the reservation, so a
+ # ComfyUI 'int8_tensorwise' (+convrot) shares the fp8 key layout, and the fp8 extraction below treats
+ # every `.weight_scale` as an fp8 scale, which for a rotated layer would leave a weight of the right shape and
+ # no relation to the one stored. The int8 layers are claimed first and stay int8. Ahead of the reservation, so a
# load that cannot finish does not evict the cache for room it will never use. The refusal is outside the
# branch on purpose: an int8 weight with no marker is refused in every case.
int8_markers = extract_int8_convrot_markers(sd, header_layers=header_layers)
@@ -539,6 +564,8 @@ class QwenVLEncoderCheckpointLoader(ModelLoader):
# layout transformers expects. See `_remap_qwen_vl_checkpoint_keys` for details.
sd = _remap_qwen_vl_checkpoint_keys(sd)
+ fp8_layers: dict[str, Fp8ScaledLayer] = {}
+
if int8_markers:
# The dense tensors are cast inside, and the fp32 scales are left alone: a blanket cast would ruin them.
quantized = install_int8_convrot_layers(
@@ -556,31 +583,40 @@ class QwenVLEncoderCheckpointLoader(ModelLoader):
"(int8_tensorwise checkpoint, dequantized per forward)"
)
else:
- # 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.
+ # ComfyUI 'scaled fp8': an fp8 weight plus its `weight_scale`, named in the header or by a per-layer marker.
+ # Extracted after the key remap so each scale travels with its weight and the recovered paths match the
+ # model's modules. Pops every scale and marker, and refuses an unparsed scale spelling beside an fp8
+ # weight rather than casting it unscaled.
+ fp8_layers = extract_fp8_scaled_layers(
+ sd, layer_hints={**extract_comfy_quant_hints(sd), **_remap_qwen_vl_checkpoint_keys(header_layers)}
+ )
+ # Text encoders have no FP8 Storage setting, so the device decides (`_storage_format`), as for the other
+ # encoders: float8 where the device can hold it or multiply in it, folded into the compute dtype elsewhere.
+ source_is_fp8 = bool(fp8_layers) or any(
+ getattr(tensor, "dtype", None) in FP8_WEIGHT_DTYPES for tensor in sd.values()
+ )
+ keep_fp8 = source_is_fp8 and device_keeps_fp8
+
+ # One reservation, before the fold or the split widens a single weight: `make_room` makes that much room
+ # rather than adding to an earlier one.
reserve_for_load(
self._ram_cache.make_room,
sd,
model_dtype,
- keep_fp8=False,
+ keep_fp8=keep_fp8,
model=model,
skip_patterns=skip_patterns,
- fp8_layers={},
+ fp8_layers=fp8_layers,
nvfp4_payloads=nvfp4_payloads,
)
-
- # 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, "Qwen2.5-VL encoder checkpoint")
- if dequantized_count > 0:
- logger.info(f"Dequantized {dequantized_count} ComfyUI-quantized weights")
- _strip_quantization_metadata(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 fp8_layers and not keep_fp8:
+ dequantize_fp8_scaled(sd, fp8_layers, model_dtype)
+ logger.info(f"Qwen VL encoder: folded {len(fp8_layers)} scaled fp8 layer(s) into {model_dtype}.")
+ fp8_layers = {}
+ # Layers the cast would widen anyway (embeddings, block-wise scales) are folded here with their scale
+ # applied, so the cast never drops one.
+ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)
+ cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)
if nvfp4_payloads:
packed = install_nvfp4_layers(model, sd, nvfp4_payloads, model_dtype, skip_patterns)
@@ -623,6 +659,20 @@ class QwenVLEncoderCheckpointLoader(ModelLoader):
if meta_params:
raise RuntimeError(f"Failed to load all parameters from checkpoint. Meta tensors remain: {meta_params[:5]}")
+ if fp8_layers:
+ # The scales go on the modules that kept their float8 weights; `CustomLinear` applies them per forward.
+ attached = attach_fp8_scales(model, fp8_layers)
+ warn_on_unattached_scales(logger, "Qwen VL encoder", attached, fp8_layers)
+ # Storage only, as for T5: the fp8 matmul quantizes the activations too, and one encoder pass per prompt gains
+ # nothing from it while outliers in the activations cost conditioning accuracy. Raw fp8 weights included.
+ kept = 0
+ for module in model.modules():
+ if isinstance(module, torch.nn.Linear) and module.weight.dtype in FP8_WEIGHT_DTYPES:
+ module._fp8_full_precision_matmul = True
+ kept += 1
+ if kept:
+ logger.info(f"Qwen VL encoder: kept {kept} Linear weight(s) in float8, dequantized per forward")
+
model.eval()
return model
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 eadd672b38..8ab8c97b19 100644
--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py
@@ -27,6 +27,7 @@ from invokeai.backend.model_manager.configs.qwen3_encoder import (
from invokeai.backend.model_manager.load.fp8_capability import Unimplemented
from invokeai.backend.model_manager.load.load_default import (
ModelLoader,
+ _device_supports_fp8_storage,
_model_declared_skip_patterns,
resolve_submodel_path,
)
@@ -45,20 +46,19 @@ from invokeai.backend.model_manager.util.llamacpp_keys import (
is_llamacpp_decoder_state_dict,
)
from invokeai.backend.quantization.fp8_scaled import (
+ FP8_WEIGHT_DTYPES,
QKV_SPLIT_SIDECHANNEL_SUFFIXES,
+ Fp8ScaledLayer,
attach_fp8_scales,
cast_state_dict,
dequantize_fp8_scaled,
- expand_weight_scale,
extract_comfy_quant_hints,
extract_fp8_scaled_layers,
full_precision_hints_respected,
- is_scale_metadata_key,
- iter_weight_scale_pairs,
parse_quantization_metadata,
read_safetensors_metadata,
reject_quantized_side_channel,
- reject_undecoded_mx_scale,
+ should_keep_fp8_weights,
split_fp8_scaled_layers,
split_qkv_sidechannel,
strip_layer_path_prefix,
@@ -1042,43 +1042,37 @@ class ZImageFunControlNetLoader(ModelLoader):
return control
-def _fold_comfy_scaled_weights(sd: dict[str, Any], dtype: torch.dtype) -> int:
- """Fold every ComfyUI-style ``weight_scale`` into its weight, in place. Returns how many.
-
- ComfyUI stores quantized weights with accompanying scale factors (``layer.weight`` quantized,
- ``layer.weight_scale`` the factor, both spellings), so ``dequantized = weight * weight_scale``.
- See https://github.com/Comfy-Org/ComfyUI/blob/master/QUANTIZATION.md.
-
- A named function rather than a loop inside the loader so the scale-axis contract below is
- reachable from a test. `expand_weight_scale` handles all three layouts (per-tensor,
- per-output-channel, block-wise); the local loop this replaced left a 1-D per-channel scale
- untouched, and ``(out, in) * (out,)`` then broadcasts on the *last* axis — scaling input
- channels instead of output channels, which is a shape error on a non-square weight and a
- silently wrong weight on a square one.
[email protected](base=BaseModelType.Any, type=ModelType.Qwen3Encoder, format=ModelFormat.Checkpoint)
+class Qwen3EncoderCheckpointLoader(ModelLoader):
+ """Class to load single-file Qwen3 Encoder models for Z-Image (safetensors format).
- The multiply runs in float32 for precision but each result is stored as ``dtype`` immediately,
- so the whole model is never materialized in float32: holding every dequantized weight at fp32
- until the caller's later cast quadruples the per-parameter cost (4 bytes vs 1 on disk) and
- dominates the cold-load RAM peak — enough to swap a 32 GB machine. Same fix as in the FLUX.2
- and Krea-2 loaders.
+ ComfyUI 'scaled fp8' Linear layers stay float8 with the file's own scale where the device can hold float8, and are
+ dequantized per forward, never multiplied in fp8. Elsewhere, and for a CPU-only encoder, they are folded into the
+ compute dtype. Embeddings are always folded; nvfp4 and int8 convrot layers stay packed.
"""
- folded = 0
- for weight_key, scale_key in list(iter_weight_scale_pairs(sd)):
- # Before the cast: `.float()` on an E8M0 grid turns the exponent bytes into ordinary numbers
- # and loses the only evidence of what they were.
- reject_undecoded_mx_scale(weight_key[: -len(".weight")], sd[scale_key])
- # Float8 needs `.float()`; torch has no direct type promotion for it.
- weight_float = sd[weight_key].float()
- scale = expand_weight_scale(weight_float, sd[scale_key].float(), weight_key)
- sd[weight_key] = (weight_float * scale).to(dtype)
- del weight_float
- folded += 1
- return folded
+ def _storage_format(self, config: AnyModelConfig) -> tuple[bool, torch.dtype]:
+ """Whether float8 Linear weights stay float8, and the compute dtype everything else is held in.
[email protected](base=BaseModelType.Any, type=ModelType.Qwen3Encoder, format=ModelFormat.Checkpoint)
-class Qwen3EncoderCheckpointLoader(ModelLoader):
- """Class to load single-file Qwen3 Encoder models for Z-Image (safetensors format)."""
+ Decided once per loader (a fresh one serves each load): the cache key and the built weights must agree, and the
+ capability probes can flip between the key computation and the build under the load lock. Float8 follows the
+ execution device, because a CPU-only encoder reads its weights on the CPU whatever the session's device is.
+ """
+ device = self._get_execution_device(config, SubModelType.TextEncoder) or self._torch_device
+ decisions = self.__dict__.setdefault("_storage_format_decisions", {})
+ if device not in decisions:
+ keep_fp8 = should_keep_fp8_weights(device) or _device_supports_fp8_storage(device, self._logger)
+ decisions[device] = (keep_fp8, TorchDevice.choose_bfloat16_safe_dtype(self._torch_device))
+ return decisions[device]
+
+ def _cache_key_variant(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> str:
+ # Device caches share one canonical CPU copy per key: a device must not adopt float8 it cannot hold, nor folded
+ # weights that throw away a capable device's saving. Keyed by the device's decision, not the file's contents,
+ # which would take a header read on every cache lookup.
+ if submodel_type == SubModelType.TextEncoder:
+ keep_fp8, dtype = self._storage_format(config)
+ return f"{'fp8-' if keep_fp8 else ''}{str(dtype).removeprefix('torch.')}"
+ return ""
def _load_model(
self,
@@ -1127,9 +1121,7 @@ class Qwen3EncoderCheckpointLoader(ModelLoader):
)
model_path = Path(config.path)
- # Determine safe dtype based on target device capabilities
- target_device = TorchDevice.choose_torch_device()
- model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
+ device_keeps_fp8, model_dtype = self._storage_format(config)
# Load the state dict from safetensors file
sd = load_file(model_path)
@@ -1137,8 +1129,8 @@ class Qwen3EncoderCheckpointLoader(ModelLoader):
# Three ComfyUI side channels reach this loader and a file carries one of them. int8 is
# decided first because it is the one the others cannot be told apart from by structure: an
- # int8 layer ships a `.weight_scale` too, so the scaled-fp8 fold further down would pair
- # every int8 code tensor with its scale and widen it, and the blanket cast after that would
+ # int8 layer ships a `.weight_scale` too, so the scaled-fp8 extraction further down would pair
+ # every int8 code tensor with its scale and drop or fold it as fp8, and the cast after that would
# turn what survived into bf16 integers. Neither raises.
int8_markers = extract_int8_convrot_markers(sd)
@@ -1157,11 +1149,10 @@ class Qwen3EncoderCheckpointLoader(ModelLoader):
sd.pop(f"lm_head.{suffix}", None)
# 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))
- )
+ # anything below reads the side channel: the fp8 extraction pops every `weight_scale`, nvfp4's block
+ # scales included, and the cast further down would widen the packed codes.
+ header_layers = parse_quantization_metadata(read_safetensors_metadata(model_path, logger))
+ nvfp4_payloads = pop_nvfp4_layers(sd, header_layers=header_layers)
# `lm_head` is tied to the embeddings below, which replaces the weight a packed module would hold.
nvfp4_payloads.pop("lm_head", None)
@@ -1276,13 +1267,14 @@ class Qwen3EncoderCheckpointLoader(ModelLoader):
model = Qwen3ForCausalLM(qwen_config)
skip_patterns = _model_declared_skip_patterns(model)
- nvfp4_bytes = predict_nvfp4_install_size(model, nvfp4_payloads, model_dtype, skip_patterns)
+ fp8_layers: dict[str, Fp8ScaledLayer] = {}
if int8_markers:
# The projections stay int8-resident, which is the whole point of the build: 8.8 GiB on
# disk stays 8.8 GiB, against the 15.3 GiB the bf16 release occupies. The reservation,
# the split and the cast all have to agree on which layers those are, which is what the
# shared install is for.
+ nvfp4_bytes = predict_nvfp4_install_size(model, nvfp4_payloads, model_dtype, skip_patterns)
kept = install_int8_convrot_layers(
model,
sd,
@@ -1295,43 +1287,40 @@ class Qwen3EncoderCheckpointLoader(ModelLoader):
)
logger.info(f"Kept {len(kept)} of {len(int8_markers)} layer(s) in int8 (dequantized per forward)")
else:
- # 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.
- # The excluded scale keys are still in `sd` and still resident, so this sum is short by
- # them -- bounded, not open-ended: `_fold_comfy_scaled_weights` refuses an MXFP8 grid by
- # name before folding, so the residue here is per-tensor and per-channel float32 scales,
- # kilobytes on this encoder. That is why this seam keeps its own sum rather than
- # `reserve_for_load`, which sizes a dict the side channel has been *popped* out of.
- new_sd_size = sum(
- tensor.nelement() * model_dtype.itemsize for key, tensor in sd.items() if not is_scale_metadata_key(key)
+ # Pops every scale and marker, so what is left loads into a model that knows no fp8. An unparsed scale
+ # spelling beside an fp8 weight is refused here rather than cast unscaled.
+ fp8_layers = extract_fp8_scaled_layers(sd, layer_hints={**extract_comfy_quant_hints(sd), **header_layers})
+ # `lm_head` is tied to the embeddings below, which replaces whatever it was loaded with.
+ fp8_layers.pop("lm_head", None)
+ sd.pop("lm_head.weight", None)
+
+ # Text encoders have no FP8 Storage setting, so the device decides (`_storage_format`), as for the other
+ # encoders: float8 where the device can hold it or multiply in it, folded into the compute dtype elsewhere.
+ source_is_fp8 = bool(fp8_layers) or any(
+ getattr(tensor, "dtype", None) in FP8_WEIGHT_DTYPES for tensor in sd.values()
+ )
+ keep_fp8 = source_is_fp8 and device_keeps_fp8
+
+ # One reservation, before the fold or the split widens a weight: `make_room` makes that much room rather
+ # than adding to an earlier one.
+ reserve_for_load(
+ self._ram_cache.make_room,
+ sd,
+ model_dtype,
+ keep_fp8=keep_fp8,
+ model=model,
+ skip_patterns=skip_patterns,
+ fp8_layers=fp8_layers,
+ nvfp4_payloads=nvfp4_payloads,
)
- self._ram_cache.make_room(new_sd_size + nvfp4_bytes)
-
- # 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")
-
- # Convert to target dtype
- for k in sd.keys():
- sd[k] = sd[k].to(model_dtype)
+ if fp8_layers and not keep_fp8:
+ dequantize_fp8_scaled(sd, fp8_layers, model_dtype)
+ logger.info(f"Qwen3 encoder: folded {len(fp8_layers)} scaled fp8 layer(s) into {model_dtype}.")
+ fp8_layers = {}
+ # Layers the cast would widen anyway (embeddings, block-wise scales) are folded here with their scale
+ # applied, so the cast never drops one.
+ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)
+ cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)
logger.info(f"Loaded state dict with {len(sd)} keys (originally {original_key_count})")
@@ -1380,6 +1369,20 @@ class Qwen3EncoderCheckpointLoader(ModelLoader):
# For other buffers, log warning
logger.warning(f"Re-initializing unknown meta buffer: {name}")
+ if fp8_layers:
+ # The scales go on the modules that kept their float8 weights; `CustomLinear` applies them per forward.
+ attached = attach_fp8_scales(model, fp8_layers)
+ warn_on_unattached_scales(logger, "Qwen3 encoder", attached, fp8_layers)
+ # Storage only, as for T5: the fp8 matmul quantizes the activations too, and one encoder pass per prompt gains
+ # nothing from it while outliers in the activations cost conditioning accuracy. Raw fp8 weights included.
+ kept = 0
+ for module in model.modules():
+ if isinstance(module, torch.nn.Linear) and module.weight.dtype in FP8_WEIGHT_DTYPES:
+ module._fp8_full_precision_matmul = True
+ kept += 1
+ if kept:
+ logger.info(f"Qwen3 encoder: kept {kept} Linear weight(s) in float8, dequantized per forward")
+
return model
diff --git a/invokeai/backend/model_manager/starter_models/common.py b/invokeai/backend/model_manager/starter_models/common.py
index d946d1d6fb..d08322ea52 100644
--- a/invokeai/backend/model_manager/starter_models/common.py
+++ b/invokeai/backend/model_manager/starter_models/common.py
@@ -166,7 +166,7 @@ qwen_vl_encoder_fp8 = StarterModel(
base=BaseModelType.Any,
source="https://huggingface.co/Comfy-Org/Qwen-Image_ComfyUI/resolve/main/split_files/text_encoders/qwen_2.5_vl_7b_fp8_scaled.safetensors",
description="ComfyUI's single-file FP8-scaled Qwen2.5-VL 7B encoder. Bundles the language model and "
- "visual tower; its tokenizer and config ship with InvokeAI. (~7GB)",
+ "visual tower; its tokenizer and config ship with InvokeAI. (~9.4GB)",
type=ModelType.QwenVLEncoder,
format=ModelFormat.Checkpoint,
)
diff --git a/invokeai/backend/quantization/nvfp4.py b/invokeai/backend/quantization/nvfp4.py
index 04f40aeb11..aca8bf0f94 100644
--- a/invokeai/backend/quantization/nvfp4.py
+++ b/invokeai/backend/quantization/nvfp4.py
@@ -302,9 +302,7 @@ def reject_nvfp4_layers_a_plain_fold_cannot_decode(sd: Mapping[str, Any], what:
"""Refuse an nvfp4 layer to a fold that only multiplies a scale into a weight.
**Wan** (`wan.py:511`) is the seam this exists for: it reads scaled fp8 and never calls
- :func:`pop_nvfp4_layers`. The other caller of the shared fold, the Qwen2.5-VL encoder, *does*
- pop first (`qwen_image.py:473`, forty-odd lines before its fold) and ships the packed layers, so
- the guard is unreachable there — do not read it as evidence that encoder lacks nvfp4 support.
+ :func:`pop_nvfp4_layers`.
The fold has no dtype gate, by design, so it takes the layer: the block-scale grid carries one
entry per 16 logical elements and the weight packs two 4-bit codes per byte, so eight packed
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
index 64d30d43e2..33c6f097ec 100644
--- a/tests/backend/model_manager/load/test_qwen3_encoder_checkpoint_loader.py
+++ b/tests/backend/model_manager/load/test_qwen3_encoder_checkpoint_loader.py
@@ -127,14 +127,15 @@ def test_an_fp4_mixed_encoder_loads_packed_and_encodes_like_its_dense_weights(
monkeypatch.setattr(z_image.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: torch.float32)
loader = object.__new__(Qwen3EncoderCheckpointLoader)
loader._ram_cache = SimpleNamespace(make_room=MagicMock())
+ loader._torch_device, loader._logger = torch.device("cpu"), MagicMock()
reserved_before_fold: list[bool] = []
- fold = z_image._fold_comfy_scaled_weights
+ fold = z_image.dequantize_fp8_scaled
- def recording_fold(sd: dict, dtype: torch.dtype) -> int:
+ def recording_fold(*args, **kwargs):
reserved_before_fold.append(loader._ram_cache.make_room.called)
- return fold(sd, dtype)
+ return fold(*args, **kwargs)
- monkeypatch.setattr(z_image, "_fold_comfy_scaled_weights", recording_fold)
+ monkeypatch.setattr(z_image, "dequantize_fp8_scaled", recording_fold)
config = Qwen3Encoder_Checkpoint_Config.model_construct(path=str(checkpoint), variant=Qwen3VariantType.Qwen3_4B)
model = loader._load_from_singlefile(config)
@@ -215,11 +216,12 @@ def test_an_int8_convrot_encoder_stays_int8_resident_and_encodes_like_its_dense_
monkeypatch.setattr(z_image.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: torch.float32)
loader = object.__new__(Qwen3EncoderCheckpointLoader)
loader._ram_cache = SimpleNamespace(make_room=MagicMock())
+ loader._torch_device, loader._logger = torch.device("cpu"), MagicMock()
def refuse(*_args, **_kwargs) -> int:
- raise AssertionError("the scaled-fp8 fold must not see an int8 checkpoint")
+ raise AssertionError("the scaled-fp8 extraction must not see an int8 checkpoint")
- monkeypatch.setattr(z_image, "_fold_comfy_scaled_weights", refuse)
+ monkeypatch.setattr(z_image, "extract_fp8_scaled_layers", refuse)
config = Qwen3Encoder_Checkpoint_Config.model_construct(path=str(checkpoint), variant=Qwen3VariantType.Qwen3_8B)
model = loader._load_from_singlefile(config)
@@ -276,6 +278,7 @@ def test_an_nvfp4_layer_missing_its_global_scale_is_refused_before_the_cache_is_
monkeypatch.setattr(z_image.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: torch.float32)
loader = object.__new__(Qwen3EncoderCheckpointLoader)
loader._ram_cache = SimpleNamespace(make_room=MagicMock())
+ loader._torch_device, loader._logger = torch.device("cpu"), MagicMock()
config = Qwen3Encoder_Checkpoint_Config.model_construct(path=str(checkpoint), variant=Qwen3VariantType.Qwen3_4B)
with pytest.raises(ValueError, match="with a weight_scale but no weight_scale_2"):
diff --git a/tests/backend/model_manager/load/test_qwen3_encoder_scaled_fp8.py b/tests/backend/model_manager/load/test_qwen3_encoder_scaled_fp8.py
new file mode 100644
index 0000000000..5d8c89c444
--- /dev/null
+++ b/tests/backend/model_manager/load/test_qwen3_encoder_scaled_fp8.py
@@ -0,0 +1,447 @@
+"""Single-file Qwen3 encoders (Z-Image, FLUX.2 Klein, Anima) in ComfyUI's scaled-fp8 layout.
+
+A tiny one-layer Qwen3 stands in for the 4B/8B encoders: the loader reads the architecture from tensor shapes, so the
+same code builds both. The file is written the way ComfyUI writes `qwen_3_*_fp8_scaled`: every projection in float8
+beside its `weight_scale` (a scalar for some, one value per output row for others), plus a scaled token table and LM
+head, and dense norms.
+
+What these pin is the storage decision and its consequences: on a device that can hold or multiply float8 the
+projections stay float8 with the file's own scale on their module and encode like the weights the file decodes to; the
+token table (not a Linear) is always folded; elsewhere everything is folded exactly as it decodes. Forwards run in
+float32: CPU bf16 matmuls fault on part of the hosted Windows fleet.
+"""
+
+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_cache.torch_module_autocast.custom_modules import custom_linear
+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (
+ apply_custom_layers_to_model,
+)
+from invokeai.backend.model_manager.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 BaseModelType, ModelType, Qwen3VariantType, SubModelType
+from invokeai.backend.quantization.block_scale_tiles import block_scale_grid
+from invokeai.backend.util.logging import InvokeAILogger
+from tests.fixtures.quantized_payloads import comfy_quant_marker
+
+FP8 = torch.float8_e4m3fn
+HIDDEN = 128
+INTERMEDIATE = 256
+VOCAB = 128
+LAYER = "model.layers.0"
+
+# (shape, whether the scale is one value per output row)
+PROJECTIONS = {
+ "self_attn.q_proj": ((HIDDEN, HIDDEN), False),
+ "self_attn.k_proj": ((HIDDEN, HIDDEN), True),
+ "self_attn.v_proj": ((HIDDEN, HIDDEN), True),
+ "self_attn.o_proj": ((HIDDEN, HIDDEN), False),
+ "mlp.gate_proj": ((INTERMEDIATE, HIDDEN), True),
+ "mlp.up_proj": ((INTERMEDIATE, HIDDEN), False),
+ "mlp.down_proj": ((HIDDEN, INTERMEDIATE), True),
+}
+MX_MODULE = f"{LAYER}.self_attn.q_proj" # 128x128: the smallest weight an MXFP8 scale grid can describe
+
+
+class _Checkpoint:
+ def __init__(self, path: Path, dense: dict[str, torch.Tensor], scales: dict[str, torch.Tensor]) -> None:
+ self.path = path
+ # What the file decodes to, computed from the codes and scales written, independently of the loader.
+ self.dense = dense
+ # The scale written for each scaled layer's module path.
+ self.scales = scales
+
+
+def _write(
+ tmp_path: Path,
+ evidence: str = "marker",
+ extra: dict[str, torch.Tensor] | None = None,
+ *,
+ scaled_fp8: bool = True,
+ mx_module: str | None = None,
+) -> _Checkpoint:
+ """`evidence` is how the file says its layers are float8: per-layer `comfy_quant` markers, the safetensors header,
+ or nothing (the scales alone). `mx_module` carries an MXFP8 scale grid, named by `evidence` alone; `scaled_fp8=False`
+ writes raw float8 weights with no scale."""
+ torch.manual_seed(0)
+ tensors: dict[str, torch.Tensor] = {}
+ dense: dict[str, torch.Tensor] = {}
+ scales: dict[str, torch.Tensor] = {}
+ layers: dict[str, dict] = {}
+
+ def scaled(path: str, shape: tuple[int, int], per_row: bool) -> None:
+ codes = torch.randint(-12, 13, shape).float()
+ scale = torch.linspace(0.25, 1.5, shape[0]) if per_row else torch.tensor(0.5)
+ tensors[f"{path}.weight"] = codes.to(FP8)
+ if not scaled_fp8:
+ dense[f"{path}.weight"] = codes
+ return
+ if path == mx_module:
+ exponents = torch.randint(125, 130, (shape[0], shape[1] // 32))
+ tensors[f"{path}.weight_scale"] = block_scale_grid(exponents.to(torch.uint8))
+ dense[f"{path}.weight"] = codes * torch.exp2(exponents.float() - 127).repeat_interleave(32, dim=1)
+ layers[path] = {"format": "mxfp8"}
+ return
+ scale = torch.linspace(0.25, 1.5, shape[0]) if per_row else torch.tensor(0.5)
+ tensors[f"{path}.weight_scale"] = scale
+ dense[f"{path}.weight"] = codes * (scale[:, None] if per_row else scale)
+ scales[path] = scale
+ layers[path] = {"format": "float8_e4m3fn"}
+
+ for name, (shape, per_row) in PROJECTIONS.items():
+ scaled(f"{LAYER}.{name}", shape, per_row)
+ scaled("model.embed_tokens", (VOCAB, HIDDEN), False)
+ scaled("lm_head", (VOCAB, HIDDEN), False)
+ for key, tensor in {
+ f"{LAYER}.input_layernorm.weight": torch.rand(HIDDEN) + 0.5,
+ f"{LAYER}.post_attention_layernorm.weight": torch.rand(HIDDEN) + 0.5,
+ f"{LAYER}.self_attn.q_norm.weight": torch.rand(128) + 0.5,
+ f"{LAYER}.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
+ tensors.update(extra or {})
+ if mx_module is not None:
+ layers = {mx_module: layers[mx_module]}
+
+ metadata = None
+ if evidence == "marker":
+ for path, marker in layers.items():
+ tensors[f"{path}.comfy_quant"] = comfy_quant_marker(marker)
+ elif evidence == "header":
+ metadata = {"_quantization_metadata": json.dumps({"layers": layers})}
+ checkpoint = tmp_path / "qwen_3_4b_fp8_scaled.safetensors"
+ save_file(tensors, checkpoint, metadata=metadata)
+ return _Checkpoint(checkpoint, dense, scales)
+
+
+def _reference(dense: dict[str, torch.Tensor]) -> Qwen3ForCausalLM:
+ """A plain Qwen3 holding the decoded weights, configured the way the loader configures 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({k: v for k, v in dense.items() if k != "lm_head.weight"}, strict=False)
+ model.tie_weights()
+ return model.eval()
+
+
+def _encode(model: torch.nn.Module) -> torch.Tensor:
+ with torch.no_grad():
+ return model(input_ids=torch.tensor([[1, 5, 7, 2, 30]]), output_hidden_states=True).hidden_states[-1]
+
+
+def _decide(
+ monkeypatch: pytest.MonkeyPatch, *, matmul: bool = False, storage: bool = False, device: str = "cuda:0"
+) -> None:
+ """The session runs on `device`; only a CUDA device passes the gates that are switched on."""
+ monkeypatch.setattr(z_image.TorchDevice, "choose_torch_device", lambda: torch.device(device))
+ monkeypatch.setattr(z_image.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: torch.float32)
+ monkeypatch.setattr(z_image, "should_keep_fp8_weights", lambda d: matmul and d.type == "cuda")
+ monkeypatch.setattr(z_image, "_device_supports_fp8_storage", lambda d, _logger=None: storage and d.type == "cuda")
+
+
+def _loader() -> Qwen3EncoderCheckpointLoader:
+ loader = object.__new__(Qwen3EncoderCheckpointLoader)
+ loader._ram_cache = SimpleNamespace(make_room=MagicMock())
+ # What `ModelLoader.__init__` reads, on the device `_decide` set.
+ loader._torch_device, loader._logger = z_image.TorchDevice.choose_torch_device(), MagicMock()
+ return loader
+
+
+def _config(checkpoint: _Checkpoint, cpu_only: bool | None = None) -> Qwen3Encoder_Checkpoint_Config:
+ return Qwen3Encoder_Checkpoint_Config.model_construct(
+ path=str(checkpoint.path), variant=Qwen3VariantType.Qwen3_4B, cpu_only=cpu_only
+ )
+
+
[email protected]("evidence", ["marker", "header", "none"])
[email protected]("reason", ["fp8_compute", "fp8_storage"])
+def test_a_device_that_holds_float8_keeps_the_projections_scaled_and_encodes_like_the_decoded_weights(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, evidence: str, reason: str
+) -> None:
+ checkpoint = _write(tmp_path, evidence)
+ _decide(monkeypatch, matmul=reason == "fp8_compute", storage=reason == "fp8_storage")
+ attached: list[tuple[int, int]] = []
+ warn = z_image.warn_on_unattached_scales
+ monkeypatch.setattr(
+ z_image,
+ "warn_on_unattached_scales",
+ lambda logger, what, count, layers: (attached.append((count, len(layers))), warn(logger, what, count, layers)),
+ )
+
+ model = _loader()._load_from_singlefile(_config(checkpoint))
+
+ layer = model.model.layers[0]
+ for name in PROJECTIONS:
+ module = layer.get_submodule(name)
+ assert module.weight.dtype is FP8, name
+ # The file's own scale, on the module the weight sits in.
+ expected_scale = checkpoint.scales[f"{LAYER}.{name}"]
+ assert torch.equal(module.weight_scale.reshape(-1), expected_scale.reshape(-1)), name
+ # Persisted would make a re-save apply it twice.
+ assert "weight_scale" not in module.state_dict(), name
+ # Storage only, whatever the producer said: the fp8 matmul would quantize the activations too.
+ assert all(layer.get_submodule(name)._fp8_full_precision_matmul is True for name in PROJECTIONS)
+ # A token table is not a Linear: kept float8 it would feed fp8 activations to the first layer. The LM head is the
+ # tied table.
+ assert model.model.embed_tokens.weight.dtype is torch.float32
+ assert torch.equal(model.model.embed_tokens.weight, checkpoint.dense["model.embed_tokens.weight"])
+ assert model.lm_head.weight is model.model.embed_tokens.weight
+ assert not hasattr(model.model.embed_tokens, "weight_scale")
+ for key, param in model.named_parameters():
+ assert (param.dtype is FP8) == (key.endswith(tuple(f"{n}.weight" for n in PROJECTIONS))), key
+ # Every kept scale found its module (the LM head's was dropped with its weight, not left dangling).
+ assert attached == [(len(PROJECTIONS), len(PROJECTIONS))]
+
+ apply_custom_layers_to_model(model)
+ torch.testing.assert_close(_encode(model), _encode(_reference(checkpoint.dense)), rtol=1e-4, atol=1e-5)
+
+
[email protected]("evidence", ["marker", "header", "none"])
+def test_a_device_without_float8_folds_every_scaled_weight_to_what_the_file_decodes_to(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, evidence: str
+) -> None:
+ checkpoint = _write(tmp_path, evidence)
+ _decide(monkeypatch)
+
+ model = _loader()._load_from_singlefile(_config(checkpoint))
+
+ assert all(param.dtype is torch.float32 for param in model.parameters())
+ assert not any(hasattr(module, "weight_scale") for module in model.modules())
+ for key, param in model.state_dict().items():
+ if key in checkpoint.dense and key != "lm_head.weight": # the head is the tied table, not its own weight
+ # Bitwise: a per-row scale folded along the wrong axis would differ here, on a square weight too.
+ assert torch.equal(param, checkpoint.dense[key]), key
+ torch.testing.assert_close(_encode(model), _encode(_reference(checkpoint.dense)), rtol=1e-4, atol=1e-5)
+
+
+def test_a_cpu_only_encoder_is_folded_whatever_device_the_session_runs_on(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ checkpoint = _write(tmp_path)
+ _decide(monkeypatch, matmul=True)
+
+ cpu = _loader()._load_from_singlefile(_config(checkpoint, cpu_only=True))
+ gpu = _loader()._load_from_singlefile(_config(checkpoint, cpu_only=None))
+
+ assert all(param.dtype is torch.float32 for param in cpu.parameters())
+ assert gpu.model.layers[0].self_attn.q_proj.weight.dtype is FP8
+
+
+def test_the_reservation_counts_float8_projections_one_byte_and_everything_else_at_the_compute_dtype(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ checkpoint = _write(tmp_path)
+ projection_elements = sum(shape[0] * shape[1] for shape, _ in PROJECTIONS.values())
+ # The folded token table, the norms, and the scales recovered out of the file (the LM head's went with its
+ # weight). The markers are consumed before anything is reserved.
+ widened = VOCAB * HIDDEN + 5 * HIDDEN # the five norms
+ scale_bytes = 4 * (
+ sum(shape[0] if per_row else 1 for shape, per_row in PROJECTIONS.values()) + 1 # the token table's
+ )
+
+ reserved = {}
+ for keep in (True, False):
+ _decide(monkeypatch, matmul=keep)
+ loader = _loader()
+ loader._load_from_singlefile(_config(checkpoint))
+ loader._ram_cache.make_room.assert_called_once()
+ reserved[keep] = loader._ram_cache.make_room.call_args.args[0]
+
+ assert reserved[True] == projection_elements + 4 * widened + scale_bytes
+ assert reserved[False] == 4 * (projection_elements + widened) + scale_bytes
+
+
[email protected]("keep", [True, False])
+def test_a_scale_spelling_the_loader_does_not_read_is_refused_rather_than_cast_unscaled(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, keep: bool
+) -> None:
+ """`weight_scale_inv` beside a float8 weight: cast to the compute dtype it would load as raw codes, off by the whole
+ scale, and encode noise."""
+ inverse = {f"{LAYER}.self_attn.q_proj.weight_scale_inv": torch.tensor(2.0)}
+ checkpoint = _write(tmp_path, extra=inverse)
+ _decide(monkeypatch, matmul=keep)
+ loader = _loader()
+
+ with pytest.raises(NotImplementedError, match="weight_scale_inv"):
+ loader._load_from_singlefile(_config(checkpoint))
+
+ loader._ram_cache.make_room.assert_not_called()
+
+
+def test_kept_layers_are_dequantized_per_forward_even_where_the_fp8_matmul_is_available(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """Quantizing the activations as well (down-projection outliers) would change the conditioning for a speedup one
+ encoder pass per prompt does not need."""
+ checkpoint = _write(tmp_path)
+ _decide(monkeypatch, matmul=True)
+ model = _loader()._load_from_singlefile(_config(checkpoint))
+ apply_custom_layers_to_model(model)
+
+ def refuse(*_args, **_kwargs):
+ raise AssertionError("an encoder layer ran on the fp8 matmul")
+
+ monkeypatch.setattr(custom_linear, "is_fp8_matmul_enabled", lambda: True)
+ monkeypatch.setattr(custom_linear, "device_supports_fp8_matmul", lambda _device: True)
+ monkeypatch.setattr(custom_linear, "scaled_mm_linear", refuse)
+
+ torch.testing.assert_close(_encode(model), _encode(_reference(checkpoint.dense)), rtol=1e-4, atol=1e-5)
+
+
+def test_an_unscaled_fp8_file_stays_fp8_where_float8_is_held_and_decodes_elsewhere(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ checkpoint = _write(tmp_path, "none", scaled_fp8=False)
+
+ _decide(monkeypatch, storage=True)
+ kept = _loader()._load_from_singlefile(_config(checkpoint))
+ for name in PROJECTIONS:
+ module = kept.model.layers[0].get_submodule(name)
+ assert module.weight.dtype is FP8 and not hasattr(module, "weight_scale"), name
+ assert module._fp8_full_precision_matmul is True, name
+ apply_custom_layers_to_model(kept)
+ torch.testing.assert_close(_encode(kept), _encode(_reference(checkpoint.dense)), rtol=1e-4, atol=1e-5)
+
+ _decide(monkeypatch, storage=True, device="cpu")
+ folded = _loader()._load_from_singlefile(_config(checkpoint))
+ assert all(param.dtype is torch.float32 for param in folded.parameters())
+ torch.testing.assert_close(_encode(folded), _encode(_reference(checkpoint.dense)), rtol=1e-4, atol=1e-5)
+
+
[email protected]("evidence", ["marker", "header"])
[email protected]("device", ["cuda:0", "cpu"])
+def test_a_mxfp8_layer_named_by_its_marker_or_the_header_is_decoded_and_the_rest_keeps_its_format(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, evidence: str, device: str
+) -> None:
+ checkpoint = _write(tmp_path, evidence, mx_module=MX_MODULE)
+ _decide(monkeypatch, storage=True, device=device)
+
+ model = _loader()._load_from_singlefile(_config(checkpoint))
+
+ # Block-wise scales never reach the matmul, so this layer is folded even where the others stay float8.
+ q_proj = model.model.layers[0].self_attn.q_proj
+ assert q_proj.weight.dtype is torch.float32
+ assert torch.equal(q_proj.weight, checkpoint.dense[f"{MX_MODULE}.weight"])
+ assert model.model.layers[0].self_attn.k_proj.weight.dtype is (FP8 if device == "cuda:0" else torch.float32)
+ apply_custom_layers_to_model(model)
+ torch.testing.assert_close(_encode(model), _encode(_reference(checkpoint.dense)), rtol=1e-4, atol=1e-5)
+
+
[email protected]("device", ["cuda:0", "cpu"])
+def test_an_mxfp8_layer_nothing_names_is_refused_before_the_cache_is_evicted(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, device: str
+) -> None:
+ checkpoint = _write(tmp_path, "none", mx_module=MX_MODULE) # the grid is there; no marker, no header
+ _decide(monkeypatch, storage=True, device=device)
+ loader = _loader()
+
+ with pytest.raises(NotImplementedError, match="MXFP8"):
+ loader._load_from_singlefile(_config(checkpoint))
+
+ loader._ram_cache.make_room.assert_not_called()
+
+
+def test_the_cache_key_and_the_stored_format_come_from_one_capability_decision(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ # The key is computed before the load lock and the build runs under it; a probe that turns positive in between
+ # must not store float8 under a key that says folded, where an incapable device would adopt it.
+ checkpoint = _write(tmp_path)
+ _decide(monkeypatch)
+ loader = _loader()
+ assert loader._cache_key_variant(_config(checkpoint), SubModelType.TextEncoder) == "float32"
+
+ _decide(monkeypatch, storage=True)
+ model = loader._load_from_singlefile(_config(checkpoint))
+
+ assert all(param.dtype is torch.float32 for param in model.parameters())
+
+
+def _device_loader(store, budget, device: str, tmp_path: Path) -> Qwen3EncoderCheckpointLoader:
+ """A loader on its own device cache that shares `store` with the others."""
+ from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache
+
+ cache = ModelCache(
+ execution_device_working_mem_gb=1.0,
+ enable_partial_loading=False,
+ keep_ram_copy_of_weights=True,
+ execution_device="cpu",
+ storage_device="cpu",
+ logger=InvokeAILogger.get_logger("test"),
+ shared_cpu_weights=store,
+ ram_budget=budget,
+ )
+ loader = object.__new__(Qwen3EncoderCheckpointLoader)
+ loader._app_config = MagicMock(log_memory_usage=False, models_path=tmp_path)
+ loader._logger = InvokeAILogger.get_logger("test")
+ loader._ram_cache = cache
+ loader._torch_device = torch.device(device)
+ return loader
+
+
[email protected]("capable_first", [True, False], ids=["capable_loads_first", "incapable_loads_first"])
+def test_device_caches_share_weights_only_with_a_device_that_builds_the_same_format(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capable_first: bool
+) -> None:
+ # Device caches share one canonical CPU copy per cache key and adopt it without rerunning the loader. Whether the
+ # projections stay float8 depends on the device, so the second device must neither adopt float8 it cannot hold nor
+ # the folded copy that throws away a capable device's saving. Two GPUs, only the first passing the storage probe.
+ from invokeai.backend.model_manager.load.model_cache.ram_budget import RamBudget
+ from invokeai.backend.model_manager.load.model_cache.shared_cpu_weights import SharedCpuWeightsStore
+
+ checkpoint = _write(tmp_path)
+ monkeypatch.setattr(z_image.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: torch.float32)
+ monkeypatch.setattr(z_image, "should_keep_fp8_weights", lambda _device: False)
+ monkeypatch.setattr(z_image, "_device_supports_fp8_storage", lambda d, _logger=None: d == torch.device("cuda:0"))
+ config = Qwen3Encoder_Checkpoint_Config.model_construct(
+ key="qwen3",
+ path=checkpoint.path.name,
+ name="qwen_3_4b_fp8_scaled",
+ base=BaseModelType.Any,
+ type=ModelType.Qwen3Encoder,
+ variant=Qwen3VariantType.Qwen3_4B,
+ cpu_only=None,
+ )
+ store = SharedCpuWeightsStore()
+ budget = RamBudget(max_bytes=10**12, shared_store=store)
+ # Both caches stay alive: a device's cache entry holds the shared weights only while its cache lives.
+ loaders = {"capable": _device_loader(store, budget, "cuda:0", tmp_path)}
+ loaders["incapable"] = _device_loader(store, budget, "cuda:1", tmp_path)
+
+ records = {}
+ for name in ["capable", "incapable"] if capable_first else ["incapable", "capable"]:
+ records[name], _claim = loaders[name]._load_and_cache(config, SubModelType.TextEncoder)
+
+ capable, incapable = (records[name].cached_model.model.model.layers[0] for name in ("capable", "incapable"))
+ for name in PROJECTIONS:
+ kept = capable.get_submodule(name)
+ assert kept.weight.dtype is FP8, name
+ assert torch.equal(kept.weight_scale.reshape(-1), checkpoint.scales[f"{LAYER}.{name}"].reshape(-1)), name
+ folded = incapable.get_submodule(name).weight
+ assert folded.dtype is torch.float32 and torch.equal(folded, checkpoint.dense[f"{LAYER}.{name}.weight"]), name
+ assert records["capable"].key != records["incapable"].key
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.py
new file mode 100644
index 0000000000..3e291ae464
--- /dev/null
+++ b/tests/backend/model_manager/load/test_qwen_image_encoder_fp8.py
@@ -0,0 +1,472 @@
+"""The Qwen-Image text encoder's single-file loader on ComfyUI's `qwen_2.5_vl_7b_fp8_scaled` layout.
+
+The real `Qwen2_5_VLForConditionalGeneration` is built at toy width from the vendored config (two language-model
+layers, 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.
+"""
+
+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 Qwen2_5_VLConfig, Qwen2_5_VLForConditionalGeneration
+
+from invokeai.backend.model_manager.configs.qwen_vl_encoder import QwenVLEncoder_Checkpoint_Config
+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules import custom_linear
+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (
+ apply_custom_layers_to_model,
+)
+from invokeai.backend.model_manager.load.model_loaders import qwen_image
+from invokeai.backend.model_manager.load.model_loaders.qwen_image import QwenVLEncoderCheckpointLoader
+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType, SubModelType
+from invokeai.backend.patches.layer_patcher import LayerPatcher
+from invokeai.backend.patches.layers.lora_layer import LoRALayer
+from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
+from invokeai.backend.quantization.block_scale_tiles import block_scale_grid
+from invokeai.backend.qwen2_5_vl.qwen2_5_vl_assets import load_bundled_qwen2_5_vl_config_dict
+from invokeai.backend.util.logging import InvokeAILogger
+from tests.fixtures.quantized_payloads import comfy_quant_marker
+
+FP8 = torch.float8_e4m3fn
+# 128x128: the smallest weight an MXFP8 scale grid (tiles of 128 rows by 4 blocks of 32) can describe.
+Q_PROJ = "model.language_model.layers.0.self_attn.q_proj"
+MX_MODULE = Q_PROJ
+
+
+def _toy_config_dict() -> dict:
+ config = load_bundled_qwen2_5_vl_config_dict()
+ config.update(
+ hidden_size=128,
+ intermediate_size=256,
+ num_hidden_layers=2,
+ num_attention_heads=4,
+ num_key_value_heads=2,
+ vocab_size=64,
+ max_window_layers=2,
+ rope_scaling={"type": "mrope", "mrope_section": [4, 6, 6]},
+ )
+ config["vision_config"].update(
+ depth=2, hidden_size=32, intermediate_size=64, num_heads=2, out_hidden_size=128, window_size=28
+ )
+ config["vision_config"]["fullatt_block_indexes"] = [1]
+ # The vendored config says bfloat16, the sub-configs included.
+ config["torch_dtype"] = config["vision_config"]["torch_dtype"] = "float32"
+ return config
+
+
+def _new_model() -> Qwen2_5_VLForConditionalGeneration:
+ config = Qwen2_5_VLConfig.from_dict(_toy_config_dict())
+ return Qwen2_5_VLForConditionalGeneration(config).eval()
+
+
+def _legacy(name: str) -> str:
+ """transformers' layout back to the file's: `model.language_model.X` -> `model.X`, `model.visual.X` -> `visual.X`."""
+ if name.startswith("model.language_model."):
+ return "model." + name.removeprefix("model.language_model.")
+ return name.removeprefix("model.") if name.startswith("model.visual.") else name
+
+
+class _Checkpoint:
+ def __init__(self, path: Path) -> None:
+ self.path = path
+ # What the file decodes to, keyed by state-dict key of the plain model.
+ self.dense: dict[str, torch.Tensor] = {}
+ # Module path -> the scale written (per-row or scalar), for the layers that carry a plain one.
+ self.scales: dict[str, torch.Tensor] = {}
+ self.linear_modules: list[str] = []
+ self.linear_elements = 0
+ self.other_elements = 0
+ self.scale_bytes = 0
+
+
+def _write(
+ tmp_path: Path,
+ *,
+ scaled: bool = True,
+ evidence: str = "none",
+ mx_module: str | None = None,
+ extra: dict[str, torch.Tensor] | None = None,
+) -> _Checkpoint:
+ """`evidence` is how the file names the layer `mx_module` (or, without one, every scaled layer): per-layer
+ `comfy_quant` markers, the safetensors header, or nothing."""
+ torch.manual_seed(4)
+ reference = _new_model()
+ checkpoint = _Checkpoint(tmp_path / "qwen_2.5_vl_7b_fp8_scaled.safetensors")
+ tensors: dict[str, torch.Tensor] = {"scaled_fp8": torch.empty(0, dtype=FP8)}
+ hints: dict[str, dict] = {}
+ count = 0
+ for key, param in reference.state_dict().items():
+ module_path, _, leaf = key.rpartition(".")
+ 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)
+ 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
+ tensors[legacy_key] = value
+ checkpoint.dense[key] = value
+ checkpoint.other_elements += param.numel()
+ continue
+ codes = torch.randint(-12, 13, tuple(param.shape)).float()
+ tensors[legacy_key] = codes.to(FP8)
+ if not scaled:
+ checkpoint.dense[key] = codes
+ elif module_path == mx_module:
+ exponents = torch.randint(125, 130, (param.shape[0], param.shape[1] // 32))
+ tensors[f"{legacy_module}.weight_scale"] = block_scale_grid(exponents.to(torch.uint8))
+ checkpoint.dense[key] = codes * torch.exp2(exponents.float() - 127).repeat_interleave(32, dim=1)
+ checkpoint.scale_bytes += 4 * exponents.numel()
+ hints[legacy_module] = {"format": "mxfp8"}
+ else:
+ per_row = count % 2 == 0
+ count += 1
+ scale = torch.linspace(0.25, 1.5, param.shape[0]) if per_row else torch.tensor(0.5)
+ tensors[f"{legacy_module}.scale_weight"] = scale
+ # 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()
+ hints[legacy_module] = {"format": "float8_e4m3fn"}
+ if is_linear:
+ checkpoint.linear_modules.append(module_path)
+ checkpoint.linear_elements += param.numel()
+ else:
+ checkpoint.other_elements += param.numel()
+ tensors.update(extra or {})
+ if mx_module is not None:
+ hints = {_legacy(mx_module): {"format": "mxfp8"}}
+ metadata = None
+ if evidence == "marker":
+ for legacy_module, marker in hints.items():
+ tensors[f"{legacy_module}.comfy_quant"] = comfy_quant_marker(marker)
+ elif evidence == "header":
+ metadata = {"_quantization_metadata": json.dumps({"layers": hints})}
+ save_file(tensors, checkpoint.path, metadata=metadata)
+ return checkpoint
+
+
+def _decide(monkeypatch: pytest.MonkeyPatch, *, device: str, matmul: bool = False, storage: bool = False) -> None:
+ """The session runs on `device`; only a CUDA device passes the gates that are switched on."""
+ monkeypatch.setattr(qwen_image, "load_bundled_qwen2_5_vl_config_dict", _toy_config_dict)
+ monkeypatch.setattr(qwen_image.TorchDevice, "choose_torch_device", lambda: torch.device(device))
+ monkeypatch.setattr(qwen_image.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: torch.float32)
+ monkeypatch.setattr(qwen_image, "should_keep_fp8_weights", lambda d: matmul and d.type == "cuda")
+ monkeypatch.setattr(
+ qwen_image, "_device_supports_fp8_storage", lambda d, _logger=None: storage and d.type == "cuda"
+ )
+
+
+def _loader() -> QwenVLEncoderCheckpointLoader:
+ loader = object.__new__(QwenVLEncoderCheckpointLoader)
+ loader._ram_cache = SimpleNamespace(make_room=MagicMock())
+ # What `ModelLoader.__init__` reads, on the device `_decide` set.
+ loader._torch_device, loader._logger = qwen_image.TorchDevice.choose_torch_device(), MagicMock()
+ return loader
+
+
+def _load(checkpoint: _Checkpoint, loader: QwenVLEncoderCheckpointLoader | None = None):
+ config = QwenVLEncoder_Checkpoint_Config.model_construct(path=str(checkpoint.path))
+ return (loader or _loader())._load_text_encoder_from_singlefile(config)
+
+
+def _plain_reference(dense: dict[str, torch.Tensor]) -> Qwen2_5_VLForConditionalGeneration:
+ model = _new_model()
+ model.load_state_dict(dense)
+ return model
+
+
+IDS = torch.tensor([[1, 5, 7, 2, 30]])
+GRID = torch.tensor([[1, 4, 4]])
+PIXELS = torch.randn(16, 3 * 2 * 14 * 14, generator=torch.Generator().manual_seed(9))
+
+
+def _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)
+
+
+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)
+ torch.testing.assert_close(vision, expected_vision, rtol=1e-4, atol=1e-4)
+
+
[email protected]("evidence", ["none", "marker", "header"])
[email protected]("reason", ["fp8_compute", "fp8_storage"])
+def test_a_device_that_holds_float8_keeps_every_scaled_linear_with_its_scale_and_encodes_the_same(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, reason: str, evidence: str
+) -> None:
+ checkpoint = _write(tmp_path, evidence=evidence)
+ _decide(monkeypatch, device="cuda:0", matmul=reason == "fp8_compute", storage=reason == "fp8_storage")
+ attached: list[tuple[int, int]] = []
+ warn = qwen_image.warn_on_unattached_scales
+ monkeypatch.setattr(
+ qwen_image,
+ "warn_on_unattached_scales",
+ lambda logger, what, count, layers: (attached.append((count, len(layers))), warn(logger, what, count, layers)),
+ )
+
+ model = _load(checkpoint)
+
+ # Language model, vision tower (qkv, proj, mlp, merger) and the untied LM head alike.
+ assert "lm_head" in checkpoint.linear_modules
+ 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:
+ module = model.get_submodule(path)
+ assert module.weight.dtype is FP8, path
+ assert torch.equal(module.weight_scale.reshape(-1), checkpoint.scales[path].reshape(-1)), path
+ assert "weight_scale" not in module.state_dict(), path
+ # Everything else is the compute dtype: a lookup table or a convolution kept float8 would feed it to the next layer.
+ for key, param in model.named_parameters():
+ assert (param.dtype is FP8) == (key.removesuffix(".weight") in checkpoint.linear_modules), key
+ embed = model.model.language_model.embed_tokens.weight
+ assert torch.equal(embed, checkpoint.dense["model.language_model.embed_tokens.weight"])
+ assert model.dtype is torch.float32 and model.model.visual.dtype is torch.float32
+ assert attached == [(len(checkpoint.linear_modules),) * 2]
+
+ apply_custom_layers_to_model(model)
+ _assert_encodes_like(model, checkpoint.dense)
+
+
+def test_kept_layers_are_dequantized_per_forward_even_where_the_fp8_matmul_is_available(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """Quantizing the activations as well (down-projection and vision outliers) would change the conditioning for a
+ speedup one encoder pass per prompt does not need."""
+ checkpoint = _write(tmp_path)
+ _decide(monkeypatch, device="cuda:0", matmul=True)
+ model = _load(checkpoint)
+ apply_custom_layers_to_model(model)
+
+ def refuse(*_args, **_kwargs):
+ raise AssertionError("an encoder layer ran on the fp8 matmul")
+
+ monkeypatch.setattr(custom_linear, "is_fp8_matmul_enabled", lambda: True)
+ monkeypatch.setattr(custom_linear, "device_supports_fp8_matmul", lambda _device: True)
+ monkeypatch.setattr(custom_linear, "scaled_mm_linear", refuse)
+
+ assert all(model.get_submodule(path)._fp8_full_precision_matmul is True for path in checkpoint.linear_modules)
+ _assert_encodes_like(model, checkpoint.dense)
+
+
+def test_a_device_without_float8_folds_every_scaled_weight_to_what_the_file_decodes_to(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ checkpoint = _write(tmp_path)
+ _decide(monkeypatch, device="cpu", matmul=True, storage=True)
+
+ model = _load(checkpoint)
+
+ assert all(param.dtype is torch.float32 for param in model.parameters())
+ assert not any(hasattr(module, "weight_scale") for module in model.modules())
+ for key, value in model.state_dict().items():
+ # Bitwise, so a per-row scale applied along the wrong axis cannot hide behind a tolerance.
+ assert torch.equal(value, checkpoint.dense[key]), key
+ _assert_encodes_like(model, checkpoint.dense)
+
+
+def test_an_unscaled_fp8_file_stays_fp8_where_float8_is_held_and_decodes_elsewhere(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ checkpoint = _write(tmp_path, scaled=False)
+
+ _decide(monkeypatch, device="cuda:0", storage=True)
+ kept = _load(checkpoint)
+ for path in checkpoint.linear_modules:
+ module = kept.get_submodule(path)
+ assert module.weight.dtype is FP8 and not hasattr(module, "weight_scale"), path
+ assert module._fp8_full_precision_matmul is True, path
+ apply_custom_layers_to_model(kept)
+ _assert_encodes_like(kept, checkpoint.dense)
+
+ _decide(monkeypatch, device="cpu", storage=True)
+ folded = _load(checkpoint)
+ assert all(param.dtype is torch.float32 for param in folded.parameters())
+ _assert_encodes_like(folded, checkpoint.dense)
+
+
[email protected]("evidence", ["marker", "header"])
[email protected]("device", ["cuda:0", "cpu"])
+def test_a_mxfp8_layer_named_by_its_marker_or_the_header_is_decoded_and_the_rest_keeps_its_format(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, evidence: str, device: str
+) -> None:
+ checkpoint = _write(tmp_path, evidence=evidence, mx_module=MX_MODULE)
+ _decide(monkeypatch, device=device, storage=True)
+
+ model = _load(checkpoint)
+
+ # 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.float32
+ assert 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)
+ if device == "cuda:0":
+ apply_custom_layers_to_model(model)
+ _assert_encodes_like(model, checkpoint.dense)
+
+
[email protected]("device", ["cuda:0", "cpu"])
+def test_an_mxfp8_layer_nothing_names_is_refused_before_the_cache_is_evicted(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, device: str
+) -> None:
+ checkpoint = _write(tmp_path, evidence="none", mx_module=MX_MODULE) # the grid is there; no marker, no header
+ _decide(monkeypatch, device=device, storage=True)
+ loader = _loader()
+
+ with pytest.raises(NotImplementedError, match="MXFP8"):
+ _load(checkpoint, loader)
+
+ loader._ram_cache.make_room.assert_not_called()
+
+
+def test_the_reservation_counts_float8_weights_one_byte_and_everything_else_at_the_compute_dtype(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ checkpoint = _write(tmp_path)
+ reserved = {}
+ for device in ("cuda:0", "cpu"):
+ _decide(monkeypatch, device=device, storage=True)
+ loader = _loader()
+ _load(checkpoint, loader)
+ loader._ram_cache.make_room.assert_called_once()
+ reserved[device] = loader._ram_cache.make_room.call_args.args[0]
+
+ # The recovered scales are resident until the split consumes them; the 1.0 `scale_input` placeholders are dropped.
+ widened = 4 * checkpoint.other_elements + checkpoint.scale_bytes
+ assert reserved["cuda:0"] == checkpoint.linear_elements + widened
+ assert reserved["cpu"] == 4 * checkpoint.linear_elements + widened
+
+
[email protected]("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)})
+ _decide(monkeypatch, device=device, storage=True)
+ loader = _loader()
+
+ with pytest.raises(NotImplementedError, match="weight_scale_inv"):
+ _load(checkpoint, loader)
+
+ loader._ram_cache.make_room.assert_not_called()
+
+
+def test_a_lora_on_a_kept_float8_layer_is_added_beside_the_scaled_weight_and_removed_afterwards(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ checkpoint = _write(tmp_path)
+ _decide(monkeypatch, device="cuda:0", storage=True)
+ model = _load(checkpoint)
+ apply_custom_layers_to_model(model)
+ rank = 4
+ torch.manual_seed(5)
+ # As large as the decoded weights (codes up to 12), so the patch visibly moves the output.
+ up, down = torch.randn(128, rank) * 2, torch.randn(rank, 128) * 2
+ patch = ModelPatchRaw({Q_PROJ: LoRALayer(up=up, mid=None, down=down, alpha=float(rank), bias=None)})
+ unpatched = _run(model)[0]
+
+ with LayerPatcher.apply_smart_model_patches(model=model, patches=[(patch, 1.0)], prefix="", dtype=torch.float32):
+ patched = _run(model)[0]
+ # The base weight is untouched: the patch is a sidecar.
+ assert model.get_submodule(Q_PROJ).weight.dtype is FP8
+
+ # Independent of the sidecar code: the plain model with the delta written into the decoded q_proj weight.
+ merged = dict(checkpoint.dense)
+ merged[f"{Q_PROJ}.weight"] = merged[f"{Q_PROJ}.weight"] + up @ down
+ torch.testing.assert_close(patched, _run(_plain_reference(merged))[0], rtol=1e-4, atol=1e-4)
+ assert (patched - unpatched).norm() > 0.05 * unpatched.norm()
+ torch.testing.assert_close(_run(model)[0], unpatched)
+
+
+def test_the_cache_key_and_the_stored_format_come_from_one_capability_decision(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ # The key is computed before the load lock and the build runs under it; a probe that turns positive in between
+ # must not store float8 under a key that says folded, where an incapable device would adopt it.
+ checkpoint = _write(tmp_path)
+ _decide(monkeypatch, device="cuda:0")
+ loader = _loader()
+ config = QwenVLEncoder_Checkpoint_Config.model_construct(path=str(checkpoint.path))
+ assert loader._cache_key_variant(config, SubModelType.TextEncoder) == "float32"
+
+ _decide(monkeypatch, device="cuda:0", storage=True)
+ model = _load(checkpoint, loader)
+
+ assert all(param.dtype is torch.float32 for param in model.parameters())
+
+
+def _device_loader(store, budget, device: str, tmp_path: Path) -> QwenVLEncoderCheckpointLoader:
+ """A loader on its own device cache that shares `store` with the others."""
+ from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache
+
+ cache = ModelCache(
+ execution_device_working_mem_gb=1.0,
+ enable_partial_loading=False,
+ keep_ram_copy_of_weights=True,
+ execution_device="cpu",
+ storage_device="cpu",
+ logger=InvokeAILogger.get_logger("test"),
+ shared_cpu_weights=store,
+ ram_budget=budget,
+ )
+ loader = object.__new__(QwenVLEncoderCheckpointLoader)
+ loader._app_config = MagicMock(log_memory_usage=False, models_path=tmp_path)
+ loader._logger = InvokeAILogger.get_logger("test")
+ loader._ram_cache = cache
+ loader._torch_device = torch.device(device)
+ return loader
+
+
[email protected]("capable_first", [True, False], ids=["capable_loads_first", "incapable_loads_first"])
+def test_device_caches_share_weights_only_with_a_device_that_builds_the_same_format(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capable_first: bool
+) -> None:
+ # Device caches share one canonical CPU copy per cache key and adopt it without rerunning the loader. Whether the
+ # Linear weights stay float8 depends on the device, so the second device must neither adopt float8 it cannot hold
+ # nor the folded copy that throws away a capable device's saving. Two GPUs, only the first passing the storage probe.
+ from invokeai.backend.model_manager.load.model_cache.ram_budget import RamBudget
+ from invokeai.backend.model_manager.load.model_cache.shared_cpu_weights import SharedCpuWeightsStore
+
+ checkpoint = _write(tmp_path)
+ monkeypatch.setattr(qwen_image, "load_bundled_qwen2_5_vl_config_dict", _toy_config_dict)
+ monkeypatch.setattr(qwen_image.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: torch.float32)
+ monkeypatch.setattr(qwen_image, "should_keep_fp8_weights", lambda _device: False)
+ monkeypatch.setattr(qwen_image, "_device_supports_fp8_storage", lambda d, _logger=None: d == torch.device("cuda:0"))
+ config = QwenVLEncoder_Checkpoint_Config.model_construct(
+ key="qwen-vl",
+ path=checkpoint.path.name,
+ name="qwen_2.5_vl_7b_fp8_scaled",
+ base=BaseModelType.Any,
+ type=ModelType.QwenVLEncoder,
+ cpu_only=None,
+ )
+ store = SharedCpuWeightsStore()
+ budget = RamBudget(max_bytes=10**12, shared_store=store)
+ # Both caches stay alive: a device's cache entry holds the shared weights only while its cache lives.
+ loaders = {"capable": _device_loader(store, budget, "cuda:0", tmp_path)}
+ loaders["incapable"] = _device_loader(store, budget, "cuda:1", tmp_path)
+
+ records = {}
+ for name in ["capable", "incapable"] if capable_first else ["incapable", "capable"]:
+ records[name], _claim = loaders[name]._load_and_cache(config, SubModelType.TextEncoder)
+
+ capable, incapable = (records[name].cached_model.model for name in ("capable", "incapable"))
+ # The vision tower's layers too: it is part of the text encoder's module and shares its cache entry.
+ assert any(path.startswith("model.visual.") for path in checkpoint.linear_modules)
+ for path in checkpoint.linear_modules:
+ kept = capable.get_submodule(path)
+ assert kept.weight.dtype is FP8, path
+ assert torch.equal(kept.weight_scale.reshape(-1), checkpoint.scales[path].reshape(-1)), path
+ folded = incapable.get_submodule(path).weight
+ assert folded.dtype is torch.float32 and torch.equal(folded, checkpoint.dense[f"{path}.weight"]), path
+ assert records["capable"].key != records["incapable"].key
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.py
index 513f907039..3216eddffe 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
@@ -4,7 +4,8 @@ Both Comfy files mix nvfp4 with scaled fp8, and an fp8 fold multiplies every `.w
block scales included. So what these tests pin is the order: the nvfp4 layers leave the state dict before any fp8
handling, come back packed under the paths the model uses (the encoder's legacy `model.X` keys become
`model.language_model.X`), and one reservation is made before anything is widened. The transformer's scaled fp8 layers
-are folded unless fp8 compute or the model's fp8 storage setting keeps them; the encoder's are always folded. The compute
+are folded unless fp8 compute or the model's fp8 storage setting keeps them; the encoder's are folded unless the
+device can hold or multiply float8 (`test_qwen_image_encoder_fp8.py`). The compute
dtype is bf16, as in production: the packed global scale must not be cast.
"""
@@ -77,7 +78,7 @@ def _patch_common(monkeypatch: pytest.MonkeyPatch, state_dict: dict, metadata: d
def _record_fold(monkeypatch: pytest.MonkeyPatch, loader, log: list[bool], *names: str) -> None:
"""At every call of the named `qwen_image` functions, log whether room had been made yet."""
- for name in names or ("_dequantize_comfyui_fp8",):
+ for name in names or ("dequantize_fp8_scaled",):
original = getattr(qwen_image, name)
def recording(*args, _original=original, **kwargs):
@@ -267,6 +268,7 @@ def test_the_encoder_keeps_marker_named_nvfp4_layers_packed_under_their_transfor
checkpoint.touch()
loader = object.__new__(QwenVLEncoderCheckpointLoader)
loader._ram_cache = SimpleNamespace(make_room=MagicMock())
+ loader._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"]
@@ -288,11 +290,13 @@ def test_the_encoder_keeps_marker_named_nvfp4_layers_packed_under_their_transfor
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.
+ # 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.
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())
+ widened = 128 + 32 * 64 + (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)
#: The shared encoder seam computes in float32; the int8 cells need bf16, since a blanket cast to it is what would ruin
diff --git a/tests/backend/model_manager/load/test_qwen_image_state_dict_utils.py b/tests/backend/model_manager/load/test_qwen_image_state_dict_utils.py
index fa6fbed0a5..7776e51465 100644
--- a/tests/backend/model_manager/load/test_qwen_image_state_dict_utils.py
+++ b/tests/backend/model_manager/load/test_qwen_image_state_dict_utils.py
@@ -10,9 +10,7 @@ import torch
from invokeai.backend.model_manager.load.model_loaders.qwen_image import (
_build_qwen_image_transformer_config,
- _dequantize_comfyui_fp8,
_remap_qwen_vl_checkpoint_keys,
- _strip_quantization_metadata,
)
from tests.backend.model_manager.load.state_dicts.qwen_vl_encoder_comfyui_keys import (
state_dict_keys as qwen_vl_keys,
@@ -27,9 +25,8 @@ _VALID_QWEN_VL_PREFIXES = ("model.visual.", "model.language_model.", "lm_head")
class TestRemapQwenVlCheckpointKeys:
def test_every_key_maps_to_the_transformers_layout(self):
"""Every legacy ComfyUI key must land under `model.visual.*` / `model.language_model.*`."""
- sd = keys_to_mock_state_dict(qwen_vl_keys)
- # The loader strips fp8 metadata (`scaled_fp8` etc.) before remapping; mirror that order.
- _strip_quantization_metadata(sd)
+ # `scaled_fp8` is the file's quantization marker, which the fp8 extraction removes; it names no module.
+ sd = {key: value for key, value in keys_to_mock_state_dict(qwen_vl_keys).items() if key != "scaled_fp8"}
remapped = _remap_qwen_vl_checkpoint_keys(sd)
@@ -68,47 +65,20 @@ class TestRemapQwenVlCheckpointKeys:
assert set(once.keys()) == set(twice.keys())
-class TestStripQuantizationMetadata:
- def test_drops_fp8_metadata_keeps_weights(self):
+class TestRemapKeepsScalesBesideTheirWeights:
+ def test_every_scale_of_the_captured_fp8_scaled_file_pairs_with_a_weight_after_the_remap(self):
+ """The loader extracts scales after the remap, so each scale must travel with its weight."""
sd = keys_to_mock_state_dict(qwen_vl_keys)
- # The captured checkpoint is fp8_scaled, so it really does ship this metadata.
- assert any(k.endswith((".scale_weight", ".scale_input")) or k == "scaled_fp8" for k in sd)
- n_weights_before = sum(1 for k in sd if k.endswith(".weight"))
-
- _strip_quantization_metadata(sd)
-
- assert not any(
- k.endswith((".scale_weight", ".scale_input")) or "comfy_quant" in k or k == "scaled_fp8" for k in sd
- )
- # Real weights are untouched.
- assert sum(1 for k in sd if k.endswith(".weight")) == n_weights_before
-
-
-class TestDequantizeComfyuiFp8:
- def test_scalar_scale(self):
- sd = {
- "l.weight": torch.full((2, 2), 2.0),
- "l.scale_weight": torch.tensor(3.0),
- "l.scale_input": torch.tensor(9.0), # activation scale, must be ignored
- }
+ scales = [k for k in sd if k.endswith((".scale_weight", ".scale_input"))]
+ assert scales, "the captured checkpoint is fp8_scaled, so it ships scales"
- count = _dequantize_comfyui_fp8(sd, torch.float32)
-
- assert count == 1
- assert torch.allclose(sd["l.weight"], torch.full((2, 2), 6.0))
-
- def test_block_wise_scale_is_broadcast(self):
- # Per-block scale [2, 1] must be repeat_interleaved up to the weight shape [4, 2].
- sd = {
- "l.weight": torch.ones(4, 2),
- "l.weight_scale": torch.tensor([[10.0], [20.0]]),
- }
-
- count = _dequantize_comfyui_fp8(sd, torch.float32)
+ remapped = _remap_qwen_vl_checkpoint_keys(sd)
- assert count == 1
- expected = torch.tensor([[10.0, 10.0], [10.0, 10.0], [20.0, 20.0], [20.0, 20.0]])
- assert torch.allclose(sd["l.weight"], expected)
+ for key in scales:
+ moved = _remap_qwen_vl_checkpoint_keys({key: None})
+ (new_key,) = moved
+ module = new_key.rsplit(".", 1)[0]
+ assert f"{module}.weight" in remapped, new_key
class TestBuildQwenImageTransformerConfig:
diff --git a/tests/backend/model_manager/load/test_scaled_fp8_fold_axis.py b/tests/backend/model_manager/load/test_scaled_fp8_fold_axis.py
index 44b75a88e8..8f75ccad6f 100644
--- a/tests/backend/model_manager/load/test_scaled_fp8_fold_axis.py
+++ b/tests/backend/model_manager/load/test_scaled_fp8_fold_axis.py
@@ -23,7 +23,6 @@ from invokeai.backend.model_manager.load.model_loaders.comfyui_state_dict_utils
)
from invokeai.backend.model_manager.load.model_loaders.flux import Flux2CheckpointModel
from invokeai.backend.model_manager.load.model_loaders.mistral_encoder import _drop_quantization_metadata
-from invokeai.backend.model_manager.load.model_loaders.z_image import _fold_comfy_scaled_weights
from invokeai.backend.quantization.fp8_scaled import (
WEIGHT_SCALE_SUFFIXES,
)
@@ -77,63 +76,6 @@ class TestMistralEncoderFold:
_drop_quantization_metadata(sd, MagicMock(), target_dtype=torch.bfloat16)
-class TestZImageQwen3EncoderFold:
- """The Z-Image Qwen3 encoder's single-file loader folds the same way."""
-
- def _fold(self, sd: dict, dtype: torch.dtype = torch.bfloat16) -> dict:
- # The real call site. It was a loop inside `_load_from_singlefile` -- unreachable without a
- # checkpoint and a transformers model -- so it was extracted; re-inlining it as a local
- # multiply fails these tests instead of passing CI.
- _fold_comfy_scaled_weights(sd, dtype)
- return sd
-
- def test_per_channel_scale_multiplies_rows(self) -> None:
- weight, scale, expected = _per_channel_case()
- sd = self._fold({"layer.weight": weight, "layer.weight_scale": scale})
- assert torch.equal(sd["layer.weight"], expected)
-
- def test_non_square_weight_does_not_raise(self) -> None:
- weight, scale, _ = _per_channel_case(out_features=6, in_features=2)
- sd = self._fold({"layer.weight": weight, "layer.weight_scale": scale})
- assert sd["layer.weight"].shape == (6, 2)
-
- def test_block_wise_scale_is_expanded_rather_than_rejected(self) -> None:
- sd = self._fold(
- {
- "layer.weight": torch.ones(4, 2).to(torch.float8_e4m3fn),
- "layer.weight_scale": torch.tensor([[1.0], [2.0]]), # one entry per 2-row block
- }
- )
- assert torch.equal(
- sd["layer.weight"],
- torch.tensor([[1.0, 1.0], [1.0, 1.0], [2.0, 2.0], [2.0, 2.0]], dtype=torch.bfloat16),
- )
-
- def test_a_scale_matching_neither_layout_is_reported(self) -> None:
- with pytest.raises(ValueError, match="neither per-tensor nor per-output-channel"):
- self._fold(
- {
- "layer.weight": torch.ones(4, 2).to(torch.float8_e4m3fn),
- "layer.weight_scale": torch.full((3,), 2.0),
- }
- )
-
- def test_an_mx_block_scale_is_refused_rather_than_folded_as_a_multiplier(self) -> None:
- """An MXFP8 grid is E8M0 exponent *bytes*: 127 means 2**0, i.e. a scale of 1.0. Folded as a
- linear multiplier it makes every weight ~127x too large, at the right shape and the right
- dtype, with nothing raised and nothing logged. `extract_fp8_scaled_layers` decodes these grids
- (`decode_mx_block_scales`) -- but these folds do not go through it, so they took the bytes as
- numbers.
- """
- sd = {
- "layer.weight": torch.ones(128, 128).to(torch.float8_e4m3fn),
- "layer.weight_scale": torch.full((128, 4), 127, dtype=torch.uint8),
- }
-
- with pytest.raises(NotImplementedError, match="MXFP8"):
- _fold_comfy_scaled_weights(sd, torch.bfloat16)
-
-
class TestSharedComfyFold:
"""`_dequantize_comfyui_fp8`, the copy the Qwen2.5-VL encoder loader
(`qwen_image.py`) reaches. Its local loop compared `scale.shape[dim] !=