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(flux3): load unsloth's diffusers-named torchao fp8 build (#10182)
Alexander Eichhornb038aa75d354
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 78a40a013c..8bf0218f5c 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@@ -19,9 +19,10 @@ speeds are on each family's own page.- ✗ not supported- – no such build exists-How an unsupported file fails depends on the file. Some are not recognized at all and install as an unknown model,-with the reason only in the server log: the Diffusers layout of LTX-2, the GGUF builds of MiniMax H3, and llama.cpp-GGUFs of Mistral Small 3's shape that declare scaled RoPE or an attention temperature, such as Devstral Small 2.+How an unsupported file fails depends on the file. Some are not recognized at all and install as an unknown model, with+the reason only in the server log: the Diffusers layout of LTX-2, Diffusers-named FLUX.3 single files that are not+torchao exports, the GGUF builds of MiniMax H3, and llama.cpp GGUFs of Mistral Small 3's shape that declare scaled RoPE+or an attention temperature, such as Devstral Small 2.Others are recognized by their layer names and fail, or misbehave, only when they load.Any GGUF, of any model, is refused at install with a message in two cases. A multi-part GGUF (llama.cpp's@@ -56,13 +57,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, 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.+ AWQ and other producers' nvfp4 at install. For Qwen-Image-2.1 and FLUX.3, unsloth's torchao FP8 builds (fp8 weights+ with one scale per output row; FLUX.3's under diffusers' key names) load as fp8 scaled; other torchao layouts, such+ as per-tensor or block-wise fp8 and INT8 builds, are refused 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/flux-3.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-3.mdxindex b44e67b6ff..9b3ab4d493 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-3.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-3.mdx@@ -1,7 +1,7 @@---title: FLUX.3description: Generate and edit images with FLUX.3 Image Klein (step-distilled) and Klein Base, including editing with up to ten reference images, LoRAs, layout boxes from Canvas regional guidance and the GGUF, single-file and quantized builds.-lastUpdated: 2026-11-03+lastUpdated: 2026-11-06sidebar:order: 6---@@ -118,6 +118,13 @@ extra pass over the weights on every load.installing it switches on, or with `fp8_compute`, the weights stay fp8; otherwise they are expanded to bf16 as themodel loads.+- **unsloth's FP8 build** (`flux-3-image-klein-FP8.safetensors`, Klein only) is fp8 with one scale per output row,+ saved under Diffusers' key names, and behaves like fp8r: on a GPU with fp8 support it stays fp8 with FP8 Storage or+ [`fp8_compute`](/configuration/optimization/fp8-compute/) (with `fp8_compute` on fp8 hardware the+ matmul runs directly on the fp8 weights), and it is expanded to bf16 as the model loads otherwise. unsloth's INT8 build and other+ torchao layouts, such as per-tensor or block-wise fp8, are refused at install with a message saying why. A+ Diffusers-named file that is not a torchao export is not recognized.+FP8 Storage does not apply to the int8 and nvfp4 builds: their quantized layers are smaller already, and the layersthey keep in bf16 stay bf16. The Model Manager can still show the toggle as on for an nvfp4 build, because installingswitches it on for any file holding fp8 numbers, and nvfp4's block scales are fp8. It has no effect there. Otherdiff --git a/invokeai/backend/flux3/checkpoint_quantization.py b/invokeai/backend/flux3/checkpoint_quantization.pyindex 63e20e932e..503b722eab 100644--- a/invokeai/backend/flux3/checkpoint_quantization.py+++ b/invokeai/backend/flux3/checkpoint_quantization.py@@ -6,8 +6,9 @@ picture and get the same answer, so a file installs exactly when the loader canat install with the reason rather than failing at the first render.The builds that load are Black Forest Labs' bf16 file with its ``variants/fp8r`` (fp8 with one scale per row) and-``variants/nvfp4`` (NVIDIA ModelOpt's layout), and Comfy-Org's bf16, ``int8_convrot`` and nvfp4 repackages. None of-them mixes two schemes. A file mixing int8 with nvfp4 or with scaled fp8 is refused rather than supported on+``variants/nvfp4`` (NVIDIA ModelOpt's layout), Comfy-Org's bf16, ``int8_convrot`` and nvfp4 repackages, and unsloth's+torchao FP8 build (float8_e4m3fn with one scale per output row, under diffusers' key names). None of them mixes two+schemes. A file mixing int8 with nvfp4 or with scaled fp8 is refused rather than supported onspeculation; nvfp4 beside scaled fp8 loads, since the loader takes each of them its own way."""@@ -16,8 +17,11 @@ from typing import Anyimport torch+from invokeai.backend.flux3.conversion import is_flux3_diffusers_layoutfrom invokeai.backend.quantization.fp8_scaled import (FP8_WEIGHT_DTYPES,+ TORCHAO_QDATA_SUFFIX,+ find_torchao_fp8_problem,iter_weight_scale_pairs,parse_quantization_metadata,strip_layer_path_prefix,@@ -43,8 +47,6 @@ _INPUT_WIDTH_WEIGHTS = ("emb_in.image.weight", "emb_in.image_cond.weight", "txt_# bitsandbytes keeps a 4-bit layer's quantization state beside its packed `uint8` weight._BITSANDBYTES_STATE = (".absmax", ".quant_map", ".quant_state")-_TORCHAO_PAYLOAD_SUFFIX = "._weight_qdata"-def flux3_header_layers(metadata: Mapping[str, Any] | None, keys: Collection[Any]) -> dict[str, Any]:"""The layers a FLUX.3 file's header names, under the prefix-stripped names in ``keys``: ComfyUI's@@ -61,13 +63,14 @@ def reject_unloadable_quantization() -> None:"""Refuse a FLUX.3 single file whose quantization the loader cannot build, naming the reason (ValueError).- ``state_dict`` holds the file's tensors under their prefix-stripped native names; meta tensors will do, since names,- dtypes and shapes are all that is read. ``header_layers`` is :func:`flux3_header_layers` of it, and ``markers`` are- its ``.comfy_quant`` markers, decoded, by layer.+ ``state_dict`` holds the file's tensors under their prefix-stripped names, native or, for the torchao build,+ diffusers'; meta tensors will do, since names, dtypes and shapes are all that is read. ``header_layers`` is+ :func:`flux3_header_layers` of it, and ``markers`` are its ``.comfy_quant`` markers, decoded, by layer.Each refusal is of a file that would otherwise load and generate noise, or fail mid-render:- - torchao's tensor subclasses, which leave no ``.weight`` to load;+ - torchao's tensor subclasses that ``translate_torchao_fp8_layers`` cannot rename to scaled fp8+ (:func:`find_torchao_fp8_problem`: INT8, per-tensor or block-wise scales, half-present pairs);- bitsandbytes 4-bit state, and any packed ``uint8`` weight that is not a named nvfp4 layer;- an fp8 weight scale in a spelling the key conversion does not carry, which would be left behind as its weight isrenamed, and the weight loaded unscaled (AWQ's ``pre_quant_scale`` beside an fp8 weight among them);@@ -76,15 +79,22 @@ def reject_unloadable_quantization(rotation group that is not a power of 4 or does not divide the input width);- what :func:`find_nvfp4_layers` refuses: AWQ, nvfp4 layers no header or marker names, malformed or half-storedones;- - int8 mixed with nvfp4 or with scaled fp8;+ - torchao tensors under Black Forest Labs' key names;+ - int8 mixed with nvfp4, scaled fp8 or torchao, and torchao mixed with nvfp4;- packed input embedders, whose stored width is not the model's."""+ if problem := find_torchao_fp8_problem(state_dict):+ raise ValueError(+ f"This FLUX.3 file is saved as torchao-quantized tensors that InvokeAI cannot load: {problem}. Only "+ "torchao float8_e4m3fn weights with one scale per output row load, as in unsloth's FP8 build. A file "+ f"missing one half of a weight/scale pair is probably incomplete: download it again. {_INSTEAD}"+ )keys = list(state_dict)- torchao = sorted(key for key in keys if key.endswith(_TORCHAO_PAYLOAD_SUFFIX))- if torchao:+ torchao = sorted(key for key in keys if key.endswith(TORCHAO_QDATA_SUFFIX))+ if torchao and not is_flux3_diffusers_layout(state_dict):raise ValueError(- f"This FLUX.3 file is saved as torchao-quantized tensors (e.g. '{torchao[0]}'), which is not supported. "- f"{_INSTEAD}"+ f"This FLUX.3 file is saved as torchao-quantized tensors (e.g. '{torchao[0]}') under Black Forest Labs' "+ "key names. Only unsloth's FP8 build, which uses diffusers' key names, loads. " + _INSTEAD)bitsandbytes = sorted(key for key in keys if any(state in key for state in _BITSANDBYTES_STATE))if bitsandbytes:@@ -123,8 +133,14 @@ def reject_unloadable_quantization(f"'{packed[0]}'), a packing InvokeAI does not read, such as bitsandbytes NF4. {_INSTEAD}")+ if int8_markers and torchao:+ raise ValueError(f"This FLUX.3 file mixes int8 and torchao layers, which no release does. {_INSTEAD}")if int8_markers and nvfp4:raise ValueError(f"This FLUX.3 file mixes int8 and nvfp4 layers, which no release does. {_INSTEAD}")+ if torchao and nvfp4:+ # The nvfp4 re-layout reads Black Forest Labs' names; under diffusers' it would swap the halves of rows that are+ # already in diffusers' order, and the image would be noise.+ raise ValueError(f"This FLUX.3 file mixes torchao and nvfp4 layers, which no release does. {_INSTEAD}")if int8_markers:scaled_fp8 = sorted(weight_keydiff --git a/invokeai/backend/flux3/conversion.py b/invokeai/backend/flux3/conversion.pyindex 723388e333..02e9307c65 100644--- a/invokeai/backend/flux3/conversion.py+++ b/invokeai/backend/flux3/conversion.py@@ -1,10 +1,11 @@"""Native FLUX.3 state dicts, converted to diffusers' ``Flux3Transformer2DModel``.-Every single-file FLUX.3 build InvokeAI loads uses Black Forest Labs' own key names: BFL's-``model.safetensors`` and its quantized ``variants/``, the ComfyUI repackages, and the GGUF conversions. The-renames are a port of diffusers' ``convert_flux3_transformer_checkpoint_to_diffusers`` (``single_file_utils.py``-in diffusers 0.42.1). Reading the structure from the weights, rather than assuming the released one, is-InvokeAI's: a finetune that changes the depth must not load as the first N blocks of the released model.+Every single-file FLUX.3 build InvokeAI loads uses Black Forest Labs' own key names -- BFL's ``model.safetensors`` and+its quantized ``variants/``, the ComfyUI repackages, and the GGUF conversions -- except unsloth's torchao FP8 build,+which is saved under diffusers' names and is not converted (:func:`is_flux3_diffusers_layout`). The renames are a port+of diffusers' ``convert_flux3_transformer_checkpoint_to_diffusers`` (``single_file_utils.py`` in diffusers 0.42.1).+Reading the structure from the weights, rather than assuming the released one, is InvokeAI's: a finetune that changes+the depth must not load as the first N blocks of the released model.Comfy-Org's ``int8_convrot`` build fuses each block's query, key and value into one ``qkv`` linear, whichdiffusers keeps apart: it is split here, its quantization side channel with it. Where a native module lands is a@@ -277,20 +278,31 @@ def _count_blocks(state_dict: Mapping[str, Any], prefix: str) -> int:return len(indices)-def flux3_transformer_config(state_dict: Mapping[str, Any]) -> dict[str, Any]:- """The ``Flux3Transformer2DModel`` config of a native FLUX.3 state dict, read from its tensor shapes.+def is_flux3_diffusers_layout(state_dict: Mapping[str, Any]) -> bool:+ """Whether a state dict already uses diffusers' names, as unsloth's torchao FP8 build does, rather than BFL's.++ Such a file needs no conversion: its rows are in diffusers' order too, so the output adaLN must not be swapped.+ """+ return "x_embedders.image.weight" in state_dict- Only shapes are read, so this works on meta tensors and on packed GGUF tensors alike. The feedforward width is- taken from ``mlp_in``'s output rows, which no supported quantization packs. A loader that takes packed nvfp4- layers out of the state dict reads this first: ``mlp_in`` is one of them. The input widths are read off the- embedders, which no supported build packs (``flux3/checkpoint_quantization.py`` refuses one that does).++def flux3_transformer_config(state_dict: Mapping[str, Any]) -> dict[str, Any]:+ """The ``Flux3Transformer2DModel`` config of a FLUX.3 state dict, read from its tensor shapes.++ Native (BFL) names, or diffusers' where :func:`is_flux3_diffusers_layout` says so: every key is looked up under+ the name the file uses. Only shapes are read, so this works on meta tensors and on packed GGUF tensors alike. The+ feedforward width is taken from ``mlp_in``'s output rows, which no supported quantization packs. A loader that+ takes packed nvfp4 layers out of the state dict reads this first: ``mlp_in`` is one of them. The input widths are+ read off the embedders, which no supported build packs (``flux3/checkpoint_quantization.py`` refuses one that+ does)."""- hidden_size, in_channels = _shape(state_dict, "emb_in.image.weight")- cond_in_channels = _shape(state_dict, "emb_in.image_cond.weight")[1]- joint_attention_dim = _shape(state_dict, "txt_in.weight")[1]- timestep_channels = _shape(state_dict, "time_in.in_layer.weight")[1]- head_dim = _shape(state_dict, "single_blocks.0.norm.query_norm.scale")[0]- mlp_hidden = _shape(state_dict, "single_blocks.0.mlp_in.weight")[0] // 2+ name = flux3_native_key_to_diffusers if is_flux3_diffusers_layout(state_dict) else str+ hidden_size, in_channels = _shape(state_dict, name("emb_in.image.weight"))+ cond_in_channels = _shape(state_dict, name("emb_in.image_cond.weight"))[1]+ joint_attention_dim = _shape(state_dict, name("txt_in.weight"))[1]+ timestep_channels = _shape(state_dict, name("time_in.in_layer.weight"))[1]+ head_dim = _shape(state_dict, name("single_blocks.0.norm.query_norm.scale"))[0]+ mlp_hidden = _shape(state_dict, name("single_blocks.0.mlp_in.weight"))[0] // 2if hidden_size % head_dim != 0:raise ValueError(f"FLUX.3 hidden size {hidden_size} is not a multiple of its head width {head_dim}.")@@ -300,9 +312,9 @@ def flux3_transformer_config(state_dict: Mapping[str, Any]) -> dict[str, Any]:"released checkpoint; this checkpoint is not supported.")- num_layers = _count_blocks(state_dict, "txt_mode_blocks.")+ num_layers = _count_blocks(state_dict, name("txt_mode_blocks."))for mode in ("image", "image_cond"):- mode_layers = _count_blocks(state_dict, f"content_mode_blocks.{mode}.")+ mode_layers = _count_blocks(state_dict, name(f"content_mode_blocks.{mode}."))if mode_layers != num_layers:raise ValueError(f"The FLUX.3 checkpoint has {mode_layers} '{mode}' blocks but {num_layers} text blocks; the per-mode "@@ -313,12 +325,12 @@ def flux3_transformer_config(state_dict: Mapping[str, Any]) -> dict[str, Any]:"in_channels": in_channels,"cond_in_channels": cond_in_channels,"num_layers": num_layers,- "num_single_layers": _count_blocks(state_dict, "single_blocks."),+ "num_single_layers": _count_blocks(state_dict, name("single_blocks.")),"attention_head_dim": head_dim,"num_attention_heads": hidden_size // head_dim,"joint_attention_dim": joint_attention_dim,"timestep_channels": timestep_channels,"mlp_ratio": mlp_hidden / hidden_size,"axes_dims_rope": FLUX3_AXES_DIMS_ROPE,- "flow_map": FLUX3_NATIVE_FLOW_MAP_KEY in state_dict,+ "flow_map": name(FLUX3_NATIVE_FLOW_MAP_KEY) in state_dict,}diff --git a/invokeai/backend/model_manager/configs/main.py b/invokeai/backend/model_manager/configs/main.pyindex a17e3553b5..59a41a70fc 100644--- a/invokeai/backend/model_manager/configs/main.py+++ b/invokeai/backend/model_manager/configs/main.py@@ -17,6 +17,7 @@ from invokeai.backend.flux.controlnet.state_dict_utils import (is_state_dict_xlabs_controlnet,)from invokeai.backend.flux3.checkpoint_quantization import flux3_header_layers, reject_unloadable_quantization+from invokeai.backend.flux3.conversion import FLUX3_NATIVE_FLOW_MAP_KEY, flux3_native_key_to_diffusersfrom invokeai.backend.ltx2 import checkpoint_layout as ltx2_layoutfrom invokeai.backend.model_manager.checkpoint_prefix import COMFYUI_KEY_PREFIXES, CheckpointPrefixfrom invokeai.backend.model_manager.configs.base import (@@ -2374,27 +2375,44 @@ _FLUX3_LORA_SUFFIXES = (def _has_flux3_keys(state_dict: dict[str | int, Any]) -> bool:- """True for a FLUX.3 Image transformer in Black Forest Labs' native layout, False for its LoRAs.+ """True for a FLUX.3 Image transformer, False for its LoRAs.- The per-mode stage before the joint blocks is unique to FLUX.3: `content_mode_blocks.<mode>.N` and- `early_stream_modulations`. FLUX.1 and FLUX.2 have `double_blocks`, Krea-2 `text_fusion`. ComfyUI's key- prefixes are tolerated; the BFL file and the ComfyUI repackage are byte-identical and carry none. torchao's- spelling of the modulation's weight is accepted too, so that such an export reaches its refusal rather than- installing as an unknown model.+ Black Forest Labs' native layout is recognized by the per-mode stage before the joint blocks, which is unique to+ FLUX.3: `content_mode_blocks.<mode>.N` and `early_stream_modulations`. FLUX.1 and FLUX.2 have `double_blocks`,+ Krea-2 `text_fusion`. ComfyUI's key prefixes are tolerated; the BFL file and the ComfyUI repackage are+ byte-identical and carry none. torchao's spelling of the modulation's weight is accepted too, so that an+ export the loader cannot read reaches its refusal rather than installing as an unknown model.++ unsloth's torchao FP8 build uses diffusers' names (`mode_blocks`, `early_stream_modulations.<mode>.linear`). That+ layout is recognized only beside torchao payloads: no other single-file FLUX.3 build is saved that way, and the+ loader reads it only on that route."""keys = [_strip_comfyui_key_prefix(key) for key in state_dict if isinstance(key, str)]if any(key.endswith(_FLUX3_LORA_SUFFIXES) for key in keys):return Falsekey_set = set(keys)- return any(+ if any(f"early_stream_modulations.image.lin.{parameter}" in key_set for parameter in ("weight", "_weight_qdata")- ) and any(key.startswith("content_mode_blocks.image.") for key in keys)+ ) and any(key.startswith("content_mode_blocks.image.") for key in keys):+ return True+ return (+ any(+ f"early_stream_modulations.image.linear.{parameter}" in key_set for parameter in ("weight", "_weight_qdata")+ )+ and any(key.startswith("mode_blocks.image.") for key in keys)+ and any(key.endswith(TORCHAO_QDATA_SUFFIX) for key in keys)+ )def _get_flux3_variant(state_dict: dict[str | int, Any]) -> Flux3VariantType:"""The step-distilled checkpoint has a second timestep embedder; the Base model does not."""keys = {_strip_comfyui_key_prefix(key) for key in state_dict if isinstance(key, str)}- return Flux3VariantType.Klein if "ref_time_in.in_layer.weight" in keys else Flux3VariantType.KleinBase+ flow_map_weights = {FLUX3_NATIVE_FLOW_MAP_KEY, flux3_native_key_to_diffusers(FLUX3_NATIVE_FLOW_MAP_KEY)}+ # torchao stores a quantized weight under `_weight_qdata`, in place of `.weight`.+ flow_map_keys = flow_map_weights | {+ f"{key.removesuffix('.weight')}{TORCHAO_QDATA_SUFFIX}" for key in flow_map_weights+ }+ return Flux3VariantType.Klein if keys & flow_map_keys else Flux3VariantType.KleinBaseclass Main_Diffusers_Flux3_Config(Diffusers_Config_Base, Main_Config_Base, Config_Base):@@ -2448,8 +2466,9 @@ class Main_Checkpoint_Flux3_Config(Checkpoint_Config_Base, Main_Config_Base, Con"""Model config for FLUX.3 Image single-file transformers.BFL's `model.safetensors` and its quantized `variants/fp8r` (per-row scaled fp8) and `variants/nvfp4` (NVIDIA- ModelOpt layout), and Comfy-Org's bf16, `int8_convrot` and nvfp4 repackages. The record is the same for all of- them: the loader reads the scheme off the file.+ ModelOpt layout), Comfy-Org's bf16, `int8_convrot` and nvfp4 repackages, and unsloth's torchao FP8 build (diffusers+ key names, one scale per output row). The record is the same for all of them: the loader reads the scheme off the+ file."""base: Literal[BaseModelType.Flux3] = Field(default=BaseModelType.Flux3)diff --git a/invokeai/backend/model_manager/load/model_loaders/flux3.py b/invokeai/backend/model_manager/load/model_loaders/flux3.pyindex bea56a0229..655c65b1f0 100644--- a/invokeai/backend/model_manager/load/model_loaders/flux3.py+++ b/invokeai/backend/model_manager/load/model_loaders/flux3.py@@ -11,7 +11,8 @@ Submodel map of a Diffusers folder (subfolder == ``SubModelType`` value, exceptSingle-file and GGUF builds are only the transformer, in Black Forest Labs' key layout. The single-file loaderalso takes the published quantized builds: BFL's per-row scaled fp8 (`variants/fp8r`) and ModelOpt nvfp4-(`variants/nvfp4`), and Comfy-Org's `int8_convrot` and nvfp4. The file says which it is.+(`variants/nvfp4`), Comfy-Org's `int8_convrot` and nvfp4, and unsloth's torchao FP8, which is saved under diffusers'+key names. The file says which it is."""from collections.abc import Callable, Mapping@@ -29,6 +30,7 @@ from invokeai.backend.flux3.conversion import (convert_flux3_native_to_diffusers,convert_flux3_nvfp4_payloads,flux3_transformer_config,+ is_flux3_diffusers_layout,)from invokeai.backend.model_manager.checkpoint_prefix import CheckpointPrefixfrom invokeai.backend.model_manager.configs.factory import AnyModelConfig@@ -47,12 +49,14 @@ from invokeai.backend.quantization.fp8_scaled import (Fp8ScaledLayer,attach_fp8_scales,cast_state_dict,+ clone_unreplaced_tensors,count_fp8_weights,dequantize_fp8_scaled,extract_comfy_quant_hints,extract_fp8_scaled_layers,read_safetensors_metadata,split_fp8_scaled_layers,+ translate_torchao_fp8_layers,warn_on_unattached_scales,)from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor@@ -104,7 +108,7 @@ def _reserve_nothing(_bytes: int) -> None:"""The reservation of a load that happens outside the RAM cache."""-def flux3_transformer_from_native(+def flux3_transformer_from_single_file(sd: dict,dtype: torch.dtype,reserve: Optional[Callable[[int], None]] = None,@@ -113,7 +117,8 @@ def flux3_transformer_from_native(keep_fp8: bool = False,logger: Optional[Logger] = None,) -> torch.nn.Module:- """The transformer of a native single-file FLUX.3 state dict in `dtype`, on the device its tensors are on, the QK+ """The transformer of a single-file FLUX.3 state dict (Black Forest Labs' names, or diffusers' for the torchao+ build) in `dtype`, on the device its tensors are on, the QKnorms in float32. Empties `sd`.`reserve` asks the RAM cache for room once, before anything widens a weight, as `reserve_for_load` does; None asks@@ -138,6 +143,8 @@ def flux3_transformer_from_native(if key.endswith(COMFY_QUANT_SUFFIX)}reject_unloadable_quantization(sd, header_layers, markers)+ # unsloth's torchao FP8 build, renamed to the scaled-fp8 form everything below reads.+ translate_torchao_fp8_layers(sd)# BFL's nvfp4 build: its layers are named in `header_layers` now and re-laid out once room is reserved for them.modelopt = is_modelopt_nvfp4(metadata, sd)@@ -151,9 +158,12 @@ def flux3_transformer_from_native(sd = drop_unconsumed_quantization_sidecars(sd)else:layer_hints = {**extract_comfy_quant_hints(sd), **header_layers}- sd = convert_flux3_native_to_diffusers(sd)- int8_markers = convert_flux3_layer_entries(int8_markers)- layer_hints = convert_flux3_layer_entries(layer_hints)+ if not is_flux3_diffusers_layout(sd):+ # A file in diffusers' names (the torchao build) is left alone: its rows are in diffusers' order, and the+ # native conversion would act on names it does not have.+ sd = convert_flux3_native_to_diffusers(sd)+ int8_markers = convert_flux3_layer_entries(int8_markers)+ layer_hints = convert_flux3_layer_entries(layer_hints)skip_patterns = _model_declared_skip_patterns(model)fp8_layers: dict[str, Fp8ScaledLayer] = {}@@ -180,6 +190,7 @@ def flux3_transformer_from_native(fp8_layers=fp8_layers,nvfp4_payloads=nvfp4_payloads,)+ mapped = dict(sd) if fp8_layers and not keep_fp8 else Noneif fp8_layers and not keep_fp8:# Kept, they would be dequantized on every forward to save memory nobody asked to save.dequantize_fp8_scaled(sd, fp8_layers, dtype)@@ -188,6 +199,11 @@ def flux3_transformer_from_native(# layer whose scale `scaled_mm` cannot apply.fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, dtype, model=model, skip_patterns=skip_patterns)cast_state_dict(sd, dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)+ if mapped is not None:+ # Tensors 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()if nvfp4_payloads:if modelopt:# After the reservation: the copies it makes are what the reservation counts for the packed layers.@@ -266,7 +282,7 @@ class Flux3DiffusersModel(ModelLoader):@ModelLoaderRegistry.register(base=BaseModelType.Flux3, type=ModelType.Main, format=ModelFormat.Checkpoint)class Flux3CheckpointModel(ModelLoader):"""Loads a FLUX.3 transformer from a single file: bf16 (BFL `model.safetensors`, or its ComfyUI repackage), or one- of the quantized builds `flux3_transformer_from_native` reads."""+ of the quantized builds `flux3_transformer_from_single_file` reads."""def _load_model(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> AnyModel:if not isinstance(config, Main_Checkpoint_Flux3_Config):@@ -278,7 +294,7 @@ class Flux3CheckpointModel(ModelLoader):model_path = Path(config.path)model_dtype = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device())- model = flux3_transformer_from_native(+ model = flux3_transformer_from_single_file(load_file(model_path),model_dtype,self._ram_cache.make_room,diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.jsonindex 0b41473225..b89a51929c 100644--- a/invokeai/frontend/api/openapi.json+++ b/invokeai/frontend/api/openapi.json@@ -79241,7 +79241,7 @@"variant"],"title": "Main_Checkpoint_Flux3_Config",- "description": "Model config for FLUX.3 Image single-file transformers.\n\nBFL's `model.safetensors` and its quantized `variants/fp8r` (per-row scaled fp8) and `variants/nvfp4` (NVIDIA\nModelOpt layout), and Comfy-Org's bf16, `int8_convrot` and nvfp4 repackages. The record is the same for all of\nthem: the loader reads the scheme off the file."+ "description": "Model config for FLUX.3 Image single-file transformers.\n\nBFL's `model.safetensors` and its quantized `variants/fp8r` (per-row scaled fp8) and `variants/nvfp4` (NVIDIA\nModelOpt layout), Comfy-Org's bf16, `int8_convrot` and nvfp4 repackages, and unsloth's torchao FP8 build (diffusers\nkey names, one scale per output row). The record is the same for all of them: the loader reads the scheme off the\nfile."},"Main_Checkpoint_Ideogram4_Config": {"properties": {diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.tsindex 52664a986d..db11f9f449 100644--- a/invokeai/frontend/api/schema.ts+++ b/invokeai/frontend/api/schema.ts@@ -32765,8 +32765,9 @@ export type components = {* @description Model config for FLUX.3 Image single-file transformers.** BFL's `model.safetensors` and its quantized `variants/fp8r` (per-row scaled fp8) and `variants/nvfp4` (NVIDIA- * ModelOpt layout), and Comfy-Org's bf16, `int8_convrot` and nvfp4 repackages. The record is the same for all of- * them: the loader reads the scheme off the file.+ * ModelOpt layout), Comfy-Org's bf16, `int8_convrot` and nvfp4 repackages, and unsloth's torchao FP8 build (diffusers+ * key names, one scale per output row). The record is the same for all of them: the loader reads the scheme off the+ * file.*/Main_Checkpoint_Flux3_Config: {/**diff --git a/scripts/calibrate_flux3_denoise_working_memory.py b/scripts/calibrate_flux3_denoise_working_memory.pyindex e4b3b1a435..a33da25d2f 100644--- a/scripts/calibrate_flux3_denoise_working_memory.py+++ b/scripts/calibrate_flux3_denoise_working_memory.py@@ -58,7 +58,7 @@ Modes- `math`: SDPA forced onto the math kernel at 1024px, next to the default kernel, in each of `--dtypes` (defaultbfloat16): what a materialized score matrix costs per element, against what the estimate charges for it.- `real`: the released model itself, a `--checkpoint` bf16 safetensors single file in BFL's layout (Klein or Klein- Base, read off its keys), loaded through the model loader's conversion (`flux3_transformer_from_native`) straight onto+ Base, read off its keys), loaded through the model loader's conversion (`flux3_transformer_from_single_file`) straight ontothe device and fully resident: 1024 and 2048 px with a `--text-tokens` caption, and 1024 px with one and with three`--reference-px` references. Each forward is set against the shipped 2-block point of the same features on thisplatform and card, and against the shipped estimate, both as the calibration script prices it (fully resident) and as@@ -413,14 +413,16 @@ class _Shape:def _load_real(point: Point, device: "torch.device") -> "torch.nn.Module":- """The point's checkpoint, built as `Flux3CheckpointModel` builds it (`flux3_transformer_from_native`), except+ """The point's checkpoint, built as `Flux3CheckpointModel` builds it (`flux3_transformer_from_single_file`), exceptstraight onto `device` and outside the RAM cache."""import torchfrom safetensors.torch import load_file- from invokeai.backend.model_manager.load.model_loaders.flux3 import flux3_transformer_from_native+ from invokeai.backend.model_manager.load.model_loaders.flux3 import flux3_transformer_from_single_file- model = flux3_transformer_from_native(load_file(point.checkpoint, device=str(device)), getattr(torch, point.dtype))+ model = flux3_transformer_from_single_file(+ load_file(point.checkpoint, device=str(device)), getattr(torch, point.dtype)+ )return model.eval()diff --git a/tests/backend/flux3/flux3_fixture.py b/tests/backend/flux3/flux3_fixture.pyindex 79fea9a53c..e93c1fe3e4 100644--- a/tests/backend/flux3/flux3_fixture.py+++ b/tests/backend/flux3/flux3_fixture.py@@ -285,3 +285,30 @@ def flux3_model_from_native(native: dict[str, torch.Tensor], flow_map: bool) ->model = Flux3Transformer2DModel(**TINY_CONFIG, flow_map=flow_map).eval()model.load_state_dict(convert_flux3_native_to_diffusers(dict(native)))return model+++_TORCHAO_BLOCKS = (+ "mode_blocks.image.0",+ "mode_blocks.image_cond.0",+ "single_transformer_blocks.0",+ "single_transformer_blocks.1",+)+_TORCHAO_LINEARS = ("attn.to_q", "attn.to_k", "attn.to_v", "attn.to_out.0", "ff.linear_in", "ff.linear_out")+++def quantize_flux3_torchao(model: Flux3Transformer2DModel, *, adaln: bool = False) -> QuantizedFlux3:+ """``model`` written the way unsloth's torchao FP8 build is, under diffusers' own names: each block linear but the+ text blocks' as e4m3 ``<layer>._weight_qdata`` with a float32 ``[out, 1]`` ``<layer>._weight_scale`` per output+ row, everything else dense. ``adaln`` quantizes ``norm_out.linear`` too, which that build does not.++ ``meant`` holds every weight dense under diffusers' names, in diffusers' row order.+ """+ stored = {key: value.clone() for key, value in model.state_dict().items()}+ meant = dict(stored)+ layers = [f"{block}.{linear}" for block in _TORCHAO_BLOCKS for linear in _TORCHAO_LINEARS]+ for layer in [*layers, *(["norm_out.linear"] if adaln else [])]:+ fp8 = quantize_per_row_fp8(stored.pop(f"{layer}.weight"))+ stored[f"{layer}._weight_qdata"] = fp8.codes+ stored[f"{layer}._weight_scale"] = fp8.scale[:, None]+ meant[f"{layer}.weight"] = fp8.dequantized+ return QuantizedFlux3(stored, meant, {"unsloth_format": "unsloth_prequant_transformer_state_dict_v1"})diff --git a/tests/backend/flux3/test_quantized_loaders.py b/tests/backend/flux3/test_quantized_loaders.pyindex 4eb823df7c..2d83fcbde5 100644--- a/tests/backend/flux3/test_quantized_loaders.py+++ b/tests/backend/flux3/test_quantized_loaders.py@@ -13,6 +13,7 @@ import jsonimport pytestimport safetensors.torchimport torch+from diffusers import Flux3Transformer2DModelfrom invokeai.backend.model_manager.configs.main import Main_Checkpoint_Flux3_Configfrom invokeai.backend.model_manager.load import load_default@@ -26,10 +27,12 @@ from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinearfrom invokeai.backend.quantization.nvfp4 import NVFP4Linearfrom tests.backend.flux3.flux3_fixture import (QUANTIZED_SCHEMES,+ TINY_CONFIG,QuantizedFlux3,flux3_model_from_native,forward,quantize_flux3_native,+ quantize_flux3_torchao,tiny_flux3_model,to_native,)@@ -321,3 +324,103 @@ def test_a_packed_input_embedder_is_refused_before_room_is_reserved(monkeypatch:run = _refused(monkeypatch, build, "stores 'txt_in.weight' packed")assert run.reserved == []+++# unsloth's torchao FP8 build: diffusers' key names, `<layer>._weight_qdata` + a `[out, 1]` `<layer>._weight_scale`.+_TORCHAO_QUANTIZED = tuple(f"{block}.{linear}" for block in _BLOCKS["fp8r"] for linear in _LINEARS)+++def _torchao(*, adaln: bool = False) -> QuantizedFlux3:+ return quantize_flux3_torchao(tiny_flux3_model(flow_map=True), adaln=adaln)+++def _assert_torchao_predicts_what_it_means(model: torch.nn.Module, build: QuantizedFlux3) -> None:+ reference = Flux3Transformer2DModel(**TINY_CONFIG, flow_map=True).eval()+ reference.load_state_dict(build.meant)+ expected = forward(reference, flow_map=True)+ assert expected.abs().max() > 0, "a forward that is zero everywhere would compare equal to anything"+ assert torch.equal(forward(model, flow_map=True), expected)++[email protected]("adaln", [False, True], ids=["released", "adaln-quantized"])+def test_a_torchao_fp8_build_loads_as_the_model_it_means(monkeypatch: pytest.MonkeyPatch, adaln: bool) -> None:+ """Folded, every quantized layer is exactly `codes * scale`. The file is already in diffusers' names and row order,+ so the output adaLN's [scale, shift] halves must not be swapped -- dense as released, or quantized with a per-row+ scale that would otherwise have to move with its rows."""+ build = _torchao(adaln=adaln)++ run, model = _load(monkeypatch, build)++ _assert_torchao_predicts_what_it_means(model, build)+ assert torch.equal(model.norm_out.linear.weight, build.meant["norm_out.linear.weight"])+ assert not any(p.dtype is torch.float8_e4m3fn for p in model.parameters())+ assert len(run.reserved) == 1+++def test_kept_torchao_fp8_layers_have_fp8_codes_and_a_flat_per_row_scale(monkeypatch: pytest.MonkeyPatch) -> None:+ """torchao writes the scale `[out, 1]`; a 2-D scale is block-wise to the fp8 matmul, which would fold the layer."""+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _device: True)+ build = _torchao(adaln=True)++ _, model = _load(monkeypatch, build)++ for name in _TORCHAO_QUANTIZED:+ module = model.get_submodule(name)+ assert module.weight.dtype is torch.float8_e4m3fn, name+ assert torch.equal(module.weight.view(torch.uint8), build.state_dict[f"{name}._weight_qdata"].view(torch.uint8))+ assert module.weight_scale.shape == (module.out_features,), name+ assert torch.equal(module.weight_scale, build.state_dict[f"{name}._weight_scale"].reshape(-1)), name+ # The output adaLN is under the model's `norm` pattern: decoded with its scale, and in diffusers' row order.+ assert model.norm_out.linear.weight.dtype is torch.float32+ assert model.get_submodule("txt_mode_blocks.0.attn.to_q").weight.dtype is torch.float32+ apply_custom_layers_to_model(model)+ _assert_torchao_predicts_what_it_means(model, build)+++ ("payload", "scale_columns", "reason"),+ [(torch.int8, 1, "torch.int8, not float8_e4m3fn"), (torch.float8_e4m3fn, 2, "not per-tensor or block-wise scales")],+ ids=["int8", "blockwise"],+)+def test_a_torchao_build_the_loader_cannot_decode_is_refused_before_room_is_reserved(+ monkeypatch: pytest.MonkeyPatch, payload: torch.dtype, scale_columns: int, reason: str+) -> None:+ build = _torchao()+ state_dict = dict(build.state_dict)+ layer = _TORCHAO_QUANTIZED[0]+ codes = state_dict[f"{layer}._weight_qdata"]+ state_dict[f"{layer}._weight_qdata"] = codes.float().to(payload)+ state_dict[f"{layer}._weight_scale"] = state_dict[f"{layer}._weight_scale"].repeat(1, scale_columns)++ run = _refused(monkeypatch, build._replace(state_dict=state_dict), reason)++ assert run.reserved == []+++def test_a_folded_torchao_load_does_not_leave_parameters_pinning_the_file_mapping(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Dense tensors already in the compute dtype (the text blocks and the embedders) are left in place+ by the fold and the cast; as parameters they would be slices of the file's mapping, which the cache's size+ calculation cannot see."""+ build = _torchao()++ _, model = _load(monkeypatch, build)++ for name in (+ "txt_mode_blocks.0.attn.to_q.weight",+ "x_embedders.image.weight",+ ):+ parameter = model.get_parameter(name)+ assert parameter.data_ptr() != build.state_dict[name].data_ptr(), name+ assert torch.equal(parameter, build.state_dict[name])+++def test_a_kept_torchao_load_does_not_copy_the_fp8_codes(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _device: True)+ build = _torchao()++ _, model = _load(monkeypatch, build)++ layer = _TORCHAO_QUANTIZED[0]+ assert model.get_submodule(layer).weight.data_ptr() == build.state_dict[f"{layer}._weight_qdata"].data_ptr()diff --git a/tests/backend/model_manager/configs/test_flux3_main_config.py b/tests/backend/model_manager/configs/test_flux3_main_config.pyindex ea77a968f7..82c2349056 100644--- a/tests/backend/model_manager/configs/test_flux3_main_config.py+++ b/tests/backend/model_manager/configs/test_flux3_main_config.py@@ -27,6 +27,7 @@ from tests.backend.model_manager.load.state_dicts import (flux3_klein_keys,flux3_klein_nvfp4_bfl_keys,flux3_klein_nvfp4_comfy_keys,+ flux3_klein_torchao_fp8_keys,)from tests.backend.model_manager.load.state_dicts.utils import write_header_only_safetensors, write_shrunk_safetensors@@ -125,18 +126,22 @@ _RELEASED_QUANTIZED = {"nvfp4-comfy": flux3_klein_nvfp4_comfy_keys,"nvfp4-bfl": flux3_klein_nvfp4_bfl_keys,"fp8r": flux3_klein_fp8r_keys,+ "torchao-fp8": flux3_klein_torchao_fp8_keys,}def _write_release(path: Path, fixture, *, base: bool = False) -> Path:"""A captured release as a small complete file: identification reads its markers' bytes and its metadata, the`_quantization_metadata` block included, beyond the tensor entries. Klein Base's builds are Klein's layout- without the flow-map embedder `ref_time_in` (checked on their headers)."""+ without the flow-map embedder, `ref_time_in` in Black Forest Labs' names and `target_timestep_embedder` in+ diffusers' (checked on the release headers; the diffusers-named Base is assumed to follow, no such file exists)."""metadata = dict(fixture.metadata)if layer_hints := getattr(fixture, "layer_hints", None):metadata["_quantization_metadata"] = json.dumps({"layers": layer_hints})keys = {- key: entry for key, entry in fixture.state_dict_keys.items() if not (base and key.startswith("ref_time_in."))+ key: entry+ for key, entry in fixture.state_dict_keys.items()+ if not (base and key.startswith(("ref_time_in.", "target_timestep_embedder.")))}return write_shrunk_safetensors(path, keys, markers=getattr(fixture, "markers", None), metadata=metadata)@@ -153,7 +158,7 @@ def test_a_released_quantized_single_file_installs_as_flux3(tmp_path: Path, name# (The nvfp4 builds get it too, from their fp8 block scales, and the loader skips it: a known issue of the shared# install default, documented on the FLUX.3 page.)fp8_storage = getattr(result.config.default_settings, "fp8_storage", None)- if name == "fp8r":+ if name in ("fp8r", "torchao-fp8"):assert fp8_storage is Trueelif name == "int8-convrot":assert fp8_storage is not True@@ -231,11 +236,17 @@ _REFUSED = {{},"do not divide its input width 128",),- "torchao": (- {_Q: {"_weight_qdata": ([3072, 3072], "F8_E4M3"), "_weight_scale": ([3072, 1], "F32")}},+ "torchao-int8": (+ {_Q: {"_weight_qdata": ([3072, 3072], "I8"), "_weight_scale": ([3072, 1], "F32")}},{},{},- "torchao",+ "torch.int8, not float8_e4m3fn",+ ),+ "torchao-blockwise": (+ {_Q: {"_weight_qdata": ([3072, 3072], "F8_E4M3"), "_weight_scale": ([3072, 24], "F32")}},+ {},+ {},+ "not per-tensor or block-wise scales",),# bitsandbytes NF4 flattens the packed weight and keeps its state beside it."bitsandbytes": (@@ -289,7 +300,39 @@ def test_a_quantized_single_file_the_loader_cannot_build_is_refused(tmp_path: Paassert any(reason in str(error) for error in result.invalid_matches), result.invalid_matches-def test_a_torchao_export_is_refused_rather_than_installed_as_unknown(tmp_path: Path) -> None:+def _torchao(dtype: str, scale_columns: int = 1) -> dict[str, tuple[list[int], str]]:+ """unsloth's torchao FP8 layout, with its quantized payloads re-typed as another torchao build would store them."""+ keys = dict(flux3_klein_torchao_fp8_keys.state_dict_keys)+ for key, (shape, _) in flux3_klein_torchao_fp8_keys.state_dict_keys.items():+ if key.endswith("._weight_qdata"):+ keys[key] = (shape, dtype)+ elif key.endswith("._weight_scale"):+ keys[key] = ([shape[0], scale_columns], "F32")+ return keys+++ ("keys", "reason"),+ [+ (_torchao("I8"), "torch.int8, not float8_e4m3fn"),+ (_torchao("F8_E4M3", 24), "not per-tensor or block-wise scales"),+ ],+ ids=["int8", "blockwise"],+)+def test_a_torchao_build_flux3_cannot_load_is_refused_rather_than_installed_as_unknown(+ tmp_path: Path, keys: dict[str, tuple[list[int], str]], reason: str+) -> None:+ """unsloth's INT8 and block-wise builds keep the FP8 build's key names, so they are recognized as FLUX.3 and then+ refused by name; the message names only what loads."""+ result = _identify(write_shrunk_safetensors(tmp_path / "flux3.safetensors", keys))++ assert result.config is None+ assert any(reason in str(error) and "unsloth's FP8 build" in str(error) for error in result.invalid_matches), (+ result.all_matches+ )+++def test_a_native_torchao_export_is_refused_rather_than_installed_as_unknown(tmp_path: Path) -> None:"""torchao quantizes every linear, the modulation the fingerprint looks at included, and stores each one withouta `.weight`; the file must still be recognized as FLUX.3 for its refusal to be reached."""keys: dict[str, tuple[list[int], str]] = {}@@ -304,7 +347,65 @@ def test_a_torchao_export_is_refused_rather_than_installed_as_unknown(tmp_path:result = _identify(write_shrunk_safetensors(tmp_path / "flux3.safetensors", keys))assert result.config is None- assert any("torchao" in str(error) for error in result.invalid_matches), result.all_matches+ assert any("under Black Forest Labs' key names" in str(error) for error in result.invalid_matches), (+ result.all_matches+ )+++def test_int8_markers_beside_torchao_layers_are_refused(tmp_path: Path) -> None:+ """The int8 pairing check reads `.weight`/`.weight_scale` pairs, which torchao layers do not have until they are+ translated; the mix is refused on the header all the same."""+ keys = dict(flux3_klein_torchao_fp8_keys.state_dict_keys)+ layer = "txt_mode_blocks.0.attn.to_q"+ del keys[f"{layer}.weight"]+ keys.update({f"{layer}.weight": ([3072, 3072], "I8"), f"{layer}.weight_scale": ([3072, 1], "F32")})+ keys[f"{layer}.comfy_quant"] = ([72], "U8")++ result = _identify(write_shrunk_safetensors(tmp_path / "flux3.safetensors", keys, markers={layer: _INT8_MARKER}))++ assert result.config is None+ assert any("mixes int8 and torchao" in str(error) for error in result.invalid_matches), result.invalid_matches+++def test_an_nvfp4_layer_beside_torchao_layers_is_refused(tmp_path: Path) -> None:+ """The nvfp4 re-layout reads Black Forest Labs' names, so in a torchao file, saved under diffusers' names, it+ would swap the halves of rows already in diffusers' order."""+ keys = dict(flux3_klein_torchao_fp8_keys.state_dict_keys)+ layer = "txt_mode_blocks.0.attn.to_q"+ del keys[f"{layer}.weight"]+ keys.update({f"{layer}.{name}": entry for name, entry in _NVFP4.items()})++ result = _identify(write_shrunk_safetensors(tmp_path / "flux3.safetensors", keys, metadata=_header_naming(layer)))++ assert result.config is None+ assert any("mixes torchao and nvfp4" in str(error) for error in result.invalid_matches), result.invalid_matches+++def test_a_torchao_klein_that_quantizes_its_flow_map_embedder_is_still_klein(tmp_path: Path) -> None:+ keys = dict(flux3_klein_torchao_fp8_keys.state_dict_keys)+ shape, _ = keys.pop("target_timestep_embedder.linear_1.weight")+ keys["target_timestep_embedder.linear_1._weight_qdata"] = (shape, "F8_E4M3")+ keys["target_timestep_embedder.linear_1._weight_scale"] = ([shape[0], 1], "F32")++ result = _identify(write_shrunk_safetensors(tmp_path / "flux3.safetensors", keys))++ assert isinstance(result.config, Main_Checkpoint_Flux3_Config)+ assert result.config.variant is Flux3VariantType.Klein+++def test_diffusers_key_names_alone_are_not_a_flux3_single_file(tmp_path: Path) -> None:+ """The torchao build is the only single file under diffusers' names that is read as FLUX.3. The same layout in+ plain bf16 is not recognized, so no new format is opened beside it."""+ keys: dict[str, tuple[list[int], str]] = {}+ for key, (shape, dtype) in flux3_klein_torchao_fp8_keys.state_dict_keys.items():+ if key.endswith("._weight_scale"):+ continue+ keys[key.replace("._weight_qdata", ".weight")] = (shape, "BF16" if dtype == "F8_E4M3" else dtype)++ result = _identify(write_shrunk_safetensors(tmp_path / "flux3.safetensors", keys))++ assert not any(isinstance(match, Main_Checkpoint_Flux3_Config) for match in result.all_matches)+ assert not isinstance(result.config, Main_Checkpoint_Flux3_Config)def test_a_lora_with_flux3_names_is_not_a_main_model(tmp_path: Path) -> None:diff --git a/tests/backend/model_manager/load/state_dicts/flux3_klein_torchao_fp8_keys.py b/tests/backend/model_manager/load/state_dicts/flux3_klein_torchao_fp8_keys.pynew file mode 100644index 0000000000..10751ac569--- /dev/null+++ b/tests/backend/model_manager/load/state_dicts/flux3_klein_torchao_fp8_keys.py@@ -0,0 +1,90 @@+"""unsloth's torchao FP8 build of FLUX.3 Image Klein, `flux-3-image-klein-FP8.safetensors`.++Captured on 2026-11-06 with `scripts/capture_state_dict_fixture.py`, which reads the header only, from a local copy of+unsloth's `flux-3-image-klein-FP8.safetensors`.++Subsetting rule: `mode_blocks.image` index 0, `mode_blocks.image_cond` index 0, `single_transformer_blocks` index 0,+`txt_mode_blocks` index 0, plus every key outside a stack. Values are `(shape, dtype)`.++The only single-file FLUX.3 build under diffusers' key names rather than Black Forest Labs'. Every block linear but the+text blocks' (`attn.to_{q,k,v}`, `attn.to_out.0`, `ff.linear_in`, `ff.linear_out`) is torchao's `Float8Tensor`: e4m3+codes under `<layer>._weight_qdata` and one float32 scale per output row, shaped `[out, 1]`, under+`<layer>._weight_scale`, with no `<layer>.weight`. The modulations, embedders, `norm_out.linear` and `proj_out` are+dense BF16, the q/k norms F32. It has the flow-map embedder (`target_timestep_embedder`), so it is Klein. A re-upload+as INT8 or with block-wise scales keeps these names and changes the payload dtype or the scale shape.+"""++state_dict_keys: dict[str, tuple[list[int], str]] = {+ "context_embedder.weight": ([3072, 20480], "BF16"),+ "early_stream_modulations.image.linear.weight": ([9216, 3072], "BF16"),+ "early_stream_modulations.image_cond.linear.weight": ([9216, 3072], "BF16"),+ "early_stream_modulations.txt.linear.weight": ([9216, 3072], "BF16"),+ "mode_blocks.image.0.attn.norm_k.weight": ([128], "F32"),+ "mode_blocks.image.0.attn.norm_q.weight": ([128], "F32"),+ "mode_blocks.image.0.attn.to_k._weight_qdata": ([3072, 3072], "F8_E4M3"),+ "mode_blocks.image.0.attn.to_k._weight_scale": ([3072, 1], "F32"),+ "mode_blocks.image.0.attn.to_out.0._weight_qdata": ([3072, 3072], "F8_E4M3"),+ "mode_blocks.image.0.attn.to_out.0._weight_scale": ([3072, 1], "F32"),+ "mode_blocks.image.0.attn.to_q._weight_qdata": ([3072, 3072], "F8_E4M3"),+ "mode_blocks.image.0.attn.to_q._weight_scale": ([3072, 1], "F32"),+ "mode_blocks.image.0.attn.to_v._weight_qdata": ([3072, 3072], "F8_E4M3"),+ "mode_blocks.image.0.attn.to_v._weight_scale": ([3072, 1], "F32"),+ "mode_blocks.image.0.ff.linear_in._weight_qdata": ([18432, 3072], "F8_E4M3"),+ "mode_blocks.image.0.ff.linear_in._weight_scale": ([18432, 1], "F32"),+ "mode_blocks.image.0.ff.linear_out._weight_qdata": ([3072, 9216], "F8_E4M3"),+ "mode_blocks.image.0.ff.linear_out._weight_scale": ([3072, 1], "F32"),+ "mode_blocks.image_cond.0.attn.norm_k.weight": ([128], "F32"),+ "mode_blocks.image_cond.0.attn.norm_q.weight": ([128], "F32"),+ "mode_blocks.image_cond.0.attn.to_k._weight_qdata": ([3072, 3072], "F8_E4M3"),+ "mode_blocks.image_cond.0.attn.to_k._weight_scale": ([3072, 1], "F32"),+ "mode_blocks.image_cond.0.attn.to_out.0._weight_qdata": ([3072, 3072], "F8_E4M3"),+ "mode_blocks.image_cond.0.attn.to_out.0._weight_scale": ([3072, 1], "F32"),+ "mode_blocks.image_cond.0.attn.to_q._weight_qdata": ([3072, 3072], "F8_E4M3"),+ "mode_blocks.image_cond.0.attn.to_q._weight_scale": ([3072, 1], "F32"),+ "mode_blocks.image_cond.0.attn.to_v._weight_qdata": ([3072, 3072], "F8_E4M3"),+ "mode_blocks.image_cond.0.attn.to_v._weight_scale": ([3072, 1], "F32"),+ "mode_blocks.image_cond.0.ff.linear_in._weight_qdata": ([18432, 3072], "F8_E4M3"),+ "mode_blocks.image_cond.0.ff.linear_in._weight_scale": ([18432, 1], "F32"),+ "mode_blocks.image_cond.0.ff.linear_out._weight_qdata": ([3072, 9216], "F8_E4M3"),+ "mode_blocks.image_cond.0.ff.linear_out._weight_scale": ([3072, 1], "F32"),+ "norm_out.linear.weight": ([6144, 3072], "BF16"),+ "proj_out.weight": ([128, 3072], "BF16"),+ "single_stream_modulations.image.linear.weight": ([9216, 3072], "BF16"),+ "single_stream_modulations.image_cond.linear.weight": ([9216, 3072], "BF16"),+ "single_stream_modulations.txt.linear.weight": ([9216, 3072], "BF16"),+ "single_transformer_blocks.0.attn.norm_k.weight": ([128], "F32"),+ "single_transformer_blocks.0.attn.norm_q.weight": ([128], "F32"),+ "single_transformer_blocks.0.attn.to_k._weight_qdata": ([3072, 3072], "F8_E4M3"),+ "single_transformer_blocks.0.attn.to_k._weight_scale": ([3072, 1], "F32"),+ "single_transformer_blocks.0.attn.to_out.0._weight_qdata": ([3072, 3072], "F8_E4M3"),+ "single_transformer_blocks.0.attn.to_out.0._weight_scale": ([3072, 1], "F32"),+ "single_transformer_blocks.0.attn.to_q._weight_qdata": ([3072, 3072], "F8_E4M3"),+ "single_transformer_blocks.0.attn.to_q._weight_scale": ([3072, 1], "F32"),+ "single_transformer_blocks.0.attn.to_v._weight_qdata": ([3072, 3072], "F8_E4M3"),+ "single_transformer_blocks.0.attn.to_v._weight_scale": ([3072, 1], "F32"),+ "single_transformer_blocks.0.ff.linear_in._weight_qdata": ([18432, 3072], "F8_E4M3"),+ "single_transformer_blocks.0.ff.linear_in._weight_scale": ([18432, 1], "F32"),+ "single_transformer_blocks.0.ff.linear_out._weight_qdata": ([3072, 9216], "F8_E4M3"),+ "single_transformer_blocks.0.ff.linear_out._weight_scale": ([3072, 1], "F32"),+ "target_timestep_embedder.linear_1.weight": ([3072, 256], "BF16"),+ "target_timestep_embedder.linear_2.weight": ([3072, 3072], "BF16"),+ "timestep_embedder.linear_1.weight": ([3072, 256], "BF16"),+ "timestep_embedder.linear_2.weight": ([3072, 3072], "BF16"),+ "txt_mode_blocks.0.attn.norm_k.weight": ([128], "F32"),+ "txt_mode_blocks.0.attn.norm_q.weight": ([128], "F32"),+ "txt_mode_blocks.0.attn.to_k.weight": ([3072, 3072], "BF16"),+ "txt_mode_blocks.0.attn.to_out.0.weight": ([3072, 3072], "BF16"),+ "txt_mode_blocks.0.attn.to_q.weight": ([3072, 3072], "BF16"),+ "txt_mode_blocks.0.attn.to_v.weight": ([3072, 3072], "BF16"),+ "txt_mode_blocks.0.ff.linear_in.weight": ([18432, 3072], "BF16"),+ "txt_mode_blocks.0.ff.linear_out.weight": ([3072, 9216], "BF16"),+ "x_embedders.image.weight": ([3072, 128], "BF16"),+ "x_embedders.image_cond.weight": ([3072, 128], "BF16"),+}++# The header's `__metadata__` is one JSON blob per tensor (362 entries); only the file-level entries are kept, the+# second one shortened.+metadata: dict[str, str] = {+ "unsloth_format": "unsloth_prequant_transformer_state_dict_v1",+ "unsloth_metadata": '{"family": "flux.3-klein", "scheme": "fp8"}',+}