Skip to content

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

feat(flux3): load quantized FLUX.3 single files (#10093)

Alexander Eichhorn0ef519ff0d2d
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 9b2f2d752f..f79b865aa8 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
@@ -47,9 +47,9 @@ InvokeAI recognizes the format from the file's contents, so you install them lik
- **GGUF** (`.gguf`, llama.cpp quantization such as Q4_K or Q8_0): weights stay packed in memory and are unpacked layer by layer during generation. Supported for the FLUX.1, FLUX.2, FLUX.3, Z-Image, Krea-2, Qwen-Image, Qwen-Image-2.1, Ideogram 4, ERNIE-Image and Wan transformers, and for the T5, Qwen3, Qwen3-VL, Mistral and Gemma 2 text encoders. ComfyUI-GGUF's `Q8_CR` and `Q4_CR` files, which store int8 or int4 convrot layers inside a `.gguf`, load for the Krea-2 transformer; for other models installation is refused with a message saying so.
- **NF4** (bitsandbytes): 4-bit. InvokeAI installs bitsandbytes on Windows and Linux, with ROCm binaries for AMD GPUs, so NF4 models load on NVIDIA and AMD GPUs; macOS installs have no bitsandbytes, and NF4 models don't load there.
- **SDNQ**: see [SDNQ Quantization](/configuration/optimization/sdnq-quantization/).
-- **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, Z-Image, Anima, Krea-2, Qwen-Image-2.1, Ideogram 4, MiniMax H3, LTX-2 and the PiD decoders, and for the Qwen3 4B and 8B, Qwen3-VL and LTX-2 Gemma encoders.
+- **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-2.1, Ideogram 4, MiniMax H3, LTX-2 and the PiD decoders, and for the Qwen3 4B and 8B, Qwen3-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 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; the Ideogram 4 and Qwen-Image-2.1 nvfp4 transformer files are refused at install.
+- **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.
- **MXFP8** (fp8 with one scale per block of 32 weights): loaded by unpacking to BF16. Turn FP8 Storage off for these; see the [FP8 Storage caution](/configuration/optimization/fp8-storage/).
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 7272d900f7..9a3453ac20 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 Support
description: Which file formats and quantizations InvokeAI loads for every model family, text encoder, VAE and adapter.
-lastUpdated: 2026-10-31
+lastUpdated: 2026-11-06
sidebar:
order: 3
---
@@ -37,7 +37,7 @@ reader's error; if the file is incomplete or corrupt, download it again.
| [SD 3](/users-guide/models/local-models/sd-3/) | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ |
| [FLUX.1](/users-guide/models/local-models/flux-1/) | ✓ | ✓ | ✓ | ✓ | L | ✗ | ✓ | ✓ | ✓ | ✓ |
| [FLUX.2](/users-guide/models/local-models/flux-2/) | ✓ | ✓ | ✓ | ✓ | L | ✗ | ✓ | ✓ | ✓ | inside the Diffusers folder (FLUX.2 [dev]) |
-| [FLUX.3](/users-guide/models/local-models/flux-3/) | ✓ | ✓ | R | R | R | R | – | ✓ | – | – |
+| [FLUX.3](/users-guide/models/local-models/flux-3/) | ✓ | ✓ | ✓ | ✓ | R | ✓ | – | ✓ | – | – |
| [CogView4](/users-guide/models/local-models/cogview4/) | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ |
| [Z-Image](/users-guide/models/local-models/z-image/) | ✓ | ✓ | ✓ | ✓ | L | ✓ | ✓ | ✓ | ✓ | ✗ |
| [Qwen-Image](/users-guide/models/local-models/qwen-image/) | ✓ | ✓ | ✓ | ✗ | ✗ | ✓ | ✓ | ✓ | ✗ | ✗ |
@@ -54,11 +54,12 @@ reader's error; if the file is incomplete or corrupt, download it again.
- **int8** means ComfyUI's `int8_convrot` (`int8_tensorwise`) builds; on NVIDIA GPUs, [int8 Compute](/configuration/optimization/int8-compute/)
runs them on the int8 tensor cores. **int4** means their packed 4-bit counterparts, `convrot_w4a4` and
`int4_tensorwise`, which most builds mix with int8 layers. **nvfp4** and **fp8 scaled** mean ComfyUI's checkpoint
- layouts; other exports of the same schemes (AWQ, ModelOpt) fail when the model loads. For Qwen-Image-2.1, torchao
- exports such as unsloth's FP8 build 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 refuses them at install.
+ layouts; other exports of the same schemes (AWQ, ModelOpt) fail when the model loads. FLUX.3 also loads Black Forest
+ Labs' 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 refuses 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 does
for `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.mdx
index 8366f870fb..7547496f0e 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,6 +1,6 @@
---
title: FLUX.3
-description: 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 workflow.
+description: 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
sidebar:
order: 6
@@ -33,15 +33,46 @@ commercially.
| Transformer build | Transformer size | Notes |
| --------------------------- | ---------------- | --------------------------------------- |
| bf16 (Diffusers or single file) | ≈ 10.3 GiB | reference quality |
+| int8 (starter model) | ≈ 5.4 GiB | stays int8 on every GPU |
+| fp8r (Black Forest Labs) | ≈ 5.8 GiB | with FP8 Storage (switched on at install) or `fp8_compute`; ≈ 10.3 GiB otherwise |
+| nvfp4 (starter model, or Black Forest Labs) | ≈ 4.9 GiB | 4-bit weights, decoded on every step |
| GGUF Q8_0 (starter model) | ≈ 5.6 GiB | close to bf16 |
| GGUF Q4_K_M (starter model) | ≈ 3.1 GiB | lowest VRAM; fine detail differs from bf16 |
The Qwen3-VL 4B encoder (≈ 8.5 GB as bf16, about half as fp8) and the FLUX.2 VAE come on top. The encoder runs
before the transformer, so the two do not have to fit on the GPU at the same time.
-Reference images add to the work per step: each 1 MP reference costs about as much as the image itself. On an
-RTX 4090 a 1024² image takes about 15 s with Klein, 25 s with one reference, 50 s with three references, and
-about 50 s with Klein Base.
+Reference images add to the work per step. Measured on an RTX 4090 with the models already loaded, a whole 1024²
+image (text encoder, denoise and decode) with Klein bf16 at its defaults takes 6.5 s without a reference, 13.5 s with
+one 1 MP reference and 31.7 s with three. Klein Base at 50 steps and CFG 3.5 takes 36.7 s.
+
+### Speed and quality by build
+
+Measured on the same RTX 4090 (24 GB) with Klein at its defaults (16 steps, CFG 1.0) and 1024², three prompts with
+three seeds each:
+
+| Build | Denoise per image | With int8 Compute / `fp8_compute` | VRAM peak | PSNR against bf16 |
+| --- | --- | --- | --- | --- |
+| bf16 | 6.22 s | 6.20 s | 19.5 GiB | reference |
+| int8 | 7.01 s | 4.07 s | 14.4 GiB | 33.2 dB; 34.5 dB with int8 Compute |
+| GGUF Q8_0 | 6.78 s | not affected | 14.5 GiB | 34.4 dB |
+| fp8r (FP8 Storage on, as installed) | 6.61 s | 5.35 s | 15.0 GiB | 26.8 dB; 25.4 dB with `fp8_compute` |
+| nvfp4 (Comfy-Org or Black Forest Labs: identical images) | 6.82–6.84 s | not affected | 14.1–14.3 GiB | 22.8 dB |
+
+The VRAM peak is what `nvidia-smi` reports, text encoder and desktop included. The PSNR is the mean over the nine
+images. With `fp8_compute` on, the text encoder used here (a scaled-fp8 checkpoint) computes in fp8 too, so the PSNR
+values with the switches on compare against bf16 images made with that same encoder.
+
+- **Closest to bf16** are int8 and GGUF Q8_0, then fp8r, then nvfp4. For the prompt with a sign, every build spelled its
+ text correctly in all three seeds, with and without the compute switches. Without the switches, every quantized build
+ scores its lowest per-image PSNR on the same seed of the sign prompt, whose letter colors shift in all of them, Q8_0
+ included.
+- **Speed:** without a compute switch, every quantized layer is dequantized on each forward, so on this card the
+ quantized builds take up to 13 % longer than bf16. [int8 Compute](/configuration/optimization/int8-compute/) makes
+ the int8 build the fastest, 1.52× as fast as bf16, and
+ [`fp8_compute`](/configuration/optimization/fp8-storage/#fp8-compute) makes fp8r 1.16× as fast as bf16. Neither
+ affects nvfp4 or GGUF.
+- **Memory:** the quantized builds peak about 5 GiB below bf16.
## Installing
@@ -65,10 +96,33 @@ FLUX.3 needs three components:
When you select a GGUF or single-file FLUX.3 model, pick the VAE and the Qwen3-VL encoder under **Components** if
they are not filled in. A Diffusers model uses its bundled components unless you override them there.
-:::note[Quantized single files]
-The fp8, int8 and nvfp4 transformer single files from Black Forest Labs and Comfy-Org are not supported yet. Installing
-one is refused with a message saying so. Use the bf16 file or a GGUF.
-:::
+### Quantized single files
+
+Comfy-Org's int8 and nvfp4 builds of both checkpoints are starter models. Black Forest Labs publishes an fp8 build
+(`fp8r`) and an nvfp4 build of each as well, in the `variants/` folder of its repositories. They are not starter models,
+because Klein's and Klein Base's files are both called `model.safetensors`. Install one by URL in the Model Manager,
+then rename it so the models can be told apart. The URLs are pinned to the revisions InvokeAI was checked against:
+the Klein file was loaded in full, the Klein Base file compared with it by its header.
+
+- Klein: `https://huggingface.co/black-forest-labs/flux-3-image-klein/resolve/337337621b8526e120f2275d250242f4a6bedd75/variants/fp8r/model.safetensors`
+- Klein Base: `https://huggingface.co/black-forest-labs/flux-3-image-klein-base/resolve/3f7fa5ee22ca1d5a5cc095ac7cc96e6a173b4c86/variants/fp8r/model.safetensors`
+
+Like every Black Forest Labs repository, these need your HuggingFace token. For nvfp4, prefer the Comfy-Org starter
+model to `variants/nvfp4/`: InvokeAI turns Black Forest Labs' file into exactly Comfy-Org's bytes while loading it, an
+extra pass over the weights on every load.
+
+- **int8** keeps its quantized layers in int8 on every GPU and decodes them on every step. On an RTX 30-series or
+ newer, [int8 Compute](/configuration/optimization/int8-compute/) multiplies them in int8 instead.
+- **nvfp4** keeps 33 of the 43 transformer blocks in 4 bits and decodes them on every step, on every GPU.
+- **fp8r** stores fp8 weights with one scale per row. With [FP8 Storage](/configuration/optimization/fp8-storage/), which
+ installing it switches on, or with `fp8_compute`, the weights stay fp8; otherwise they are expanded to bf16 as the
+ model loads.
+
+FP8 Storage does not apply to the int8 and nvfp4 builds: their quantized layers are smaller already, and the layers
+they keep in bf16 stay bf16. The Model Manager can still show the toggle as on for an nvfp4 build, because installing
+switches it on for any file holding fp8 numbers, and nvfp4's block scales are fp8. It has no effect there. Other
+quantized files, such as AWQ or bitsandbytes exports or nvfp4 files from other tools, are refused at install with a
+message saying why.
## Reference images
diff --git a/docs/src/content/docs/configuration/Optimization/fp8-storage.mdx b/docs/src/content/docs/configuration/Optimization/fp8-storage.mdx
index 2a2a25df8a..0f98c364f2 100644
--- a/docs/src/content/docs/configuration/Optimization/fp8-storage.mdx
+++ b/docs/src/content/docs/configuration/Optimization/fp8-storage.mdx
@@ -37,7 +37,7 @@ before this rule may still have it stored as on; it then does nothing, and the l
| Full precision (FP16, BF16, FP32) | **Yes**: what it is for. |
| fp8 or scaled fp8 checkpoint | **On after install.** The weights stay in fp8 with their own scale; without the setting they would be unpacked to BF16 at twice the size. See [Checkpoints that are already FP8](#checkpoints-that-are-already-fp8). |
| MXFP8 checkpoint | **Turn it off.** It stores one scale per block of 32 weights, which InvokeAI does not keep on any GPU: the layers are unpacked at load, and FP8 Storage then re-encodes them as fp8 *without* a scale: blocks whose scale is far below 1 lose their weights to underflow. If the file also has per-tensor fp8 layers, those stay fp8 and FP8 Storage changes nothing. |
-| int8 and nvfp4 single files | **Partly.** Their quantized layers stay as they are; only the layers the build ships in full precision are stored in FP8. On an Ideogram 4 or Qwen-Image-2.1 int8 file, nothing at all. |
+| int8 and nvfp4 single files | **Partly.** Their quantized layers stay as they are; only the layers the build ships in full precision are stored in FP8. On an Ideogram 4, Qwen-Image-2.1 or FLUX.3 int8 file, and on a FLUX.3 nvfp4 file, nothing at all. |
| GGUF, NF4 and [SDNQ](/configuration/optimization/sdnq-quantization/) | **No**: already quantized. The setting is not shown. |
If your model is quantized, its full-precision variant gets the full effect of FP8 Storage.
@@ -48,6 +48,7 @@ If your model is quantized, its full-precision variant gets the full effect of F
| --- | --- |
| Main models: SD1, SD2, SDXL, SDXL Refiner, SD3, CogView4 | Yes |
| FLUX.1, FLUX.2 (all variants) | Yes |
+| FLUX.3 | Yes — except int8 and nvfp4 single files, where it does nothing. The toggle can still show as on for an nvfp4 build, since installing switches it on for its fp8 block scales |
| Z-Image, Anima, Krea-2, Qwen-Image, Qwen-Image-2.1, ERNIE-Image, MOSS-Image | Yes |
| Ideogram 4, single-file safetensors | Yes, for each transformer branch's file |
| LTX-2 | Yes |
@@ -156,7 +157,7 @@ Either way the setting stays editable under **Default Settings**, and re-identif
For these, FP8 Storage re-encodes nothing: it stops InvokeAI from unpacking them. That matters because the file stores
a scale beside each weight, and re-encoding the unpacked result would throw that scale away: on FLUX.2 Klein 4B roughly
3% of the weights would round to zero, for a file that was already one byte per weight. The cost is a little speed,
-since each layer is unpacked on use. Measured on an RTX 4090, the Ideogram 4 fp8 pair generates 1024px in 40.6s, against
+since each layer is unpacked on use. FLUX.3's `fp8r` build from Black Forest Labs is a scaled fp8 file too, so the setting keeps it in fp8. Measured on an RTX 4090, the Ideogram 4 fp8 pair generates 1024px in 40.6s, against
35.6s with [FP8 Compute](/configuration/optimization/fp8-compute/), and holds 8.7GB per branch instead of the 17.3GB the
unpacked weights need: the difference between fitting on a 24GB card and running out of memory in the first step.
@@ -168,7 +169,7 @@ still get nearly the full saving.
The loader reports what it kept and which setting kept it, for example
`Ideogram 4: kept 208 layer(s) in fp8 (scaled fp8 checkpoint, kept for FP8 Storage, dequantized per forward)`. On
-FLUX.1, FLUX.2, Z-Image and Anima the model then goes to the layer cast, which declines it with
+FLUX.1, FLUX.2, FLUX.3, Z-Image and Anima the model then goes to the layer cast, which declines it with
`FP8 storage skipped for <model>: … weight(s) are already fp8, …`, so you see both lines for the same model. Both are
the intended outcome, not a failure. Qwen-Image keeps its fp8 layers without the first line.
diff --git a/docs/src/content/docs/configuration/Optimization/int8-compute.mdx b/docs/src/content/docs/configuration/Optimization/int8-compute.mdx
index f605917812..a666624334 100644
--- a/docs/src/content/docs/configuration/Optimization/int8-compute.mdx
+++ b/docs/src/content/docs/configuration/Optimization/int8-compute.mdx
@@ -26,6 +26,7 @@ layer then rotates and quantizes its input to int8 per token and multiplies int8
<BenchmarkRow label="FLUX.1 dev, 20 steps, 1536²" before={36.2} after={23.88} />
<BenchmarkRow label="Krea-2 Turbo, 8 steps, 1024²" before={9.22} after={4.51} />
<BenchmarkRow label="Krea-2 Turbo, 8 steps, 1536²" before={21.64} after={12.32} />
+ <BenchmarkRow label="FLUX.3 Klein, 16 steps, 1024²" before={7.01} after={4.07} />
</BenchmarkChart>
The gain shrinks at higher resolutions because attention, which `int8_compute` does not touch, takes a larger share of
@@ -43,9 +44,10 @@ Other int8 families use the same layers but have not been measured. A convrot in
(`qwen_3_8b_int8_convrot` with FLUX.2 Klein 9B) works with it as well; its speed has not been measured.
It is **opt-in** because quantizing the inputs changes the numbers: images made with `int8_compute` are not
-pixel-identical to the default path at the same seed. In the measurements above they were visually equivalent (PSNR
-30–46dB against the default path). Each path is bit-identical from run to run, and how much of the model is in VRAM does
-not change the image.
+pixel-identical to the default path at the same seed. In the Z-Image, FLUX.1 and Krea-2 measurements above they were
+visually equivalent (PSNR 30–46dB against the default path). FLUX.3 Klein was compared with bf16 instead: a mean PSNR of
+34.5dB with `int8_compute` and 33.2dB without. Each path is bit-identical from run to run, and how much of the model is
+in VRAM does not change the image.
## Requirements
diff --git a/docs/src/content/docs/start-here/system-requirements.mdx b/docs/src/content/docs/start-here/system-requirements.mdx
index 2877a5e4bf..bdb0ce01c9 100644
--- a/docs/src/content/docs/start-here/system-requirements.mdx
+++ b/docs/src/content/docs/start-here/system-requirements.mdx
@@ -2,7 +2,7 @@
title: Hardware Requirements
sidebar:
order: 1
-lastUpdated: 2026-10-18
+lastUpdated: 2026-10-31
---
import { Tabs, TabItem, Steps } from '@astrojs/starlight/components'
@@ -31,7 +31,7 @@ The requirements below are rough guidelines for best performance. GPUs with less
| FLUX.1 | 1024x1024 | Nvidia 20xx+ | 10GB | 32GB | Download totals: NF4 ~12GB, int8 ~18GB, bf16 ~33GB. The int8 transformer is 11.5GB resident on any supported GPU, so it streams on a 10GB card |
| FLUX.2 Klein 4B | 1024x1024 | Nvidia 30xx+ | 12GB | 16GB | FP8 works with 8GB+; Diffusers + encoder |
| FLUX.2 Klein 9B | 1024x1024 | Nvidia 30xx+ | 12GB | 32GB | int8 transformer ~9.5GB on any supported GPU; FP8 checkpoints stay about as small with FP8 Storage, which installation switches on. The Qwen3 8B encoder is 15GB (int8 7.6GB) and streams on a 12GB card |
-| FLUX.3 Klein | 1024x1024 | Nvidia 30xx+ | 12GB | 32GB | Transformer bf16 10.3GB, GGUF Q8_0 5.6GB, Q4_K_M 3.1GB, plus the Qwen3-VL 4B encoder (8.5GB bf16). Diffusers ~20GB; single files and GGUFs need a standalone FLUX.2 VAE + Qwen3-VL encoder. Each 1MP reference image adds about as much working memory as the image itself |
+| FLUX.3 Klein | 1024x1024 | Nvidia 30xx+ | 12GB | 32GB | Transformer bf16 10.3GB, fp8 5.8GB, int8 5.4GB, nvfp4 4.9GB, GGUF Q8_0 5.6GB, Q4_K_M 3.1GB, plus the Qwen3-VL 4B encoder (8.5GB bf16). Diffusers ~20GB; single files and GGUFs need a standalone FLUX.2 VAE + Qwen3-VL encoder. Each 1MP reference image adds about as much working memory as the image itself |
| Z-Image Turbo | 1024x1024 | Nvidia 20xx+ | 8GB | 16GB | Q4_K / NVFP4 / int8 8GB (int8 ~6GB resident); Q8/BF16 16GB+ |
| Krea-2 (Turbo / Raw) | 1024x1024 | Nvidia 40xx | 24GB | 32GB | FP8 works with 16GB+; NVFP4 or GGUF Q4_K transformer ~7GB, plus the Qwen3-VL encoder (8.5GB bf16, ~2.8GB as GGUF Q4_K), int8 transformer 12.6GB. Diffusers ~26GB; single files need a standalone VAE + Qwen3-VL encoder (GGUF encoder ~2.8GB) |
| Ideogram 4 | 1024x1024 | Nvidia 30xx+ | 24GB | 32GB | Two transformers resident at once. nf4 build fits 24GB (CUDA only); single-file fp8 or int8 pair ~17.5GB, GGUF Q4_0 pair ~11GB, plus the Qwen3-VL 8B encoder. See [Ideogram 4](/users-guide/models/local-models/ideogram4/) |
diff --git a/invokeai/backend/flux3/checkpoint_quantization.py b/invokeai/backend/flux3/checkpoint_quantization.py
new file mode 100644
index 0000000000..63e20e932e
--- /dev/null
+++ b/invokeai/backend/flux3/checkpoint_quantization.py
@@ -0,0 +1,145 @@
+"""Which quantized FLUX.3 single files load, decided once for identification and for the loader.
+
+Identification sees a header -- the tensor names, dtypes and shapes on the meta device, the safetensors metadata, and
+the ``.comfy_quant`` markers read from their bytes -- while the loader sees the tensors. Both hand this module the same
+picture and get the same answer, so a file installs exactly when the loader can build it, and one it cannot is refused
+at 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
+speculation; nvfp4 beside scaled fp8 loads, since the loader takes each of them its own way.
+"""
+
+from collections.abc import Collection, Mapping
+from typing import Any
+
+import torch
+
+from invokeai.backend.quantization.fp8_scaled import (
+ FP8_WEIGHT_DTYPES,
+ iter_weight_scale_pairs,
+ parse_quantization_metadata,
+ strip_layer_path_prefix,
+ unparsed_fp8_scale_keys,
+)
+from invokeai.backend.quantization.int8_convrot import (
+ INT8_TENSORWISE_FORMAT,
+ check_int8_layer_layout,
+ check_int8_rotation_width,
+ reject_unmarked_int8_weights,
+)
+from invokeai.backend.quantization.nvfp4 import find_nvfp4_layers, modelopt_nvfp4_header_layers
+
+_INSTEAD = (
+ "Install the bf16 file, Comfy-Org's int8 or nvfp4 build, Black Forest Labs' fp8r or nvfp4 variant, or a GGUF "
+ "instead."
+)
+
+# The weights `flux3_transformer_config` reads the model's input widths from. Packed two codes to a byte, an nvfp4
+# weight stores its width halved, and the transformer would be built for that.
+_INPUT_WIDTH_WEIGHTS = ("emb_in.image.weight", "emb_in.image_cond.weight", "txt_in.weight", "time_in.in_layer.weight")
+
+# 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
+ ``_quantization_metadata`` entries, and for NVIDIA ModelOpt's nvfp4 export, Black Forest Labs', every packed layer,
+ since its metadata names the scheme once for all of them."""
+ return {
+ **strip_layer_path_prefix(parse_quantization_metadata(metadata)),
+ **modelopt_nvfp4_header_layers(metadata, keys),
+ }
+
+
+def reject_unloadable_quantization(
+ state_dict: dict[str, Any], header_layers: Mapping[str, Any], markers: Mapping[str, Mapping[str, Any]]
+) -> 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.
+
+ 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;
+ - 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 is
+ renamed, and the weight loaded unscaled (AWQ's ``pre_quant_scale`` beside an fp8 weight among them);
+ - int8 weights without an ``int8_tensorwise`` marker, or a layout the int8 linears cannot be built from
+ (:func:`check_int8_layer_layout`, :func:`check_int8_rotation_width`: a missing scale, a blockwise scale, a
+ 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-stored
+ ones;
+ - int8 mixed with nvfp4 or with scaled fp8;
+ - packed input embedders, whose stored width is not the model's.
+ """
+ keys = list(state_dict)
+ torchao = sorted(key for key in keys if key.endswith(_TORCHAO_PAYLOAD_SUFFIX))
+ if torchao:
+ raise ValueError(
+ f"This FLUX.3 file is saved as torchao-quantized tensors (e.g. '{torchao[0]}'), which is not supported. "
+ f"{_INSTEAD}"
+ )
+ bitsandbytes = sorted(key for key in keys if any(state in key for state in _BITSANDBYTES_STATE))
+ if bitsandbytes:
+ raise ValueError(
+ f"This FLUX.3 file carries bitsandbytes 4-bit quantization state (e.g. '{bitsandbytes[0]}'), which is not "
+ f"supported. {_INSTEAD}"
+ )
+ unparsed = unparsed_fp8_scale_keys(state_dict)
+ if unparsed:
+ raise ValueError(
+ f"{len(unparsed)} fp8 weight scale(s) of this FLUX.3 file use a spelling InvokeAI does not read (e.g. "
+ f"'{unparsed[0]}'), so their weights would load unscaled. {_INSTEAD}"
+ )
+
+ int8_markers = {path: marker for path, marker in markers.items() if marker.get("format") == INT8_TENSORWISE_FORMAT}
+ reject_unmarked_int8_weights(state_dict, int8_markers, "FLUX.3")
+ for path, marker in int8_markers.items():
+ try:
+ weight = state_dict.get(f"{path}.weight")
+ layout = check_int8_layer_layout(path, marker, weight, state_dict.get(f"{path}.weight_scale"))
+ check_int8_rotation_width(path, layout, weight)
+ except ValueError as e:
+ raise ValueError(f"{e} {_INSTEAD}") from None
+
+ nvfp4 = set(find_nvfp4_layers(state_dict, header_layers, markers=markers))
+ packed = sorted(
+ key
+ for key in keys
+ if key.endswith(".weight")
+ and getattr(state_dict[key], "dtype", None) is torch.uint8
+ and key[: -len(".weight")] not in nvfp4
+ )
+ if packed:
+ raise ValueError(
+ f"{len(packed)} weight(s) of this FLUX.3 file are packed into bytes without an nvfp4 global scale (e.g. "
+ f"'{packed[0]}'), a packing InvokeAI does not read, such as bitsandbytes NF4. {_INSTEAD}"
+ )
+
+ if int8_markers and nvfp4:
+ raise ValueError(f"This FLUX.3 file mixes int8 and nvfp4 layers, which no release does. {_INSTEAD}")
+ if int8_markers:
+ scaled_fp8 = sorted(
+ weight_key
+ for weight_key, _scale_key in iter_weight_scale_pairs(state_dict)
+ if getattr(state_dict[weight_key], "dtype", None) in FP8_WEIGHT_DTYPES
+ )
+ if scaled_fp8:
+ raise ValueError(
+ f"This FLUX.3 file mixes int8 layers with scaled fp8 ones (e.g. '{scaled_fp8[0]}'), which no release "
+ f"does. {_INSTEAD}"
+ )
+
+ packed_inputs = [key for key in _INPUT_WIDTH_WEIGHTS if key[: -len(".weight")] in nvfp4]
+ if packed_inputs:
+ raise ValueError(
+ f"This FLUX.3 file stores '{packed_inputs[0]}' packed, so its shape is not the model's input width. No "
+ f"release quantizes the input embedders. {_INSTEAD}"
+ )
diff --git a/invokeai/backend/flux3/conversion.py b/invokeai/backend/flux3/conversion.py
index d7561725ce..723388e333 100644
--- a/invokeai/backend/flux3/conversion.py
+++ b/invokeai/backend/flux3/conversion.py
@@ -1,19 +1,35 @@
"""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``, the ComfyUI repackage (byte-identical to it), 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.
+``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.
+
+Comfy-Org's ``int8_convrot`` build fuses each block's query, key and value into one ``qkv`` linear, which
+diffusers keeps apart: it is split here, its quantization side channel with it. Where a native module lands is a
+function of its name alone (:func:`flux3_native_module_to_diffusers`), because a fused ``qkv`` is split or
+refused, never left fused. A loader therefore re-keys what it read under the native names -- int8 markers, header
+entries, popped nvfp4 layers -- through that same function, and cannot drift from the conversion.
"""
import re
from collections.abc import Mapping
-from typing import Any
+from typing import Any, TypeVar
import torch
+from invokeai.backend.quantization.fp8_scaled import (
+ FP8_WEIGHT_DTYPES,
+ LAYER_SIDECHANNEL_SUFFIXES,
+ WEIGHT_SCALE_SUFFIXES,
+ split_qkv_sidechannel,
+)
from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
+from invokeai.backend.quantization.nvfp4 import WEIGHT_SCALE_2_SUFFIX, NVFP4Payload, split_nvfp4_rows
+from invokeai.backend.util.logging import InvokeAILogger
+
+logger = InvokeAILogger.get_logger(__name__)
FLUX3_NATIVE_FLOW_MAP_KEY = "ref_time_in.in_layer.weight"
"""Only the step-distilled checkpoint has it: the embedder of the timestep each step jumps to."""
@@ -41,7 +57,8 @@ _PREFIX_MAP = {
"single_blocks.": "single_transformer_blocks.",
}
-_ADALN_KEY = "final_layer.image.adaLN_modulation.1.weight"
+_ADALN_MODULE = "final_layer.image.adaLN_modulation.1"
+_ADALN_KEY = f"{_ADALN_MODULE}.weight"
_KEY_RENAMES = {
"time_in.in_layer.weight": "timestep_embedder.linear_1.weight",
@@ -55,19 +72,52 @@ _KEY_RENAMES = {
# Training-only REPA projection heads; not part of the inference model.
_TRAINING_ONLY_PREFIX = "repa_projectors."
+# ComfyUI's per-block attention-kernel hint, `{"attention": "comfy_kitchen_int8"}` in the int8_convrot build. It
+# selects one of ComfyUI's own kernels and says nothing about the weights.
+_COMFY_ATTENTION_CONFIG_SUFFIX = ".comfy_attention.config"
+
+# Comfy-Org's int8 build stores a block's query, key and value as one linear, rows in that order.
+_FUSED_QKV_SUFFIX = ".qkv"
+_QKV_PARTS = ("q_proj", "k_proj", "v_proj")
+
+# A layer's quantization side channel, carried to wherever its weight lands.
+_SIDE_CHANNEL_SUFFIXES = (WEIGHT_SCALE_2_SUFFIX, *LAYER_SIDECHANNEL_SUFFIXES)
+
+_Entry = TypeVar("_Entry")
+
def _swap_shift_scale(weight: torch.Tensor) -> torch.Tensor:
"""BFL's output adaLN produces [shift, scale]; ``Flux3AdaLayerNorm`` expects [scale, shift].
- The halves are output rows, so a packed GGML tensor is unpacked first: a row swap inside quantized
- blocks is not something a byte shuffle can express for every quantization type.
+ The halves are output rows. A packed GGML tensor is unpacked first: a row swap inside quantized blocks is not
+ something a byte shuffle can express for every quantization type. int8 and float8 codes are swapped as stored,
+ float8 as its bytes, which every supported torch build can concatenate; their per-row scale moves with them
+ (:func:`_swap_scale_rows`).
"""
if isinstance(weight, GGMLTensor):
weight = weight.get_dequantized_tensor()
+ if weight.dtype in FP8_WEIGHT_DTYPES:
+ return _swap_shift_scale(weight.view(torch.uint8)).view(weight.dtype)
shift, scale = weight.chunk(2, dim=0)
return torch.cat([scale, shift], dim=0)
+def _swap_scale_rows(suffix: str, value: Any) -> Any:
+ """The output adaLN's weight scale, swapped with the rows it scales.
+
+ A per-row scale (``[N]`` or ``[N, 1]``) has one entry per output row. A per-tensor scale, an activation scale
+ and a marker describe the whole layer and stay as they are.
+ """
+ if suffix not in WEIGHT_SCALE_SUFFIXES or not isinstance(value, torch.Tensor) or value.numel() <= 1:
+ return value
+ return _swap_shift_scale(value)
+
+
+def _is_discarded(path: str) -> bool:
+ """Whether the conversion drops a native module, and with it its side channel and any packed form."""
+ return path.startswith(_TRAINING_ONLY_PREFIX)
+
+
def flux3_native_key_to_diffusers(key: str) -> str:
"""The diffusers name of one native FLUX.3 parameter (identity for names it does not know)."""
if key in _KEY_RENAMES:
@@ -84,20 +134,128 @@ def flux3_native_key_to_diffusers(key: str) -> str:
return new_key
+def _native_module_to_diffusers(path: str) -> str:
+ """One native module's diffusers path. A norm keeps its parameter as ``scale`` and every other module as
+ ``weight``; diffusers calls both ``weight``."""
+ renamed = flux3_native_key_to_diffusers(f"{path}.scale")
+ if not renamed.endswith(".weight"):
+ renamed = flux3_native_key_to_diffusers(f"{path}.weight")
+ return renamed[: -len(".weight")]
+
+
+def flux3_native_module_to_diffusers(path: str) -> list[str]:
+ """The diffusers module(s) a native FLUX.3 module becomes: a block's fused ``qkv`` three, any other one."""
+ if path.endswith(_FUSED_QKV_SUFFIX):
+ block = path[: -len(_FUSED_QKV_SUFFIX)]
+ return [_native_module_to_diffusers(f"{block}.{part}") for part in _QKV_PARTS]
+ return [_native_module_to_diffusers(path)]
+
+
+def convert_flux3_layer_entries(entries: Mapping[str, _Entry]) -> dict[str, _Entry]:
+ """Re-key per-layer entries read under native module paths -- int8 markers, ``_quantization_metadata`` hints --
+ to the diffusers modules their weights become. A fused ``qkv``'s entry describes each of its three parts."""
+ return {
+ target: entry
+ for path, entry in entries.items()
+ if not _is_discarded(path)
+ for target in flux3_native_module_to_diffusers(path)
+ }
+
+
+def _side_channel_parts(key: str) -> tuple[str, str] | None:
+ """``(module path, suffix)`` for a quantization side-channel key, else None."""
+ for suffix in _SIDE_CHANNEL_SUFFIXES:
+ if key.endswith(suffix):
+ return key[: -len(suffix)], suffix
+ return None
+
+
+def _split_fused_qkv(key: str, weight: torch.Tensor) -> tuple[torch.Tensor, ...]:
+ """The query, key and value rows of a fused ``qkv`` weight.
+
+ Rows split cleanly for int8 and float8 codes: their scales are per row or per tensor, and ``convrot`` rotates
+ along the input dimension. A packed weight is refused: GGML blocks and nvfp4's two codes per byte are not split
+ here. (A header-named nvfp4 ``qkv`` never gets here; :func:`convert_flux3_nvfp4_payloads` splits its packed form
+ on whole scale tiles.)
+ """
+ if isinstance(weight, GGMLTensor) or weight.dtype is torch.uint8:
+ raise ValueError(
+ f"The FLUX.3 checkpoint stores the fused '{key}' packed, and a packed fused projection cannot be split "
+ "into the separate query, key and value the model has. Use a build with q_proj, k_proj and v_proj, or the "
+ "bf16 file."
+ )
+ if weight.dim() != 2 or weight.shape[0] % 3 != 0:
+ raise ValueError(
+ f"The FLUX.3 checkpoint's fused '{key}' has shape {tuple(weight.shape)}, which does not split into equal "
+ "query, key and value rows."
+ )
+ return weight.chunk(3, dim=0)
+
+
def convert_flux3_native_to_diffusers(state_dict: dict[str, Any]) -> dict[str, Any]:
"""Rename a native FLUX.3 transformer state dict to the diffusers module, in place of the input.
- The input dict is emptied as it is converted, so the caller's reference does not keep a second copy of
- every tensor alive.
+ A quantization side channel (weight and input scales, ``.comfy_quant`` markers) follows its weight: a fused
+ ``qkv``'s is split with it (``split_qkv_sidechannel``), and the output adaLN's per-row weight scale is swapped
+ with its rows. Left behind under a name the model does not have, a scale would be dropped and its weight loaded
+ off by ``1/weight_scale``, with nothing in the log.
+
+ The input dict is emptied as it is converted, so the caller's reference does not keep a second copy of every
+ tensor alive.
"""
converted: dict[str, Any] = {}
+ attention_hints = 0
for key in list(state_dict.keys()):
value = state_dict.pop(key)
- if key.startswith(_TRAINING_ONLY_PREFIX):
+ if key.endswith(_COMFY_ATTENTION_CONFIG_SUFFIX):
+ attention_hints += 1
+ continue
+ side_channel = _side_channel_parts(key)
+ module = side_channel[0] if side_channel is not None else key.rpartition(".")[0]
+ if _is_discarded(module):
continue
- if key == _ADALN_KEY:
- value = _swap_shift_scale(value)
- converted[flux3_native_key_to_diffusers(key)] = value
+ targets = flux3_native_module_to_diffusers(module)
+ if side_channel is not None:
+ suffix = side_channel[1]
+ if module == _ADALN_MODULE:
+ value = _swap_scale_rows(suffix, value)
+ parts = split_qkv_sidechannel(key, value) if len(targets) > 1 else (value,)
+ converted.update({f"{target}{suffix}": part for target, part in zip(targets, parts, strict=True)})
+ elif len(targets) > 1 and key == f"{module}.weight":
+ projections = _split_fused_qkv(key, value)
+ converted.update({f"{target}.weight": part for target, part in zip(targets, projections, strict=True)})
+ else:
+ converted[flux3_native_key_to_diffusers(key)] = _swap_shift_scale(value) if key == _ADALN_KEY else value
+ if attention_hints:
+ logger.debug(f"FLUX.3: dropped {attention_hints} ComfyUI attention-kernel hint(s) (comfy_attention.config).")
+ return converted
+
+
+def convert_flux3_nvfp4_payloads(payloads: Mapping[str, NVFP4Payload]) -> dict[str, NVFP4Payload]:
+ """Re-key packed nvfp4 layers, taken out of a native state dict, to the diffusers modules they become.
+
+ The packed counterpart of :func:`convert_flux3_native_to_diffusers`, for the layers a loader takes out before
+ converting: a fused ``qkv`` splits into thirds and the output adaLN swaps its halves, both on whole 128-row bands
+ (``split_nvfp4_rows``). The codes stay as stored, and so does the grid, in either of its layouts: a band of
+ ComfyUI's cuBLAS tiles is a band of rows, as it is of ModelOpt's row-major grid, which is therefore re-laid out
+ after this as well as before.
+ """
+ converted: dict[str, NVFP4Payload] = {}
+ for path, payload in payloads.items():
+ if _is_discarded(path):
+ continue
+ if path == _ADALN_MODULE:
+ shift, scale = split_nvfp4_rows(path, payload, 2)
+ # The block scales as bytes, which every supported torch build can concatenate.
+ grid = torch.cat([scale.weight_scale.view(torch.uint8), shift.weight_scale.view(torch.uint8)])
+ payload = NVFP4Payload(
+ weight=torch.cat([scale.weight, shift.weight]),
+ weight_scale=grid.view(payload.weight_scale.dtype),
+ weight_scale_2=payload.weight_scale_2,
+ )
+ targets = flux3_native_module_to_diffusers(path)
+ parts = split_nvfp4_rows(path, payload, len(targets)) if len(targets) > 1 else [payload]
+ converted.update(zip(targets, parts, strict=True))
return converted
@@ -122,8 +280,10 @@ def _count_blocks(state_dict: Mapping[str, Any], prefix: str) -> int:
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.
- 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.
+ 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]
diff --git a/invokeai/backend/flux3/denoise_working_memory.py b/invokeai/backend/flux3/denoise_working_memory.py
index cec5f2e3f5..ac64186932 100644
--- a/invokeai/backend/flux3/denoise_working_memory.py
+++ b/invokeai/backend/flux3/denoise_working_memory.py
@@ -102,10 +102,12 @@ The analytic terms:
calibration script, whose models are always resident, declares them so (`weights_resident`), and the term is zero.
- Where SDPA has no fused kernel for these shapes it materializes the score matrices, shaped (batch, heads, S, S) over
the joint sequence: `sdpa_score_matrix_bytes` prices them only where they are really built. No mask is passed.
-- The dequantization copy a GGUF build materializes per quantized linear and forward, alive alongside the activations
- and invisible to them (`peak_dequant_transient_bytes`); zero for every other build.
-- The compute-dtype copies of a layer's float8-stored weights that FP8 Storage widens per forward
- (`peak_fp8_cast_transient_bytes`); zero for every other build.
+- The dequantization copy a GGUF, int8 or nvfp4 build materializes per quantized linear and forward, alive alongside
+ the activations and invisible to them (`peak_dequant_transient_bytes`); zero for a build that keeps no layer
+ quantized.
+- The compute-dtype copies of a layer's float8-stored weights that FP8 Storage widens per forward, or that a kept
+ scaled-fp8 checkpoint (BFL's fp8r) dequantizes with its scale (`peak_fp8_cast_transient_bytes`); zero for a build
+ that holds no float8 weight.
- What the LoRAs on the transformer need beside the activations, their sidecar layers' tensors and the largest
update a patched module forms per forward (`patches.sidecar_working_memory.lora_sidecar_bytes`): an update has a row
per token of the joint sequence of every sample, but in the timestep embedders (`_TIMESTEP_EMBEDDERS`), which run
diff --git a/invokeai/backend/model_manager/configs/main.py b/invokeai/backend/model_manager/configs/main.py
index 3c6edff437..a989b5145f 100644
--- a/invokeai/backend/model_manager/configs/main.py
+++ b/invokeai/backend/model_manager/configs/main.py
@@ -1,4 +1,5 @@
import re
+import struct
from abc import ABC
from pathlib import Path
from typing import Any, ClassVar, Literal, Self
@@ -15,8 +16,9 @@ from invokeai.backend.anima.checkpoint_layout import (
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.ltx2 import checkpoint_layout as ltx2_layout
-from invokeai.backend.model_manager.checkpoint_prefix import COMFYUI_KEY_PREFIXES
+from invokeai.backend.model_manager.checkpoint_prefix import COMFYUI_KEY_PREFIXES, CheckpointPrefix
from invokeai.backend.model_manager.configs.base import (
Checkpoint_Config_Base,
Config_Base,
@@ -76,6 +78,7 @@ from invokeai.backend.model_manager.taxonomy import (
)
from invokeai.backend.patches.lora_conversions.sd3_lora_constants import sd3_variant_from_width
from invokeai.backend.quantization.fp8_scaled import (
+ COMFY_QUANT_SUFFIX,
FP8_WEIGHT_DTYPES,
is_scale_metadata_key,
parse_quantization_metadata,
@@ -2350,25 +2353,23 @@ _FLUX3_LORA_SUFFIXES = (
".alpha",
)
-# A quantized side channel next to a weight, or a weight stored in a quantized dtype. FLUX.3 loads these
-# builds later; until it does, they are refused with a message rather than loaded wrongly.
-_FLUX3_QUANTIZATION_SUFFIXES = (".weight_scale", ".weight_scale_2", ".input_scale", ".scale_weight", ".comfy_quant")
-_FLUX3_QUANTIZED_DTYPES = (torch.float8_e4m3fn, torch.float8_e5m2, torch.uint8, torch.int8)
-
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.
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.
+ 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.
"""
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 False
- return "early_stream_modulations.image.lin.weight" in set(keys) and any(
- key.startswith("content_mode_blocks.image.") for key in keys
- )
+ key_set = set(keys)
+ return 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)
def _get_flux3_variant(state_dict: dict[str | int, Any]) -> Flux3VariantType:
@@ -2425,7 +2426,12 @@ class Main_Diffusers_Flux3_Config(Diffusers_Config_Base, Main_Config_Base, Confi
class Main_Checkpoint_Flux3_Config(Checkpoint_Config_Base, Main_Config_Base, Config_Base):
- """Model config for FLUX.3 Image single-file transformers (BFL `model.safetensors`, ComfyUI bf16)."""
+ """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.
+ """
base: Literal[BaseModelType.Flux3] = Field(default=BaseModelType.Flux3)
format: Literal[ModelFormat.Checkpoint] = Field(default=ModelFormat.Checkpoint)
@@ -2445,24 +2451,35 @@ class Main_Checkpoint_Flux3_Config(Checkpoint_Config_Base, Main_Config_Base, Con
raise NotAMatchError("state dict does not look like a FLUX.3 model")
if _has_ggml_tensors(state_dict):
raise NotAMatchError("state dict looks like GGUF quantized")
- cls._raise_for_quantized_weights(state_dict)
+ cls._raise_for_unsupported_quantization(mod, state_dict)
variant = override_fields.pop("variant", None) or _get_flux3_variant(state_dict)
return cls(**override_fields, variant=variant)
@classmethod
- def _raise_for_quantized_weights(cls, state_dict: dict[str | int, Any]) -> None:
- for key, value in state_dict.items():
- if not isinstance(key, str):
- continue
- if key.endswith(_FLUX3_QUANTIZATION_SUFFIXES) or (
- key.endswith(".weight") and getattr(value, "dtype", None) in _FLUX3_QUANTIZED_DTYPES
- ):
+ def _raise_for_unsupported_quantization(cls, mod: ModelOnDisk, state_dict: dict[str | int, Any]) -> None:
+ """Refuse at install what the loader would refuse at the first render.
+
+ The rules are the loader's own (`flux3/checkpoint_quantization.py`), applied to the header: the tensors'
+ names, dtypes and shapes, the metadata, and the `.comfy_quant` markers, read from their bytes since a meta
+ tensor has none.
+ """
+ prefix = CheckpointPrefix.detect(state_dict)
+ native = prefix.strip({key: value for key, value in state_dict.items() if isinstance(key, str)})
+ markers: dict[str, dict[str, Any]] = {}
+ if any(key.endswith(COMFY_QUANT_SUFFIX) for key in native):
+ try:
+ markers = prefix.strip(read_comfy_quant_markers(mod.path))
+ except (OSError, ValueError, KeyError, struct.error) as e:
raise InvalidMatchError(
- "this FLUX.3 build is quantized (fp8, int8 or nvfp4), which is not supported yet; install the "
- "bf16 file or a GGUF build"
- )
+ f"the `.comfy_quant` markers of this FLUX.3 file could not be read ({e}), so its quantization "
+ "cannot be identified"
+ ) from None
+ try:
+ reject_unloadable_quantization(native, flux3_header_layers(mod.metadata(), native), markers)
+ except ValueError as e:
+ raise InvalidMatchError(str(e)) from None
class Main_GGUF_Flux3_Config(Checkpoint_Config_Base, Main_Config_Base, Config_Base):
diff --git a/invokeai/backend/model_manager/load/model_loaders/flux3.py b/invokeai/backend/model_manager/load/model_loaders/flux3.py
index 4bef391ecc..bea56a0229 100644
--- a/invokeai/backend/model_manager/load/model_loaders/flux3.py
+++ b/invokeai/backend/model_manager/load/model_loaders/flux3.py
@@ -9,18 +9,27 @@ Submodel map of a Diffusers folder (subfolder == ``SubModelType`` value, except
- ``text_encoder`` -> ``Qwen3VLModel`` (Qwen3-VL 4B Instruct), visual tower dropped
- tokenizer -> ``AutoTokenizer`` from ``text_encoder/``, where the release keeps its tokenizer files
-Single-file and GGUF builds are only the transformer, in Black Forest Labs' key layout.
+Single-file and GGUF builds are only the transformer, in Black Forest Labs' key layout. The single-file loader
+also 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.
"""
-from collections.abc import Callable
+from collections.abc import Callable, Mapping
+from logging import Logger
from pathlib import Path
-from typing import Optional
+from typing import Any, Optional
import accelerate
import torch
from transformers import AutoConfig, AutoTokenizer, Qwen3VLModel
-from invokeai.backend.flux3.conversion import convert_flux3_native_to_diffusers, flux3_transformer_config
+from invokeai.backend.flux3.checkpoint_quantization import flux3_header_layers, reject_unloadable_quantization
+from invokeai.backend.flux3.conversion import (
+ convert_flux3_layer_entries,
+ convert_flux3_native_to_diffusers,
+ convert_flux3_nvfp4_payloads,
+ flux3_transformer_config,
+)
from invokeai.backend.model_manager.checkpoint_prefix import CheckpointPrefix
from invokeai.backend.model_manager.configs.factory import AnyModelConfig
from invokeai.backend.model_manager.configs.main import (
@@ -32,15 +41,44 @@ from invokeai.backend.model_manager.load.load_default import ModelLoader, _model
from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistry
from invokeai.backend.model_manager.taxonomy import AnyModel, BaseModelType, ModelFormat, ModelType, SubModelType
from invokeai.backend.model_manager.util.qwen3_vl import drop_qwen3vl_visual_tower, normalize_qwen3vl_rope_config
-from invokeai.backend.quantization.fp8_scaled import cast_state_dict, reject_quantized_side_channel
+from invokeai.backend.quantization.dequantizing_linear import DequantizingLinear
+from invokeai.backend.quantization.fp8_scaled import (
+ COMFY_QUANT_SUFFIX,
+ Fp8ScaledLayer,
+ attach_fp8_scales,
+ cast_state_dict,
+ count_fp8_weights,
+ dequantize_fp8_scaled,
+ extract_comfy_quant_hints,
+ extract_fp8_scaled_layers,
+ read_safetensors_metadata,
+ split_fp8_scaled_layers,
+ warn_on_unattached_scales,
+)
from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader, unpack_ggml_at_load
+from invokeai.backend.quantization.int8_convrot import (
+ drop_unconsumed_quantization_sidecars,
+ extract_int8_convrot_markers,
+ install_int8_convrot_layers,
+ parse_comfy_quant_marker,
+)
+from invokeai.backend.quantization.int8_matmul import is_int8_compute_enabled
from invokeai.backend.quantization.load_plan import reserve_for_load
+from invokeai.backend.quantization.nvfp4 import (
+ install_nvfp4_layers,
+ is_modelopt_nvfp4,
+ pop_nvfp4_layers,
+ relayout_modelopt_nvfp4_payloads,
+)
from invokeai.backend.util.devices import TorchDevice
+from invokeai.backend.util.logging import InvokeAILogger
from invokeai.backend.util.state_dict_loading import load_state_dict_ignoring_extras, reject_incomplete_load
_QK_NORM_WEIGHTS = (".norm_q.weight", ".norm_k.weight")
+_logger = InvokeAILogger.get_logger(__name__)
+
def _keep_qk_norms_in_fp32(model: torch.nn.Module) -> None:
"""Hold the attention QK-norm weights in float32, as diffusers' `_keep_in_fp32_modules` does on a folder load.
@@ -62,34 +100,106 @@ def _build_transformer(state_dict: dict) -> torch.nn.Module:
return Flux3Transformer2DModel(**model_config)
+def _reserve_nothing(_bytes: int) -> None:
+ """The reservation of a load that happens outside the RAM cache."""
+
+
def flux3_transformer_from_native(
- sd: dict, dtype: torch.dtype, reserve: Optional[Callable[[int], None]] = None
+ sd: dict,
+ dtype: torch.dtype,
+ reserve: Optional[Callable[[int], None]] = None,
+ *,
+ metadata: Optional[Mapping[str, Any]] = None,
+ 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
- norms in float32. Empties `sd`. `reserve` asks the RAM cache for room before the cast, as `reserve_for_load` does;
- None asks nothing, for a caller that loads outside the cache (the working-memory calibration script)."""
+ norms in float32. Empties `sd`.
+
+ `reserve` asks the RAM cache for room once, before anything widens a weight, as `reserve_for_load` does; None asks
+ nothing, for a caller that loads outside the cache (the working-memory calibration script). `metadata` is the
+ file's safetensors metadata: ComfyUI's nvfp4 build names its layers there, and BFL's says it is a ModelOpt export.
+ `keep_fp8` keeps scaled fp8 weights quantized with their scales attached, for the fp8 matmul or FP8 Storage;
+ without it they are folded into `dtype`.
+
+ A quantized layer stays quantized where the model has a plain Linear outside its precision-sensitive modules:
+ int8 as `Int8ConvrotLinear`, nvfp4 as `NVFP4Linear`, scaled fp8 with `keep_fp8`. Anything else, such as
+ `norm_out.linear` (the output adaLN, under the model's `norm` pattern), is decoded into `dtype` with its scale.
+ What the loader cannot build is refused first, by the same rules identification applies to the header
+ (`flux3/checkpoint_quantization.py`).
+ """
+ log = logger or _logger
+ make_room = reserve or _reserve_nothing
sd = CheckpointPrefix.detect(sd).strip(sd)
- # Identification refuses quantized builds already; this catches a record made before it did.
- reject_quantized_side_channel(sd, "a FLUX.3 single-file checkpoint")
-
+ header_layers = flux3_header_layers(metadata, sd)
+ markers = {
+ key[: -len(COMFY_QUANT_SUFFIX)]: parse_comfy_quant_marker(value)
+ for key, value in sd.items()
+ if key.endswith(COMFY_QUANT_SUFFIX)
+ }
+ reject_unloadable_quantization(sd, header_layers, markers)
+ # 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)
+
+ # Shaped before the nvfp4 layers leave the state dict: `mlp_in`, whose rows give the feedforward width, is one.
model = _build_transformer(sd)
+ nvfp4_payloads = convert_flux3_nvfp4_payloads(pop_nvfp4_layers(sd, header_layers))
+ # Before the fp8 hints, which take every `.comfy_quant` marker out of the state dict, the int8 ones included.
+ int8_markers = extract_int8_convrot_markers(sd)
+ layer_hints: dict[str, Any] = {}
+ if int8_markers:
+ 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)
+
skip_patterns = _model_declared_skip_patterns(model)
- if reserve is not None:
+ fp8_layers: dict[str, Fp8ScaledLayer] = {}
+ if int8_markers:
+ # No int8 build carries nvfp4 or scaled fp8 layers beside them; `reject_unloadable_quantization` refused that.
+ int8_layers = install_int8_convrot_layers(
+ model, sd, int8_markers, dtype, architecture="FLUX.3", reserve=make_room, skip_patterns=skip_patterns
+ )
+ how = (
+ "multiplied in int8 where int8 Compute's kernels cover them, dequantized per forward elsewhere"
+ if is_int8_compute_enabled()
+ else "dequantized per forward"
+ )
+ log.info(f"FLUX.3: kept {len(int8_layers)} of {len(int8_markers)} layer(s) in int8 (int8_tensorwise, {how}).")
+ else:
+ fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)
reserve_for_load(
- reserve,
+ make_room,
sd,
dtype,
- keep_fp8=False,
+ keep_fp8=keep_fp8,
model=model,
skip_patterns=skip_patterns,
- fp8_layers={},
- nvfp4_payloads={},
+ fp8_layers=fp8_layers,
+ nvfp4_payloads=nvfp4_payloads,
)
- cast_state_dict(sd, dtype, keep_fp8=False, model=model, skip_patterns=skip_patterns)
+ if 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)
+ fp8_layers = {}
+ # The scaled layers the cast would widen are folded with their scale first: `norm_out.linear`, and any
+ # 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 nvfp4_payloads:
+ if modelopt:
+ # After the reservation: the copies it makes are what the reservation counts for the packed layers.
+ relayout_modelopt_nvfp4_payloads(nvfp4_payloads)
+ packed = install_nvfp4_layers(model, sd, nvfp4_payloads, dtype, skip_patterns)
+ log.info(f"FLUX.3: kept {packed} of {len(nvfp4_payloads)} nvfp4 layer(s) packed (dequantized per forward).")
+
load_state_dict_ignoring_extras(model, sd, source="FLUX.3 single-file checkpoint", assign=True, allow_missing=True)
reject_incomplete_load(model, what="FLUX.3 single-file checkpoint")
sd.clear()
+ if fp8_layers:
+ warn_on_unattached_scales(log, "FLUX.3", attach_fp8_scales(model, fp8_layers), fp8_layers)
_keep_qk_norms_in_fp32(model)
return model
@@ -155,7 +265,8 @@ 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 bf16 file (BFL `model.safetensors`, or its ComfyUI repackage)."""
+ """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."""
def _load_model(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> AnyModel:
if not isinstance(config, Main_Checkpoint_Flux3_Config):
@@ -165,8 +276,30 @@ class Flux3CheckpointModel(ModelLoader):
from safetensors.torch import load_file
+ model_path = Path(config.path)
model_dtype = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device())
- model = flux3_transformer_from_native(load_file(Path(config.path)), model_dtype, self._ram_cache.make_room)
+ model = flux3_transformer_from_native(
+ load_file(model_path),
+ model_dtype,
+ self._ram_cache.make_room,
+ metadata=read_safetensors_metadata(model_path, self._logger),
+ keep_fp8=self._keep_fp8_weights(config, SubModelType.Transformer),
+ logger=self._logger,
+ )
+ if any(isinstance(module, DequantizingLinear) for module in model.modules()):
+ # What FP8 Storage could still cast is the dense remainder: the modulations, the embedders, the output
+ # layers and, in the nvfp4 builds, the blocks BFL excludes from quantization. The build left those in bf16
+ # on purpose, and the storage cast would round them to unscaled fp8, so it is skipped, as for FLUX.2's int8.
+ if self._fp8_storage_asked_for(config, SubModelType.Transformer):
+ self._logger.info(
+ "FLUX.3: FP8 Storage skipped - this int8 or nvfp4 build keeps its quantized layers as stored and "
+ "its other layers in the precision the build chose."
+ )
+ return model
+ if kept := count_fp8_weights(model):
+ self._logger.info(
+ f"FLUX.3: kept {kept} layer(s) in fp8 (fp8 checkpoint, kept for {self._fp8_kept_reason()})."
+ )
return self._apply_fp8_layerwise_casting(model, config, SubModelType.Transformer)
diff --git a/invokeai/backend/model_manager/starter_models/__init__.py b/invokeai/backend/model_manager/starter_models/__init__.py
index 37786e1984..ca3ee652e3 100644
--- a/invokeai/backend/model_manager/starter_models/__init__.py
+++ b/invokeai/backend/model_manager/starter_models/__init__.py
@@ -182,9 +182,13 @@ from invokeai.backend.model_manager.starter_models.flux2 import (
from invokeai.backend.model_manager.starter_models.flux3 import (
flux3_klein,
flux3_klein_base,
+ flux3_klein_base_int8,
+ flux3_klein_base_nvfp4,
flux3_klein_base_single_file,
flux3_klein_gguf_q4_k_m,
flux3_klein_gguf_q8_0,
+ flux3_klein_int8,
+ flux3_klein_nvfp4,
flux3_klein_single_file,
flux3_prompt_upsampler,
flux3_prompt_upsampler_int8,
@@ -592,6 +596,10 @@ STARTER_MODELS: list[StarterModel] = [
flux3_klein_base,
flux3_klein_single_file,
flux3_klein_base_single_file,
+ flux3_klein_int8,
+ flux3_klein_nvfp4,
+ flux3_klein_base_int8,
+ flux3_klein_base_nvfp4,
flux3_klein_gguf_q4_k_m,
flux3_klein_gguf_q8_0,
flux3_prompt_upsampler,
diff --git a/invokeai/backend/model_manager/starter_models/flux3.py b/invokeai/backend/model_manager/starter_models/flux3.py
index 440f9d4ede..a58e8b9ec3 100644
--- a/invokeai/backend/model_manager/starter_models/flux3.py
+++ b/invokeai/backend/model_manager/starter_models/flux3.py
@@ -69,6 +69,70 @@ flux3_klein_base_single_file = StarterModel(
dependencies=[flux2_vae, qwen3_vl_encoder_4b],
)
+# Comfy-Org's quantized repackages, pinned to a commit rather than `main`. That is a correctness matter, not only
+# reproducibility: the int8 decode follows each layer's `comfy_quant` marker (`convrot`, its group size) and the nvfp4
+# one the layers the header names, so a re-upload at the same path that changed either would load cleanly and
+# generate noise. The repository has renamed its files once already. Black Forest Labs' own `variants/` builds are
+# not listed: Klein's and Klein Base's are both `model.safetensors`, so they are installed by URL (see the FLUX.3 docs).
+_COMFY_QUANTIZED = (
+ "https://huggingface.co/black-forest-labs/flux-3-image-klein-comfy/resolve/"
+ "feef60b0aaf63a4773ace96636ebbcf43b881312/diffusion_models"
+)
+_INT8_NOTE = (
+ "Its quantized layers stay int8 in memory on every GPU and are decoded per step, or with int8 Compute (RTX 30-series "
+ "and newer) multiplied in int8."
+)
+_NVFP4_NOTE = "Its 4-bit weights are decoded on every step."
+
+flux3_klein_int8 = StarterModel(
+ name="FLUX.3 Klein (int8)",
+ base=BaseModelType.Flux3,
+ source=f"{_COMFY_QUANTIZED}/flux3-image-klein-int8-convrot.safetensors",
+ description="FLUX.3 Image Klein transformer in Comfy-Org's int8_convrot build, about half the memory of bf16. "
+ f"{_INT8_NOTE} The FLUX.2 VAE and Qwen3-VL 4B encoder are installed as dependencies. ~5.8GB. {_LICENSE}",
+ type=ModelType.Main,
+ format=ModelFormat.Checkpoint,
+ variant=Flux3VariantType.Klein,
+ dependencies=[flux2_vae, qwen3_vl_encoder_4b],
+)
+
+flux3_klein_nvfp4 = StarterModel(
+ name="FLUX.3 Klein (NVFP4)",
+ base=BaseModelType.Flux3,
+ source=f"{_COMFY_QUANTIZED}/flux3-image-klein-nvfp4.safetensors",
+ description="FLUX.3 Image Klein transformer in Comfy-Org's nvfp4 build: 33 of its 43 blocks in 4 bits, the rest "
+ f"bf16. {_NVFP4_NOTE} The FLUX.2 VAE and Qwen3-VL 4B encoder are installed as dependencies. ~5.3GB. {_LICENSE}",
+ type=ModelType.Main,
+ format=ModelFormat.Checkpoint,
+ variant=Flux3VariantType.Klein,
+ dependencies=[flux2_vae, qwen3_vl_encoder_4b],
+)
+
+flux3_klein_base_int8 = StarterModel(
+ name="FLUX.3 Klein Base (int8)",
+ base=BaseModelType.Flux3,
+ source=f"{_COMFY_QUANTIZED}/flux3-image-klein-base-int8-convrot.safetensors",
+ description="FLUX.3 Image Klein Base transformer in Comfy-Org's int8_convrot build, about half the memory of bf16. "
+ f"{_INT8_NOTE} The FLUX.2 VAE and Qwen3-VL 4B encoder are installed as dependencies. ~5.8GB. {_LICENSE}",
+ type=ModelType.Main,
+ format=ModelFormat.Checkpoint,
+ variant=Flux3VariantType.KleinBase,
+ dependencies=[flux2_vae, qwen3_vl_encoder_4b],
+)
+
+flux3_klein_base_nvfp4 = StarterModel(
+ name="FLUX.3 Klein Base (NVFP4)",
+ base=BaseModelType.Flux3,
+ source=f"{_COMFY_QUANTIZED}/flux3-image-klein-base-nvfp4.safetensors",
+ description="FLUX.3 Image Klein Base transformer in Comfy-Org's nvfp4 build: 33 of its 43 blocks in 4 bits, the "
+ f"rest bf16. {_NVFP4_NOTE} The FLUX.2 VAE and Qwen3-VL 4B encoder are installed as dependencies. ~5.3GB. "
+ f"{_LICENSE}",
+ type=ModelType.Main,
+ format=ModelFormat.Checkpoint,
+ variant=Flux3VariantType.KleinBase,
+ dependencies=[flux2_vae, qwen3_vl_encoder_4b],
+)
+
flux3_klein_gguf_q4_k_m = StarterModel(
name="FLUX.3 Klein (GGUF Q4_K_M)",
base=BaseModelType.Flux3,
diff --git a/invokeai/backend/quantization/block_scale_tiles.py b/invokeai/backend/quantization/block_scale_tiles.py
index 66d42f1a9d..71cd804aaa 100644
--- a/invokeai/backend/quantization/block_scale_tiles.py
+++ b/invokeai/backend/quantization/block_scale_tiles.py
@@ -9,6 +9,10 @@ Two schemes in this tree arrive in it, with different block widths and different
nvfp4 (16-element blocks, ``float8_e4m3fn`` entries) and MXFP8 (32-element blocks, E8M0 exponent
bytes). The tiling is over the *grid*, so it is the same permutation for both and belongs to
neither scheme -- which is why it lives here rather than in one of them importing the other.
+
+Not every producer tiles. NVIDIA's ModelOpt exports, Black Forest Labs' FLUX.3 nvfp4 build among them,
+store the grid row-major; :func:`block_scale_grid` tiles such a grid once at load, so that every decode
+here reads one layout.
"""
import torch
@@ -48,3 +52,19 @@ def unblock_scale_grid(scale: torch.Tensor) -> torch.Tensor:
check_tile_layout(rows, blocks)
tiles = scale.reshape(rows // TILE_ROWS, blocks // TILE_BLOCKS, 32, 4, TILE_BLOCKS)
return tiles.permute(0, 3, 2, 1, 4).reshape(rows, blocks)
+
+
+def block_scale_grid(grid: torch.Tensor) -> torch.Tensor:
+ """Lay a row-major ``[rows, blocks]`` grid out in cuBLAS's tiled layout: the inverse of
+ :func:`unblock_scale_grid`.
+
+ Row-major ``(tile row, row // 32, row % 32, tile column, block)`` becomes the stored ``(tile row,
+ tile column, row % 32, row // 32, block)``. It is the same permutation of axes as the unblocking one,
+ which swaps two axes and so undoes itself.
+ """
+ if grid.dim() != 2:
+ raise ValueError(f"expected a 2-D block-scale grid, got shape {tuple(grid.shape)}")
+ rows, blocks = grid.shape
+ check_tile_layout(rows, blocks)
+ tiles = grid.reshape(rows // TILE_ROWS, 4, 32, blocks // TILE_BLOCKS, TILE_BLOCKS)
+ return tiles.permute(0, 3, 2, 1, 4).reshape(rows, blocks)
diff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.py
index d97fde5263..d86dbffe56 100644
--- a/invokeai/backend/quantization/fp8_scaled.py
+++ b/invokeai/backend/quantization/fp8_scaled.py
@@ -416,19 +416,30 @@ def _usable_input_scale(scale: torch.Tensor | None) -> torch.Tensor | None:
_MX_SCALE_DTYPES = tuple(dtype for dtype in (torch.uint8, getattr(torch, "float8_e8m0fnu", None)) if dtype is not None)
-def _reject_unparsed_scales(sd: Mapping[str, Any]) -> None:
- """Refuse a scale spelling this module does not parse when it sits beside an fp8 weight.
+def unparsed_fp8_scale_keys(sd: Mapping[str, Any]) -> list[str]:
+ """The scale keys beside an fp8 weight in a spelling this module does not parse, such as ``.weight_scale_inv``.
- Loaders ignore unexpected keys (logged at DEBUG), so a leftover ``.weight_scale_inv``-style
- key would otherwise let its weight load unscaled and generate noise instead of failing here.
+ Read off the key names beside each ``<module>.weight``, so it is only right in the namespace the scale was
+ written in: a loader that renames keys has to ask before renaming, or a scale its converter does not carry is
+ left behind under the old name, sits beside no weight any more, and its weight loads unscaled.
"""
- unparsed = sorted(
+ return sorted(
key
for key in sd
if isinstance(key, str)
and "scale" in key.rsplit(".", 1)[-1]
+ and not key.endswith(WEIGHT_SCALE_SUFFIXES + INPUT_SCALE_SUFFIXES)
and getattr(sd.get(f"{key.rsplit('.', 1)[0]}.weight"), "dtype", None) in FP8_WEIGHT_DTYPES
)
+
+
+def _reject_unparsed_scales(sd: Mapping[str, Any]) -> None:
+ """Refuse a scale spelling this module does not parse when it sits beside an fp8 weight.
+
+ Loaders ignore unexpected keys (logged at DEBUG), so a leftover ``.weight_scale_inv``-style
+ key would otherwise let its weight load unscaled and generate noise instead of failing here.
+ """
+ unparsed = unparsed_fp8_scale_keys(sd)
if unparsed:
raise NotImplementedError(
f"Unsupported fp8 scale layout: {unparsed[:8]}{' ...' if len(unparsed) > 8 else ''}. InvokeAI reads "
diff --git a/invokeai/backend/quantization/int8_convrot.py b/invokeai/backend/quantization/int8_convrot.py
index 3ceb401bb9..829ba012ba 100644
--- a/invokeai/backend/quantization/int8_convrot.py
+++ b/invokeai/backend/quantization/int8_convrot.py
@@ -1021,6 +1021,47 @@ def _pinned_quantized_keys(quantized: Mapping[str, Any]) -> set[str]:
return {key for path in quantized for key in (f"{path}.weight", f"{path}.weight_scale")}
+def check_int8_layer_layout(
+ path: str, marker: Mapping[str, Any], weight: torch.Tensor | None, scale: torch.Tensor | None
+) -> ConvrotLayout:
+ """Refuse a marked layer the int8/int4 linears cannot be built from, and return its layout.
+
+ Both tensors present, a 2-D weight, a scale granularity the decode implements, a readable marker. Whether the
+ rotation fits the layer's width is :func:`check_int8_rotation_width`, kept apart so the swap can report a payload
+ that does not match the architecture first. Only shapes are read, so an installer can ask it of meta tensors.
+ """
+ fmt = marker.get("format")
+ if weight is None or scale is None:
+ raise ValueError(
+ f"'{path}' is marked {fmt} but is missing its {'weight' if weight is None else 'weight_scale'}."
+ )
+ if weight.dim() != 2:
+ raise ValueError(
+ f"'{path}' is marked {fmt} but its weight is {tuple(weight.shape)}, not 2-D. "
+ "Only a Linear weight can be kept quantized; dequantize this one instead."
+ )
+ check_int8_scale_layout(path, weight, scale)
+ return marker_layout(marker)
+
+
+def check_int8_rotation_width(path: str, layout: ConvrotLayout, weight: torch.Tensor) -> None:
+ """Refuse a rotation group that is not a power of 4 or does not divide the decoded input width."""
+ if layout.convrot:
+ try:
+ check_hadamard_size(layout.group_size)
+ except ValueError:
+ raise ValueError(
+ f"'{path}' is rotated in groups of {layout.group_size}; a rotation is undone only in groups of a "
+ "power of 4 (256 in every release)."
+ ) from None
+ in_features = weight.shape[1] * (2 if layout.packed_int4 else 1)
+ if in_features % layout.group_size != 0:
+ raise ValueError(
+ f"'{path}' is rotated in groups of {layout.group_size}, which do not divide its input width "
+ f"{in_features}."
+ )
+
+
def swap_in_int8_linears(model: torch.nn.Module, sd: dict[str, Any], quantized: dict[str, dict[str, Any]]) -> None:
"""Replace each quantized ``nn.Linear`` with an ``Int8ConvrotLinear`` or, for a packed int4 marker, an
``Int4ConvrotLinear``, sized from the state dict.
@@ -1047,17 +1088,8 @@ def swap_in_int8_linears(model: torch.nn.Module, sd: dict[str, Any], quantized:
for path, marker in quantized.items():
fmt = marker.get("format")
weight, scale = sd.get(f"{path}.weight"), sd.get(f"{path}.weight_scale")
- if weight is None or scale is None:
- raise ValueError(
- f"'{path}' is marked {fmt} but is missing its {'weight' if weight is None else 'weight_scale'}."
- )
- if weight.dim() != 2:
- raise ValueError(
- f"'{path}' is marked {fmt} but its weight is {tuple(weight.shape)}, not 2-D. "
- "Only a Linear weight can be kept quantized; dequantize this one instead."
- )
- check_int8_scale_layout(path, weight, scale)
- layout = marker_layout(marker)
+ layout = check_int8_layer_layout(path, marker, weight, scale)
+ assert weight is not None
parent, attribute, target = _resolve_int8_target(model, path)
decoded = (weight.shape[0], weight.shape[1] * (2 if layout.packed_int4 else 1))
if decoded != (target.out_features, target.in_features):
@@ -1078,6 +1110,7 @@ def swap_in_int8_linears(model: torch.nn.Module, sd: dict[str, Any], quantized:
f"'{path}' is marked {fmt} and the {extra}'s Linear has a bias, but the "
f"{missing} has none. The checkpoint does not match this architecture."
)
+ check_int8_rotation_width(path, layout, weight)
layer: Int4ConvrotLinear | Int8ConvrotLinear
if layout.packed_int4:
layer = Int4ConvrotLinear(
diff --git a/invokeai/backend/quantization/nvfp4.py b/invokeai/backend/quantization/nvfp4.py
index cea81a00c5..04f40aeb11 100644
--- a/invokeai/backend/quantization/nvfp4.py
+++ b/invokeai/backend/quantization/nvfp4.py
@@ -24,6 +24,12 @@ its conditioning slightly worse -- which is why tests pin the layout against the
and a slice of a real checkpoint. Nothing guarantees that another producer writing the same key names
shares these conventions, so a layer is only read when a Comfy marker or header entry names it nvfp4.
+One other producer's conventions are known: NVIDIA ModelOpt's, in Black Forest Labs' FLUX.3 nvfp4 build.
+Same key names and the same numbers in another byte layout, named once in the safetensors metadata. A
+loader that finds one (:func:`is_modelopt_nvfp4`) names its layers with
+:func:`modelopt_nvfp4_header_layers` and re-lays the popped layers out into ComfyUI's with
+:func:`relayout_modelopt_nvfp4_payloads`.
+
Loaders keep the layers packed: :func:`pop_nvfp4_layers` takes them out of the state dict before any fp8
handling, and :func:`install_nvfp4_layers` swaps :class:`NVFP4Linear` modules in before the load. A layer
then occupies about 0.56 bytes per weight element against bf16's 2 and dequantizes per forward.
@@ -33,21 +39,34 @@ plain decode would produce wrong weights.
"""
import functools
-from collections.abc import Iterable, Mapping
+from collections.abc import Collection, Iterable, Mapping
from dataclasses import dataclass
from typing import Any
import torch
import torch.nn.functional as F
-from invokeai.backend.quantization.block_scale_tiles import TILE_ROWS, check_tile_layout, unblock_scale_grid
+from invokeai.backend.quantization.block_scale_tiles import (
+ TILE_ROWS,
+ block_scale_grid,
+ check_tile_layout,
+ unblock_scale_grid,
+)
from invokeai.backend.quantization.dequantizing_linear import DequantizingLinear
-from invokeai.backend.quantization.fp8_scaled import COMFY_QUANT_SUFFIX, INPUT_SCALE_SUFFIXES, iter_weight_scale_pairs
+from invokeai.backend.quantization.fp8_scaled import (
+ COMFY_QUANT_SUFFIX,
+ INPUT_SCALE_SUFFIXES,
+ QUANT_METADATA_KEY,
+ iter_weight_scale_pairs,
+)
from invokeai.backend.quantization.int8_convrot import parse_comfy_quant_marker
NVFP4_FORMAT = "nvfp4"
NVFP4_BLOCK_SIZE = 16
+# Where a ModelOpt export names its scheme: once, in the safetensors metadata, as `"quantization": "nvfp4"`.
+MODELOPT_QUANTIZATION_METADATA_KEY = "quantization"
+
WEIGHT_SCALE_2_SUFFIX = ".weight_scale_2"
PRE_QUANT_SCALE_SUFFIX = ".pre_quant_scale"
@@ -203,7 +222,7 @@ def find_nvfp4_layers(
Detection is structural -- a ``weight_scale_2`` beside the weight -- and decided per layer, never per
file. Refused, naming the layers: AWQ layers; markers that contradict their tensors; packed weights
- with a ``weight_scale`` but no ``weight_scale_2``; malformed layers; and layers that neither a
+ with a ``weight_scale`` but no ``weight_scale_2``; malformed layers, a grid that is not whole scale tiles among them; and layers that neither a
``.comfy_quant`` marker nor a ``_quantization_metadata`` entry (``header_layers``, in ``sd``'s key
space) names as nvfp4.
@@ -225,6 +244,12 @@ def find_nvfp4_layers(
"wrong weights."
)
+ if markers is None:
+ markers = {
+ key[: -len(COMFY_QUANT_SUFFIX)]: parse_comfy_quant_marker(sd[key])
+ for key in sd
+ if isinstance(key, str) and key.endswith(COMFY_QUANT_SUFFIX)
+ }
marked: dict[str, Any] = {}
for key in [k for k in sd if isinstance(k, str) and k.endswith(COMFY_QUANT_SUFFIX)]:
path = key[: -len(COMFY_QUANT_SUFFIX)]
@@ -327,6 +352,58 @@ def reject_nvfp4_layers_a_plain_fold_cannot_decode(sd: Mapping[str, Any], what:
)
+def is_modelopt_nvfp4(metadata: Mapping[str, Any] | None, keys: Iterable[Any]) -> bool:
+ """Whether a checkpoint is an NVIDIA ModelOpt nvfp4 export, whose layers :func:`relayout_modelopt_nvfp4_payloads`
+ re-lays out.
+
+ Strictly: the metadata says ``"quantization": "nvfp4"``, and the file carries nothing of ComfyUI's way of
+ naming its layers, neither a ``_quantization_metadata`` entry nor a ``.comfy_quant`` marker. A ComfyUI file is
+ therefore never re-laid out, and a file mixing the two is held to ComfyUI's rule, which refuses every layer it
+ does not name. ``keys`` are the checkpoint's tensor names.
+ """
+ if not metadata or metadata.get(MODELOPT_QUANTIZATION_METADATA_KEY) != NVFP4_FORMAT:
+ return False
+ if metadata.get(QUANT_METADATA_KEY):
+ return False
+ return not any(isinstance(key, str) and key.endswith(COMFY_QUANT_SUFFIX) for key in keys)
+
+
+def modelopt_nvfp4_header_layers(metadata: Mapping[str, Any] | None, keys: Collection[Any]) -> dict[str, Any]:
+ """The layers a ModelOpt export's metadata names, as ComfyUI's ``_quantization_metadata`` names them: every
+ ``weight_scale_2`` layer, nvfp4. Empty for any other file (:func:`is_modelopt_nvfp4`). ``keys`` are the
+ checkpoint's tensor names, in the key space the entries are wanted in."""
+ if not is_modelopt_nvfp4(metadata, keys):
+ return {}
+ return {
+ key[: -len(WEIGHT_SCALE_2_SUFFIX)]: {"format": NVFP4_FORMAT}
+ for key in keys
+ if isinstance(key, str) and key.endswith(WEIGHT_SCALE_2_SUFFIX)
+ }
+
+
+def relayout_modelopt_nvfp4_payloads(payloads: dict[str, NVFP4Payload]) -> None:
+ """Re-lay the popped nvfp4 layers of a ModelOpt export out the way ComfyUI stores them, in place.
+
+ ModelOpt packs element ``2j`` into the *lower* nibble and stores the block-scale grid row-major, where this
+ module decodes ComfyUI's layout: upper nibble first, grid in cuBLAS tiles. The numbers are the same: Black Forest
+ Labs' FLUX.3 ``variants/nvfp4`` file, re-laid out this way, is byte for byte Comfy-Org's nvfp4 file of the same
+ model, global and input scales included.
+
+ For payloads :func:`pop_nvfp4_layers` took out, whose layout it has checked. What happens to them before -- the
+ checks, a split into row ranges, a swap of halves -- cuts whole 128-row bands, which leaves either grid layout
+ whole, so this can run last: after the loader has reserved room. Every payload is replaced by a new copy, so the
+ pass allocates what the packed layers occupy, which is what the reservation counts for them; a payload's stored
+ tensors are released as its copy replaces it, unless something else still holds them.
+ """
+ for path in list(payloads):
+ payload = payloads[path]
+ payloads[path] = NVFP4Payload(
+ weight=(payload.weight << 4) | (payload.weight >> 4),
+ weight_scale=block_scale_grid(payload.weight_scale.view(torch.uint8)).view(payload.weight_scale.dtype),
+ weight_scale_2=payload.weight_scale_2,
+ )
+
+
def pop_nvfp4_layers(sd: dict[str, Any], header_layers: Mapping[str, Any] | None = None) -> dict[str, NVFP4Payload]:
"""Take every nvfp4 layer's packed tensors out of ``sd`` and drop the rest of its side channel.
diff --git a/invokeai/frontend/api/openapi.json b/invokeai/frontend/api/openapi.json
index 5a10a994a5..fbeca637ef 100644
--- a/invokeai/frontend/api/openapi.json
+++ b/invokeai/frontend/api/openapi.json
@@ -77363,7 +77363,7 @@
"variant"
],
"title": "Main_Checkpoint_Flux3_Config",
- "description": "Model config for FLUX.3 Image single-file transformers (BFL `model.safetensors`, ComfyUI bf16)."
+ "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."
},
"Main_Checkpoint_Ideogram4_Config": {
"properties": {
diff --git a/invokeai/frontend/api/schema.ts b/invokeai/frontend/api/schema.ts
index d757771208..f37052850c 100644
--- a/invokeai/frontend/api/schema.ts
+++ b/invokeai/frontend/api/schema.ts
@@ -31862,7 +31862,11 @@ export type components = {
};
/**
* Main_Checkpoint_Flux3_Config
- * @description Model config for FLUX.3 Image single-file transformers (BFL `model.safetensors`, ComfyUI bf16).
+ * @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.
*/
Main_Checkpoint_Flux3_Config: {
/**
diff --git a/scripts/capture_state_dict_fixture.py b/scripts/capture_state_dict_fixture.py
index 8184f93521..2785fa18a4 100644
--- a/scripts/capture_state_dict_fixture.py
+++ b/scripts/capture_state_dict_fixture.py
@@ -3,8 +3,8 @@
The loader conformance work needs real key layouts: invented names fall through the converters'
format probes as "no match", the converter becomes a no-op, and a test written against them asserts
nothing. But everything such a fixture records -- key names, shapes, dtypes, scale spellings, the
-`_quantization_metadata` header block and the per-layer `.comfy_quant` markers -- lives in the
-safetensors *header*, which is a few kilobytes at the front of the file. So a layout nobody here
+header's metadata with its `_quantization_metadata` block, and the per-layer `.comfy_quant` markers --
+lives in the safetensors *header*, which is a few kilobytes at the front of the file. So a layout nobody here
owns is still a layout that can be reproduced: point this at a URL and it reads the header over an
HTTP range request.
@@ -42,7 +42,11 @@ from typing import Any, Iterable, Mapping, Protocol
import httpx
from huggingface_hub.utils import build_hf_headers
-from invokeai.backend.quantization.fp8_scaled import COMFY_QUANT_SUFFIX, parse_quantization_metadata
+from invokeai.backend.quantization.fp8_scaled import (
+ COMFY_QUANT_SUFFIX,
+ QUANT_METADATA_KEY,
+ parse_quantization_metadata,
+)
from invokeai.backend.quantization.int8_convrot import parse_comfy_quant_bytes
# Not read from the environment on purpose: `HF_ENDPOINT` often points at a caching proxy here, and
@@ -291,6 +295,7 @@ def render_module(
chosen: Mapping[str, int],
layer_hints: Mapping[str, Any],
markers: Mapping[str, Any],
+ metadata: Mapping[str, Any] | None = None,
) -> str:
"""The fixture module, in the shape the state_dicts fixtures beside it already have."""
if chosen:
@@ -337,6 +342,16 @@ def render_module(
lines += [f" {_py(name)}: {_py(marker)}," for name, marker in sorted(markers.items())]
lines.append("}")
+ if metadata:
+ lines += [
+ "",
+ "# The rest of the header's `__metadata__`, as the producer wrote it. A producer that names its scheme",
+ "# only here -- NVIDIA ModelOpt's `quantization` -- is told apart by these alone.",
+ "metadata: dict[str, str] = {",
+ ]
+ lines += [f" {_py(key)}: {_py(value)}," for key, value in sorted(metadata.items())]
+ lines.append("}")
+
return "\n".join(lines) + "\n"
@@ -366,6 +381,7 @@ def capture(source_argument: str, *, block: int | None, subset: bool, want_marke
source=str(source),
tensors=subsetted,
chosen=chosen,
+ metadata={key: value for key, value in metadata.items() if key != QUANT_METADATA_KEY},
layer_hints=layer_hints,
markers=markers,
)
diff --git a/tests/backend/flux3/flux3_fixture.py b/tests/backend/flux3/flux3_fixture.py
index 2915df50b1..79fea9a53c 100644
--- a/tests/backend/flux3/flux3_fixture.py
+++ b/tests/backend/flux3/flux3_fixture.py
@@ -6,17 +6,31 @@ captured real one), not derived from the converter under test; ``test_conversion
The head width is the released 128: the rotary axes are fixed at (32, 32, 32, 32) and the loader refuses any
other width. Everything else is small. Weights are random rather than the diffusers zero-init, so a forward
-through a mis-wired parameter cannot pass by multiplying by zero.
+through a mis-wired parameter cannot pass by multiplying by zero. The widths are multiples of 256, so every
+block linear can be quantized the way the releases quantize it: int8 rotates in groups of 256, and nvfp4 needs
+whole 128-row, 64-column scale tiles.
"""
+import json
from pathlib import Path
+from typing import NamedTuple
import gguf
import torch
from diffusers import Flux3Transformer2DModel
from gguf.quants import dequantize, quantize
-from invokeai.backend.flux3.conversion import flux3_native_key_to_diffusers
+from invokeai.backend.flux3.conversion import convert_flux3_native_to_diffusers, flux3_native_key_to_diffusers
+from tests.fixtures.quantized_payloads import (
+ comfy_quant_marker,
+ nvfp4_codes,
+ nvfp4_modelopt_tensors,
+ nvfp4_tensors,
+ nvfp4_weight,
+ quantize_convrot,
+ quantize_per_row_fp8,
+ stored_layout,
+)
TINY_CONFIG = {
"in_channels": 32,
@@ -138,3 +152,136 @@ def write_flux3_gguf(
writer.write_tensors_to_file()
writer.close()
return meant
+
+
+QUANTIZED_SCHEMES = ("int8_convrot", "nvfp4_comfy", "nvfp4_bfl", "fp8r")
+"""The released builds, as `quantize_flux3_native` names them."""
+
+ADALN = "final_layer.image.adaLN_modulation.1"
+NVFP4_GLOBAL_SCALE = 1 / 32
+"""With block scales of 1 and 2 an nvfp4 weight is +-1/32 or +-1/16: the tiny model's magnitude, exact in float32."""
+
+_LINEARS = ("q_proj", "k_proj", "v_proj", "attn_out", "mlp_in", "mlp_out")
+_QKV = _LINEARS[:3]
+_MODULATIONS = tuple(
+ f"{stage}.{mode}.lin"
+ for stage in ("early_stream_modulations", "single_stream_modulations")
+ for mode in ("image", "image_cond", "txt")
+)
+_INT8_MARKER = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 256}
+# Comfy-Org's int8 build marks the image and the joint blocks for its own int8 attention kernel.
+_COMFY_ATTENTION_HINT = {"attention": "comfy_kitchen_int8"}
+
+# Which blocks each release quantizes, on the tiny model's one block per mode stack and two joint blocks: int8 all of
+# them; nvfp4 all but the text blocks, the first image block and the last joint blocks; fp8r all but the text blocks,
+# plus the six modulations. The safetensors metadata is each release's own.
+_BLOCKS = {
+ "int8_convrot": (
+ "content_mode_blocks.image.0",
+ "content_mode_blocks.image_cond.0",
+ "txt_mode_blocks.0",
+ "single_blocks.0",
+ "single_blocks.1",
+ ),
+ "nvfp4": ("content_mode_blocks.image_cond.0", "single_blocks.0"),
+ "fp8r": ("content_mode_blocks.image.0", "content_mode_blocks.image_cond.0", "single_blocks.0", "single_blocks.1"),
+}
+_METADATA = {
+ "int8_convrot": {"format": "pt", "model": "f3-image-small"},
+ "nvfp4_comfy": {"format": "pt", "model": "f3-image-small"},
+ "nvfp4_bfl": {"format": "pt", "model": "f3-image-small", "quantization": "nvfp4"},
+ "fp8r": {"format": "pt", "model": "f3-image-small", "quantization": "fp8r", "scale": "per_row_fp32"},
+}
+
+
+class QuantizedFlux3(NamedTuple):
+ state_dict: dict[str, torch.Tensor]
+ """The native checkpoint as the build stores it."""
+ meant: dict[str, torch.Tensor]
+ """Every weight dense, as the build means it, a fused ``qkv`` as its three projections: a model converted from
+ these is what a load must give."""
+ metadata: dict[str, str]
+ """The file's safetensors metadata."""
+
+
+def quantize_flux3_native(
+ native: dict[str, torch.Tensor], scheme: str, *, adaln: bool = False, fuse_qkv: bool = False, seed: int = 0
+) -> QuantizedFlux3:
+ """``native`` written the way the release ``scheme`` of `QUANTIZED_SCHEMES` writes it.
+
+ ``int8_convrot`` is Comfy-Org's: a block's q, k and v fused into one ``qkv`` (as that build always does),
+ ``int8_tensorwise`` + convrot codes with a ``[N, 1]`` scale and a ``.comfy_quant`` marker per layer. ``nvfp4_comfy``
+ and ``nvfp4_bfl`` hold the same numbers, in ComfyUI's layout with the layers named in ``_quantization_metadata``,
+ and in ModelOpt's with the metadata saying ``quantization: nvfp4``; their weights are drawn rather than quantized,
+ random signs under a random grid of block scales 1 and 2, so the expected weight is exact. ``fp8r`` is BFL's per-row
+ e4m3 with a ``[N]`` scale.
+
+ ``adaln`` quantizes the output adaLN as well, which no release does; ``fuse_qkv`` fuses the nvfp4 ``qkv`` of
+ ComfyUI's layout as the int8 build does.
+ """
+ generator = torch.Generator().manual_seed(seed)
+ stored = dict(native)
+ meant = dict(native)
+ blocks = _BLOCKS["nvfp4" if scheme.startswith("nvfp4") else scheme]
+ fused = scheme == "int8_convrot" or (scheme == "nvfp4_comfy" and fuse_qkv)
+ layers: list[str] = []
+ for block in blocks:
+ if fused:
+ weights = [stored.pop(f"{block}.{name}.weight") for name in _QKV]
+ stored[f"{block}.qkv.weight"] = torch.cat(weights)
+ layers += [f"{block}.qkv", *(f"{block}.{name}" for name in _LINEARS[3:])]
+ else:
+ layers += [f"{block}.{name}" for name in _LINEARS]
+ if scheme == "int8_convrot" and not block.startswith(("content_mode_blocks.image_cond", "txt_mode_blocks")):
+ stored[f"{block}.comfy_attention.config"] = comfy_quant_marker(_COMFY_ATTENTION_HINT)
+ if scheme == "fp8r":
+ layers += list(_MODULATIONS)
+ if adaln:
+ layers.append(ADALN)
+
+ for layer in layers:
+ weight = stored.pop(f"{layer}.weight")
+ if scheme == "int8_convrot":
+ payload = quantize_convrot(weight)
+ stored[f"{layer}.weight"], stored[f"{layer}.weight_scale"] = payload.codes, payload.scale
+ stored[f"{layer}.comfy_quant"] = comfy_quant_marker(_INT8_MARKER)
+ meant[f"{layer}.weight"] = payload.dequantized
+ elif scheme == "fp8r":
+ fp8 = quantize_per_row_fp8(weight)
+ stored[f"{layer}.weight"], stored[f"{layer}.weight_scale"] = fp8.codes, fp8.scale
+ meant[f"{layer}.weight"] = fp8.dequantized
+ else:
+ positive = torch.randint(0, 2, weight.shape, generator=generator, dtype=torch.bool)
+ grid = torch.randint(1, 3, (weight.shape[0], weight.shape[1] // 16), generator=generator).float()
+ if scheme == "nvfp4_comfy":
+ stored.update(
+ nvfp4_tensors(
+ layer, nvfp4_codes(positive), block_scale=stored_layout(grid), global_scale=NVFP4_GLOBAL_SCALE
+ )
+ )
+ else:
+ stored.update(
+ nvfp4_modelopt_tensors(layer, nvfp4_codes(positive), grid=grid, global_scale=NVFP4_GLOBAL_SCALE)
+ )
+ # Both releases ship an activation scale for fp4 compute, which a dequantizing load has no use for.
+ stored[f"{layer}.input_scale"] = torch.tensor(1.0)
+ meant[f"{layer}.weight"] = nvfp4_weight(positive, grid, NVFP4_GLOBAL_SCALE)
+
+ # A fused layer means its query, key and value rows, in that order: stated here rather than left to the
+ # converter under test, so that a reference built from `meant` does not share its split.
+ for layer in [layer for layer in layers if layer.endswith(".qkv")]:
+ block = layer[: -len(".qkv")]
+ for name, part in zip(_QKV, meant.pop(f"{layer}.weight").chunk(3), strict=True):
+ meant[f"{block}.{name}.weight"] = part
+
+ metadata = dict(_METADATA[scheme])
+ if scheme == "nvfp4_comfy":
+ metadata["_quantization_metadata"] = json.dumps({"layers": {layer: {"format": "nvfp4"} for layer in layers}})
+ return QuantizedFlux3(stored, meant, metadata)
+
+
+def flux3_model_from_native(native: dict[str, torch.Tensor], flow_map: bool) -> Flux3Transformer2DModel:
+ """A float32 reference model holding ``native``'s values, converted to the diffusers layout."""
+ model = Flux3Transformer2DModel(**TINY_CONFIG, flow_map=flow_map).eval()
+ model.load_state_dict(convert_flux3_native_to_diffusers(dict(native)))
+ return model
diff --git a/tests/backend/flux3/test_conversion.py b/tests/backend/flux3/test_conversion.py
index 01a1cbe09f..7adc17e45e 100644
--- a/tests/backend/flux3/test_conversion.py
+++ b/tests/backend/flux3/test_conversion.py
@@ -1,9 +1,9 @@
"""Native FLUX.3 checkpoints -> diffusers' FLUX.3 transformer.
-The real-layout tests read the key names and shapes captured from the released Klein and Klein Base files.
-Converted onto diffusers' ``Flux3Transformer2DModel`` (on the meta device), every parameter must be filled and
-nothing may be left over -- a renamed key in a re-upload shows up here, not as a block silently missing from a
-generation.
+The real-layout tests read the key names and shapes captured from the released Klein and Klein Base files and
+from Klein's quantized builds. Converted onto diffusers' ``Flux3Transformer2DModel`` (on the meta device), every
+parameter must be filled and nothing may be left over, and every quantization scale must land beside its weight --
+a renamed key in a re-upload shows up here, not as a block silently missing from a generation.
"""
import accelerate
@@ -12,13 +12,24 @@ import torch
from diffusers import Flux3Transformer2DModel
from invokeai.backend.flux3.conversion import (
+ convert_flux3_layer_entries,
convert_flux3_native_to_diffusers,
flux3_native_key_to_diffusers,
+ flux3_native_module_to_diffusers,
flux3_transformer_config,
)
from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
from tests.backend.flux3.flux3_fixture import TINY_CONFIG, native_flux3_keys
-from tests.backend.model_manager.load.state_dicts import flux3_klein_base_keys, flux3_klein_keys
+from tests.backend.model_manager.load.state_dicts import (
+ flux3_klein_base_keys,
+ flux3_klein_fp8r_keys,
+ flux3_klein_int8_convrot_keys,
+ flux3_klein_keys,
+ flux3_klein_nvfp4_bfl_keys,
+ flux3_klein_nvfp4_comfy_keys,
+)
+from tests.backend.model_manager.load.state_dicts.utils import keys_to_meta_state_dict
+from tests.fixtures.quantized_payloads import comfy_quant_marker
# The released transformer config (transformer/config.json of both repositories, 2026-10-15).
_RELEASED = {
@@ -32,15 +43,11 @@ _RELEASED = {
}
-def _meta_state_dict(keys: dict[str, tuple[list[int], str]]) -> dict[str, torch.Tensor]:
- return {name: torch.empty(shape, device="meta") for name, (shape, _dtype) in keys.items()}
-
-
@pytest.mark.parametrize(
("fixture", "flow_map"), [(flux3_klein_keys, True), (flux3_klein_base_keys, False)], ids=["klein", "base"]
)
def test_the_released_layout_fills_the_diffusers_model_exactly(fixture, flow_map: bool) -> None:
- native = _meta_state_dict(fixture.state_dict_keys)
+ native = keys_to_meta_state_dict(fixture.state_dict_keys)
config = flux3_transformer_config(native)
assert {key: config[key] for key in _RELEASED} == _RELEASED
@@ -89,9 +96,18 @@ def test_a_packed_gguf_adaln_is_unpacked_before_the_halves_swap() -> None:
def test_training_only_heads_are_dropped() -> None:
converted = convert_flux3_native_to_diffusers(
- {"repa_projectors.0.weight": torch.zeros(1), "txt_in.weight": torch.zeros(1)}
+ {
+ "repa_projectors.0.weight": torch.zeros(1),
+ "repa_projectors.0.weight_scale": torch.ones(1),
+ "txt_in.weight": torch.zeros(1),
+ }
)
assert set(converted) == {"context_embedder.weight"}
+ # The quantization entries read under native names go with them, and a fused `qkv`'s describes all three parts.
+ marker = {"format": "int8_tensorwise"}
+ assert convert_flux3_layer_entries({"repa_projectors.0": marker, "single_blocks.2.qkv": marker}) == {
+ f"single_transformer_blocks.2.attn.{projection}": marker for projection in ("to_q", "to_k", "to_v")
+ }
@pytest.mark.parametrize(
@@ -145,6 +161,127 @@ def test_per_mode_stacks_of_different_depth_are_refused() -> None:
flux3_transformer_config(native)
+_QUANTIZED_RELEASES = {
+ "int8-convrot": flux3_klein_int8_convrot_keys,
+ "nvfp4-comfy": flux3_klein_nvfp4_comfy_keys,
+ "nvfp4-bfl": flux3_klein_nvfp4_bfl_keys,
+ "fp8r": flux3_klein_fp8r_keys,
+}
+_SIDE_CHANNEL = (".weight_scale_2", ".weight_scale", ".input_scale", ".comfy_quant")
+
+
[email protected]("fixture", _QUANTIZED_RELEASES.values(), ids=_QUANTIZED_RELEASES.keys())
+def test_every_side_channel_of_a_quantized_release_lands_beside_its_weight(fixture) -> None:
+ """A scale or marker left under a name the model does not have is dropped, and its weight loads off by
+ `1/weight_scale` without a word. So each must land beside its own weight, on a Linear of the release geometry,
+ and a per-row one must have that weight's rows: the int8 build's fused `qkv` splits three ways, scales included.
+ The weights themselves fill the model exactly, and ComfyUI's attention-kernel hints are gone."""
+ native = keys_to_meta_state_dict(fixture.state_dict_keys)
+ with accelerate.init_empty_weights():
+ model = Flux3Transformer2DModel(**flux3_transformer_config(native))
+ linears = {name: module for name, module in model.named_modules() if isinstance(module, torch.nn.Linear)}
+
+ converted = convert_flux3_native_to_diffusers(dict(native))
+
+ side_channels = {key: value for key, value in converted.items() if key.endswith(_SIDE_CHANNEL)}
+ assert side_channels
+ assert set(converted) - set(side_channels) == set(model.state_dict())
+ for key, value in side_channels.items():
+ module = key.rpartition(".")[0]
+ assert module in linears, key
+ if value.numel() > 1 and not key.endswith(".comfy_quant"):
+ assert value.shape[0] == converted[f"{module}.weight"].shape[0] == linears[module].out_features, key
+
+
[email protected]("scale_shape", [(768, 1), (768,), ()], ids=["per-row", "per-row-1d", "per-tensor"])
+def test_a_fused_qkv_splits_into_query_key_and_value_with_its_side_channel(scale_shape: tuple[int, ...]) -> None:
+ """Rows in query, key, value order, as Comfy-Org's int8 build stores them; a per-row scale splits with its rows,
+ and whatever describes the whole layer -- a per-tensor scale, the activation scale, the marker -- goes to all
+ three."""
+ rows = torch.arange(768, dtype=torch.float32)
+ marker = comfy_quant_marker({"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 256})
+ scale = rows.reshape(scale_shape) if scale_shape else torch.tensor(0.5)
+ native = {
+ "single_blocks.0.qkv.weight": rows.unsqueeze(1).expand(768, 4).clone(),
+ "single_blocks.0.qkv.weight_scale": scale,
+ "single_blocks.0.qkv.input_scale": torch.tensor(2.0),
+ "single_blocks.0.qkv.comfy_quant": marker,
+ }
+
+ converted = convert_flux3_native_to_diffusers(native)
+
+ for index, projection in enumerate(("to_q", "to_k", "to_v")):
+ prefix = f"single_transformer_blocks.0.attn.{projection}"
+ own_rows = rows[256 * index : 256 * (index + 1)]
+ assert torch.equal(converted[f"{prefix}.weight"], own_rows.unsqueeze(1).expand(256, 4))
+ expected_scale = own_rows.reshape(256, *scale_shape[1:]) if scale_shape else torch.tensor(0.5)
+ assert torch.equal(converted[f"{prefix}.weight_scale"], expected_scale)
+ assert torch.equal(converted[f"{prefix}.input_scale"], torch.tensor(2.0))
+ assert torch.equal(converted[f"{prefix}.comfy_quant"], marker)
+ assert not any(".qkv." in key for key in converted)
+
+
[email protected]("dtype", [torch.float8_e4m3fn, torch.int8])
[email protected]("scale_shape", [(4,), (4, 1), ()], ids=["per-row", "per-row-2d", "per-tensor"])
+def test_the_output_adalns_weight_scale_moves_with_its_rows(dtype: torch.dtype, scale_shape: tuple[int, ...]) -> None:
+ """The codes are swapped as stored, and a per-row scale with them; folded or dequantized later, a scale left
+ unswapped would scale every row of the scale half by a row of the shift half."""
+ shift, scale = torch.full((2, 3), 1.0), torch.full((2, 3), 2.0)
+ row_scales = torch.tensor([1.0, 2.0, 3.0, 4.0])
+ native = {
+ "final_layer.image.adaLN_modulation.1.weight": torch.cat([shift, scale]).to(dtype),
+ "final_layer.image.adaLN_modulation.1.weight_scale": row_scales.reshape(scale_shape)
+ if scale_shape
+ else row_scales[0],
+ "final_layer.image.adaLN_modulation.1.input_scale": torch.tensor(0.5),
+ }
+
+ converted = convert_flux3_native_to_diffusers(native)
+
+ # Compared as bytes: `torch.equal` is not implemented for float8 on the CPU.
+ weight = converted["norm_out.linear.weight"]
+ assert weight.dtype is dtype
+ assert torch.equal(weight.view(torch.uint8), torch.cat([scale, shift]).to(dtype).view(torch.uint8))
+ swapped = torch.tensor([3.0, 4.0, 1.0, 2.0])
+ expected = swapped.reshape(scale_shape) if scale_shape else row_scales[0]
+ assert torch.equal(converted["norm_out.linear.weight_scale"], expected)
+ assert torch.equal(converted["norm_out.linear.input_scale"], torch.tensor(0.5))
+
+
[email protected]("packed", ["nvfp4", "gguf"])
+def test_a_packed_fused_qkv_is_refused(packed: str) -> None:
+ """nvfp4 packs two codes per byte and GGML whole blocks of a row; neither is split into projections here."""
+ import gguf
+
+ if packed == "nvfp4":
+ weight = torch.zeros(768, 128, dtype=torch.uint8)
+ else:
+ weight = GGMLTensor(
+ torch.zeros(768, 8 * 34, dtype=torch.uint8),
+ ggml_quantization_type=gguf.GGMLQuantizationType.Q8_0,
+ tensor_shape=torch.Size([768, 256]),
+ compute_dtype=torch.float32,
+ )
+
+ with pytest.raises(ValueError, match="packed"):
+ convert_flux3_native_to_diffusers({"single_blocks.0.qkv.weight": weight})
+
+
+ ("native", "diffusers"),
+ [
+ ("content_mode_blocks.image_cond.1.qkv", [f"mode_blocks.image_cond.1.attn.to_{p}" for p in "qkv"]),
+ ("txt_mode_blocks.2.qkv", [f"txt_mode_blocks.2.attn.to_{p}" for p in "qkv"]),
+ # A norm stores its parameter as `scale`, so its module is found through that name.
+ ("single_blocks.3.norm.key_norm", ["single_transformer_blocks.3.attn.norm_k"]),
+ ("single_stream_modulations.image.lin", ["single_stream_modulations.image.linear"]),
+ ("final_layer.image.adaLN_modulation.1", ["norm_out.linear"]),
+ ],
+)
+def test_module_renames(native: str, diffusers: list[str]) -> None:
+ assert flux3_native_module_to_diffusers(native) == diffusers
+
+
def _shapes_of_tiny() -> dict[str, torch.Tensor]:
hidden = TINY_CONFIG["attention_head_dim"] * TINY_CONFIG["num_attention_heads"]
return {
diff --git a/tests/backend/flux3/test_loaders.py b/tests/backend/flux3/test_loaders.py
index 91bd65a1a7..ef30a20006 100644
--- a/tests/backend/flux3/test_loaders.py
+++ b/tests/backend/flux3/test_loaders.py
@@ -8,9 +8,7 @@ which diffusers' transformer runs in float32.
import gguf
import pytest
import torch
-from diffusers import Flux3Transformer2DModel
-from invokeai.backend.flux3.conversion import convert_flux3_native_to_diffusers
from invokeai.backend.model_manager.configs.main import Main_Checkpoint_Flux3_Config, Main_GGUF_Flux3_Config
from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (
apply_custom_layers_to_model,
@@ -19,7 +17,13 @@ from invokeai.backend.model_manager.load.model_loaders import flux3 as flux3_loa
from invokeai.backend.model_manager.load.model_loaders.flux3 import Flux3CheckpointModel, Flux3GGUFCheckpointModel
from invokeai.backend.model_manager.taxonomy import Flux3VariantType, SubModelType
from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
-from tests.backend.flux3.flux3_fixture import TINY_CONFIG, forward, tiny_flux3_model, to_native, write_flux3_gguf
+from tests.backend.flux3.flux3_fixture import (
+ flux3_model_from_native,
+ forward,
+ tiny_flux3_model,
+ to_native,
+ write_flux3_gguf,
+)
from tests.fixtures.loader_seams import Seam, prepare
FLOW_MAP = pytest.mark.parametrize("flow_map", [True, False], ids=["klein", "base"])
@@ -43,7 +47,7 @@ def test_a_single_file_loads_as_the_model_it_was_written_from(monkeypatch, flow_
load_file_host=safetensors.torch,
patches_device=True,
)
- run = prepare(seam, monkeypatch, state_dict=native)
+ run = prepare(seam, monkeypatch, state_dict=native, metadata=None)
config = Main_Checkpoint_Flux3_Config.model_construct(
path="flux3.safetensors", name="flux3", variant=_variant(flow_map)
)
@@ -58,24 +62,6 @@ def test_a_single_file_loads_as_the_model_it_was_written_from(monkeypatch, flow_
torch.testing.assert_close(forward(model, flow_map), forward(reference, flow_map), rtol=0, atol=0)
-def test_a_quantized_side_channel_is_refused_by_the_single_file_loader(monkeypatch) -> None:
- import safetensors.torch
-
- native = to_native(tiny_flux3_model(flow_map=True))
- native["single_blocks.0.q_proj.weight_scale"] = torch.ones(1)
- seam = Seam(
- loader=Flux3CheckpointModel, module=flux3_loaders, entry="_load_model", load_file_host=safetensors.torch
- )
- run = prepare(seam, monkeypatch, state_dict=native)
- config = Main_Checkpoint_Flux3_Config.model_construct(
- path="x.safetensors", name="x", variant=Flux3VariantType.Klein
- )
-
- with pytest.raises(ValueError, match="quantization side channel"):
- run.load(config, SubModelType.Transformer)
- assert run.reserved == [], "a refused file must not reserve cache room first"
-
-
@FLOW_MAP
@pytest.mark.parametrize(
# The `gguf` package writes no K-quants, so the packed path is driven through the block types it can write.
@@ -103,7 +89,6 @@ def test_a_gguf_loads_and_predicts_what_its_dequantized_weights_mean(
for name, module in model.named_modules():
if name.endswith((".norm_q", ".norm_k")):
assert not isinstance(module.weight, GGMLTensor) and module.weight.dtype == torch.float32, name
- reference = Flux3Transformer2DModel(**TINY_CONFIG, flow_map=flow_map).eval()
- reference.load_state_dict(convert_flux3_native_to_diffusers(dict(meant)))
+ reference = flux3_model_from_native(meant, flow_map)
# Q8_0 blocks dequantize through their fp16 scale, so the two forwards agree to fp16 precision.
torch.testing.assert_close(forward(model, flow_map), forward(reference, flow_map), rtol=1e-3, atol=1e-3)
diff --git a/tests/backend/flux3/test_quantized_loaders.py b/tests/backend/flux3/test_quantized_loaders.py
new file mode 100644
index 0000000000..3c1f5121be
--- /dev/null
+++ b/tests/backend/flux3/test_quantized_loaders.py
@@ -0,0 +1,323 @@
+"""The FLUX.3 single-file loader over the quantized releases, driven through `Flux3CheckpointModel`.
+
+Each build is a tiny native checkpoint written the way its release writes it (`quantize_flux3_native`), and what
+is asserted is the forward: a loaded model must predict what a dense model of the values the build means predicts.
+That covers the rename of the quantized layers and of their side channels -- the int8 build's fused `qkv` above all,
+whose codes and per-row scales split three ways -- the output adaLN's row swap carried onto its quantized forms, and
+BFL's ModelOpt nvfp4 layout re-laid out into ComfyUI's. The forwards run in float32, since a CPU bf16 GEMM faults on
+part of the hosted Windows fleet.
+"""
+
+import json
+
+import pytest
+import safetensors.torch
+import torch
+
+from invokeai.backend.model_manager.configs.main import Main_Checkpoint_Flux3_Config
+from invokeai.backend.model_manager.load import load_default
+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 flux3 as flux3_loaders
+from invokeai.backend.model_manager.load.model_loaders.flux3 import Flux3CheckpointModel
+from invokeai.backend.model_manager.taxonomy import Flux3VariantType, SubModelType
+from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
+from invokeai.backend.quantization.nvfp4 import NVFP4Linear
+from tests.backend.flux3.flux3_fixture import (
+ QUANTIZED_SCHEMES,
+ QuantizedFlux3,
+ flux3_model_from_native,
+ forward,
+ quantize_flux3_native,
+ tiny_flux3_model,
+ to_native,
+)
+from tests.fixtures.loader_seams import Seam, SeamRun, prepare
+from tests.fixtures.quantized_payloads import nvfp4_codes, nvfp4_tensors
+
+SEAM = Seam(
+ loader=Flux3CheckpointModel,
+ module=flux3_loaders,
+ entry="_load_model",
+ load_file_host=safetensors.torch,
+ patches_device=True,
+)
+
+HIDDEN = 256
+"""The tiny model's width: two heads of 128."""
+
+# The diffusers modules each release keeps quantized, spelled out rather than derived from the converter.
+_BLOCKS = {
+ "int8_convrot": (
+ "mode_blocks.image.0",
+ "mode_blocks.image_cond.0",
+ "txt_mode_blocks.0",
+ "single_transformer_blocks.0",
+ "single_transformer_blocks.1",
+ ),
+ "nvfp4": ("mode_blocks.image_cond.0", "single_transformer_blocks.0"),
+ "fp8r": (
+ "mode_blocks.image.0",
+ "mode_blocks.image_cond.0",
+ "single_transformer_blocks.0",
+ "single_transformer_blocks.1",
+ ),
+}
+_LINEARS = ("attn.to_q", "attn.to_k", "attn.to_v", "attn.to_out.0", "ff.linear_in", "ff.linear_out")
+_MODULATIONS = tuple(
+ f"{stage}.{mode}.linear"
+ for stage in ("early_stream_modulations", "single_stream_modulations")
+ for mode in ("image", "image_cond", "txt")
+)
+
+
+def _build(scheme: str, *, flow_map: bool = True, **options) -> QuantizedFlux3:
+ return quantize_flux3_native(to_native(tiny_flux3_model(flow_map=flow_map)), scheme, **options)
+
+
+def _config(flow_map: bool = True) -> Main_Checkpoint_Flux3_Config:
+ variant = Flux3VariantType.Klein if flow_map else Flux3VariantType.KleinBase
+ return Main_Checkpoint_Flux3_Config.model_construct(path="flux3.safetensors", name="flux3", variant=variant)
+
+
+def _load(
+ monkeypatch: pytest.MonkeyPatch, build: QuantizedFlux3, observe: tuple[str, ...] = (), *, flow_map: bool = True
+) -> tuple[SeamRun, torch.nn.Module]:
+ run = prepare(SEAM, monkeypatch, state_dict=build.state_dict, metadata=build.metadata, observe=observe)
+ return run, run.load(_config(flow_map), SubModelType.Transformer)
+
+
+def _refused(monkeypatch: pytest.MonkeyPatch, build: QuantizedFlux3, match: str) -> SeamRun:
+ run = prepare(SEAM, monkeypatch, state_dict=build.state_dict, metadata=build.metadata)
+ with pytest.raises(ValueError, match=match):
+ run.load(_config(), SubModelType.Transformer)
+ return run
+
+
+def _assert_predicts_what_it_means(
+ model: torch.nn.Module, build: QuantizedFlux3, *, exact: bool, flow_map: bool = True
+) -> None:
+ reference = forward(flux3_model_from_native(build.meant, flow_map=flow_map), flow_map=flow_map)
+ assert reference.abs().max() > 0, "a forward that is zero everywhere would compare equal to anything"
+ loaded = forward(model, flow_map=flow_map)
+ if exact:
+ # nvfp4 and fp8 decode to exactly the meant weights, so the forward is the reference's to the bit.
+ assert torch.equal(loaded, reference)
+ else:
+ # int8 derotates a fused qkv per projection, the reference all three at once: BLAS may sum differently.
+ torch.testing.assert_close(loaded, reference, rtol=1e-5, atol=1e-6)
+
+
[email protected]("scheme", QUANTIZED_SCHEMES)
+def test_a_quantized_release_loads_as_the_model_it_means(monkeypatch: pytest.MonkeyPatch, scheme: str) -> None:
+ build = _build(scheme)
+
+ run, model = _load(monkeypatch, build)
+
+ _assert_predicts_what_it_means(model, build, exact=scheme != "int8_convrot")
+ assert len(run.reserved) == 1, "one reservation, before anything widens"
+ if scheme == "fp8r":
+ # Neither the fp8 matmul nor FP8 Storage asked for them here, so the scales are folded in.
+ assert not any(p.dtype is torch.float8_e4m3fn for p in model.parameters())
+ else:
+ packed = Int8ConvrotLinear if scheme == "int8_convrot" else NVFP4Linear
+ blocks = _BLOCKS["int8_convrot" if scheme == "int8_convrot" else "nvfp4"]
+ for name in (f"{block}.{linear}" for block in blocks for linear in _LINEARS):
+ assert isinstance(model.get_submodule(name), packed), name
+ if scheme.startswith("nvfp4"):
+ # The blocks the release leaves in bf16 stay plain linears.
+ for block in ("mode_blocks.image.0", "txt_mode_blocks.0", "single_transformer_blocks.1"):
+ assert type(model.get_submodule(f"{block}.attn.to_q")) is torch.nn.Linear
+ # The FP8 Storage pass runs only where no layer is kept quantized by the build itself.
+ assert run.casting_calls == (1 if scheme == "fp8r" else 0)
+
+
[email protected]("scheme", QUANTIZED_SCHEMES)
+def test_a_quantized_klein_base_release_loads_as_klein_base(monkeypatch: pytest.MonkeyPatch, scheme: str) -> None:
+ """Klein Base's builds are Klein's without the flow-map embedder; nothing in the quantized path may assume it."""
+ build = _build(scheme, flow_map=False)
+
+ _, model = _load(monkeypatch, build, flow_map=False)
+
+ assert model.config.flow_map is False
+ _assert_predicts_what_it_means(model, build, exact=scheme != "int8_convrot", flow_map=False)
+
+
+def test_one_reservation_holds_the_int8_codes_at_one_byte(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Counted by hand: codes at one byte, their float32 scales as stored, every dense tensor at the compute dtype
+ (float32 here). The markers and the attention-kernel hints are dropped before the load and cost nothing."""
+ build = _build("int8_convrot")
+ codes = sum(t.numel() for t in build.state_dict.values() if t.dtype is torch.int8)
+ scales = sum(t.numel() for key, t in build.state_dict.items() if key.endswith(".weight_scale"))
+ dense = sum(
+ t.numel() for key, t in build.state_dict.items() if t.is_floating_point() and not key.endswith(".weight_scale")
+ )
+
+ run, _ = _load(monkeypatch, build)
+
+ assert run.reserved == [codes + 4 * scales + 4 * dense]
+
+
[email protected]("scheme", ["nvfp4_comfy", "nvfp4_bfl"])
+def test_one_reservation_holds_the_nvfp4_layers_as_stored(monkeypatch: pytest.MonkeyPatch, scheme: str) -> None:
+ """Counted by hand: each packed layer at its stored size (codes, grid, float32 global scale), every dense tensor at
+ the compute dtype (float32 here). The activation scales are dropped and cost nothing. BFL's layers are re-laid out
+ after the reservation, into copies of the same size."""
+ sd = _build(scheme).state_dict
+ layers = [key[: -len(".weight_scale_2")] for key in sd if key.endswith(".weight_scale_2")]
+ side = {
+ f"{layer}{part}" for layer in layers for part in (".weight", ".weight_scale", ".weight_scale_2", ".input_scale")
+ }
+ packed = sum(sd[f"{layer}.weight"].numel() + sd[f"{layer}.weight_scale"].numel() + 4 for layer in layers)
+ dense = sum(t.numel() for key, t in sd.items() if key not in side)
+
+ run, _ = _load(monkeypatch, _build(scheme))
+
+ assert run.reserved == [packed + 4 * dense]
+
+
+def test_one_reservation_holds_a_folded_fp8r_build_at_the_compute_dtype(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Counted by hand: with no consumer for fp8, every weight is folded to the compute dtype (float32 here), and the
+ per-row scales are held beside the weights until the fold has used them."""
+ build = _build("fp8r")
+
+ run, _ = _load(monkeypatch, build)
+
+ assert run.reserved == [4 * sum(t.numel() for t in build.state_dict.values())]
+
+
+def test_one_reservation_holds_kept_fp8r_weights_at_one_byte(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Counted by hand: kept for the fp8 matmul, every quantized weight stays one byte per element, its per-row scale
+ float32, and the rest is at the compute dtype (float32 here)."""
+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _device: True)
+ sd = _build("fp8r").state_dict
+ fp8 = sum(t.numel() for t in sd.values() if t.dtype is torch.float8_e4m3fn)
+ scales = sum(t.numel() for key, t in sd.items() if key.endswith(".weight_scale"))
+ dense = sum(t.numel() for key, t in sd.items() if t.dtype is torch.float32 and not key.endswith(".weight_scale"))
+
+ run, _ = _load(monkeypatch, _build("fp8r"))
+
+ assert run.reserved == [fp8 + 4 * scales + 4 * dense]
+
+
[email protected]("scheme", QUANTIZED_SCHEMES)
+def test_a_quantized_output_adaln_is_decoded_with_its_halves_swapped(
+ monkeypatch: pytest.MonkeyPatch, scheme: str
+) -> None:
+ """No release quantizes it, and a build that did would load wrong without a word: BFL stores [shift, scale]
+ rows, the per-row scales of int8 and fp8r beside them, and nvfp4's grid in 128-row tiles. `norm_out.linear` sits
+ under the model's `norm` pattern, so it is decoded rather than kept quantized."""
+ build = _build(scheme, adaln=True)
+
+ _, model = _load(monkeypatch, build)
+
+ adaln = model.norm_out.linear
+ assert type(adaln) is torch.nn.Linear and adaln.weight.dtype is torch.float32
+ _assert_predicts_what_it_means(model, build, exact=scheme != "int8_convrot")
+
+
+def test_a_fused_nvfp4_qkv_splits_on_whole_scale_tiles(monkeypatch: pytest.MonkeyPatch) -> None:
+ build = _build("nvfp4_comfy", fuse_qkv=True)
+
+ _, model = _load(monkeypatch, build)
+
+ for block in _BLOCKS["nvfp4"]:
+ for projection in ("to_q", "to_k", "to_v"):
+ module = model.get_submodule(f"{block}.attn.{projection}")
+ assert isinstance(module, NVFP4Linear) and module.out_features == HIDDEN
+ _assert_predicts_what_it_means(model, build, exact=True)
+
+
+def test_a_comfy_nvfp4_file_is_never_re_laid_out(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The ModelOpt layout is keyed on BFL's metadata *and* on the absence of ComfyUI's names. A ComfyUI file that also
+ says `quantization: nvfp4` is read as ComfyUI's; re-laid out, every nibble pair and scale tile would be swapped."""
+ build = _build("nvfp4_comfy")
+ build.metadata["quantization"] = "nvfp4"
+
+ _, model = _load(monkeypatch, build)
+
+ _assert_predicts_what_it_means(model, build, exact=True)
+
+
+def test_the_ordered_steps_run_after_the_one_reservation(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The fold and the cast widen weights, BFL's nvfp4 re-layout copies every packed layer, and the packed layers go
+ in last; all of it inside the room."""
+ run, _ = _load(monkeypatch, _build("fp8r"), observe=("dequantize_fp8_scaled", "cast_state_dict"))
+ assert run.order == [("dequantize_fp8_scaled", 1), ("cast_state_dict", 1)]
+
+ run, _ = _load(monkeypatch, _build("nvfp4_comfy"), observe=("cast_state_dict", "install_nvfp4_layers"))
+ assert run.order == [("cast_state_dict", 1), ("install_nvfp4_layers", 1)]
+
+ observe = ("relayout_modelopt_nvfp4_payloads", "install_nvfp4_layers")
+ run, _ = _load(monkeypatch, _build("nvfp4_bfl"), observe=observe)
+ assert run.order == [("relayout_modelopt_nvfp4_payloads", 1), ("install_nvfp4_layers", 1)]
+
+
+def test_kept_fp8r_weights_carry_their_per_row_scale(monkeypatch: pytest.MonkeyPatch) -> None:
+ """With the fp8 matmul on, the weights stay e4m3 and the `[N]` scale goes on as a buffer, which `scaled_mm`
+ applies to the output columns. The text blocks BFL leaves in bf16 and the output adaLN, under the `norm`
+ pattern, are not fp8."""
+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _device: True)
+ build = _build("fp8r", adaln=True)
+
+ _, model = _load(monkeypatch, build)
+
+ for name in (*(f"{block}.{linear}" for block in _BLOCKS["fp8r"] for linear in _LINEARS), *_MODULATIONS):
+ module = model.get_submodule(name)
+ assert module.weight.dtype is torch.float8_e4m3fn, name
+ assert module.weight_scale.shape == (module.out_features,), name
+ assert model.get_submodule("txt_mode_blocks.0.attn.to_q").weight.dtype is torch.float32
+ assert model.norm_out.linear.weight.dtype is torch.float32
+ apply_custom_layers_to_model(model)
+ _assert_predicts_what_it_means(model, build, exact=True)
+
+
+def test_an_fp8_scale_the_conversion_does_not_carry_is_refused_before_room_is_reserved(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """`weight_scale_inv` is no spelling the key conversion moves: renamed, the weight would leave it behind under the
+ old name and load unscaled. Asked on the native names, before anything is renamed."""
+ build = _build("fp8r")
+ sd = dict(build.state_dict)
+ sd["single_blocks.0.q_proj.weight_scale_inv"] = sd.pop("single_blocks.0.q_proj.weight_scale")
+
+ run = _refused(monkeypatch, build._replace(state_dict=sd), "a spelling InvokeAI does not read")
+
+ assert run.reserved == []
+
+
+def test_int8_weights_without_a_marker_are_refused_before_room_is_reserved(monkeypatch: pytest.MonkeyPatch) -> None:
+ build = _build("int8_convrot")
+ unmarked = {key: value for key, value in build.state_dict.items() if not key.endswith(".comfy_quant")}
+
+ run = _refused(monkeypatch, build._replace(state_dict=unmarked), "no `comfy_quant` marker")
+
+ assert run.reserved == []
+
+
+def test_nvfp4_layers_named_by_no_producer_are_refused_before_room_is_reserved(monkeypatch: pytest.MonkeyPatch) -> None:
+ """ComfyUI's layout with its header gone: another producer's file under the same key names, whose bytes
+ nothing here can vouch for."""
+ build = _build("nvfp4_comfy")
+ metadata = {key: value for key, value in build.metadata.items() if key != "_quantization_metadata"}
+
+ run = _refused(monkeypatch, build._replace(metadata=metadata), "no ComfyUI `comfy_quant` marker")
+
+ assert run.reserved == []
+
+
+def test_a_packed_input_embedder_is_refused_before_room_is_reserved(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The model's input widths are read off the embedders' weights, which nvfp4 stores at half width. Named in the
+ header like the rest, so what refuses it is the width, not the naming."""
+ build = _build("nvfp4_comfy")
+ positive = torch.randint(0, 2, (HIDDEN, HIDDEN), dtype=torch.bool)
+ del build.state_dict["txt_in.weight"]
+ build.state_dict.update(nvfp4_tensors("txt_in", nvfp4_codes(positive), block_scale=1.0, global_scale=1.0))
+ header = json.loads(build.metadata["_quantization_metadata"])
+ header["layers"]["txt_in"] = {"format": "nvfp4"}
+ build.metadata["_quantization_metadata"] = json.dumps(header)
+
+ run = _refused(monkeypatch, build, "stores 'txt_in.weight' packed")
+
+ assert run.reserved == []
diff --git a/tests/backend/model_manager/configs/test_flux3_main_config.py b/tests/backend/model_manager/configs/test_flux3_main_config.py
index f4898b44c2..42923ce104 100644
--- a/tests/backend/model_manager/configs/test_flux3_main_config.py
+++ b/tests/backend/model_manager/configs/test_flux3_main_config.py
@@ -20,8 +20,15 @@ from invokeai.backend.model_manager.configs.main import (
from invokeai.backend.model_manager.model_on_disk import ModelOnDisk
from invokeai.backend.model_manager.taxonomy import Flux3VariantType, ModelFormat
from tests.backend.flux3.flux3_fixture import tiny_flux3_model, to_native, write_flux3_gguf
-from tests.backend.model_manager.load.state_dicts import flux3_klein_base_keys, flux3_klein_keys
-from tests.backend.model_manager.load.state_dicts.utils import write_header_only_safetensors
+from tests.backend.model_manager.load.state_dicts import (
+ flux3_klein_base_keys,
+ flux3_klein_fp8r_keys,
+ flux3_klein_int8_convrot_keys,
+ flux3_klein_keys,
+ flux3_klein_nvfp4_bfl_keys,
+ flux3_klein_nvfp4_comfy_keys,
+)
+from tests.backend.model_manager.load.state_dicts.utils import write_header_only_safetensors, write_shrunk_safetensors
# The released folder's JSON files (black-forest-labs/flux-3-image-klein, 2026-10-15), shortened where nothing
# reads the rest. The root `config.json` is BFL's own package config, which sits beside the pipeline.
@@ -113,31 +120,191 @@ def test_a_released_single_file_installs_as_flux3(tmp_path: Path, fixture, varia
assert result.config.variant is variant
-# What each quantized release changes on one linear, reduced to the header entries the refusal reads.
-_QUANTIZED_LAYERS = {
- # BFL `variants/fp8r`: per-row E4M3 with a scale vector.
- "fp8r": {"weight": ([3072, 3072], "F8_E4M3"), "weight_scale": ([3072], "F32")},
- # A plain fp8 cast with no side channel.
- "fp8-raw": {"weight": ([3072, 3072], "F8_E4M3")},
- # ComfyUI `int8_convrot`: int8 weights tagged by a `.comfy_quant` marker.
- "int8-convrot": {"weight": ([3072, 3072], "I8"), "comfy_quant": ([16], "U8")},
- # nvfp4 (ComfyUI and ModelOpt): two values per byte, block and tensor scales.
- "nvfp4": {"weight": ([3072, 1536], "U8"), "weight_scale": ([3072, 192], "F8_E4M3"), "weight_scale_2": ([], "F32")},
+_RELEASED_QUANTIZED = {
+ "int8-convrot": flux3_klein_int8_convrot_keys,
+ "nvfp4-comfy": flux3_klein_nvfp4_comfy_keys,
+ "nvfp4-bfl": flux3_klein_nvfp4_bfl_keys,
+ "fp8r": flux3_klein_fp8r_keys,
}
[email protected]("layout", sorted(_QUANTIZED_LAYERS))
-def test_a_quantized_single_file_is_refused_with_a_reason(tmp_path: Path, layout: str) -> None:
+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)."""
+ 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."))
+ }
+ return write_shrunk_safetensors(path, keys, markers=getattr(fixture, "markers", None), metadata=metadata)
+
+
[email protected]("base", [False, True], ids=["klein", "base"])
[email protected]("name", _RELEASED_QUANTIZED)
+def test_a_released_quantized_single_file_installs_as_flux3(tmp_path: Path, name: str, base: bool) -> None:
+ result = _identify(_write_release(tmp_path / "flux3.safetensors", _RELEASED_QUANTIZED[name], base=base))
+
+ assert result.match_count == 1, [type(match).__name__ for match in result.all_matches]
+ assert isinstance(result.config, Main_Checkpoint_Flux3_Config)
+ assert result.config.variant is (Flux3VariantType.KleinBase if base else Flux3VariantType.Klein)
+ # FP8 Storage comes on at install for the fp8 build, which then stays fp8; an int8 build has no fp8 to keep.
+ # (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":
+ assert fp8_storage is True
+ elif name == "int8-convrot":
+ assert fp8_storage is not True
+
+
+_INT8 = {"weight": ([3072, 3072], "I8"), "weight_scale": ([3072, 1], "F32"), "comfy_quant": ([72], "U8")}
+_INT8_MARKER = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 256}
+_NVFP4 = {"weight": ([3072, 1536], "U8"), "weight_scale": ([3072, 192], "F8_E4M3"), "weight_scale_2": ([], "F32")}
+_FP8_SCALED = {"weight": ([3072, 3072], "F8_E4M3"), "weight_scale": ([], "F32")}
+
+
+def _header_naming(*layers: str) -> dict[str, str]:
+ return {"_quantization_metadata": json.dumps({"layers": {layer: {"format": "nvfp4"} for layer in layers}})}
+
+
+def _with(layers: dict[str, dict[str, tuple[list[int], str]]]) -> dict[str, tuple[list[int], str]]:
+ """The released Klein layout with each of `layers` stored as its entries instead."""
keys = dict(flux3_klein_keys.state_dict_keys)
- for suffix, entry in _QUANTIZED_LAYERS[layout].items():
- keys[f"single_blocks.0.q_proj.{suffix}"] = entry
- path = write_header_only_safetensors(tmp_path / f"flux3_{layout}.safetensors", keys)
+ for layer, entries in layers.items():
+ keys = {key: entry for key, entry in keys.items() if not key.startswith(f"{layer}.")}
+ keys.update({f"{layer}.{suffix}": entry for suffix, entry in entries.items()})
+ return keys
+
+
+ ("layers", "markers"),
+ [
+ # A plain fp8 cast, no scale.
+ ({"single_blocks.0.q_proj": {"weight": ([3072, 3072], "F8_E4M3")}}, None),
+ # Per-tensor scaled fp8, as ComfyUI writes it.
+ ({"single_blocks.0.q_proj": _FP8_SCALED}, None),
+ # nvfp4 named by ComfyUI's per-layer marker rather than its header.
+ (
+ {"single_blocks.0.q_proj": {**_NVFP4, "comfy_quant": ([18], "U8")}},
+ {"single_blocks.0.q_proj": {"format": "nvfp4"}},
+ ),
+ ],
+ ids=["fp8-raw", "fp8-per-tensor", "nvfp4-comfy-marker"],
+)
+def test_the_other_loadable_quantizations_install_as_flux3(tmp_path: Path, layers, markers) -> None:
+ result = _identify(write_shrunk_safetensors(tmp_path / "flux3.safetensors", _with(layers), markers=markers))
+
+ assert result.match_count == 1, [type(match).__name__ for match in result.all_matches]
+ assert isinstance(result.config, Main_Checkpoint_Flux3_Config)
+
+
+_Q, _K = "single_blocks.0.q_proj", "single_blocks.0.k_proj"
+
+# What the loader cannot build, each on a layer or two of the released layout: the layers, their markers, the file's
+# metadata, and the reason the refusal must give.
+_REFUSED = {
+ "int8-unmarked": (
+ {_Q: {"weight": ([3072, 3072], "I8"), "weight_scale": ([3072, 1], "F32")}},
+ {},
+ {},
+ "no `comfy_quant` marker",
+ ),
+ "int8-group-size": ({_Q: _INT8}, {_Q: {**_INT8_MARKER, "convrot_groupsize": 512}}, {}, "groups of 512"),
+ "int8-missing-scale": (
+ {_Q: {"weight": ([3072, 3072], "I8"), "comfy_quant": ([72], "U8")}},
+ {_Q: _INT8_MARKER},
+ {},
+ "missing its weight_scale",
+ ),
+ "int8-blockwise-scale": (
+ {_Q: {**_INT8, "weight_scale": ([24, 24], "F32")}},
+ {_Q: _INT8_MARKER},
+ {},
+ "Blockwise scale grids are not implemented",
+ ),
+ # A 256-wide rotation group does not fit a 128-wide input.
+ "int8-group-wider-than-input": (
+ {_Q: {**_INT8, "weight": ([3072, 128], "I8")}},
+ {_Q: _INT8_MARKER},
+ {},
+ "do not divide its input width 128",
+ ),
+ "torchao": (
+ {_Q: {"_weight_qdata": ([3072, 3072], "F8_E4M3"), "_weight_scale": ([3072, 1], "F32")}},
+ {},
+ {},
+ "torchao",
+ ),
+ # bitsandbytes NF4 flattens the packed weight and keeps its state beside it.
+ "bitsandbytes": (
+ {_Q: {"weight": ([4718592, 1], "U8"), "weight.absmax": ([147456], "F32"), "weight.quant_map": ([16], "F32")}},
+ {},
+ {},
+ "bitsandbytes 4-bit quantization state",
+ ),
+ "packed-without-global-scale": ({_Q: {"weight": ([3072, 1536], "U8")}}, {}, {}, "without an nvfp4 global scale"),
+ "awq": ({_Q: {**_NVFP4, "pre_quant_scale": ([3072], "F32")}}, {}, _header_naming(_Q), "AWQ"),
+ "fp8-unparsed-scale": (
+ {_Q: {"weight": ([3072, 3072], "F8_E4M3"), "weight_scale_inv": ([3072], "F32")}},
+ {},
+ {},
+ "a spelling InvokeAI does not read",
+ ),
+ "nvfp4-unnamed": ({_Q: _NVFP4}, {}, {}, "no ComfyUI `comfy_quant` marker"),
+ # 100 rows are no whole 128-row scale tile.
+ "nvfp4-misaligned": (
+ {_Q: {"weight": ([100, 1536], "U8"), "weight_scale": ([100, 192], "F8_E4M3"), "weight_scale_2": ([], "F32")}},
+ {},
+ _header_naming(_Q),
+ "tile layout",
+ ),
+ "int8-with-nvfp4": ({_Q: _INT8, _K: _NVFP4}, {_Q: _INT8_MARKER}, _header_naming(_K), "mixes int8 and nvfp4"),
+ "int8-with-scaled-fp8": ({_Q: _INT8, _K: _FP8_SCALED}, {_Q: _INT8_MARKER}, {}, "scaled fp8"),
+ "packed-embedder": (
+ {
+ "txt_in": {
+ "weight": ([3072, 10240], "U8"),
+ "weight_scale": ([3072, 1280], "F8_E4M3"),
+ "weight_scale_2": ([], "F32"),
+ }
+ },
+ {},
+ _header_naming("txt_in"),
+ "stores 'txt_in.weight' packed",
+ ),
+}
+
+
[email protected]("layout", sorted(_REFUSED))
+def test_a_quantized_single_file_the_loader_cannot_build_is_refused(tmp_path: Path, layout: str) -> None:
+ layers, markers, metadata, reason = _REFUSED[layout]
+ path = write_shrunk_safetensors(tmp_path / "flux3.safetensors", _with(layers), markers=markers, metadata=metadata)
result = _identify(path)
# Refused outright: neither installed as FLUX.3 nor taken by another config, nor registered as unknown.
assert result.config is None
- assert any("quantized" in str(error) for error in result.invalid_matches)
+ assert 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:
+ """torchao quantizes every linear, the modulation the fingerprint looks at included, and stores each one without
+ a `.weight`; the file must still be recognized as FLUX.3 for its refusal to be reached."""
+ keys: dict[str, tuple[list[int], str]] = {}
+ for key, (shape, dtype) in flux3_klein_keys.state_dict_keys.items():
+ if key.endswith(".weight") and len(shape) == 2:
+ layer = key[: -len(".weight")]
+ keys[f"{layer}._weight_qdata"] = (shape, "F8_E4M3")
+ keys[f"{layer}._weight_scale"] = ([shape[0], 1], "F32")
+ else:
+ keys[key] = (shape, dtype)
+
+ 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
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_fp8r_keys.py b/tests/backend/model_manager/load/state_dicts/flux3_klein_fp8r_keys.py
new file mode 100644
index 0000000000..b5ded547c8
--- /dev/null
+++ b/tests/backend/model_manager/load/state_dicts/flux3_klein_fp8r_keys.py
@@ -0,0 +1,96 @@
+"""Black Forest Labs' per-row fp8 export of FLUX.3 Image Klein, `variants/fp8r/model.safetensors`.
+
+Captured on 2026-10-31 with `scripts/capture_state_dict_fixture.py`,
+which reads the header only, from
+`https://huggingface.co/black-forest-labs/flux-3-image-klein/resolve/337337621b8526e120f2275d250242f4a6bedd75/variants/fp8r/model.safetensors`.
+
+Subsetting rule: `content_mode_blocks.image` index 0, `content_mode_blocks.image_cond` index 0, `single_blocks` index 0, `txt_mode_blocks` index 0, plus every key outside a stack. Values are `(shape, dtype)`.
+
+Every block linear but the text blocks' is e4m3 with one float32 scale per output row (`weight_scale` `[N]`; the
+export's manifest states `weight.float() * weight_scale[:, None]`), and so are the six modulation `lin` layers.
+The metadata says `quantization: fp8r`, `scale: per_row_fp32`, and no layer carries a marker. `scaled_mm` applies
+a per-row scale to its output, so with the fp8 matmul or FP8 Storage the weights stay fp8.
+"""
+
+state_dict_keys: dict[str, tuple[list[int], str]] = {
+ "content_mode_blocks.image.0.attn_out.weight": ([3072, 3072], "F8_E4M3"),
+ "content_mode_blocks.image.0.attn_out.weight_scale": ([3072], "F32"),
+ "content_mode_blocks.image.0.k_proj.weight": ([3072, 3072], "F8_E4M3"),
+ "content_mode_blocks.image.0.k_proj.weight_scale": ([3072], "F32"),
+ "content_mode_blocks.image.0.mlp_in.weight": ([18432, 3072], "F8_E4M3"),
+ "content_mode_blocks.image.0.mlp_in.weight_scale": ([18432], "F32"),
+ "content_mode_blocks.image.0.mlp_out.weight": ([3072, 9216], "F8_E4M3"),
+ "content_mode_blocks.image.0.mlp_out.weight_scale": ([3072], "F32"),
+ "content_mode_blocks.image.0.norm.key_norm.scale": ([128], "BF16"),
+ "content_mode_blocks.image.0.norm.query_norm.scale": ([128], "BF16"),
+ "content_mode_blocks.image.0.q_proj.weight": ([3072, 3072], "F8_E4M3"),
+ "content_mode_blocks.image.0.q_proj.weight_scale": ([3072], "F32"),
+ "content_mode_blocks.image.0.v_proj.weight": ([3072, 3072], "F8_E4M3"),
+ "content_mode_blocks.image.0.v_proj.weight_scale": ([3072], "F32"),
+ "content_mode_blocks.image_cond.0.attn_out.weight": ([3072, 3072], "F8_E4M3"),
+ "content_mode_blocks.image_cond.0.attn_out.weight_scale": ([3072], "F32"),
+ "content_mode_blocks.image_cond.0.k_proj.weight": ([3072, 3072], "F8_E4M3"),
+ "content_mode_blocks.image_cond.0.k_proj.weight_scale": ([3072], "F32"),
+ "content_mode_blocks.image_cond.0.mlp_in.weight": ([18432, 3072], "F8_E4M3"),
+ "content_mode_blocks.image_cond.0.mlp_in.weight_scale": ([18432], "F32"),
+ "content_mode_blocks.image_cond.0.mlp_out.weight": ([3072, 9216], "F8_E4M3"),
+ "content_mode_blocks.image_cond.0.mlp_out.weight_scale": ([3072], "F32"),
+ "content_mode_blocks.image_cond.0.norm.key_norm.scale": ([128], "BF16"),
+ "content_mode_blocks.image_cond.0.norm.query_norm.scale": ([128], "BF16"),
+ "content_mode_blocks.image_cond.0.q_proj.weight": ([3072, 3072], "F8_E4M3"),
+ "content_mode_blocks.image_cond.0.q_proj.weight_scale": ([3072], "F32"),
+ "content_mode_blocks.image_cond.0.v_proj.weight": ([3072, 3072], "F8_E4M3"),
+ "content_mode_blocks.image_cond.0.v_proj.weight_scale": ([3072], "F32"),
+ "early_stream_modulations.image.lin.weight": ([9216, 3072], "F8_E4M3"),
+ "early_stream_modulations.image.lin.weight_scale": ([9216], "F32"),
+ "early_stream_modulations.image_cond.lin.weight": ([9216, 3072], "F8_E4M3"),
+ "early_stream_modulations.image_cond.lin.weight_scale": ([9216], "F32"),
+ "early_stream_modulations.txt.lin.weight": ([9216, 3072], "F8_E4M3"),
+ "early_stream_modulations.txt.lin.weight_scale": ([9216], "F32"),
+ "emb_in.image.weight": ([3072, 128], "BF16"),
+ "emb_in.image_cond.weight": ([3072, 128], "BF16"),
+ "final_layer.image.adaLN_modulation.1.weight": ([6144, 3072], "BF16"),
+ "final_layer.image.linear.weight": ([128, 3072], "BF16"),
+ "ref_time_in.in_layer.weight": ([3072, 256], "BF16"),
+ "ref_time_in.out_layer.weight": ([3072, 3072], "BF16"),
+ "single_blocks.0.attn_out.weight": ([3072, 3072], "F8_E4M3"),
+ "single_blocks.0.attn_out.weight_scale": ([3072], "F32"),
+ "single_blocks.0.k_proj.weight": ([3072, 3072], "F8_E4M3"),
+ "single_blocks.0.k_proj.weight_scale": ([3072], "F32"),
+ "single_blocks.0.mlp_in.weight": ([18432, 3072], "F8_E4M3"),
+ "single_blocks.0.mlp_in.weight_scale": ([18432], "F32"),
+ "single_blocks.0.mlp_out.weight": ([3072, 9216], "F8_E4M3"),
+ "single_blocks.0.mlp_out.weight_scale": ([3072], "F32"),
+ "single_blocks.0.norm.key_norm.scale": ([128], "BF16"),
+ "single_blocks.0.norm.query_norm.scale": ([128], "BF16"),
+ "single_blocks.0.q_proj.weight": ([3072, 3072], "F8_E4M3"),
+ "single_blocks.0.q_proj.weight_scale": ([3072], "F32"),
+ "single_blocks.0.v_proj.weight": ([3072, 3072], "F8_E4M3"),
+ "single_blocks.0.v_proj.weight_scale": ([3072], "F32"),
+ "single_stream_modulations.image.lin.weight": ([9216, 3072], "F8_E4M3"),
+ "single_stream_modulations.image.lin.weight_scale": ([9216], "F32"),
+ "single_stream_modulations.image_cond.lin.weight": ([9216, 3072], "F8_E4M3"),
+ "single_stream_modulations.image_cond.lin.weight_scale": ([9216], "F32"),
+ "single_stream_modulations.txt.lin.weight": ([9216, 3072], "F8_E4M3"),
+ "single_stream_modulations.txt.lin.weight_scale": ([9216], "F32"),
+ "time_in.in_layer.weight": ([3072, 256], "BF16"),
+ "time_in.out_layer.weight": ([3072, 3072], "BF16"),
+ "txt_in.weight": ([3072, 20480], "BF16"),
+ "txt_mode_blocks.0.attn_out.weight": ([3072, 3072], "BF16"),
+ "txt_mode_blocks.0.k_proj.weight": ([3072, 3072], "BF16"),
+ "txt_mode_blocks.0.mlp_in.weight": ([18432, 3072], "BF16"),
+ "txt_mode_blocks.0.mlp_out.weight": ([3072, 9216], "BF16"),
+ "txt_mode_blocks.0.norm.key_norm.scale": ([128], "BF16"),
+ "txt_mode_blocks.0.norm.query_norm.scale": ([128], "BF16"),
+ "txt_mode_blocks.0.q_proj.weight": ([3072, 3072], "BF16"),
+ "txt_mode_blocks.0.v_proj.weight": ([3072, 3072], "BF16"),
+}
+
+# The rest of the header's `__metadata__`, as the producer wrote it. A producer that names its scheme
+# only here -- NVIDIA ModelOpt's `quantization` -- is told apart by these alone.
+metadata: dict[str, str] = {
+ "format": "pt",
+ "model": "f3-image-small",
+ "quantization": "fp8r",
+ "scale": "per_row_fp32",
+}
diff --git a/tests/backend/model_manager/load/state_dicts/flux3_klein_int8_convrot_keys.py b/tests/backend/model_manager/load/state_dicts/flux3_klein_int8_convrot_keys.py
new file mode 100644
index 0000000000..a025c87bcb
--- /dev/null
+++ b/tests/backend/model_manager/load/state_dicts/flux3_klein_int8_convrot_keys.py
@@ -0,0 +1,127 @@
+"""Comfy-Org's `int8_convrot` build of FLUX.3 Image Klein, `flux3-image-klein-int8-convrot.safetensors`.
+
+Captured on 2026-10-31 with `scripts/capture_state_dict_fixture.py`,
+which reads the header only, from
+`https://huggingface.co/black-forest-labs/flux-3-image-klein-comfy/resolve/feef60b0aaf63a4773ace96636ebbcf43b881312/diffusion_models/flux3-image-klein-int8-convrot.safetensors`.
+
+Subsetting rule: `content_mode_blocks.image` index 0, `content_mode_blocks.image_cond` index 0, `single_blocks` index 0, `txt_mode_blocks` index 0, plus every key outside a stack. Values are `(shape, dtype)`.
+
+Every block linear of all 43 blocks is `int8_tensorwise` + convrot, with a `[N, 1]` float32 scale and a
+`.comfy_quant` marker each, and each block's query, key and value are fused into one `qkv` (`[9216, 3072]`, rows
+in that order), which diffusers keeps apart: the loader splits the codes and the scales three ways and gives each
+part the marker. The modulations, embedders and output layers stay bf16. `<block>.comfy_attention.config` (33 of
+them, on the image and the joint blocks) asks for ComfyUI's own int8 attention kernel and says nothing about the
+weights; the loader drops it. Klein Base's build has the same layout without `ref_time_in`.
+"""
+
+state_dict_keys: dict[str, tuple[list[int], str]] = {
+ "content_mode_blocks.image.0.attn_out.comfy_quant": ([72], "U8"),
+ "content_mode_blocks.image.0.attn_out.weight": ([3072, 3072], "I8"),
+ "content_mode_blocks.image.0.attn_out.weight_scale": ([3072, 1], "F32"),
+ "content_mode_blocks.image.0.comfy_attention.config": ([35], "U8"),
+ "content_mode_blocks.image.0.mlp_in.comfy_quant": ([72], "U8"),
+ "content_mode_blocks.image.0.mlp_in.weight": ([18432, 3072], "I8"),
+ "content_mode_blocks.image.0.mlp_in.weight_scale": ([18432, 1], "F32"),
+ "content_mode_blocks.image.0.mlp_out.comfy_quant": ([72], "U8"),
+ "content_mode_blocks.image.0.mlp_out.weight": ([3072, 9216], "I8"),
+ "content_mode_blocks.image.0.mlp_out.weight_scale": ([3072, 1], "F32"),
+ "content_mode_blocks.image.0.norm.key_norm.scale": ([128], "BF16"),
+ "content_mode_blocks.image.0.norm.query_norm.scale": ([128], "BF16"),
+ "content_mode_blocks.image.0.qkv.comfy_quant": ([72], "U8"),
+ "content_mode_blocks.image.0.qkv.weight": ([9216, 3072], "I8"),
+ "content_mode_blocks.image.0.qkv.weight_scale": ([9216, 1], "F32"),
+ "content_mode_blocks.image_cond.0.attn_out.comfy_quant": ([72], "U8"),
+ "content_mode_blocks.image_cond.0.attn_out.weight": ([3072, 3072], "I8"),
+ "content_mode_blocks.image_cond.0.attn_out.weight_scale": ([3072, 1], "F32"),
+ "content_mode_blocks.image_cond.0.mlp_in.comfy_quant": ([72], "U8"),
+ "content_mode_blocks.image_cond.0.mlp_in.weight": ([18432, 3072], "I8"),
+ "content_mode_blocks.image_cond.0.mlp_in.weight_scale": ([18432, 1], "F32"),
+ "content_mode_blocks.image_cond.0.mlp_out.comfy_quant": ([72], "U8"),
+ "content_mode_blocks.image_cond.0.mlp_out.weight": ([3072, 9216], "I8"),
+ "content_mode_blocks.image_cond.0.mlp_out.weight_scale": ([3072, 1], "F32"),
+ "content_mode_blocks.image_cond.0.norm.key_norm.scale": ([128], "BF16"),
+ "content_mode_blocks.image_cond.0.norm.query_norm.scale": ([128], "BF16"),
+ "content_mode_blocks.image_cond.0.qkv.comfy_quant": ([72], "U8"),
+ "content_mode_blocks.image_cond.0.qkv.weight": ([9216, 3072], "I8"),
+ "content_mode_blocks.image_cond.0.qkv.weight_scale": ([9216, 1], "F32"),
+ "early_stream_modulations.image.lin.weight": ([9216, 3072], "BF16"),
+ "early_stream_modulations.image_cond.lin.weight": ([9216, 3072], "BF16"),
+ "early_stream_modulations.txt.lin.weight": ([9216, 3072], "BF16"),
+ "emb_in.image.weight": ([3072, 128], "BF16"),
+ "emb_in.image_cond.weight": ([3072, 128], "BF16"),
+ "final_layer.image.adaLN_modulation.1.weight": ([6144, 3072], "BF16"),
+ "final_layer.image.linear.weight": ([128, 3072], "BF16"),
+ "ref_time_in.in_layer.weight": ([3072, 256], "BF16"),
+ "ref_time_in.out_layer.weight": ([3072, 3072], "BF16"),
+ "single_blocks.0.attn_out.comfy_quant": ([72], "U8"),
+ "single_blocks.0.attn_out.weight": ([3072, 3072], "I8"),
+ "single_blocks.0.attn_out.weight_scale": ([3072, 1], "F32"),
+ "single_blocks.0.comfy_attention.config": ([35], "U8"),
+ "single_blocks.0.mlp_in.comfy_quant": ([72], "U8"),
+ "single_blocks.0.mlp_in.weight": ([18432, 3072], "I8"),
+ "single_blocks.0.mlp_in.weight_scale": ([18432, 1], "F32"),
+ "single_blocks.0.mlp_out.comfy_quant": ([72], "U8"),
+ "single_blocks.0.mlp_out.weight": ([3072, 9216], "I8"),
+ "single_blocks.0.mlp_out.weight_scale": ([3072, 1], "F32"),
+ "single_blocks.0.norm.key_norm.scale": ([128], "BF16"),
+ "single_blocks.0.norm.query_norm.scale": ([128], "BF16"),
+ "single_blocks.0.qkv.comfy_quant": ([72], "U8"),
+ "single_blocks.0.qkv.weight": ([9216, 3072], "I8"),
+ "single_blocks.0.qkv.weight_scale": ([9216, 1], "F32"),
+ "single_stream_modulations.image.lin.weight": ([9216, 3072], "BF16"),
+ "single_stream_modulations.image_cond.lin.weight": ([9216, 3072], "BF16"),
+ "single_stream_modulations.txt.lin.weight": ([9216, 3072], "BF16"),
+ "time_in.in_layer.weight": ([3072, 256], "BF16"),
+ "time_in.out_layer.weight": ([3072, 3072], "BF16"),
+ "txt_in.weight": ([3072, 20480], "BF16"),
+ "txt_mode_blocks.0.attn_out.comfy_quant": ([72], "U8"),
+ "txt_mode_blocks.0.attn_out.weight": ([3072, 3072], "I8"),
+ "txt_mode_blocks.0.attn_out.weight_scale": ([3072, 1], "F32"),
+ "txt_mode_blocks.0.mlp_in.comfy_quant": ([72], "U8"),
+ "txt_mode_blocks.0.mlp_in.weight": ([18432, 3072], "I8"),
+ "txt_mode_blocks.0.mlp_in.weight_scale": ([18432, 1], "F32"),
+ "txt_mode_blocks.0.mlp_out.comfy_quant": ([72], "U8"),
+ "txt_mode_blocks.0.mlp_out.weight": ([3072, 9216], "I8"),
+ "txt_mode_blocks.0.mlp_out.weight_scale": ([3072, 1], "F32"),
+ "txt_mode_blocks.0.norm.key_norm.scale": ([128], "BF16"),
+ "txt_mode_blocks.0.norm.query_norm.scale": ([128], "BF16"),
+ "txt_mode_blocks.0.qkv.comfy_quant": ([72], "U8"),
+ "txt_mode_blocks.0.qkv.weight": ([9216, 3072], "I8"),
+ "txt_mode_blocks.0.qkv.weight_scale": ([9216, 1], "F32"),
+}
+
+# The per-layer `.comfy_quant` markers, decoded from the blobs themselves.
+markers: dict[str, dict[str, object]] = {
+ "content_mode_blocks.image.0.attn_out": {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 256},
+ "content_mode_blocks.image.0.mlp_in": {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 256},
+ "content_mode_blocks.image.0.mlp_out": {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 256},
+ "content_mode_blocks.image.0.qkv": {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 256},
+ "content_mode_blocks.image_cond.0.attn_out": {
+ "format": "int8_tensorwise",
+ "convrot": True,
+ "convrot_groupsize": 256,
+ },
+ "content_mode_blocks.image_cond.0.mlp_in": {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 256},
+ "content_mode_blocks.image_cond.0.mlp_out": {
+ "format": "int8_tensorwise",
+ "convrot": True,
+ "convrot_groupsize": 256,
+ },
+ "content_mode_blocks.image_cond.0.qkv": {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 256},
+ "single_blocks.0.attn_out": {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 256},
+ "single_blocks.0.mlp_in": {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 256},
+ "single_blocks.0.mlp_out": {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 256},
+ "single_blocks.0.qkv": {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 256},
+ "txt_mode_blocks.0.attn_out": {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 256},
+ "txt_mode_blocks.0.mlp_in": {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 256},
+ "txt_mode_blocks.0.mlp_out": {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 256},
+ "txt_mode_blocks.0.qkv": {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 256},
+}
+
+# The rest of the header's `__metadata__`, as the producer wrote it. A producer that names its scheme
+# only here -- NVIDIA ModelOpt's `quantization` -- is told apart by these alone.
+metadata: dict[str, str] = {
+ "dtype": "bfloat16",
+ "format": "pt",
+ "model": "f3-image-small",
+}
diff --git a/tests/backend/model_manager/load/state_dicts/flux3_klein_nvfp4_bfl_keys.py b/tests/backend/model_manager/load/state_dicts/flux3_klein_nvfp4_bfl_keys.py
new file mode 100644
index 0000000000..ba5598f7db
--- /dev/null
+++ b/tests/backend/model_manager/load/state_dicts/flux3_klein_nvfp4_bfl_keys.py
@@ -0,0 +1,108 @@
+"""Black Forest Labs' nvfp4 export of FLUX.3 Image Klein (NVIDIA ModelOpt), `variants/nvfp4/model.safetensors`.
+
+Captured on 2026-10-31 with `scripts/capture_state_dict_fixture.py`,
+which reads the header only, from
+`https://huggingface.co/black-forest-labs/flux-3-image-klein/resolve/337337621b8526e120f2275d250242f4a6bedd75/variants/nvfp4/model.safetensors`.
+
+Subsetting rule: `content_mode_blocks.image` index 0, `content_mode_blocks.image_cond` index 0, `single_blocks` index 0, `txt_mode_blocks` index 0, plus every key outside a stack. Values are `(shape, dtype)`.
+
+Names, shapes and dtypes are those of Comfy-Org's nvfp4 build (`flux3_klein_nvfp4_comfy_keys`), and so are the
+numbers, in another byte layout: element `2j` in the lower nibble, the block-scale grid row-major. Nothing per
+layer names the scheme, neither a `.comfy_quant` marker nor `_quantization_metadata`; only `quantization: nvfp4` in
+the metadata does, and the loader keys the re-layout on it. The `hf_quant_config.json` beside the file (`NVFP4`,
+group size 16, the excluded blocks) is not read: an install by URL does not fetch it.
+"""
+
+state_dict_keys: dict[str, tuple[list[int], str]] = {
+ "content_mode_blocks.image.0.attn_out.weight": ([3072, 3072], "BF16"),
+ "content_mode_blocks.image.0.k_proj.weight": ([3072, 3072], "BF16"),
+ "content_mode_blocks.image.0.mlp_in.weight": ([18432, 3072], "BF16"),
+ "content_mode_blocks.image.0.mlp_out.weight": ([3072, 9216], "BF16"),
+ "content_mode_blocks.image.0.norm.key_norm.scale": ([128], "BF16"),
+ "content_mode_blocks.image.0.norm.query_norm.scale": ([128], "BF16"),
+ "content_mode_blocks.image.0.q_proj.weight": ([3072, 3072], "BF16"),
+ "content_mode_blocks.image.0.v_proj.weight": ([3072, 3072], "BF16"),
+ "content_mode_blocks.image_cond.0.attn_out.input_scale": ([], "F32"),
+ "content_mode_blocks.image_cond.0.attn_out.weight": ([3072, 1536], "U8"),
+ "content_mode_blocks.image_cond.0.attn_out.weight_scale": ([3072, 192], "F8_E4M3"),
+ "content_mode_blocks.image_cond.0.attn_out.weight_scale_2": ([], "F32"),
+ "content_mode_blocks.image_cond.0.k_proj.input_scale": ([], "F32"),
+ "content_mode_blocks.image_cond.0.k_proj.weight": ([3072, 1536], "U8"),
+ "content_mode_blocks.image_cond.0.k_proj.weight_scale": ([3072, 192], "F8_E4M3"),
+ "content_mode_blocks.image_cond.0.k_proj.weight_scale_2": ([], "F32"),
+ "content_mode_blocks.image_cond.0.mlp_in.input_scale": ([], "F32"),
+ "content_mode_blocks.image_cond.0.mlp_in.weight": ([18432, 1536], "U8"),
+ "content_mode_blocks.image_cond.0.mlp_in.weight_scale": ([18432, 192], "F8_E4M3"),
+ "content_mode_blocks.image_cond.0.mlp_in.weight_scale_2": ([], "F32"),
+ "content_mode_blocks.image_cond.0.mlp_out.input_scale": ([], "F32"),
+ "content_mode_blocks.image_cond.0.mlp_out.weight": ([3072, 4608], "U8"),
+ "content_mode_blocks.image_cond.0.mlp_out.weight_scale": ([3072, 576], "F8_E4M3"),
+ "content_mode_blocks.image_cond.0.mlp_out.weight_scale_2": ([], "F32"),
+ "content_mode_blocks.image_cond.0.norm.key_norm.scale": ([128], "BF16"),
+ "content_mode_blocks.image_cond.0.norm.query_norm.scale": ([128], "BF16"),
+ "content_mode_blocks.image_cond.0.q_proj.input_scale": ([], "F32"),
+ "content_mode_blocks.image_cond.0.q_proj.weight": ([3072, 1536], "U8"),
+ "content_mode_blocks.image_cond.0.q_proj.weight_scale": ([3072, 192], "F8_E4M3"),
+ "content_mode_blocks.image_cond.0.q_proj.weight_scale_2": ([], "F32"),
+ "content_mode_blocks.image_cond.0.v_proj.input_scale": ([], "F32"),
+ "content_mode_blocks.image_cond.0.v_proj.weight": ([3072, 1536], "U8"),
+ "content_mode_blocks.image_cond.0.v_proj.weight_scale": ([3072, 192], "F8_E4M3"),
+ "content_mode_blocks.image_cond.0.v_proj.weight_scale_2": ([], "F32"),
+ "early_stream_modulations.image.lin.weight": ([9216, 3072], "BF16"),
+ "early_stream_modulations.image_cond.lin.weight": ([9216, 3072], "BF16"),
+ "early_stream_modulations.txt.lin.weight": ([9216, 3072], "BF16"),
+ "emb_in.image.weight": ([3072, 128], "BF16"),
+ "emb_in.image_cond.weight": ([3072, 128], "BF16"),
+ "final_layer.image.adaLN_modulation.1.weight": ([6144, 3072], "BF16"),
+ "final_layer.image.linear.weight": ([128, 3072], "BF16"),
+ "ref_time_in.in_layer.weight": ([3072, 256], "BF16"),
+ "ref_time_in.out_layer.weight": ([3072, 3072], "BF16"),
+ "single_blocks.0.attn_out.input_scale": ([], "F32"),
+ "single_blocks.0.attn_out.weight": ([3072, 1536], "U8"),
+ "single_blocks.0.attn_out.weight_scale": ([3072, 192], "F8_E4M3"),
+ "single_blocks.0.attn_out.weight_scale_2": ([], "F32"),
+ "single_blocks.0.k_proj.input_scale": ([], "F32"),
+ "single_blocks.0.k_proj.weight": ([3072, 1536], "U8"),
+ "single_blocks.0.k_proj.weight_scale": ([3072, 192], "F8_E4M3"),
+ "single_blocks.0.k_proj.weight_scale_2": ([], "F32"),
+ "single_blocks.0.mlp_in.input_scale": ([], "F32"),
+ "single_blocks.0.mlp_in.weight": ([18432, 1536], "U8"),
+ "single_blocks.0.mlp_in.weight_scale": ([18432, 192], "F8_E4M3"),
+ "single_blocks.0.mlp_in.weight_scale_2": ([], "F32"),
+ "single_blocks.0.mlp_out.input_scale": ([], "F32"),
+ "single_blocks.0.mlp_out.weight": ([3072, 4608], "U8"),
+ "single_blocks.0.mlp_out.weight_scale": ([3072, 576], "F8_E4M3"),
+ "single_blocks.0.mlp_out.weight_scale_2": ([], "F32"),
+ "single_blocks.0.norm.key_norm.scale": ([128], "BF16"),
+ "single_blocks.0.norm.query_norm.scale": ([128], "BF16"),
+ "single_blocks.0.q_proj.input_scale": ([], "F32"),
+ "single_blocks.0.q_proj.weight": ([3072, 1536], "U8"),
+ "single_blocks.0.q_proj.weight_scale": ([3072, 192], "F8_E4M3"),
+ "single_blocks.0.q_proj.weight_scale_2": ([], "F32"),
+ "single_blocks.0.v_proj.input_scale": ([], "F32"),
+ "single_blocks.0.v_proj.weight": ([3072, 1536], "U8"),
+ "single_blocks.0.v_proj.weight_scale": ([3072, 192], "F8_E4M3"),
+ "single_blocks.0.v_proj.weight_scale_2": ([], "F32"),
+ "single_stream_modulations.image.lin.weight": ([9216, 3072], "BF16"),
+ "single_stream_modulations.image_cond.lin.weight": ([9216, 3072], "BF16"),
+ "single_stream_modulations.txt.lin.weight": ([9216, 3072], "BF16"),
+ "time_in.in_layer.weight": ([3072, 256], "BF16"),
+ "time_in.out_layer.weight": ([3072, 3072], "BF16"),
+ "txt_in.weight": ([3072, 20480], "BF16"),
+ "txt_mode_blocks.0.attn_out.weight": ([3072, 3072], "BF16"),
+ "txt_mode_blocks.0.k_proj.weight": ([3072, 3072], "BF16"),
+ "txt_mode_blocks.0.mlp_in.weight": ([18432, 3072], "BF16"),
+ "txt_mode_blocks.0.mlp_out.weight": ([3072, 9216], "BF16"),
+ "txt_mode_blocks.0.norm.key_norm.scale": ([128], "BF16"),
+ "txt_mode_blocks.0.norm.query_norm.scale": ([128], "BF16"),
+ "txt_mode_blocks.0.q_proj.weight": ([3072, 3072], "BF16"),
+ "txt_mode_blocks.0.v_proj.weight": ([3072, 3072], "BF16"),
+}
+
+# The rest of the header's `__metadata__`, as the producer wrote it. A producer that names its scheme
+# only here -- NVIDIA ModelOpt's `quantization` -- is told apart by these alone.
+metadata: dict[str, str] = {
+ "format": "pt",
+ "model": "f3-image-small",
+ "quantization": "nvfp4",
+}
diff --git a/tests/backend/model_manager/load/state_dicts/flux3_klein_nvfp4_comfy_keys.py b/tests/backend/model_manager/load/state_dicts/flux3_klein_nvfp4_comfy_keys.py
new file mode 100644
index 0000000000..a74ebbdba7
--- /dev/null
+++ b/tests/backend/model_manager/load/state_dicts/flux3_klein_nvfp4_comfy_keys.py
@@ -0,0 +1,124 @@
+"""Comfy-Org's nvfp4 build of FLUX.3 Image Klein, `flux3-image-klein-nvfp4.safetensors`.
+
+Captured on 2026-10-31 with `scripts/capture_state_dict_fixture.py`,
+which reads the header only, from
+`https://huggingface.co/black-forest-labs/flux-3-image-klein-comfy/resolve/feef60b0aaf63a4773ace96636ebbcf43b881312/diffusion_models/flux3-image-klein-nvfp4.safetensors`.
+
+Subsetting rule: `content_mode_blocks.image` index 0, `content_mode_blocks.image_cond` index 0, `single_blocks` index 0, `txt_mode_blocks` index 0, plus every key outside a stack. Values are `(shape, dtype)`.
+
+33 of the 43 blocks are nvfp4, q, k and v apart: all but `content_mode_blocks.image.0` (bf16 here, beside the
+quantized `image_cond.0` and `single_blocks.0`), `single_blocks.24` to `27` and the text blocks. No layer carries a
+`.comfy_quant` marker; the header's `_quantization_metadata` names each one, so a loader that read only per-tensor
+markers would refuse every layer as unnamed. The tensors are Black Forest Labs' `variants/nvfp4` export
+(`flux3_klein_nvfp4_bfl_keys`) re-laid out into ComfyUI's bytes, `input_scale` included. Klein Base's build has the
+same layout without `ref_time_in`.
+"""
+
+state_dict_keys: dict[str, tuple[list[int], str]] = {
+ "content_mode_blocks.image.0.attn_out.weight": ([3072, 3072], "BF16"),
+ "content_mode_blocks.image.0.k_proj.weight": ([3072, 3072], "BF16"),
+ "content_mode_blocks.image.0.mlp_in.weight": ([18432, 3072], "BF16"),
+ "content_mode_blocks.image.0.mlp_out.weight": ([3072, 9216], "BF16"),
+ "content_mode_blocks.image.0.norm.key_norm.scale": ([128], "BF16"),
+ "content_mode_blocks.image.0.norm.query_norm.scale": ([128], "BF16"),
+ "content_mode_blocks.image.0.q_proj.weight": ([3072, 3072], "BF16"),
+ "content_mode_blocks.image.0.v_proj.weight": ([3072, 3072], "BF16"),
+ "content_mode_blocks.image_cond.0.attn_out.input_scale": ([], "F32"),
+ "content_mode_blocks.image_cond.0.attn_out.weight": ([3072, 1536], "U8"),
+ "content_mode_blocks.image_cond.0.attn_out.weight_scale": ([3072, 192], "F8_E4M3"),
+ "content_mode_blocks.image_cond.0.attn_out.weight_scale_2": ([], "F32"),
+ "content_mode_blocks.image_cond.0.k_proj.input_scale": ([], "F32"),
+ "content_mode_blocks.image_cond.0.k_proj.weight": ([3072, 1536], "U8"),
+ "content_mode_blocks.image_cond.0.k_proj.weight_scale": ([3072, 192], "F8_E4M3"),
+ "content_mode_blocks.image_cond.0.k_proj.weight_scale_2": ([], "F32"),
+ "content_mode_blocks.image_cond.0.mlp_in.input_scale": ([], "F32"),
+ "content_mode_blocks.image_cond.0.mlp_in.weight": ([18432, 1536], "U8"),
+ "content_mode_blocks.image_cond.0.mlp_in.weight_scale": ([18432, 192], "F8_E4M3"),
+ "content_mode_blocks.image_cond.0.mlp_in.weight_scale_2": ([], "F32"),
+ "content_mode_blocks.image_cond.0.mlp_out.input_scale": ([], "F32"),
+ "content_mode_blocks.image_cond.0.mlp_out.weight": ([3072, 4608], "U8"),
+ "content_mode_blocks.image_cond.0.mlp_out.weight_scale": ([3072, 576], "F8_E4M3"),
+ "content_mode_blocks.image_cond.0.mlp_out.weight_scale_2": ([], "F32"),
+ "content_mode_blocks.image_cond.0.norm.key_norm.scale": ([128], "BF16"),
+ "content_mode_blocks.image_cond.0.norm.query_norm.scale": ([128], "BF16"),
+ "content_mode_blocks.image_cond.0.q_proj.input_scale": ([], "F32"),
+ "content_mode_blocks.image_cond.0.q_proj.weight": ([3072, 1536], "U8"),
+ "content_mode_blocks.image_cond.0.q_proj.weight_scale": ([3072, 192], "F8_E4M3"),
+ "content_mode_blocks.image_cond.0.q_proj.weight_scale_2": ([], "F32"),
+ "content_mode_blocks.image_cond.0.v_proj.input_scale": ([], "F32"),
+ "content_mode_blocks.image_cond.0.v_proj.weight": ([3072, 1536], "U8"),
+ "content_mode_blocks.image_cond.0.v_proj.weight_scale": ([3072, 192], "F8_E4M3"),
+ "content_mode_blocks.image_cond.0.v_proj.weight_scale_2": ([], "F32"),
+ "early_stream_modulations.image.lin.weight": ([9216, 3072], "BF16"),
+ "early_stream_modulations.image_cond.lin.weight": ([9216, 3072], "BF16"),
+ "early_stream_modulations.txt.lin.weight": ([9216, 3072], "BF16"),
+ "emb_in.image.weight": ([3072, 128], "BF16"),
+ "emb_in.image_cond.weight": ([3072, 128], "BF16"),
+ "final_layer.image.adaLN_modulation.1.weight": ([6144, 3072], "BF16"),
+ "final_layer.image.linear.weight": ([128, 3072], "BF16"),
+ "ref_time_in.in_layer.weight": ([3072, 256], "BF16"),
+ "ref_time_in.out_layer.weight": ([3072, 3072], "BF16"),
+ "single_blocks.0.attn_out.input_scale": ([], "F32"),
+ "single_blocks.0.attn_out.weight": ([3072, 1536], "U8"),
+ "single_blocks.0.attn_out.weight_scale": ([3072, 192], "F8_E4M3"),
+ "single_blocks.0.attn_out.weight_scale_2": ([], "F32"),
+ "single_blocks.0.k_proj.input_scale": ([], "F32"),
+ "single_blocks.0.k_proj.weight": ([3072, 1536], "U8"),
+ "single_blocks.0.k_proj.weight_scale": ([3072, 192], "F8_E4M3"),
+ "single_blocks.0.k_proj.weight_scale_2": ([], "F32"),
+ "single_blocks.0.mlp_in.input_scale": ([], "F32"),
+ "single_blocks.0.mlp_in.weight": ([18432, 1536], "U8"),
+ "single_blocks.0.mlp_in.weight_scale": ([18432, 192], "F8_E4M3"),
+ "single_blocks.0.mlp_in.weight_scale_2": ([], "F32"),
+ "single_blocks.0.mlp_out.input_scale": ([], "F32"),
+ "single_blocks.0.mlp_out.weight": ([3072, 4608], "U8"),
+ "single_blocks.0.mlp_out.weight_scale": ([3072, 576], "F8_E4M3"),
+ "single_blocks.0.mlp_out.weight_scale_2": ([], "F32"),
+ "single_blocks.0.norm.key_norm.scale": ([128], "BF16"),
+ "single_blocks.0.norm.query_norm.scale": ([128], "BF16"),
+ "single_blocks.0.q_proj.input_scale": ([], "F32"),
+ "single_blocks.0.q_proj.weight": ([3072, 1536], "U8"),
+ "single_blocks.0.q_proj.weight_scale": ([3072, 192], "F8_E4M3"),
+ "single_blocks.0.q_proj.weight_scale_2": ([], "F32"),
+ "single_blocks.0.v_proj.input_scale": ([], "F32"),
+ "single_blocks.0.v_proj.weight": ([3072, 1536], "U8"),
+ "single_blocks.0.v_proj.weight_scale": ([3072, 192], "F8_E4M3"),
+ "single_blocks.0.v_proj.weight_scale_2": ([], "F32"),
+ "single_stream_modulations.image.lin.weight": ([9216, 3072], "BF16"),
+ "single_stream_modulations.image_cond.lin.weight": ([9216, 3072], "BF16"),
+ "single_stream_modulations.txt.lin.weight": ([9216, 3072], "BF16"),
+ "time_in.in_layer.weight": ([3072, 256], "BF16"),
+ "time_in.out_layer.weight": ([3072, 3072], "BF16"),
+ "txt_in.weight": ([3072, 20480], "BF16"),
+ "txt_mode_blocks.0.attn_out.weight": ([3072, 3072], "BF16"),
+ "txt_mode_blocks.0.k_proj.weight": ([3072, 3072], "BF16"),
+ "txt_mode_blocks.0.mlp_in.weight": ([18432, 3072], "BF16"),
+ "txt_mode_blocks.0.mlp_out.weight": ([3072, 9216], "BF16"),
+ "txt_mode_blocks.0.norm.key_norm.scale": ([128], "BF16"),
+ "txt_mode_blocks.0.norm.query_norm.scale": ([128], "BF16"),
+ "txt_mode_blocks.0.q_proj.weight": ([3072, 3072], "BF16"),
+ "txt_mode_blocks.0.v_proj.weight": ([3072, 3072], "BF16"),
+}
+
+# The `_quantization_metadata` header block, layer names exactly as the producer wrote them.
+layer_hints: dict[str, dict[str, object]] = {
+ "content_mode_blocks.image_cond.0.attn_out": {"format": "nvfp4"},
+ "content_mode_blocks.image_cond.0.k_proj": {"format": "nvfp4"},
+ "content_mode_blocks.image_cond.0.mlp_in": {"format": "nvfp4"},
+ "content_mode_blocks.image_cond.0.mlp_out": {"format": "nvfp4"},
+ "content_mode_blocks.image_cond.0.q_proj": {"format": "nvfp4"},
+ "content_mode_blocks.image_cond.0.v_proj": {"format": "nvfp4"},
+ "single_blocks.0.attn_out": {"format": "nvfp4"},
+ "single_blocks.0.k_proj": {"format": "nvfp4"},
+ "single_blocks.0.mlp_in": {"format": "nvfp4"},
+ "single_blocks.0.mlp_out": {"format": "nvfp4"},
+ "single_blocks.0.q_proj": {"format": "nvfp4"},
+ "single_blocks.0.v_proj": {"format": "nvfp4"},
+}
+
+# The rest of the header's `__metadata__`, as the producer wrote it. A producer that names its scheme
+# only here -- NVIDIA ModelOpt's `quantization` -- is told apart by these alone.
+metadata: dict[str, str] = {
+ "format": "pt",
+ "model": "f3-image-small",
+}
diff --git a/tests/backend/model_manager/load/state_dicts/utils.py b/tests/backend/model_manager/load/state_dicts/utils.py
index 343c865772..18ee55e2e7 100644
--- a/tests/backend/model_manager/load/state_dicts/utils.py
+++ b/tests/backend/model_manager/load/state_dicts/utils.py
@@ -4,7 +4,7 @@ Mirrors `tests/backend/patches/lora_conversions/lora_state_dicts/utils.py`: a fi
exports `state_dict_keys`, key name -> shape (or `(shape, dtype)` for the layouts
`scripts/capture_state_dict_fixture.py` captures from a real checkpoint's header). Tests expand it to a
mock state dict with `keys_to_mock_state_dict()`, or write it back as a header with
-`write_header_only_safetensors()`.
+`write_header_only_safetensors()`, or as a small complete file with `write_shrunk_safetensors()`.
"""
import json
@@ -15,6 +15,7 @@ from pathlib import Path
from typing import Any
import torch
+from safetensors.torch import save_file
def keys_to_mock_state_dict(keys: dict[str, list[int]]) -> dict[str, torch.Tensor]:
@@ -66,3 +67,70 @@ def write_header_only_safetensors(
encoded += b" " * (-len(encoded) % 8)
path.write_bytes(struct.pack("<Q", len(encoded)) + encoded + b"".join(blobs.values()))
return path
+
+
+_TORCH_DTYPES = {
+ "F32": torch.float32,
+ "F16": torch.float16,
+ "BF16": torch.bfloat16,
+ "F8_E4M3": torch.float8_e4m3fn,
+ "F8_E5M2": torch.float8_e5m2,
+ "I64": torch.int64,
+ "I8": torch.int8,
+ "U8": torch.uint8,
+}
+
+
+def keys_to_meta_state_dict(keys: Mapping[str, tuple[list[int], str]]) -> dict[str, torch.Tensor]:
+ """A captured layout as meta tensors of its real shapes and dtypes: what identification and a conversion see of
+ a file, at no memory cost."""
+ return {key: torch.empty(shape, dtype=_TORCH_DTYPES[dtype], device="meta") for key, (shape, dtype) in keys.items()}
+
+
+def write_shrunk_safetensors(
+ path: Path,
+ keys: Mapping[str, tuple[list[int], str]],
+ *,
+ markers: Mapping[str, Mapping[str, Any]] | None = None,
+ metadata: Mapping[str, str] | None = None,
+) -> Path:
+ """Write a fixture's layout as a complete safetensors file, every tensor zeros at `token_extents`.
+
+ For identification that reads more of a file than its tensor entries. The header's metadata comes through
+ `safe_open`, which refuses a file whose data a header-only write left out, and a `.comfy_quant` marker is read
+ from its bytes: each marker the fixture decoded (`markers`, keyed by layer) is written back as its JSON.
+
+ Two layouts keep a size, because identification checks it. An int8 weight keeps up to one rotation group of input
+ columns (`_CONVROT_GROUP`), so a rotated layer stays divisible and an undivisible one stays so. A packed nvfp4 weight and its block-scale grid keep
+ one whole scale tile of rows and blocks (`_NVFP4_TILE`), so a released layer stays a valid one and a misaligned
+ one stays misaligned. Nothing else that reads a size may use this.
+ """
+ tensors: dict[str, torch.Tensor] = {}
+ for key, (shape, dtype) in keys.items():
+ layer = key.removesuffix(".comfy_quant")
+ if markers is not None and layer != key and layer in markers:
+ raw = json.dumps(dict(markers[layer])).encode("utf-8")
+ tensors[key] = torch.frombuffer(bytearray(raw), dtype=torch.uint8).clone()
+ else:
+ tensors[key] = torch.zeros(_shrunk_extents(key, shape, dtype), dtype=_TORCH_DTYPES[dtype])
+ save_file(tensors, str(path), metadata=dict(metadata) if metadata else None)
+ return path
+
+
+# One cuBLAS scale tile of an nvfp4 layer: 128 rows by 4 blocks of 16 elements, two elements packed per byte.
+_NVFP4_TILE = {"U8": (128, 32), "F8_E4M3": (128, 4)}
+
+
+# The rotation group of every int8 convrot release, in input columns.
+_CONVROT_GROUP = 256
+
+
+def _shrunk_extents(key: str, shape: list[int], dtype: str) -> list[int]:
+ """`token_extents`, except for an nvfp4 layer's packed weight and grid, which keep at most one scale tile, and an
+ int8 weight, which keeps at most one rotation group of columns."""
+ if len(shape) == 2 and dtype == "I8" and key.endswith(".weight"):
+ return [min(shape[0], 4), min(shape[1], _CONVROT_GROUP)]
+ nvfp4_part = (dtype == "U8" and key.endswith(".weight")) or (dtype == "F8_E4M3" and key.endswith(".weight_scale"))
+ if len(shape) == 2 and nvfp4_part:
+ return [min(extent, limit) for extent, limit in zip(shape, _NVFP4_TILE[dtype], strict=True)]
+ return token_extents(shape)
diff --git a/tests/backend/model_manager/test_starter_models.py b/tests/backend/model_manager/test_starter_models.py
index d471ae7307..489036a2cb 100644
--- a/tests/backend/model_manager/test_starter_models.py
+++ b/tests/backend/model_manager/test_starter_models.py
@@ -1,4 +1,4 @@
-"""Tests for the starter-model bundles and the LTX-2 GGUF transformers.
+"""Tests for the starter-model bundles, the LTX-2 GGUF transformers and the FLUX.3 single files.
A single-file (nvfp4) or GGUF Krea-2 transformer ships *only* the transformer, so it is unusable without a
standalone Qwen-Image VAE and Qwen3-VL text encoder. These tests assert that the Krea-2 launchpad
@@ -15,6 +15,7 @@ from invokeai.backend.model_manager.starter_models import (
)
from invokeai.backend.model_manager.taxonomy import (
BaseModelType,
+ Flux3VariantType,
Krea2VariantType,
LTX2VariantType,
ModelFormat,
@@ -189,3 +190,22 @@ def test_the_ltx2_gguf_transformers_pull_the_components_and_the_encoder() -> Non
(ModelType.Gemma4Encoder, ModelFormat.Gemma4Encoder),
}, model.name
assert all(dep.source in starter_sources for dep in dependencies), model.name
+
+
+def test_every_flux3_transformer_only_starter_pulls_the_vae_and_the_encoder() -> None:
+ """The single files, quantized or not, and the GGUFs hold only the transformer: installing one has to pull the
+ FLUX.2 VAE and the Qwen3-VL encoder, both installable starters themselves. Klein and Klein Base both ship that way."""
+ transformer_only = [
+ m for m in STARTER_MODELS if m.base is BaseModelType.Flux3 and m.type is ModelType.Main and m.format is not None
+ ]
+ starter_sources = {m.source for m in STARTER_MODELS}
+
+ assert {m.format for m in transformer_only} == {ModelFormat.Checkpoint, ModelFormat.GGUFQuantized}
+ assert {m.variant for m in transformer_only if m.format is ModelFormat.Checkpoint} == {
+ Flux3VariantType.Klein,
+ Flux3VariantType.KleinBase,
+ }
+ for model in transformer_only:
+ dependencies = model.dependencies or []
+ assert {dep.type for dep in dependencies} == {ModelType.VAE, ModelType.Qwen3VLEncoder}, model.name
+ assert all(dep.source in starter_sources for dep in dependencies), model.name
diff --git a/tests/backend/quantization/test_block_scale_tiles.py b/tests/backend/quantization/test_block_scale_tiles.py
index c596bf5a33..22207222a8 100644
--- a/tests/backend/quantization/test_block_scale_tiles.py
+++ b/tests/backend/quantization/test_block_scale_tiles.py
@@ -9,7 +9,7 @@ files, written out explicitly, rather than from the implementation's reshape.
import pytest
import torch
-from invokeai.backend.quantization.block_scale_tiles import unblock_scale_grid
+from invokeai.backend.quantization.block_scale_tiles import block_scale_grid, unblock_scale_grid
from tests.fixtures.quantized_payloads import stored_layout
@@ -21,15 +21,26 @@ def test_a_stored_grid_is_restored_to_row_major(shape: tuple[int, int]) -> None:
assert torch.equal(unblock_scale_grid(stored_layout(grid)), grid)
[email protected]("shape", [(128, 4), (128, 8), (256, 16), (384, 8)])
+def test_a_row_major_grid_is_tiled_as_checkpoints_store_it(shape: tuple[int, int]) -> None:
+ """The inverse, for a producer that writes its grid row-major (ModelOpt): it must land where the index formula
+ puts each entry, which is where every decode here reads it."""
+ grid = torch.arange(shape[0] * shape[1], dtype=torch.float64).reshape(shape)
+
+ assert torch.equal(block_scale_grid(grid), stored_layout(grid))
+
+
[email protected]("permute", [unblock_scale_grid, block_scale_grid])
@pytest.mark.parametrize("shape", [(100, 8), (128, 6)])
-def test_a_grid_outside_the_tile_layout_is_refused_rather_than_guessed(shape: tuple[int, int]) -> None:
+def test_a_grid_outside_the_tile_layout_is_refused_rather_than_guessed(permute, shape: tuple[int, int]) -> None:
"""`to_blocked` pads such a grid and the padding is cropped on the way back. No published
checkpoint needs it, so it is refused rather than implemented from the spec and shipped
untested."""
with pytest.raises(ValueError, match="tile layout"):
- unblock_scale_grid(torch.zeros(shape))
+ permute(torch.zeros(shape))
-def test_a_one_dimensional_grid_is_refused() -> None:
[email protected]("permute", [unblock_scale_grid, block_scale_grid])
+def test_a_one_dimensional_grid_is_refused(permute) -> None:
with pytest.raises(ValueError, match="2-D"):
- unblock_scale_grid(torch.zeros(512))
+ permute(torch.zeros(512))
diff --git a/tests/backend/quantization/test_nvfp4.py b/tests/backend/quantization/test_nvfp4.py
index afe8fa2354..53e786d5da 100644
--- a/tests/backend/quantization/test_nvfp4.py
+++ b/tests/backend/quantization/test_nvfp4.py
@@ -4,7 +4,8 @@ No expected value here comes from `nvfp4.py` itself. Nibble order and the E2M1 t
against literal bytes; the block-scale layout against the index formula measured on real checkpoints,
written out as arithmetic; and the whole decode against a slice of a real Comfy-Org checkpoint and its
bf16 build. That slice is one tile row high: it pins the layout inside a row of tiles against real data,
-while the order of the tile rows rests on the formula test.
+while the order of the tile rows rests on the formula test. The ModelOpt re-layout is held to the same
+layer encoded both ways by index formulas of their own.
"""
from pathlib import Path
@@ -24,14 +25,21 @@ from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes, requires_sidecar_patching
from invokeai.backend.quantization.nvfp4 import (
NVFP4Linear,
+ NVFP4Payload,
dequantize_nvfp4_weight,
find_nvfp4_layers,
install_nvfp4_layers,
pop_nvfp4_layers,
predict_nvfp4_install_size,
+ relayout_modelopt_nvfp4_payloads,
split_nvfp4_rows,
)
-from tests.fixtures.quantized_payloads import comfy_quant_marker, nvfp4_tensors, stored_layout
+from tests.fixtures.quantized_payloads import (
+ comfy_quant_marker,
+ nvfp4_modelopt_tensors,
+ nvfp4_tensors,
+ stored_layout,
+)
FIXTURE = Path(__file__).parent / "data" / "z_image_turbo_nvfp4_slices.safetensors"
@@ -102,6 +110,48 @@ def test_a_real_checkpoint_slice_decodes_to_its_bf16_build(layer: str) -> None:
assert torch.equal(module(x), torch.nn.functional.linear(x, decoded.view(128, 128)))
+def test_a_modelopt_layer_is_re_laid_out_into_the_bytes_comfyui_stores() -> None:
+ """NVIDIA ModelOpt (Black Forest Labs' FLUX.3 nvfp4 build) and ComfyUI store the same layer two ways: ModelOpt
+ packs element ``2j`` into the low nibble and keeps the block-scale grid row-major, ComfyUI packs it high and tiles
+ the grid. Each encoding is written by an index formula of its own (`nvfp4_modelopt_tensors`, and `nvfp4_tensors`
+ over `stored_layout`), not by the code under test. Every E2M1 code appears, neighbours always differ, and the grid
+ varies along rows and blocks, so a skipped nibble swap, a skipped tiling or a tiling along the wrong axes changes
+ bytes."""
+ rows, blocks = 128, 4
+ codes = (torch.arange(rows * blocks * 16) * 5 % 16).reshape(rows, blocks * 16).to(torch.uint8)
+ # Finite, positive e4m3 bit patterns (0x01-0x7E), different in neighbouring rows and blocks.
+ grid_bytes = (torch.arange(rows).unsqueeze(1) * 7 + torch.arange(blocks).unsqueeze(0) * 31) % 126 + 1
+ grid = grid_bytes.to(torch.uint8).view(torch.float8_e4m3fn).float()
+ modelopt = nvfp4_modelopt_tensors("layer", codes, grid=grid, global_scale=0.25)
+ comfy = nvfp4_tensors("layer", codes, block_scale=stored_layout(grid), global_scale=0.25)
+ assert not torch.equal(modelopt["layer.weight"], comfy["layer.weight"])
+ assert not torch.equal(
+ modelopt["layer.weight_scale"].view(torch.uint8), comfy["layer.weight_scale"].view(torch.uint8)
+ )
+
+ payloads = {
+ "layer": NVFP4Payload(
+ modelopt["layer.weight"], modelopt["layer.weight_scale"], modelopt["layer.weight_scale_2"]
+ )
+ }
+
+ relayout_modelopt_nvfp4_payloads(payloads)
+
+ relaid = payloads["layer"]
+ assert torch.equal(relaid.weight, comfy["layer.weight"])
+ assert relaid.weight_scale.dtype is torch.float8_e4m3fn
+ # As bytes: `torch.equal` is not implemented for float8 on the CPU.
+ assert torch.equal(relaid.weight_scale.view(torch.uint8), comfy["layer.weight_scale"].view(torch.uint8))
+ # And what both mean, from the E2M1 table and the row-major grid: every product here is exact in float32.
+ e2m1 = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0])
+ expected = e2m1[codes.long()] * grid.repeat_interleave(16, dim=1) * 0.25
+ for weight, scale, scale_2 in (
+ (relaid.weight, relaid.weight_scale, relaid.weight_scale_2),
+ (comfy["layer.weight"], comfy["layer.weight_scale"], comfy["layer.weight_scale_2"]),
+ ):
+ assert torch.equal(dequantize_nvfp4_weight(weight, scale, scale_2, torch.float32), expected)
+
+
@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16, torch.float32])
def test_the_decode_lands_in_the_dtype_it_was_asked_for(dtype: torch.dtype) -> None:
"""The per-forward decode has to honour the dtype it is handed, not one of its own.
diff --git a/tests/backend/quantization/test_quantized_payloads.py b/tests/backend/quantization/test_quantized_payloads.py
index f35ddf6e97..55e36360ce 100644
--- a/tests/backend/quantization/test_quantized_payloads.py
+++ b/tests/backend/quantization/test_quantized_payloads.py
@@ -23,7 +23,13 @@ import torch
from invokeai.backend.quantization.fp8_scaled import dequantize_fp8_scaled, extract_fp8_scaled_layers
from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, Int8ConvrotLinear
from invokeai.backend.quantization.nvfp4 import NVFP4Linear
-from tests.fixtures.quantized_payloads import mxfp8_tensors, nvfp4_signed_tensors, quantize_convrot, quantize_scaled_fp8
+from tests.fixtures.quantized_payloads import (
+ mxfp8_tensors,
+ nvfp4_signed_tensors,
+ quantize_convrot,
+ quantize_per_row_fp8,
+ quantize_scaled_fp8,
+)
CPU = torch.device("cpu")
@@ -114,6 +120,22 @@ def test_the_scaled_fp8_codes_reach_the_top_of_e4m3() -> None:
assert payload.codes.float().isfinite().all(), "the scale let a weight overflow e4m3"
+def test_the_per_row_fp8_payload_dequantizes_through_the_real_extraction() -> None:
+ """The `[N]` scale must reach the weight's rows: broadcast like any trailing axis it would scale the columns of a
+ square layer instead, at the right shape and magnitude."""
+ torch.manual_seed(5)
+ original = torch.randn(16, 16) * torch.logspace(-2, 1, 16).unsqueeze(1)
+ payload = quantize_per_row_fp8(original)
+ state_dict = {"lin.weight": payload.codes, "lin.weight_scale": payload.scale}
+
+ layers = extract_fp8_scaled_layers(state_dict)
+ dequantize_fp8_scaled(state_dict, layers, torch.float32)
+
+ assert set(state_dict) == {"lin.weight"}
+ assert torch.equal(state_dict["lin.weight"], payload.dequantized)
+ assert torch.corrcoef(torch.stack([state_dict["lin.weight"].flatten(), original.flatten()]))[0, 1] > 0.999
+
+
def test_the_nvfp4_payload_unpacks_to_the_exact_weights_it_claims() -> None:
"""Exact, not approximate: the signed payload is built from the two codes worth +-1.0 and scales
that are powers of two, so every product is representable. A swapped nibble order transposes the
diff --git a/tests/fixtures/quantized_payloads.py b/tests/fixtures/quantized_payloads.py
index ff266d8218..3df1a23abc 100644
--- a/tests/fixtures/quantized_payloads.py
+++ b/tests/fixtures/quantized_payloads.py
@@ -163,6 +163,17 @@ def quantize_scaled_fp8(weight: torch.Tensor) -> ScaledFp8Payload:
return ScaledFp8Payload(codes, scale, codes.float() * scale)
+def quantize_per_row_fp8(weight: torch.Tensor) -> ScaledFp8Payload:
+ """Mirror of Black Forest Labs' ``fp8r`` export: e4m3 codes and one float32 scale per output row, ``[out]``.
+
+ The export's manifest states the convention, ``weight.float() * weight_scale[:, None]``. A 1-D scale broadcast
+ the default way scales the input columns instead, which a square layer does not reveal by its shape.
+ """
+ scale = (weight.abs().amax(dim=1) / FP8_E4M3_MAX).to(torch.float32)
+ codes = (weight / scale[:, None]).to(torch.float8_e4m3fn)
+ return ScaledFp8Payload(codes, scale, codes.float() * scale[:, None])
+
+
def nvfp4_codes(positive: torch.Tensor) -> torch.Tensor:
"""Codes for a layer of exactly +1.0 and -1.0 in E2M1, one per element of ``positive``."""
return torch.where(positive, NVFP4_CODE_PLUS_ONE, NVFP4_CODE_MINUS_ONE).to(torch.uint8)
@@ -205,6 +216,30 @@ def nvfp4_signed_tensors(path: str, positive: torch.Tensor) -> tuple[dict[str, t
return tensors, torch.where(positive, 0.5, -0.5)
+def nvfp4_modelopt_tensors(
+ path: str, codes: torch.Tensor, *, grid: torch.Tensor, global_scale: float
+) -> dict[str, torch.Tensor]:
+ """One nvfp4 layer as NVIDIA ModelOpt writes it: Black Forest Labs' FLUX.3 ``variants/nvfp4`` file.
+
+ The tensors and names of :func:`nvfp4_tensors`, laid out the other way on both counts that matter: element ``2j``
+ is the *lower* nibble, and the block-scale grid is row-major, ``grid[m, k]`` scaling elements ``16k`` to
+ ``16k + 15`` of row ``m``. Both were read off BFL's file against Comfy-Org's repack of it. Since nothing here is
+ tiled, :func:`nvfp4_weight` states what such a layer means without restating any permutation.
+ """
+ return {
+ f"{path}.weight": (codes[:, 1::2] << 4) | codes[:, 0::2],
+ f"{path}.weight_scale": grid.to(torch.float8_e4m3fn),
+ f"{path}.weight_scale_2": torch.tensor(global_scale),
+ }
+
+
+def nvfp4_weight(positive: torch.Tensor, grid: torch.Tensor, global_scale: float) -> torch.Tensor:
+ """What a layer of :func:`nvfp4_codes` means under a row-major ``grid``: +-1 times its block's scale times the
+ global scale. Exact in float32 when the scales are powers of two. For ComfyUI's layout, store the grid as
+ ``stored_layout(grid)``."""
+ return torch.where(positive, 1.0, -1.0) * grid.repeat_interleave(16, dim=1) * global_scale
+
+
def stored_layout(grid: torch.Tensor) -> torch.Tensor:
"""Lay a row-major grid out the way checkpoints store it.
@@ -214,10 +249,11 @@ def stored_layout(grid: torch.Tensor) -> torch.Tensor:
"""
rows, blocks = grid.shape
flat = torch.full((rows * blocks,), float("nan"), dtype=grid.dtype)
- for m in range(rows):
- for k in range(blocks):
- position = ((((m // 128) * (blocks // 4) + k // 4) * 32 + m % 32) * 4 + (m % 128) // 32) * 4 + k % 4
- flat[position] = grid[m, k]
+ # The formula over every (m, k) at once rather than in a Python loop, which a model-sized fixture would wait on.
+ m = torch.arange(rows).unsqueeze(1)
+ k = torch.arange(blocks).unsqueeze(0)
+ position = ((((m // 128) * (blocks // 4) + k // 4) * 32 + m % 32) * 4 + (m % 128) // 32) * 4 + k % 4
+ flat[position.flatten()] = grid.flatten()
return flat.reshape(rows, blocks)