Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(model-manager): load unsloth's torchao fp8 Qwen-Image-2.1 builds (#10179)
Alexander Eichhorn194a7cf5a027
diff --git a/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx b/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdxindex d38fb59cfd..78a40a013c 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@@ -1,7 +1,7 @@---title: Model Format Supportdescription: Which file formats and quantizations InvokeAI loads for every model family, text encoder, VAE and adapter.-lastUpdated: 2026-11-06+lastUpdated: 2026-11-10sidebar:order: 3---@@ -56,11 +56,13 @@ reader's error; if the file is incomplete or corrupt, download it again.`int4_tensorwise`, which most builds mix with int8 layers. **nvfp4** and **fp8 scaled** mean ComfyUI's checkpointlayouts; other exports of the same schemes (AWQ, ModelOpt) fail when the model loads. FLUX.3 also loads Black ForestLabs' own builds: the nvfp4 export in NVIDIA ModelOpt's layout and `fp8r` (fp8 with one scale per row). It refuses- AWQ and other producers' nvfp4 at install. For Qwen-Image-2.1 and FLUX.3, torchao exports such as unsloth's FP8- builds are refused at install. MOSS-Image loads Comfy-Org's int8 build and GGUFs; its fp8, nvfp4 and w4a8- transformers, and unsloth's torchao builds, are refused at install, unscaled fp8 included. ComfyUI's other low-bit- layouts (`w4a8`, `w6a8`, SVDQuant) are not supported; Krea-2,- Qwen-Image and Wan 2.2 refuse them at install.+ AWQ and other producers' nvfp4 at install. For Qwen-Image-2.1, unsloth's torchao FP8 builds (fp8 weights with one+ scale per output row) load as fp8 scaled; other torchao layouts, such as per-tensor or block-wise fp8 and INT8+ builds, are refused at install. FLUX.3 refuses every torchao export at install. Ideogram 4 refuses the torchao+ exports it recognizes; one that also quantized the projections Ideogram 4 is recognized by does not install as+ Ideogram 4 at all. MOSS-Image loads Comfy-Org's int8 build and GGUFs; its fp8, nvfp4 and w4a8 transformers, and+ unsloth's torchao builds, are refused at install, unscaled fp8 included. ComfyUI's other low-bit layouts (`w4a8`,+ `w6a8`, SVDQuant) are not supported; Krea-2, Qwen-Image and Wan 2.2 refuse them at install.- **GGUF** covers the llama.cpp types (Q4_0 through Q8_0, the K-quants, BF16). ComfyUI-GGUF's `Q8_CR` (int8) and`Q4_CR` (int4) files load for Krea-2 only; for every other model with GGUF support the install fails, as it doesfor `Q4_CR` files of ComfyUI-GGUF's retired W4A16 kind.diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image-2-1.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image-2-1.mdxindex 30b64925c7..1574ec8116 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image-2-1.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/qwen-image-2-1.mdx@@ -1,7 +1,7 @@---title: Qwen-Image-2.1description: Generate images with Qwen-Image-2.1 and its 8-step Turbo variant, from the Diffusers folders, a GGUF or an int8 transformer, including transparent (RGBA) output.-lastUpdated: 2026-11-01+lastUpdated: 2026-11-06sidebar:order: 9---@@ -42,7 +42,7 @@ The **Qwen-Image-2.1 (Q4_K_M GGUF)** starter model, from [`unsloth/Qwen-Image-2.The **Qwen-Image-2.1 (int8)** and **Qwen-Image-2.1 Turbo (int8)** starter models, Comfy-Org's `int8_convrot` builds (~7.3 GB each), install the same VAE and 8B encoder. Their int8 layers stay int8 on every supported GPU, and [int8 Compute](/configuration/optimization/int8-compute/) can run them on NVIDIA int8 tensor cores.-Single-file transformers in bf16, scaled fp8 or `int8_convrot` (ComfyUI repackages) load as well. nvfp4 files, torchao-quantized files (such as unsloth's FP8 build), and int8 files without ComfyUI's `int8_convrot` marker, are refused at install. GGUF files with int8 layers (ComfyUI-GGUF's `Q8_CR`) are refused too.+Single-file transformers in bf16, scaled fp8 or `int8_convrot` (ComfyUI repackages) load as well, as do torchao FP8 files with one scale per output row, such as unsloth's FP8 builds. nvfp4 files, other torchao layouts (per-tensor or block-wise fp8, and INT8 builds such as unsloth's), and other int8 files without ComfyUI's `int8_convrot` marker, are refused at install. GGUF files with int8 layers (ComfyUI-GGUF's `Q8_CR`) are refused too.The Turbo variant is recognized from the filename: a single file or GGUF whose name contains `turbo` installs as Turbo, anything else as the base model. If a file was detected as the wrong variant, edit the model in the Model Manager and change its **Variant**. The default settings were chosen at install, so also set **Steps** under **Default Settings**: 8 for Turbo, 40 for the base model.diff --git a/invokeai/backend/model_manager/configs/main.py b/invokeai/backend/model_manager/configs/main.pyindex a20e2d0cc5..a17e3553b5 100644--- a/invokeai/backend/model_manager/configs/main.py+++ b/invokeai/backend/model_manager/configs/main.py@@ -80,6 +80,8 @@ from invokeai.backend.patches.lora_conversions.sd3_lora_constants import sd3_varfrom invokeai.backend.quantization.fp8_scaled import (COMFY_QUANT_SUFFIX,FP8_WEIGHT_DTYPES,+ TORCHAO_QDATA_SUFFIX,+ find_torchao_fp8_problem,is_scale_metadata_key,parse_quantization_metadata,)@@ -1700,7 +1702,12 @@ def _raise_for_undecodable_int8_weights(def _raise_for_unsupported_comfy_quantization(- mod: ModelOnDisk, state_dict: dict[str | int, Any], family: str, *, supported: str | None = None+ mod: ModelOnDisk,+ state_dict: dict[str | int, Any],+ family: str,+ *,+ supported: str | None = None,+ accepts_torchao_fp8: bool = False,) -> None:"""Refuse the ComfyUI quantization schemes the Ideogram 4 and Qwen-Image-2.1 single-file loaders cannot build.@@ -1708,10 +1715,12 @@ def _raise_for_unsupported_comfy_quantization(right outcome is a refusal the installer shows, not a fall-through to `Unknown_Config` thatregisters it as a model nothing can load.- Three of them. torchao's serialized tensor subclasses (unsloth's Qwen-Image-2.1 FP8 build) store each quantized+ Three of them. torchao's serialized tensor subclasses (unsloth's FP8 and INT8 builds) store each quantizedweight as `<layer>._weight_qdata` beside its scale, with no `<layer>.weight` the transformer could load. Onlya family whose fingerprint reads unquantized tensors gets here with such a file: Qwen-Image-2.1 does, while an- Ideogram 4 build that quantized its fingerprint Linears would not match at all.+ Ideogram 4 build that quantized its fingerprint Linears would not match at all. A family whose loader+ translates the fp8 form (`translate_torchao_fp8_layers`) passes `accepts_torchao_fp8`; it then refuses only+ what `find_torchao_fp8_problem` names, which includes every INT8 build.nvfp4 packs two codes per byte, so its uint8 weights are indistinguishable fromthe `comfy_quant` markers every repack carries -- including the two supported ones; the@@ -1728,7 +1737,17 @@ def _raise_for_unsupported_comfy_quantization(is a header parse plus one seek per marker, and it only happens for a file that has int8weights to explain in the first place."""- if any(isinstance(key, str) and key.endswith("._weight_qdata") for key in state_dict):+ if accepts_torchao_fp8:+ problem = find_torchao_fp8_problem(state_dict)+ if problem is not None:+ raise InvalidMatchError(+ f"this {family} transformer is saved as torchao-quantized tensors that InvokeAI cannot load: "+ f"{problem}. Only torchao float8_e4m3fn weights with one scale per output row load, such as "+ "unsloth's FP8 builds; other layouts, including INT8 builds, are not supported. A file that is "+ "missing one half of a weight/scale pair is probably incomplete: download it again. Otherwise "+ "install the bf16, fp8_scaled or int8_convrot build, or a GGUF."+ )+ elif any(isinstance(key, str) and key.endswith(TORCHAO_QDATA_SUFFIX) for key in state_dict):raise InvalidMatchError(f"this {family} transformer is saved as torchao-quantized tensors (as unsloth's FP8 and INT8 builds "f"are), which is not supported. {supported or 'Install the bf16, fp8_scaled or int8_convrot build, or a GGUF, instead.'}"@@ -2749,7 +2768,7 @@ class Main_Diffusers_QwenImage21_Config(Diffusers_Config_Base, Main_Config_Base,class Main_Checkpoint_QwenImage21_Config(Checkpoint_Config_Base, Main_Config_Base, Config_Base):- """Model config for Qwen-Image-2.1 single-file transformers (bf16, ComfyUI fp8 scaled or int8 convrot)."""+ """Model config for Qwen-Image-2.1 single-file transformers (bf16, ComfyUI fp8 scaled, torchao fp8 or int8 convrot)."""base: Literal[BaseModelType.QwenImage21] = Field(default=BaseModelType.QwenImage21)format: Literal[ModelFormat.Checkpoint] = Field(default=ModelFormat.Checkpoint)@@ -2766,7 +2785,7 @@ class Main_Checkpoint_QwenImage21_Config(Checkpoint_Config_Base, Main_Config_Basraise NotAMatchError("state dict does not look like a Qwen-Image-2.1 transformer")if _has_ggml_tensors(sd):raise NotAMatchError("state dict looks like GGUF quantized")- _raise_for_unsupported_comfy_quantization(mod, sd, "Qwen-Image-2.1")+ _raise_for_unsupported_comfy_quantization(mod, sd, "Qwen-Image-2.1", accepts_torchao_fp8=True)variant = override_fields.pop("variant", None) or _get_qwen_image21_variant_from_name(mod.path.name)diff --git a/invokeai/backend/model_manager/load/model_loaders/qwen_image_2_1.py b/invokeai/backend/model_manager/load/model_loaders/qwen_image_2_1.pyindex a26d788731..756e86bbc7 100644--- a/invokeai/backend/model_manager/load/model_loaders/qwen_image_2_1.py+++ b/invokeai/backend/model_manager/load/model_loaders/qwen_image_2_1.py@@ -24,6 +24,7 @@ from invokeai.backend.model_manager.util.qwen3_vl import drop_qwen3vl_visual_towfrom invokeai.backend.quantization.fp8_scaled import (attach_fp8_scales,cast_state_dict,+ clone_unreplaced_tensors,dequantize_fp8_scaled,extract_comfy_quant_hints,extract_fp8_scaled_layers,@@ -31,6 +32,7 @@ from invokeai.backend.quantization.fp8_scaled import (read_safetensors_metadata,split_fp8_scaled_layers,strip_layer_path_prefix,+ translate_torchao_fp8_layers,warn_on_unattached_scales,)from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader, unpack_ggml_at_load@@ -199,9 +201,9 @@ def _load_vision_tower(folder: Path, dtype: torch.dtype) -> torch.nn.Module:class QwenImage21CheckpointModel(ModelLoader):"""Loads a Qwen-Image-2.1 transformer from a single safetensors file.- Plain bf16/fp16 files, ComfyUI 'scaled fp8' (fp8 weights + `weight_scale`) and ComfyUI `int8_tensorwise`- (+convrot) files, with or without ComfyUI's prefix. The fused `img_mlp.gate_up` is split before any- quantization side channel is read, so every quantized layer names a diffusers Linear.+ Plain bf16/fp16 files, ComfyUI 'scaled fp8' (fp8 weights + `weight_scale`), unsloth's torchao fp8 (renamed to it)+ and ComfyUI `int8_tensorwise` (+convrot) files, with or without ComfyUI's prefix. The fused `img_mlp.gate_up` is+ split before any quantization side channel is read, so every quantized layer names a diffusers Linear."""def _load_model(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> AnyModel:@@ -217,6 +219,8 @@ class QwenImage21CheckpointModel(ModelLoader):sd = load_file(model_path)sd = CheckpointPrefix.detect(sd).strip(sd)+ # unsloth's torchao FP8 build, renamed to the ComfyUI scaled-fp8 form everything below reads.+ translate_torchao_fp8_layers(sd)header_layers = split_fused_layer_names(strip_layer_path_prefix(parse_quantization_metadata(read_safetensors_metadata(model_path, self._logger))))@@ -268,11 +272,17 @@ class QwenImage21CheckpointModel(ModelLoader):fp8_layers=fp8_layers,nvfp4_payloads={},)+ mapped = dict(sd) if fp8_layers and not keep_fp8 else Noneif fp8_layers and not keep_fp8:dequantize_fp8_scaled(sd, fp8_layers, model_dtype)fp8_layers = {}fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)kept = cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)+ if mapped is not None:+ # Parameters the fold and cast left as they were are slices of the file mapping and would pin it,+ # uncounted. Only on this path: kept fp8 codes stay mapped, as copying them would defeat the keep.+ clone_unreplaced_tensors(sd, mapped)+ mapped.clear()load_state_dict_ignoring_extras(model, sd, source="Qwen-Image-2.1 single-file checkpoint", assign=True, allow_missing=Truediff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.pyindex d86dbffe56..672fdda1f6 100644--- a/invokeai/backend/quantization/fp8_scaled.py+++ b/invokeai/backend/quantization/fp8_scaled.py@@ -513,6 +513,106 @@ def _normalize_weight_scale(scale: torch.Tensor) -> torch.Tensor:return scale.flatten()+TORCHAO_QDATA_SUFFIX = "._weight_qdata"+TORCHAO_SCALE_SUFFIX = "._weight_scale"+++def find_torchao_fp8_problem(sd: Mapping[Any, Any]) -> str | None:+ """Why ``sd`` holds torchao layers that cannot be translated, or None if it holds none or all are fine.++ torchao's serialized ``Float8Tensor`` (unsloth's FP8 builds) stores each quantized Linear as+ ``<layer>._weight_qdata`` (``float8_e4m3fn``, ``[out, in]``) plus ``<layer>._weight_scale`` (float32, one+ per output row) in place of ``<layer>.weight``. Only that layout is accepted; per-tensor and block-wise+ scales, int8 payloads (which add a ``_weight_zero_point``) and half-present pairs are named and refused+ rather than guessed at. Reads only key names, dtypes and shapes, so it also works on meta tensors.+ """+ keys = {key for key in sd if isinstance(key, str)}+ # Any other `<layer>._weight_<name>` (a zero point, `_weight_act_pre_scale`, ...) is state this decode does+ # not apply, and a loader that ignores extras would then compute the layer wrongly without saying so.+ extras = {+ layer: name+ for layer, sep, name in (key.rpartition("._weight_") for key in keys)+ if sep and name not in ("qdata", "scale")+ }+ for key in sorted(keys):+ if key.endswith(TORCHAO_SCALE_SUFFIX):+ layer = key[: -len(TORCHAO_SCALE_SUFFIX)]+ if layer + TORCHAO_QDATA_SUFFIX not in keys:+ return f"'{layer}' has a torchao scale but no quantized weight"+ continue+ if not key.endswith(TORCHAO_QDATA_SUFFIX):+ continue+ layer = key[: -len(TORCHAO_QDATA_SUFFIX)]+ qdata = sd[key]+ if layer in extras:+ if extras[layer] == "zero_point":+ return f"'{layer}' carries a zero point (an integer torchao quantization)"+ return f"'{layer}' carries torchao tensor '_weight_{extras[layer]}', which is not supported"+ if qdata.dtype != FP8_DTYPE:+ return f"'{layer}' is stored as {qdata.dtype}, not float8_e4m3fn"+ if qdata.dim() != 2:+ return f"'{layer}' has a {qdata.dim()}-D quantized weight, expected 2-D"+ if f"{layer}.weight" in keys:+ return f"'{layer}' has both a quantized and a plain weight"+ scale = sd.get(layer + TORCHAO_SCALE_SUFFIX)+ if scale is None:+ return f"'{layer}' has a quantized weight but no torchao scale"+ out = qdata.shape[0]+ if scale.dtype != torch.float32:+ return f"'{layer}' has a {scale.dtype} scale, expected float32"+ if tuple(scale.shape) not in ((out, 1), (out,)):+ return (+ f"'{layer}' has a scale of shape {tuple(scale.shape)}; only one scale per output row "+ f"({out} rows) is supported, not per-tensor or block-wise scales"+ )+ return None+++def translate_torchao_fp8_layers(sd: dict[Any, Any]) -> int:+ """Rename torchao fp8 layers in place to the ComfyUI scaled-fp8 form; return how many there were.++ ``<layer>._weight_qdata`` becomes ``<layer>.weight`` and ``<layer>._weight_scale`` becomes+ ``<layer>.weight_scale``, so the rest of the scaled-fp8 pipeline applies. Tensors are renamed,+ never copied.++ The scale is per output row. A loader that renames keys after translating must carry the scale along+ (:func:`detach_layer_sidechannel` / :func:`reattach_layer_sidechannel`), and anything that permutes a+ weight's rows must permute the scale the same way. A state dict without torchao keys is left alone (returns 0).++ Raises ``ValueError`` for a layout :func:`find_torchao_fp8_problem` names.+ """+ problem = find_torchao_fp8_problem(sd)+ if problem is not None:+ raise ValueError(f"Unsupported torchao fp8 checkpoint: {problem}.")+ layers = [+ key[: -len(TORCHAO_QDATA_SUFFIX)] for key in sd if isinstance(key, str) and key.endswith(TORCHAO_QDATA_SUFFIX)+ ]+ for layer in layers:+ sd[f"{layer}.weight"] = sd.pop(layer + TORCHAO_QDATA_SUFFIX)+ # torchao writes the per-row scale as `[out, 1]`. `_normalize_weight_scale` keeps a 2-D scale as+ # block-wise, which `is_matmul_usable_scale` rejects, and the split would then silently fold the+ # layer to bf16. Flat `[out]` is the per-output-channel form.+ sd[f"{layer}.weight_scale"] = sd.pop(layer + TORCHAO_SCALE_SUFFIX).reshape(-1)+ return len(layers)+++def clone_unreplaced_tensors(sd: dict[Any, Any], before: Mapping[Any, Any]) -> int:+ """Clone every tensor in ``sd`` that is still the very object ``before`` held; return how many.++ ``before`` is a shallow ``dict(sd)`` taken ahead of a fold and cast. Those leave a tensor in place when+ nothing needed changing (a bf16 weight cast to bf16 is the same object), and ``load_file`` tensors are slices of+ one file mapping, so each kept one pins the whole mapping for the model's cached life without the cache's size+ calculation seeing it. Tensors the fold or cast replaced are already fresh and are not copied again. Their+ storage cannot tell the two apart: every ``load_file`` tensor reports its own storage and size.+ """+ cloned = 0+ for key, tensor in sd.items():+ if before.get(key) is tensor and isinstance(tensor, torch.Tensor):+ sd[key] = tensor.clone()+ cloned += 1+ return cloned++def reject_undecoded_mx_scale(path: str, scale: Any) -> None:"""Refuse an MX exponent grid to anything that is about to multiply it as a number.diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex f366c16196..0b41473225 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -80266,7 +80266,7 @@"variant"],"title": "Main_Checkpoint_QwenImage21_Config",- "description": "Model config for Qwen-Image-2.1 single-file transformers (bf16, ComfyUI fp8 scaled or int8 convrot)."+ "description": "Model config for Qwen-Image-2.1 single-file transformers (bf16, ComfyUI fp8 scaled, torchao fp8 or int8 convrot)."},"Main_Checkpoint_QwenImage_Config": {"properties": {diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex 52e8097495..52664a986d 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -33346,7 +33346,7 @@ export type components = {};/*** Main_Checkpoint_QwenImage21_Config- * @description Model config for Qwen-Image-2.1 single-file transformers (bf16, ComfyUI fp8 scaled or int8 convrot).+ * @description Model config for Qwen-Image-2.1 single-file transformers (bf16, ComfyUI fp8 scaled, torchao fp8 or int8 convrot).*/Main_Checkpoint_QwenImage21_Config: {/**diff --git a/tests/backend/model_manager/configs/test_ideogram4_checkpoint_config.py b/tests/backend/model_manager/configs/test_ideogram4_checkpoint_config.pyindex 6093280855..c6f2ee37bb 100644--- a/tests/backend/model_manager/configs/test_ideogram4_checkpoint_config.py+++ b/tests/backend/model_manager/configs/test_ideogram4_checkpoint_config.py@@ -168,6 +168,18 @@ class TestRefusals:with pytest.raises(NotAMatchError, match="Ideogram 4 transformer"):_identify(_mod(sd))+ def test_rejects_torchao_tensors_its_loader_cannot_decode(self) -> None:+ sd = _state_dict(+ **{+ "layers.0.attention.qkv._weight_qdata": torch.zeros(24, 8, dtype=torch.float8_e4m3fn),+ "layers.0.attention.qkv._weight_scale": torch.ones(24, 1),+ }+ )+ del sd["layers.0.attention.qkv.weight"]++ with pytest.raises(InvalidMatchError, match="torchao"):+ _identify(_mod(sd))+def test_rejects_the_nvfp4_repack(self) -> None:# The released file keeps `input_proj` in fp8 and packs only the block linears, so the# refusal cannot key on one tensor's dtype -- and a packed nvfp4 weight is uint8, the samediff --git a/tests/backend/model_manager/configs/test_qwen_image_2_1_config.py b/tests/backend/model_manager/configs/test_qwen_image_2_1_config.pyindex a45a0fcdb6..1821cc9644 100644--- a/tests/backend/model_manager/configs/test_qwen_image_2_1_config.py+++ b/tests/backend/model_manager/configs/test_qwen_image_2_1_config.py@@ -95,16 +95,31 @@ def test_a_lora_with_norm_diffs_is_qwen_image_2_1(tmp_path: Path) -> None:assert _probe(LoRA_LyCORIS_QwenImage21_Config, sd, tmp_path)-def test_a_torchao_file_is_refused_at_install() -> None:- # unsloth's FP8 build: torchao Float8Tensors, saved as the payload and a per-row scale, no `.weight`.+def _torchao_layer(payload: torch.dtype = torch.float8_e4m3fn, **extra: Any) -> dict[str, Any]:+ """One layer as unsloth's torchao builds store it: the payload and a per-row scale, no `.weight`."""layer = "transformer_blocks.0.attn.to_q"- sd = _transformer(- **{- f"{layer}._weight_qdata": torch.zeros(8, 8, dtype=torch.float8_e4m3fn),- f"{layer}._weight_scale": torch.ones(8, 1),- }- )- with pytest.raises(InvalidMatchError, match="torchao"):+ return {+ f"{layer}._weight_qdata": torch.zeros(8, 8, dtype=payload),+ f"{layer}._weight_scale": torch.ones(8, 1),+ **{f"{layer}.{name}": value for name, value in extra.items()},+ }+++def test_unsloths_torchao_fp8_build_installs() -> None:+ config = _identify(_transformer(**_torchao_layer()), Path("Qwen-Image-2.1-FP8.safetensors"))+ assert config.base is BaseModelType.QwenImage21+++def test_unsloths_torchao_int8_build_is_refused_at_install() -> None:+ sd = _transformer(**_torchao_layer(torch.int8, _weight_zero_point=torch.zeros(8, 1, dtype=torch.int8)))+ with pytest.raises(InvalidMatchError, match="INT8"):+ _identify(sd, Path("Qwen-Image-2.1-INT8.safetensors"))+++def test_a_torchao_fp8_layout_the_loader_cannot_translate_is_refused_at_install() -> None:+ sd = _transformer(**_torchao_layer())+ sd["transformer_blocks.0.attn.to_q._weight_scale"] = torch.ones(8, 2)+ with pytest.raises(InvalidMatchError, match="transformer_blocks.0.attn.to_q"):_identify(sd, Path("Qwen-Image-2.1-FP8.safetensors"))diff --git a/tests/backend/model_manager/load/test_qwen_image_2_1_torchao_loader.py b/tests/backend/model_manager/load/test_qwen_image_2_1_torchao_loader.pynew file mode 100644index 0000000000..c1b272fa07--- /dev/null+++ b/tests/backend/model_manager/load/test_qwen_image_2_1_torchao_loader.py@@ -0,0 +1,160 @@+"""Qwen-Image-2.1's single-file loader reads unsloth's torchao FP8 build as a ComfyUI scaled-fp8 checkpoint.++The file stores each quantized Linear as `<layer>._weight_qdata` plus a `[out, 1]` scale. What these tests pin is the+end state of the module: the layer keeps its fp8 codes with a flat per-row scale when something uses fp8, and is folded+to exactly `codes * scale` when nothing does.+"""++import pytest+import safetensors.torch+import torch++from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettings+from invokeai.backend.model_manager.configs.main import Main_Checkpoint_QwenImage21_Config+from invokeai.backend.model_manager.load import load_default+from invokeai.backend.model_manager.load.model_loaders import qwen_image_2_1+from invokeai.backend.model_manager.load.model_loaders.qwen_image_2_1 import QwenImage21CheckpointModel+from invokeai.backend.model_manager.taxonomy import SubModelType+from tests.fixtures.loader_seams import Seam, prepare++FP8 = torch.float8_e4m3fn+++class _TinyTransformer(torch.nn.Module):+ """The module paths of the released model that matter here, at toy width: a quantized attention Linear, the+ `norm_out.linear` that matches the `norm` skip pattern, and a dense input projection."""++ _skip_layerwise_casting_patterns = ["norm"]++ def __init__(self) -> None:+ super().__init__()+ block = torch.nn.Module()+ block.attn = torch.nn.Module()+ block.attn.to_q = torch.nn.Linear(16, 32)+ block.img_mlp = torch.nn.Module()+ block.img_mlp.gate_layer = torch.nn.Linear(16, 32)+ block.img_mlp.proj = torch.nn.Linear(16, 32)+ self.transformer_blocks = torch.nn.ModuleList([block])+ self.norm_out = torch.nn.Module()+ self.norm_out.linear = torch.nn.Linear(16, 32)+ self.img_in = torch.nn.Linear(16, 32)+++SEAM = Seam(+ loader=QwenImage21CheckpointModel,+ module=qwen_image_2_1,+ entry="_load_model",+ compute_dtype=torch.bfloat16,+ # The loader imports `load_file` inside the method, so the name it resolves is the package's.+ load_file_host=safetensors.torch,+ patches_device=True,+)++QUANTIZED = ("transformer_blocks.0.attn.to_q", "norm_out.linear")+# ComfyUI-layout fused projection, gate rows first; the loader splits it into `gate_layer` and `proj`.+FUSED = "transformer_blocks.0.img_mlp.gate_up"+++def _checkpoint() -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor], dict[str, torch.Tensor]]:+ """The file's tensors, its codes and its per-row scales, keyed by layer path."""+ torch.manual_seed(0)+ state_dict: dict[str, torch.Tensor] = {+ # Already in the compute dtype, so the cast leaves them as they are.+ "img_in.weight": torch.randn(32, 16).to(torch.bfloat16),+ "img_in.bias": torch.randn(32).to(torch.bfloat16),+ }+ codes: dict[str, torch.Tensor] = {}+ scales: dict[str, torch.Tensor] = {}+ for path in QUANTIZED:+ codes[path] = (torch.randn(32, 16) * 40).to(FP8)+ scales[path] = torch.rand(32, 1) + 0.5+ state_dict[f"{path}._weight_qdata"] = codes[path]+ state_dict[f"{path}._weight_scale"] = scales[path]+ state_dict[f"{path}.bias"] = torch.randn(32)+ codes[FUSED] = (torch.randn(64, 16) * 40).to(FP8)+ scales[FUSED] = torch.rand(64, 1) + 0.5+ state_dict[f"{FUSED}._weight_qdata"] = codes[FUSED]+ state_dict[f"{FUSED}._weight_scale"] = scales[FUSED]+ state_dict[f"{FUSED}.bias"] = torch.randn(64)+ return {f"model.diffusion_model.{key}": value for key, value in state_dict.items()}, codes, scales+++def _load(+ monkeypatch: pytest.MonkeyPatch, tmp_path, *, keep_fp8: bool+) -> tuple[torch.nn.Module, dict[str, torch.Tensor]]:+ """The model, and the tensors `load_file` returned for the real file the loader read."""+ state_dict, _, _ = _checkpoint()+ checkpoint = tmp_path / "Qwen-Image-2.1-FP8.safetensors"+ safetensors.torch.save_file(state_dict, checkpoint)+ loaded: dict[str, torch.Tensor] = {}+ real_load_file = safetensors.torch.load_file++ def recording_load_file(path):+ tensors = real_load_file(path)+ loaded.update(tensors)+ return tensors++ monkeypatch.setattr(safetensors.torch, "load_file", recording_load_file)+ config = Main_Checkpoint_QwenImage21_Config.model_construct(+ path=str(checkpoint), name="qwen21", default_settings=MainModelDefaultSettings(fp8_storage=False)+ )++ def install(patch: pytest.MonkeyPatch) -> None:+ patch.setattr(load_default, "should_keep_fp8_weights", lambda _device: keep_fp8)+ patch.setattr(qwen_image_2_1, "_build_transformer", lambda _sd: _TinyTransformer())++ run = prepare(SEAM, monkeypatch, metadata=None, geometry=install)+ return run.load(config, SubModelType.Transformer), loaded+++def test_the_fp8_layers_stay_quantized_with_a_flat_per_row_scale(monkeypatch, tmp_path) -> None:+ model, _ = _load(monkeypatch, tmp_path, keep_fp8=True)+ _, codes, scales = _checkpoint()++ layer = model.transformer_blocks[0].attn.to_q+ assert layer.weight.dtype is FP8+ assert torch.equal(layer.weight.view(torch.uint8), codes["transformer_blocks.0.attn.to_q"].view(torch.uint8))+ assert layer.weight_scale.shape == (32,)+ assert torch.equal(layer.weight_scale, scales["transformer_blocks.0.attn.to_q"].reshape(-1))+ # The fused projection is split after the translation: each half keeps its rows' codes and scales.+ mlp = model.transformer_blocks[0].img_mlp+ for half, rows in ((mlp.gate_layer, slice(0, 32)), (mlp.proj, slice(32, 64))):+ assert half.weight.dtype is FP8+ assert torch.equal(half.weight.view(torch.uint8), codes[FUSED][rows].view(torch.uint8))+ assert half.weight_scale.shape == (32,)+ assert torch.equal(half.weight_scale, scales[FUSED][rows].reshape(-1))+ # `norm_out.linear` matches the `norm` skip pattern, so it is folded with its scale rather than kept.+ assert model.norm_out.linear.weight.dtype is torch.bfloat16+ assert model.img_in.weight.dtype is torch.bfloat16++[email protected]("keep_fp8", [True, False])+def test_a_folded_layer_is_exactly_the_codes_times_the_scale(monkeypatch, tmp_path, keep_fp8: bool) -> None:+ model, _ = _load(monkeypatch, tmp_path, keep_fp8=keep_fp8)+ _, codes, scales = _checkpoint()++ folded = codes["norm_out.linear"].float() * scales["norm_out.linear"]+ assert torch.equal(model.norm_out.linear.weight, folded.to(torch.bfloat16))+ if not keep_fp8:+ assert model.transformer_blocks[0].attn.to_q.weight.dtype is torch.bfloat16+++PREFIX = "model.diffusion_model."+++def test_a_folded_load_does_not_leave_parameters_pinning_the_file_mapping(monkeypatch, tmp_path) -> None:+ """`img_in` is stored in the compute dtype, so neither the fold nor the cast replaces it; assigned as a parameter it+ would be a slice of the file's mapping, which the cache's size calculation cannot see."""+ model, loaded = _load(monkeypatch, tmp_path, keep_fp8=False)++ for name in ("img_in.weight", "img_in.bias"):+ parameter = model.get_parameter(name)+ assert parameter.data_ptr() != loaded[PREFIX + name].data_ptr(), name+ assert torch.equal(parameter, loaded[PREFIX + name])+++def test_a_kept_fp8_load_does_not_copy_the_codes(monkeypatch, tmp_path) -> None:+ model, loaded = _load(monkeypatch, tmp_path, keep_fp8=True)++ codes = model.transformer_blocks[0].attn.to_q.weight+ assert codes.data_ptr() == loaded[PREFIX + "transformer_blocks.0.attn.to_q._weight_qdata"].data_ptr()diff --git a/tests/backend/quantization/test_fp8_scaled.py b/tests/backend/quantization/test_fp8_scaled.pyindex 15ed5cad8d..b888683fd9 100644--- a/tests/backend/quantization/test_fp8_scaled.py+++ b/tests/backend/quantization/test_fp8_scaled.py@@ -23,6 +23,7 @@ from invokeai.backend.quantization.fp8_scaled import (expand_weight_scale,extract_comfy_quant_hints,extract_fp8_scaled_layers,+ find_torchao_fp8_problem,forget_inconclusive_fp8_matmul_probe,is_matmul_usable_scale,is_scale_metadata_key,@@ -37,6 +38,7 @@ from invokeai.backend.quantization.fp8_scaled import (should_keep_fp8_weights,split_fp8_scaled_layers,strip_layer_path_prefix,+ translate_torchao_fp8_layers,warn_on_unattached_scales,)from tests.fixtures.quantized_payloads import (@@ -1679,3 +1681,97 @@ class TestTheDecodeWidensTheGridOutsideThisPrediction:predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=True, model=model, scaled_layers=layers)== sd["lin.weight"].nelement() * 2)+++def _torchao_layer(layer: str, out_f: int = 32, in_f: int = 16) -> tuple[dict[str, torch.Tensor], torch.Tensor]:+ """One layer as unsloth's torchao FP8 build stores it, and the weight it means (`q.float() * scale`)."""+ torch.manual_seed(0)+ q = (torch.randn(out_f, in_f) * 40).to(FP8_DTYPE)+ scale = torch.rand(out_f, 1) + 0.5+ return {f"{layer}._weight_qdata": q, f"{layer}._weight_scale": scale}, q.float() * scale+++class TestTorchaoFp8:+ def test_a_translated_layer_dequantizes_to_the_weight_the_file_means(self) -> None:+ sd, meant = _torchao_layer("lin")++ assert translate_torchao_fp8_layers(sd) == 1++ assert set(sd) == {"lin.weight", "lin.weight_scale"}+ layers = extract_fp8_scaled_layers(sd)+ dequantize_fp8_scaled(sd, layers, torch.float32)+ assert torch.equal(sd["lin.weight"], meant)++ def test_a_translated_layer_stays_fp8_with_a_flat_scale_through_the_split(self) -> None:+ """The `[out, 1]` scale reads as block-wise unless flattened; the split would then fold the layer to bf16."""+ sd, meant = _torchao_layer("lin")+ model = torch.nn.Sequential()+ model.add_module("lin", torch.nn.Linear(16, 32))+ translate_torchao_fp8_layers(sd)+ layers = extract_fp8_scaled_layers(sd)++ assert layers["lin"].weight_scale.shape == (32,)+ kept = split_fp8_scaled_layers(sd, layers, torch.bfloat16, model=model)++ assert set(kept) == {"lin"}+ assert sd["lin.weight"].dtype is FP8_DTYPE+ assert torch.equal(dequantize_weight(sd["lin.weight"], kept["lin"].weight_scale, torch.float32), meant)++ @pytest.mark.parametrize("scale_shape", [(32, 1), (32,)])+ def test_a_per_row_scale_is_accepted_flat_or_not(self, scale_shape: tuple[int, ...]) -> None:+ sd, _ = _torchao_layer("lin")+ sd["lin._weight_scale"] = sd["lin._weight_scale"].reshape(scale_shape)+ assert find_torchao_fp8_problem(sd) is None++ def test_a_state_dict_without_torchao_keys_has_nothing_to_translate(self) -> None:+ sd = {"lin.weight": torch.zeros(4, 4), 7: torch.zeros(1)}+ assert find_torchao_fp8_problem(sd) is None+ assert translate_torchao_fp8_layers(sd) == 0+ assert set(sd) == {"lin.weight", 7}++ @pytest.mark.parametrize(+ ("label", "edit", "fragment"),+ [+ ("int8 payload", lambda sd: sd.update({"b._weight_qdata": torch.zeros(32, 16, dtype=torch.int8)}), "int8"),+ (+ "zero point",+ lambda sd: sd.update({"b._weight_zero_point": torch.zeros(32, 1, dtype=torch.int8)}),+ "zero point",+ ),+ ("per-tensor scale", lambda sd: sd.update({"b._weight_scale": torch.ones(1)}), "per-tensor"),+ ("block-wise scale", lambda sd: sd.update({"b._weight_scale": torch.ones(32, 4)}), "block-wise"),+ ("half precision scale", lambda sd: sd.update({"b._weight_scale": torch.ones(32, 1).half()}), "float32"),+ ("orphaned payload", lambda sd: sd.pop("b._weight_scale"), "no torchao scale"),+ ("orphaned scale", lambda sd: sd.pop("b._weight_qdata"), "no quantized weight"),+ (+ "torchao tensor this decode does not apply",+ lambda sd: sd.update({"b._weight_act_pre_scale": torch.ones(16)}),+ "_weight_act_pre_scale",+ ),+ ("plain weight beside it", lambda sd: sd.update({"b.weight": torch.zeros(32, 16)}), "plain weight"),+ (+ "3-D payload",+ lambda sd: sd.update({"b._weight_qdata": torch.zeros(32, 4, 4).to(FP8_DTYPE)}),+ "3-D",+ ),+ ],+ )+ def test_anything_but_the_per_row_fp8_layout_is_refused_by_name(self, label: str, edit, fragment: str) -> None:+ # A good layer sorts before the bad one: a check that stops at the first layer would pass.+ sd = {**_torchao_layer("a")[0], **_torchao_layer("b")[0]}+ edit(sd)+ before = dict(sd)++ problem = find_torchao_fp8_problem(sd)++ assert problem is not None and "'b'" in problem and fragment in problem, label+ with pytest.raises(ValueError, match="torchao"):+ translate_torchao_fp8_layers(sd)+ assert sd == before, "a refused state dict must be left as it was"++ def test_identification_can_check_meta_tensors(self) -> None:+ sd, _ = _torchao_layer("a")+ meta = {key: value.to("meta") for key, value in sd.items()}+ assert find_torchao_fp8_problem(meta) is None+ meta["a._weight_scale"] = torch.empty(32, 4, device="meta")+ assert find_torchao_fp8_problem(meta) is not None