Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(model-manager): keep int8/int4 builds out of FP8 Storage, stop enabling it for nvfp4 (#10276)
Alexander Eichhorn6cb11aaef5f7
diff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-3.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-3.mdxindex 3aa1638b75..5cf7ed14a9 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-3.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/flux-3.mdx@@ -1,7 +1,7 @@---title: FLUX.3description: Generate and edit images with FLUX.3 Image Klein (step-distilled) and Klein Base, including editing with up to ten reference images, LoRAs, layout boxes from Canvas regional guidance and the GGUF, single-file and quantized builds.-lastUpdated: 2026-11-06+lastUpdated: 2026-11-15sidebar:order: 6---@@ -126,10 +126,9 @@ extra pass over the weights on every load.Diffusers-named file that is not a torchao export is not recognized.FP8 Storage does not apply to the int8 and nvfp4 builds: their quantized layers are smaller already, and the 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.+they keep in bf16 stay bf16. The toggle still shows for these builds and may be on; 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 imagesdiff --git a/docs/src/content/docs/Users Guide/03.Models/Local Models/moss-image.mdx b/docs/src/content/docs/Users Guide/03.Models/Local Models/moss-image.mdxindex 8d228f5d09..ba2180be03 100644--- a/docs/src/content/docs/Users Guide/03.Models/Local Models/moss-image.mdx+++ b/docs/src/content/docs/Users Guide/03.Models/Local Models/moss-image.mdx@@ -130,8 +130,9 @@ Not supported, and refused at install with a message saying so: ComfyUI's scaledtorchao exports other than the fp8 layout above (INT8 builds, per-tensor or block-wise fp8), files that mix torchao fp8with ComfyUI-quantized layers, nvfp4 and w4a8 builds, and the ComfyUI-GGUF `Q8_CR` and `Q4_CR` files. Install the bf16file, the fp8 or int8 build above, or a GGUF instead. To save VRAM with a bf16 file, turn on **FP8 Storage** in the-model's **Default Settings**. FP8 Storage does nothing for a GGUF; for the fp8 build it only keeps the file's fp8 layers-packed, and for the int8 build it applies only to the layers that are not already int8.+model's **Default Settings**. FP8 Storage does nothing for a GGUF or the int8 build; the int8 build keeps the layers it+did not quantize in bf16. The Model Manager can still show the toggle for the int8 build, because it is the same kind+of file as the bf16 one. It has no effect there. For the fp8 build it only keeps the file's fp8 layers packed.The int8 build and the GGUFs save memory; they are not faster. In InvokeAI's measurements on an RTX 4090 they took3-15 % longer per image than bf16. Int8 and Q8_0 keep the scene of a bf16 image and shift its details.diff --git a/docs/src/content/docs/configuration/Optimization/fp8-storage.mdx b/docs/src/content/docs/configuration/Optimization/fp8-storage.mdxindex 9f751a6cdf..0d0899f4a5 100644--- a/docs/src/content/docs/configuration/Optimization/fp8-storage.mdx+++ b/docs/src/content/docs/configuration/Optimization/fp8-storage.mdx@@ -1,7 +1,7 @@---title: FP8 Storagedescription: Halve a full-precision model's VRAM by keeping its weights in FP8 on the GPU, per model, from the Model Manager.-lastUpdated: 2026-10-26+lastUpdated: 2026-11-15sidebar:order: 3---@@ -28,8 +28,9 @@ the setting only stores the layers that shipped without a scale as fp8, as it do## What it applies to-The Model Manager shows the **FP8 storage** setting only for models where it changes something. A model installed-before this rule may still have it stored as on; it then does nothing, and the log says so once when the model loads:+The Model Manager shows the **FP8 storage** setting only for models where it changes something, with the exceptions+under [By file format](#by-file-format) and [When installing](#when-installing). A model installed before this rule may still have it stored as on; it then does+nothing, and the log says so once when the model loads:`FP8 Storage is set for '<model>' but does nothing here: <reason>`.### By file format@@ -39,18 +40,36 @@ 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. Wan 2.2 does not re-encode the unpacked layers, so turning it off is not needed there. |-| 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. |+| int8 and int4 single files | **No.** Their quantized layers stay as stored and their other layers stay in the precision the build ships. Those are the layers the build leaves dense (timestep, input and output layers, modulations, text paths), and FP8 Storage would re-encode them without a scale. Measured on the published files, that zeroes 43% of the weights of Krea-2 Turbo's output layer and 95% of MOSS-Image int8's timestep layer, for a saving of 0–7% of the model's size. The setting can still show for these files, since they are the same kind of file as a full-precision one, but it does nothing there. |+| nvfp4 single files | **Off after install; your choice.** Their nvfp4 layers stay as stored. Turned on, FP8 Storage stores the layers the build ships in full precision in FP8, which saves 4–16% of the model's size (about 4% on Krea-2, 16% on Z-Image). Small weights there can round to zero, but in InvokeAI's measurements the nvfp4 images did not visibly change. FLUX.3 and LTX-2 nvfp4 files ignore the setting. |+| nvfp4 file with scaled fp8 layers (Qwen-Image's nvfp4 build) | **On after install; keep it on.** Its fp8 layers stay in fp8 with their own scale; unpacked to BF16 they would add about 10.5 GiB. As on Qwen-Image's other scaled fp8 files, its remaining full-precision layers are stored in FP8 too. || 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.+<details>+<summary>What the log shows for quantized single files</summary>++On a GPU that passes the FP8 test, Anima, Krea-2, Qwen-Image, Z-Image, Wan and MOSS-Image log once per load for an+int8 or int4 build,+`FP8 Storage skipped for <model> - this quantized build keeps its quantized layers as stored and its other layers in the precision the build chose.`+FLUX.1, FLUX.2 and FLUX.3 log their own line+(`FLUX: the model's fp8_storage setting was skipped - …`, `FLUX.2: …`,+`FLUX.3: FP8 Storage skipped - this int8 or nvfp4 build …`) whenever the setting is on, also on the CPU. LTX-2,+Qwen-Image-2.1 and Ideogram 4 log nothing for their quantized builds. A Krea-2, Qwen-Image or Z-Image nvfp4 build logs+`FP8 layerwise casting enabled for <model> …`, like a full-precision file.++</details>+### By model+The rows describe full-precision files, unless a row says otherwise. Quantized single files follow [By file format](#by-file-format).+| Model | FP8 Storage || --- | --- || 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 |+| FLUX.3 | Yes || 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 |@@ -122,8 +141,8 @@ without FP8 and the log warns once: `FP8 storage probe failed on <device> (…);</TabItem><TabItem label="CPU and Apple silicon">Not used. PyTorch can hold FP8 on the CPU, but casting is emulated in software and costs more than the memory saves.-With the setting on, the loader returns the model unchanged, without a log line. Checkpoints that store FP8 weights are-unpacked to BF16 here.+With the setting on, the loader returns the model unchanged, without a log line (FLUX.1 and FLUX.2 still log their skip line+for int8 builds, FLUX.3 for int8 and nvfp4 builds). Checkpoints that store FP8 weights are unpacked to BF16 here.</TabItem></Tabs>@@ -131,7 +150,7 @@ unpacked to BF16 here.<Steps>1. Open the **Model Manager**.-2. Select a model (Main, ControlNet or T2I-Adapter). The setting only appears where it has an effect.+2. Select a model (Main, ControlNet or T2I-Adapter). The setting only appears where it has an effect, with a few exceptions ([By file format](#by-file-format)).3. Under **Default Settings**, turn on **FP8 storage**.4. Click **Save Defaults**.</Steps>@@ -148,8 +167,9 @@ adapters. For small SD1 and SD2 models the savings are negligible and not worth| --- | --- || A checkpoint whose transformer or UNet stores FP8 weights | **On automatically.** InvokeAI reads the weight types from the file, not its name, so a full-precision file with "fp8" in its name is not affected. Only the denoiser counts: an all-in-one checkpoint with an FP8 text encoder beside a full-precision UNet or transformer is left alone. The log says `denoiser weights are stored in float8, enabling FP8 Storage by default`. || A scaled fp8 checkpoint | **On automatically**, and it costs no precision: the weights stay exactly as published, with their scale. |+| An nvfp4 checkpoint | **Off unless the denoiser also stores float8 weights**, as Qwen-Image's nvfp4 file with scaled fp8 layers does. The fp8 block scales of the nvfp4 format alone do not switch it on; turn it on yourself to store the full-precision layers in FP8 (FLUX.3 and LTX-2 ignore it). If it is already on for an nvfp4 model, it stores those layers in FP8 until you turn it off. || An MXFP8 checkpoint | **On automatically, but turn it off**: it costs quality (see [By file format](#by-file-format)). Wan 2.2 is the exception, see above. |-| Anything else, from a file path, URL or Hugging Face repo, or from folder scan results | **Tick FP8 storage** next to the install source. It applies to the models from there that support it; for the others the request is dropped, so no model is recorded with a setting that does nothing. Starter models don't offer it. |+| Anything else, from a file path, URL or Hugging Face repo, or from folder scan results | **Tick FP8 storage** next to the install source. It applies to the models from there that support it; for the others the request is dropped, so no model is recorded with a setting that does nothing, except a quantized single file that ignores the setting ([By file format](#by-file-format)), which keeps the request recorded. Starter models don't offer it. |Either way the setting stays editable under **Default Settings**, and re-identifying a model keeps it.@@ -172,7 +192,7 @@ 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)`. OnFLUX.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 and Wan 2.2 keep their fp8 layers without the first line.+the intended outcome, not a failure. Qwen-Image and Wan 2.2 keep their fp8 layers without the first line; they log `FP8 layerwise casting enabled for <model> …` with the number of scaled fp8 layers kept with their own scale instead.</details>@@ -195,7 +215,7 @@ with partial loading also works, but costs speed and reproducibility.| Symptom | What to do || --- | --- |-| VRAM didn't drop after turning it on | A model in use is evicted only when its generation finishes: start a new generation. If it still hasn't dropped, look in the log for `FP8 layerwise casting enabled for <model>`. Without it, the model is one FP8 Storage skips ([What it applies to](#what-it-applies-to)), or already FP8 (`FP8 storage skipped … already fp8`: nothing needed re-encoding). |+| VRAM didn't drop after turning it on | A model in use is evicted only when its generation finishes: start a new generation. If it still hasn't dropped, look in the log for `FP8 layerwise casting enabled for <model>`. Without it, the model is one FP8 Storage skips ([What it applies to](#what-it-applies-to)) already FP8 (`FP8 storage skipped … already fp8`: nothing needed re-encoding), or a quantized single file that ignores the setting ([By file format](#by-file-format)). || `FP8 storage probe failed` in the log | Your GPU, driver or PyTorch build can't store FP8; the model loads without it. FP8 Storage is never used on the CPU or Apple silicon. || Quality regression on one model | Turn FP8 Storage off for that model and reload. If quality comes back, the model has FP8-sensitive layers outside the skip list: please report it (below). || `RuntimeError: … float8_e4m3fn …` | Your PyTorch predates FP8 support (added in 2.1). Reinstall with the official launcher, whose PyTorch supports it. |diff --git a/invokeai/backend/model_manager/configs/factory.py b/invokeai/backend/model_manager/configs/factory.pyindex 9d89d0bec1..713b2a8578 100644--- a/invokeai/backend/model_manager/configs/factory.py+++ b/invokeai/backend/model_manager/configs/factory.py@@ -277,6 +277,12 @@ def _denoiser_stores_float8_weights(mod: ModelOnDisk) -> bool:let the layerwise cast re-encode the result as *unscaled* fp8, which on `flux-2-klein-4b-fp8` flushed 3.4% of theweights to zero for the byte count the file already had. The loaders now keep such a file in its own scaled forminstead, so switching the setting on is lossless and worth doing by default.++ A float8 tensor named as a scale (`<layer>.weight_scale`) is not evidence: nvfp4 stores its block scales in+ F8_E4M3 beside a packed U8 weight, and they are not fp8 weights. For such a build FP8 Storage would store only the+ layers the file ships in full precision, a lossy trade rather than the lossless keep a scaled-fp8 file gets, so+ it is left to the user instead of switched on. An nvfp4 file that also stores scaled fp8 weights (Qwen-Image's+ nvfp4 build) still counts."""if mod.path.is_file():candidates = [mod.path]@@ -298,7 +304,9 @@ def _denoiser_stores_float8_weights(mod: ModelOnDisk) -> bool:continuedenoiser = {key: info for key, info in header.items() if not key.startswith(_BUNDLED_COMPONENT_KEY_PREFIXES)}stores_float8 = stores_float8 or any(- isinstance(info, dict) and info.get("dtype") in _FP8_SAFETENSORS_DTYPES for info in denoiser.values()+ isinstance(info, dict) and info.get("dtype") in _FP8_SAFETENSORS_DTYPES+ for key, info in denoiser.items()+ if not key.endswith("_scale"))return stores_float8diff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.pyindex 825313a715..28c70d8f07 100644--- a/invokeai/backend/model_manager/load/load_default.py+++ b/invokeai/backend/model_manager/load/load_default.py@@ -29,6 +29,7 @@ from invokeai.backend.model_manager.taxonomy import (AnyModel,SubModelType,)+from invokeai.backend.quantization.dequantizing_linear import DequantizingLinearfrom invokeai.backend.quantization.fp8_scaled import count_fp8_weights, should_keep_fp8_weightsfrom invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.fp8 import FP8_COMPUTE_DTYPE_ATTR, FP8_STORAGE_DTYPES, set_fp8_compute_dtype@@ -635,6 +636,21 @@ class ModelLoader(ModelLoaderBase):)return model+ # A quantized build leaves its timestep, input/output, modulation and text layers dense, at the precision the+ # build chose. For int8 an unscaled e4m3 cast flushes small weights there to zero (94.8% of MOSS-Image int8's+ # `time_embedding.2`) and moved Krea-2 int8's step-0 output error from 1.9% to 2.8%, for a saving of 0-7% of+ # the model, so a scheme keeps its build as shipped unless it sets `leaves_dense_layers_to_fp8_storage`. After+ # the fp8 check so that a model holding fp8 weights gets the single "already fp8" notice.+ if isinstance(model, torch.nn.Module) and any(+ isinstance(module, DequantizingLinear) and not module.leaves_dense_layers_to_fp8_storage+ for module in model.modules()+ ):+ self._logger.info(+ f"FP8 Storage skipped for {config.name} - this quantized build keeps its quantized layers as "+ "stored and its other layers in the precision the build chose."+ )+ return model+storage_dtype = torch.float8_e4m3fncompute_dtype = self._torch_dtypediff --git a/invokeai/backend/model_manager/load/model_loaders/anima.py b/invokeai/backend/model_manager/load/model_loaders/anima.pyindex d72f57c57c..69aa59f726 100644--- a/invokeai/backend/model_manager/load/model_loaders/anima.py+++ b/invokeai/backend/model_manager/load/model_loaders/anima.py@@ -236,8 +236,8 @@ class AnimaCheckpointModel(ModelLoader):# nothing stayed packed, the state dict was cast to a single `model_dtype` above, so the# layerwise cast has one unambiguous compute dtype to restore to; when something did stay# packed, the cast bails out on its own rather than upcast a scaled weight without applying- # its scale. AnimaTransformer is a plain nn.Module, so this takes the hook-based path in- # `_apply_fp8_to_nn_module`.+ # its scale or cast the dense remainder of an int8 build. AnimaTransformer is a plain nn.Module, so this+ # takes the hook-based path in `_apply_fp8_to_nn_module`.if fp8_layers:attached = attach_fp8_scales(model, fp8_layers)logger.info(diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.pyindex c9f3298890..cca4cc16c4 100644--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py@@ -515,7 +515,8 @@ class Krea2CheckpointModel(ModelLoader):``.weight_scale``) and ComfyUI 'int8_tensorwise' checkpoints (int8 weight + per-output-channel``.weight_scale`` + a ``.comfy_quant`` marker, optionally convrot-rotated), in both the diffusersand native/ComfyUI key naming. Apply the fp8-storage setting to keep the (large) transformer- fp8-resident; otherwise it loads in full precision.+ fp8-resident (not for an int8 or int4 build, which keeps every layer as shipped); otherwise it loads in+ full precision.The int8 build stays int8-resident: `swap_in_int8_linears` installs `Int8ConvrotLinear`, whichholds the stored codes and dequantizes per forward, so a 12.0 GiB checkpoint stays 12.0 GiB.diff --git a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py b/invokeai/backend/model_manager/load/model_loaders/qwen_image.pyindex 647c967563..e6e9a05e7a 100644--- a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/qwen_image.py@@ -325,8 +325,8 @@ class QwenImageCheckpointModel(ModelLoader):if int8_markers:sd = drop_unconsumed_quantization_sidecars(sd)fp8_layers = {}- # Nothing scaled to keep for fp8 storage; the outer `_apply_fp8_layerwise_casting` still casts the dense- # remainder when the model asks for fp8 storage.+ # Nothing scaled to keep for fp8 storage; the int8 layers make the outer `_apply_fp8_layerwise_casting`+ # decline the model, so the dense remainder stays as loaded.use_fp8_storage = Falsekeep_fp8 = Falseelse:diff --git a/invokeai/backend/model_manager/load/model_loaders/wan.py b/invokeai/backend/model_manager/load/model_loaders/wan.pyindex 71fb2d44e7..ac3cb3f372 100644--- a/invokeai/backend/model_manager/load/model_loaders/wan.py+++ b/invokeai/backend/model_manager/load/model_loaders/wan.py@@ -545,6 +545,7 @@ class WanCheckpointModel(ModelLoader):``float8_e4m3fn`` weights with no scales (cast the same way as any other non-bf16 dtype). ComfyUI``int8_tensorwise`` (convrot) builds keep their marked layers in int8 as ``Int8ConvrotLinear`` and dequantizethem per forward; layers the model reads outside a matmul (``condition_embedder``) are widened at load instead.+ FP8 Storage leaves an int8 build as loaded.Like the GGUF loader, one file is one expert; A14B pairing happens at theWanModelLoaderInvocation layer.diff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.pyindex c0ec4c5ed3..7b7fcf559e 100644--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py@@ -726,10 +726,10 @@ class ZImageCheckpointModel(ModelLoader):# FP8 *storage* on top. When nothing was kept quantized above, every param is uniform# `model_dtype` here, so the layerwise cast has one unambiguous compute dtype to restore to.- # When weights *were* kept fp8, `_apply_fp8_layerwise_casting` bails out on its own (and- # says so in the log): its hooks would restore the compute dtype before every forward, which- # disables the fp8 matmul where there is one and drops the `weight_scale` where there is- # not -- and saves no VRAM either way.+ # When weights *were* kept fp8, or an int8 layer was kept, `_apply_fp8_layerwise_casting` bails out on its+ # own (and says so in the log). For fp8 its hooks would restore the compute dtype before every forward,+ # which disables the fp8 matmul where there is one and drops the `weight_scale` where there is not -- and+ # saves no VRAM either way. An nvfp4 build is cast: its dense layers go to fp8, its nvfp4 buffers stay.model = self._apply_fp8_layerwise_casting(model, config, SubModelType.Transformer)return modeldiff --git a/invokeai/backend/quantization/dequantizing_linear.py b/invokeai/backend/quantization/dequantizing_linear.pyindex 7dde9ff9ba..7c2f1773a7 100644--- a/invokeai/backend/quantization/dequantizing_linear.py+++ b/invokeai/backend/quantization/dequantizing_linear.py@@ -3,15 +3,16 @@Three schemes store their Linears this way, ``int8_convrot``, ``nvfp4`` and Ideogram 4's row-wise fp8(``fp8_rowwise``); GGUF keeps a plain Linear but packs its weight in a ``GGMLTensor`` and dequantizes itper forward just the same. The code around them-needs the same two answers about any of these: whether a LoRA has to ride along as a sidecar, and how-much memory one forward needs on top of the model's resident size. Both are asked of the loaded module-tree and live here, so callers ask once for every scheme: a module-level scheme answers by subclassing,-GGUF -- whose quantization lives on the weight, not the module -- is delegated to.+needs the same three answers about any of these: whether a LoRA has to ride along as a sidecar, how+much memory one forward needs on top of the model's resident size, and whether FP8 Storage may cast the+build's other, full-precision layers (`leaves_dense_layers_to_fp8_storage`). The first two are asked of the+loaded module tree and live here, so callers ask once for every scheme: a module-level scheme answers by+subclassing, GGUF -- whose quantization lives on the weight, not the module -- is delegated to."""import abcimport sys-from typing import Any+from typing import Any, ClassVarimport torchimport torch.nn.functional as F@@ -35,6 +36,11 @@ class DequantizingLinear(torch.nn.Module, abc.ABC):rather than in the denoise node that sizes its working memory from them."""+ #: Whether FP8 Storage may cast the other, full-precision layers of a build holding this scheme. By default it+ #: declines the whole build: those layers keep the precision the build chose. A scheme opts in only where+ #: measurement showed that casting them costs nothing material.+ leaves_dense_layers_to_fp8_storage: ClassVar[bool] = False+in_features: intout_features: intbias: torch.Tensor | Nonediff --git a/invokeai/backend/quantization/nvfp4.py b/invokeai/backend/quantization/nvfp4.pyindex aca8bf0f94..fe146942a6 100644--- a/invokeai/backend/quantization/nvfp4.py+++ b/invokeai/backend/quantization/nvfp4.py@@ -155,6 +155,11 @@ class NVFP4Linear(DequantizingLinear):sidecar LoRA patches, and a partial load that leaves its buffers on the CPU streams them per forward."""+ # FP8 Storage may cast the layers the build ships in full precision. On an RTX 4090 that barely moved the step-0+ # transformer output against bf16 (Krea-2 Turbo 8.4% -> 8.9%, Z-Image Turbo 31.6% -> 31.8%) and did not change the+ # image PSNR, and it saves 4-16% of the model.+ leaves_dense_layers_to_fp8_storage = True+def __init__(self,weight: torch.Tensor,diff --git a/tests/backend/model_manager/configs/test_identified_default_settings.py b/tests/backend/model_manager/configs/test_identified_default_settings.pyindex 5f06cd2941..bcdcc06460 100644--- a/tests/backend/model_manager/configs/test_identified_default_settings.py+++ b/tests/backend/model_manager/configs/test_identified_default_settings.py@@ -18,6 +18,7 @@ from safetensors.torch import save_filefrom invokeai.backend.model_manager.configs.factory import ModelConfigFactoryfrom invokeai.backend.model_manager.configs.main import Main_Checkpoint_QwenImage_Configfrom invokeai.backend.model_manager.taxonomy import ModelType+from tests.fixtures.quantized_payloads import comfy_quant_marker, nvfp4_codes, nvfp4_tensors_DIFFUSERS_FIXTURE = Path(__file__).parents[1] / "data" / "test_files" / "test-diffusers-main"@@ -68,6 +69,39 @@ def test_a_scaled_fp8_checkpoint_gets_it_too(tmp_path: Path, scale_key: str) ->assert config.default_settings.fp8_storage is True+def _nvfp4_img_in() -> dict[str, torch.Tensor]:+ """An nvfp4 `img_in`: a packed U8 weight beside block scales stored as F8_E4M3, the way Comfy writes it."""+ layer = nvfp4_tensors("img_in", nvfp4_codes(torch.rand(128, 64) > 0.5), block_scale=1.0, global_scale=0.5)+ return {**layer, "img_in.comfy_quant": comfy_quant_marker({"format": "nvfp4"})}+++def test_nvfp4_block_scales_are_not_float8_weights(tmp_path: Path) -> None:+ """Only the block scales are float8 in such a file. FP8 Storage would store just the layers the build ships in full+ precision, a lossy trade, so identification leaves it to the user."""+ nvfp4 = _nvfp4_img_in()+ assert nvfp4["img_in.weight_scale"].dtype is torch.float8_e4m3fn++ config = _identify(_qwen_image_checkpoint(tmp_path / "qwen_image_nvfp4.safetensors", torch.bfloat16, **nvfp4))++ assert config.default_settings is None or config.default_settings.fp8_storage is None+++def test_an_nvfp4_file_that_also_stores_float8_weights_gets_it(tmp_path: Path) -> None:+ """Qwen-Image's nvfp4 build keeps scaled fp8 layers (an F8 weight beside an F32 `weight_scale`) beside the nvfp4+ ones, and FP8 Storage keeps those packed."""+ path = _qwen_image_checkpoint(+ tmp_path / "qwen_image_nvfp4.safetensors",+ torch.float8_e4m3fn,+ **_nvfp4_img_in(),+ **{"txt_in.weight_scale": torch.ones(1)},+ )++ config = _identify(path)++ assert config.default_settings is not None+ assert config.default_settings.fp8_storage is True++def test_a_full_precision_file_named_fp8_is_left_alone(tmp_path: Path) -> None:config = _identify(_qwen_image_checkpoint(tmp_path / "qwen_image_fp8_scaled.safetensors", torch.bfloat16))diff --git a/tests/backend/model_manager/load/test_anima_fp8_wiring.py b/tests/backend/model_manager/load/test_anima_fp8_wiring.pyindex 62705ab3f9..25b8beda16 100644--- a/tests/backend/model_manager/load/test_anima_fp8_wiring.py+++ b/tests/backend/model_manager/load/test_anima_fp8_wiring.py@@ -21,12 +21,16 @@ import torchfrom invokeai.backend.anima.anima_transformer import AnimaTransformerfrom invokeai.backend.anima.checkpoint_layout import ANIMA_TRANSFORMER_CONFIGfrom invokeai.backend.model_manager.configs.main import Main_Checkpoint_Anima_Config, MainModelDefaultSettings+from invokeai.backend.model_manager.load import load_defaultfrom invokeai.backend.model_manager.load.load_default import (_FP8_DEFAULT_SKIP_PATTERNS,_FP8_SUPPORTED_PYTORCH_LAYERS,)from invokeai.backend.model_manager.load.model_loaders.anima import AnimaCheckpointModelfrom invokeai.backend.model_manager.taxonomy import SubModelType+from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, Int8ConvrotLinear+from tests.fixtures.loader_seams import assert_fp8_storage_declined, logged_info+from tests.fixtures.quantized_payloads import comfy_quant_marker, quantize_convrotfrom tests.fixtures.safetensors_files import record_reads, served_checkpoint# Every cast-eligible module in the real Anima graph that the declared patterns protect. Pinned@@ -157,6 +161,68 @@ def test_single_file_loader_applies_fp8_layerwise_casting(monkeypatch, tmp_path)assert cast_calls == [(config, SubModelType.Transformer)]+class _TinyInt8AnimaTransformer(torch.nn.Module):+ """One layer an int8 build quantizes beside one it leaves dense, under the names its markers use."""++ def __init__(self, **_kwargs) -> None:+ super().__init__()+ self.proj = torch.nn.Linear(CONVROT_GROUP_SIZE, 4, bias=False)+ self.embed = torch.nn.Linear(8, 4)+++def test_fp8_storage_leaves_an_int8_build_as_loaded(monkeypatch, tmp_path) -> None:+ """The int8 layer stays int8 and the dense one keeps the compute dtype: the build is the same tensor for tensor+ as the load without FP8 Storage."""+ import invokeai.backend.anima.anima_transformer as anima_transformer_module++ quantized = quantize_convrot(torch.randn(4, CONVROT_GROUP_SIZE))+ dense = {"embed.weight": torch.randn(4, 8), "embed.bias": torch.randn(4)}+ state_dict = {+ "proj.weight": quantized.codes,+ "proj.weight_scale": quantized.scale,+ "proj.comfy_quant": comfy_quant_marker(+ {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE}+ ),+ **dense,+ }+ checkpoint_path = tmp_path / "anima_int8.safetensors"+ safetensors.torch.save_file(state_dict, str(checkpoint_path))+ monkeypatch.setattr(anima_transformer_module, "AnimaTransformer", _TinyInt8AnimaTransformer)+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.anima.anima_transformer_config", lambda _sd: {}+ )+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.anima.TorchDevice.choose_torch_device",+ lambda: torch.device("cpu"),+ )+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.anima.TorchDevice.choose_anima_inference_dtype",+ lambda _device: torch.bfloat16,+ )+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda *_args: True)++ def load(fp8_storage: bool):+ config = Main_Checkpoint_Anima_Config.model_construct(+ path=str(checkpoint_path),+ name="anima_int8",+ default_settings=MainModelDefaultSettings(fp8_storage=fp8_storage),+ )+ loader = object.__new__(AnimaCheckpointModel)+ loader._ram_cache = SimpleNamespace(make_room=MagicMock())+ loader._torch_device = torch.device("cpu")+ loader._torch_dtype = torch.bfloat16+ loader._logger = MagicMock()+ return loader._load_from_singlefile(config), loader++ plain, _ = load(False)+ model, loader = load(True)++ assert isinstance(model.proj, Int8ConvrotLinear)+ assert model.proj.weight.dtype is torch.int8+ assert model.embed.weight.dtype is torch.bfloat16+ assert_fp8_storage_declined(model, plain, logged_info(loader._logger), "anima_int8")++def test_an_all_in_ones_vae_text_encoder_and_exporter_metadata_are_never_read(monkeypatch, tmp_path) -> None:"""A ComfyUI bundle carries the VAE and text encoder under namespaces of their own, and exporters add samplingschedules and derived buffers. Read through ``pread`` they would cost their size in process memory only to bediff --git a/tests/backend/model_manager/load/test_krea2_nvfp4_loader.py b/tests/backend/model_manager/load/test_krea2_nvfp4_loader.pyindex 9cbd463b26..190dfa0962 100644--- a/tests/backend/model_manager/load/test_krea2_nvfp4_loader.py+++ b/tests/backend/model_manager/load/test_krea2_nvfp4_loader.py@@ -15,12 +15,14 @@ from unittest.mock import MagicMockimport pytestimport torch-from invokeai.backend.model_manager.configs.main import Main_Checkpoint_Krea2_Config+from invokeai.backend.model_manager.configs.main import Main_Checkpoint_Krea2_Config, MainModelDefaultSettings+from invokeai.backend.model_manager.load import load_defaultfrom invokeai.backend.model_manager.load.model_loaders import krea2from invokeai.backend.model_manager.load.model_loaders.krea2 import Krea2CheckpointModelfrom invokeai.backend.model_manager.taxonomy import Krea2VariantTypefrom invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, Int8ConvrotLinearfrom invokeai.backend.quantization.nvfp4 import NVFP4Linear+from tests.fixtures.loader_seams import assert_fp8_storage_declined, logged_infofrom tests.fixtures.quantized_payloads import comfy_quant_marker, nvfp4_signed_tensorsfrom tests.fixtures.safetensors_files import served_checkpoint@@ -73,8 +75,7 @@ def _packed_bytes(rows: int, columns: int) -> int:return rows * columns // 2 + rows * (columns // 16) + 4[email protected](params=["dense", "int8"])-def loaded(request, monkeypatch: pytest.MonkeyPatch, tmp_path) -> SimpleNamespace:+def _load(monkeypatch: pytest.MonkeyPatch, tmp_path, neighbour: str, fp8_storage: bool = False) -> SimpleNamespace:"""The loader run over a native nvfp4 file whose `blocks.0.attn.wk` neighbour is dense or int8 -- the twoside-channel branches the nvfp4 layers have to pass through untouched."""import diffusers@@ -98,7 +99,7 @@ def loaded(request, monkeypatch: pytest.MonkeyPatch, tmp_path) -> SimpleNamespacstate_dict["tmlp.0.bias"] = torch.randn(128)state_dict["first.weight"] = torch.randn(4, 8)state_dict["first.bias"] = torch.randn(4)- if request.param == "dense":+ if neighbour == "dense":state_dict["blocks.0.attn.wk.weight"] = torch.randn(128, CONVROT_GROUP_SIZE)else:state_dict["blocks.0.attn.wk.weight"] = torch.randint(-127, 128, (128, CONVROT_GROUP_SIZE), dtype=torch.int8)@@ -111,7 +112,10 @@ def loaded(request, monkeypatch: pytest.MonkeyPatch, tmp_path) -> SimpleNamespaccheckpoint_path = tmp_path / "krea2_turbo_nvfp4.safetensors"checkpoint_path.touch()config = Main_Checkpoint_Krea2_Config.model_construct(- path=str(checkpoint_path), variant=Krea2VariantType.Turbo, fp8_storage=None+ path=str(checkpoint_path),+ name="krea2_turbo_nvfp4",+ variant=Krea2VariantType.Turbo,+ default_settings=MainModelDefaultSettings(fp8_storage=fp8_storage),)loader = object.__new__(Krea2CheckpointModel)loader._ram_cache = SimpleNamespace(make_room=MagicMock())@@ -119,7 +123,7 @@ def loaded(request, monkeypatch: pytest.MonkeyPatch, tmp_path) -> SimpleNamespac# Supplied because the loader reads it when it decides whether to keep fp8 weights packed:# a fixture built with `object.__new__` has to provide every attribute that path touches.loader._torch_device = torch.device("cpu")- loader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: model+ loader._torch_dtype = COMPUTE_DTYPEmonkeypatch.setattr(diffusers, "Krea2Transformer2DModel", _TinyKrea2, raising=False)monkeypatch.setattr(@@ -132,11 +136,19 @@ def loaded(request, monkeypatch: pytest.MonkeyPatch, tmp_path) -> SimpleNamespaclambda _path, _logger: {"_quantization_metadata": json.dumps({"layers": header_layers})},)monkeypatch.setattr(krea2, "should_keep_fp8_weights", lambda _device: False)+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda *_args: True)monkeypatch.setattr(krea2.TorchDevice, "choose_torch_device", lambda: torch.device("cpu"))monkeypatch.setattr(krea2.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: COMPUTE_DTYPE)model = loader._load_from_singlefile(config)- return SimpleNamespace(model=model, loader=loader, expected=expected, dense=dense, neighbour=request.param)+ return SimpleNamespace(+ model=model, loader=loader, expected=expected, dense=dense, neighbour=neighbour, config=config+ )++[email protected](params=["dense", "int8"])+def loaded(request, monkeypatch: pytest.MonkeyPatch, tmp_path) -> SimpleNamespace:+ return _load(monkeypatch, tmp_path, request.param)def test_header_named_nvfp4_layers_are_packed_under_their_diffusers_paths(loaded) -> None:@@ -187,3 +199,40 @@ def test_one_reservation_counts_the_nvfp4_layers_as_they_are_held(loaded) -> Nonelse:neighbour = 128 * CONVROT_GROUP_SIZE * COMPUTE_DTYPE.itemsizeloaded.loader._ram_cache.make_room.assert_called_once_with(packed + decoded + dense + neighbour)+++def test_fp8_storage_casts_the_dense_layers_of_an_nvfp4_build_and_leaves_its_nvfp4_buffers(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ """Turned on, FP8 Storage stores the layers the build ships in full precision in fp8. The nvfp4 layers are buffers,+ so they stay as stored."""+ plain = _load(monkeypatch, tmp_path, "dense")+ stored = _load(monkeypatch, tmp_path, "dense", fp8_storage=True)++ assert plain.model.img_in.weight.dtype is COMPUTE_DTYPE+ assert stored.model.img_in.weight.dtype is torch.float8_e4m3fn+ packed = 0+ for name, module in stored.model.named_modules():+ if isinstance(module, NVFP4Linear):+ packed += 1+ for key, buffer in module.state_dict().items():+ reference = plain.model.get_submodule(name).state_dict()[key]+ assert buffer.dtype is reference.dtype, (name, key)+ assert torch.equal(buffer.float(), reference.float()), (name, key)+ assert packed == len(PACKED)+ assert any(+ line.startswith("FP8 layerwise casting enabled for krea2_turbo_nvfp4")+ for line in logged_info(stored.loader._logger)+ )+ assert not any("FP8 Storage skipped" in line for line in logged_info(stored.loader._logger))+++def test_fp8_storage_leaves_an_int8_neighbour_build_as_loaded(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:+ """One int8 layer beside the nvfp4 ones makes FP8 Storage decline the build: the decoded time embedding, the dense+ projection and the int8 neighbour keep what the build ships, with no float8 tensor, and every tensor equal to the+ load without FP8 Storage."""+ plain = _load(monkeypatch, tmp_path, "int8")+ stored = _load(monkeypatch, tmp_path, "int8", fp8_storage=True)++ assert stored.model.img_in.weight.dtype is COMPUTE_DTYPE+ assert_fp8_storage_declined(stored.model, plain.model, logged_info(stored.loader._logger), "krea2_turbo_nvfp4")diff --git a/tests/backend/model_manager/load/test_load_default_fp8.py b/tests/backend/model_manager/load/test_load_default_fp8.pyindex e227da322e..e2c55d52ff 100644--- a/tests/backend/model_manager/load/test_load_default_fp8.py+++ b/tests/backend/model_manager/load/test_load_default_fp8.py@@ -36,7 +36,11 @@ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torchapply_custom_layers_to_model,)from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType, SubModelType+from invokeai.backend.quantization.int8_convrot import Int4ConvrotLinear, Int8ConvrotLinear+from invokeai.backend.quantization.nvfp4 import NVFP4Linearfrom invokeai.backend.util.fp8 import FP8_COMPUTE_DTYPE_ATTR+from tests.fixtures.loader_seams import FP8_STORAGE_SKIPPED+from tests.fixtures.quantized_payloads import nvfp4_codes, nvfp4_tensors_MISSING = object()@@ -1306,3 +1310,73 @@ def test_a_krea2_pipelines_encoders_never_take_fp8_storage(submodel):with _device_holds_fp8():assert loader._should_use_fp8(config, SubModelType.Transformer) is Trueassert loader._should_use_fp8(config, submodel) is False+++def _quantized_layer(scheme: str) -> torch.nn.Module:+ if scheme == "int8":+ codes = torch.randint(-127, 128, (128, 64), dtype=torch.int8)+ return Int8ConvrotLinear(codes, torch.rand(128, 1) + 0.5, convrot=False, bias=torch.randn(128))+ if scheme == "int4":+ packed = torch.randint(-128, 128, (128, 32), dtype=torch.int8)+ return Int4ConvrotLinear(packed, torch.rand(128, 1) + 0.5, convrot=False, bias=torch.randn(128))+ tensors = nvfp4_tensors("layer", nvfp4_codes(torch.rand(128, 64) > 0.5), block_scale=1.0, global_scale=0.5)+ return NVFP4Linear(tensors["layer.weight"], tensors["layer.weight_scale"], tensors["layer.weight_scale_2"])++[email protected]("scheme", ["int8", "int4", "nvfp4", None])+def test_fp8_storage_declines_an_int8_or_int4_build_and_casts_the_dense_layers_of_any_other(scheme, caplog) -> None:+ """One int8 or int4 layer declines the whole model, so its dense neighbour keeps the precision the build chose. An+ nvfp4 build is cast like a dense one: the dense layer goes to fp8 and the nvfp4 buffers stay as stored."""+ torch.manual_seed(0)+ model = torch.nn.Module()+ model.dense = torch.nn.Linear(16, 32).to(torch.bfloat16)+ if scheme is not None:+ model.quantized = _quantized_layer(scheme)+ before = {name: tensor.clone() for name, tensor in model.state_dict().items()}+ config = _make_config(ModelType.Main, fp8=True, base=BaseModelType.ZImage, fmt=ModelFormat.Checkpoint)++ with caplog.at_level("INFO", logger="test"), _device_holds_fp8():+ _make_loader()._apply_fp8_layerwise_casting(model, config, SubModelType.Transformer)++ messages = [record.getMessage() for record in caplog.records]+ skipped = [m for m in messages if m.startswith("FP8 Storage skipped for test - ")]+ if scheme in ("int8", "int4"):+ after = model.state_dict()+ assert after.keys() == before.keys()+ for name, tensor in before.items():+ assert after[name].dtype is tensor.dtype, name+ assert torch.equal(after[name], tensor), name+ assert getattr(model, FP8_COMPUTE_DTYPE_ATTR, None) is None+ assert skipped == [FP8_STORAGE_SKIPPED.format(name="test")]+ return+ assert model.dense.weight.dtype is torch.float8_e4m3fn+ assert getattr(model, FP8_COMPUTE_DTYPE_ATTR, None) is torch.bfloat16+ assert not skipped+ assert any(m.startswith("FP8 layerwise casting enabled for test") for m in messages)+ for name, tensor in before.items():+ if name.startswith("quantized."):+ assert model.state_dict()[name].dtype is tensor.dtype, name+ assert torch.equal(model.state_dict()[name].float(), tensor.float()), name+++def test_an_int8_build_that_also_holds_fp8_weights_is_reported_as_already_fp8(caplog) -> None:+ """A build that holds scaled fp8 layers keeps them packed only because FP8 Storage is on. The notice names that,+ not the quantized layers: the latter would read as a reason to turn the setting off, which unpacks every scaled+ layer."""+ model = torch.nn.Module()+ model.dense = torch.nn.Linear(16, 32).to(torch.bfloat16)+ model.quantized = _quantized_layer("int8")+ model.scaled = torch.nn.Linear(16, 32)+ model.scaled.weight = torch.nn.Parameter(torch.zeros(32, 16).to(torch.float8_e4m3fn), requires_grad=False)+ dense_before = model.dense.weight.clone()+ config = _make_config(ModelType.Main, fp8=True, base=BaseModelType.ZImage, fmt=ModelFormat.Checkpoint)++ with caplog.at_level("INFO", logger="test"), _device_holds_fp8():+ _make_loader()._apply_fp8_layerwise_casting(model, config, SubModelType.Transformer)++ messages = [record.getMessage() for record in caplog.records]+ assert sum("weight(s) are already fp8" in message for message in messages) == 1+ assert not any("this quantized build" in message for message in messages)+ assert model.dense.weight.dtype is torch.bfloat16+ assert torch.equal(model.dense.weight, dense_before)+ assert getattr(model, FP8_COMPUTE_DTYPE_ATTR, None) is Nonediff --git a/tests/backend/model_manager/load/test_moss_image_loader.py b/tests/backend/model_manager/load/test_moss_image_loader.pyindex 2dbf1640cb..d86e23e980 100644--- a/tests/backend/model_manager/load/test_moss_image_loader.py+++ b/tests/backend/model_manager/load/test_moss_image_loader.py@@ -22,8 +22,10 @@ from invokeai.backend.model_manager.configs.main import (Main_Checkpoint_MossImage_Config,Main_Diffusers_MossImage_Config,Main_GGUF_MossImage_Config,+ MainModelDefaultSettings,)from invokeai.backend.model_manager.configs.vae import VAE_Checkpoint_Flux2_Config+from invokeai.backend.model_manager.load import load_defaultfrom invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (apply_custom_layers_to_model,)@@ -53,6 +55,7 @@ from tests.backend.model_manager.load.moss_image_fixtures import ()from tests.backend.model_manager.load.state_dicts.moss_image_dit_keys import state_dict_keys as moss_dit_keysfrom tests.backend.model_manager.load.state_dicts.moss_image_vae_keys import state_dict_keys as moss_vae_keys+from tests.fixtures.loader_seams import assert_fp8_storage_declinedfrom tests.fixtures.quantized_payloads import comfy_quant_markerfrom tests.fixtures.safetensors_files import (needs_mapping_that_shows_file_writes,@@ -472,11 +475,17 @@ class TestFusedAndInt8Checkpoints:def _load(self, monkeypatch: pytest.MonkeyPatch, path: Path, *, fp8_storage: bool = False) -> tuple[Any, Any]:loader = _loader(MossImageCheckpointModel, monkeypatch)- if fp8_storage:- loader._should_use_fp8 = lambda _config, _submodel=None: True- config = Main_Checkpoint_MossImage_Config.model_construct(path=str(path), name="moss")+ config = self._config(path, fp8_storage=fp8_storage)return loader._load_model(config, SubModelType.Transformer), loader+ @staticmethod+ def _config(path: Path, *, fp8_storage: bool = False) -> Main_Checkpoint_MossImage_Config:+ return Main_Checkpoint_MossImage_Config.model_construct(+ path=str(path),+ name="moss",+ default_settings=MainModelDefaultSettings(fp8_storage=True) if fp8_storage else None,+ )+@pytest.mark.parametrize("prefix", ["", "model.diffusion_model."])def test_a_fused_bf16_file_loads_as_the_split_model(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, prefix: str@@ -530,21 +539,26 @@ class TestFusedAndInt8Checkpoints:):self._load(monkeypatch, path)- def test_fp8_storage_leaves_the_int8_layers_alone_and_still_runs(- self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+ def test_fp8_storage_leaves_an_int8_build_as_the_build_stores_it(+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:- stored, meant = int8_convrot_state_dict(tiny_reference())+ stored, _ = int8_convrot_state_dict(tiny_reference())path = tmp_path / "moss_image_base_int8_convrot.safetensors"save_file(stored, str(path))-- model, _ = self._load(monkeypatch, path, fp8_storage=True)-- assert all(isinstance(model.layers[0].proj[name], Int8ConvrotLinear) for name in ("k", "v", "o", "ffn_down"))- assert model.layers[0].proj["q"].weight.dtype is torch.float32- # The dense Linears nothing reads the dtype of are the ones that took the cast.- assert model.text_embedder.blocks[0].qkv.weight.dtype is torch.float8_e4m3fn- expected = forward(with_state_dict(meant))- assert (forward(model) - expected).norm() / expected.norm() < 0.1+ # Only the device probe is doubled: the request, the model kind and the format go through the real gate.+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda *_args, **_kwargs: True)++ with caplog.at_level(logging.INFO, logger=__name__):+ plain, _ = self._load(monkeypatch, path)+ model, loader = self._load(monkeypatch, path, fp8_storage=True)++ assert loader._should_use_fp8(self._config(path, fp8_storage=True), SubModelType.Transformer)+ assert [+ n for n, t in [*model.named_parameters(), *model.named_buffers()] if t.dtype is torch.float8_e4m3fn+ ] == []+ # Same keys, dtypes and values as the plain load, and the skip line once, for the load that asked.+ assert_fp8_storage_declined(model, plain, [record.getMessage() for record in caplog.records], "moss")+ assert torch.equal(forward(model), forward(plain))class TestTorchaoFp8Checkpoint:diff --git a/tests/backend/model_manager/load/test_qwen_image_int8_convrot_loader.py b/tests/backend/model_manager/load/test_qwen_image_int8_convrot_loader.pyindex ae7d41a9de..2d05e21b77 100644--- a/tests/backend/model_manager/load/test_qwen_image_int8_convrot_loader.py+++ b/tests/backend/model_manager/load/test_qwen_image_int8_convrot_loader.py@@ -22,7 +22,7 @@ from invokeai.backend.model_manager.load.model_loaders.qwen_image import QwenImafrom invokeai.backend.model_manager.taxonomy import SubModelTypefrom invokeai.backend.quantization.int8_convrot import Int8ConvrotLinearfrom invokeai.backend.quantization.nvfp4 import NVFP4Linear-from tests.fixtures.loader_seams import Seam, SeamRun, prepare+from tests.fixtures.loader_seams import Seam, SeamRun, assert_fp8_storage_declined, logged_info, preparefrom tests.fixtures.quantized_payloads import (INT8_LEVELS,comfy_quant_marker,@@ -226,21 +226,24 @@ def test_the_reservation_is_one_call_made_before_the_split_and_the_cast_widen_anassert widening_steps == [("split_int8_convrot_layers", 1), ("cast_unquantized", 1)]-def test_fp8_storage_leaves_the_int8_layers_int8(monkeypatch, tmp_path) -> None:- """The model-level storage cast walks the dense remainder; the int8 buffers are not layers it casts."""- state_dict, expected = _state_dict()- run, config = _run(monkeypatch, tmp_path, state_dict, fp8_storage=True)+def test_fp8_storage_leaves_an_int8_build_as_loaded(monkeypatch, tmp_path) -> None:+ """The int8 layers stay int8 and the dense remainder (`img_in`, the modulation) stays at the compute dtype: the+ build is the same tensor for tensor as the load without FP8 Storage."""monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda *_args: True)- run.loader._torch_dtype = COMPUTE_DTYPE-- model = run.loader._load_model(config, SubModelType.Transformer)-+ loaded = {}+ for fp8_storage in (False, True):+ state_dict, expected = _state_dict()+ run, config = _run(monkeypatch, tmp_path, state_dict, fp8_storage=fp8_storage)+ run.loader._torch_dtype = COMPUTE_DTYPE+ loaded[fp8_storage] = (run.loader._load_model(config, SubModelType.Transformer), run)++ model, run = loaded[True]for path in expected:layer = model.get_submodule(path)assert isinstance(layer, Int8ConvrotLinear), pathassert layer.weight.dtype is torch.int8, path- assert layer.weight_scale.dtype is torch.float32, path- assert model.img_in.weight.dtype is torch.float8_e4m3fn+ assert model.img_in.weight.dtype is COMPUTE_DTYPE+ assert_fp8_storage_declined(model, loaded[False][0], logged_info(run.loader._logger), config.name)def test_a_marked_layer_the_model_needs_dense_is_widened_with_its_scale_applied(monkeypatch, tmp_path) -> None:diff --git a/tests/backend/model_manager/load/test_wan_checkpoint_loader.py b/tests/backend/model_manager/load/test_wan_checkpoint_loader.pyindex 076821b886..c978fa447d 100644--- a/tests/backend/model_manager/load/test_wan_checkpoint_loader.py+++ b/tests/backend/model_manager/load/test_wan_checkpoint_loader.py@@ -18,6 +18,7 @@ import safetensors.torchimport torchfrom safetensors.torch import save_file+from invokeai.backend.model_manager.configs.main import Main_Checkpoint_Wan_Config, MainModelDefaultSettingsfrom invokeai.backend.model_manager.load import load_defaultfrom invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (apply_custom_layers_to_model,@@ -30,6 +31,7 @@ from invokeai.backend.model_manager.load.model_loaders.wan import (from invokeai.backend.model_manager.taxonomy import SubModelType, WanVariantTypefrom invokeai.backend.quantization.fp8_scaled import is_scale_metadata_key, set_full_precision_hints_respectedfrom invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear+from tests.fixtures.loader_seams import assert_fp8_storage_declined, logged_infofrom tests.fixtures.quantized_payloads import (comfy_quant_marker,mxfp8_tensors,@@ -113,10 +115,12 @@ def _load(variant: WanVariantType = WanVariantType.T2V_A14B,loader: WanCheckpointModel | None = None,dtype: torch.dtype = torch.bfloat16,+ config=None,):- config = MagicMock()- config.path = str(path)- config.variant = variant+ if config is None:+ config = MagicMock()+ config.path = str(path)+ config.variant = variantwith (patch("invokeai.backend.model_manager.load.model_loaders.wan.TorchDevice.choose_torch_device"),@@ -772,28 +776,39 @@ class TestInt8Convrot:expected += tensor.numel() * torch.bfloat16.itemsizeloader._ram_cache.make_room.assert_called_once_with(expected)- def test_fp8_storage_leaves_the_int8_buffers_alone(self, tmp_path: Path) -> None:- """The loader ends in the FP8 Storage pass for every path. It walks parameters and an ``Int8ConvrotLinear``- holds buffers, so the codes and their fp32 scales must come out untouched while the dense remainder is- cast."""+ def test_fp8_storage_leaves_an_int8_build_as_loaded(self, tmp_path: Path) -> None:+ """The loader ends in the FP8 Storage pass for every path. An int8 build is declined whole: the codes and+ their fp32 scales stay, and so does a block Linear the checkpoint left dense -- every tensor equals the load+ without FP8 Storage."""dense_layer = BLOCK_LAYERS[-1]quantized = BLOCK_LAYERS[:-1]_, sd = _int8_checkpoint(quantized)path = _write(tmp_path, sd)- loader = _make_loader()- loader._should_use_fp8 = lambda *_args: True- loader._torch_dtype = torch.bfloat16- loader._logger = MagicMock()- model = _load(path, loader=loader)+ def load(fp8_storage: bool):+ config = Main_Checkpoint_Wan_Config.model_construct(+ path=str(path),+ name="wan_int8",+ variant=WanVariantType.T2V_A14B,+ default_settings=MainModelDefaultSettings(fp8_storage=fp8_storage),+ )+ loader = _make_loader()+ loader._torch_dtype = torch.bfloat16+ loader._torch_device = torch.device("cpu")+ loader._logger = MagicMock()+ with patch.object(load_default, "_device_supports_fp8_storage", return_value=True):+ return _load(path, loader=loader, config=config), loader++ plain, _ = load(False)+ model, loader = load(True)for name in quantized:layer = model.get_submodule(name)assert isinstance(layer, Int8ConvrotLinear), nameassert layer.weight.dtype is torch.int8, nameassert layer.weight_scale.dtype is torch.float32, name- # The pass really ran: a block Linear the checkpoint left dense is now stored as fp8.- assert model.get_submodule(dense_layer).weight.dtype is torch.float8_e4m3fn+ assert model.get_submodule(dense_layer).weight.dtype is torch.bfloat16+ assert_fp8_storage_declined(model, plain, logged_info(loader._logger), "wan_int8")def test_an_int8_weight_without_a_marker_is_refused(self, tmp_path: Path) -> None:"""Cast as raw codes it would be a model of small integers that loads without complaint."""diff --git a/tests/backend/model_manager/load/test_z_image_loader_boundaries.py b/tests/backend/model_manager/load/test_z_image_loader_boundaries.pyindex 99032f1bae..07569454ae 100644--- a/tests/backend/model_manager/load/test_z_image_loader_boundaries.py+++ b/tests/backend/model_manager/load/test_z_image_loader_boundaries.py@@ -6,6 +6,7 @@ loads cleanly and generates noise. These drive `_load_from_singlefile` itself anreaches the module."""+import dataclassesimport jsonimport diffusers@@ -19,7 +20,7 @@ from invokeai.backend.model_manager.load.model_loaders import z_imagefrom invokeai.backend.model_manager.load.model_loaders.z_image import ZImageCheckpointModelfrom invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, Int8ConvrotLinearfrom invokeai.backend.quantization.nvfp4 import NVFP4Linear-from tests.fixtures.loader_seams import Seam, prepare+from tests.fixtures.loader_seams import Seam, assert_fp8_storage_declined, logged_info, preparefrom tests.fixtures.quantized_payloads import (comfy_quant_marker,nvfp4_codes,@@ -53,7 +54,11 @@ SEAM = Seam()-def _driver(monkeypatch, tmp_path, state_dict: dict, model_class=None):+#: The real storage cast: `SEAM` stubs it out, for the tests that are about what reaches the module.+STORAGE_SEAM = dataclasses.replace(SEAM, casts_fp8_storage=False)+++def _driver(monkeypatch, tmp_path, state_dict: dict, model_class=None, seam: Seam = SEAM):checkpoint = tmp_path / "z_image_int8_convrot.safetensors"checkpoint.touch()config = Main_Checkpoint_ZImage_Config.model_construct(path=str(checkpoint), name="z-image")@@ -61,7 +66,7 @@ def _driver(monkeypatch, tmp_path, state_dict: dict, model_class=None):def geometry(patch):patch.setattr(diffusers, "ZImageTransformer2DModel", model_class or _TinyZImage, raising=False)- return prepare(SEAM, monkeypatch, state_dict=state_dict, geometry=geometry), config+ return prepare(seam, monkeypatch, state_dict=state_dict, geometry=geometry), configclass _TinyMixedZImage(torch.nn.Module):@@ -282,13 +287,23 @@ def _nvfp4_layer(return nvfp4_tensors(path, nvfp4_codes(positive), block_scale=grid, global_scale=global_scale)-def test_an_nvfp4_checkpoint_loads_packed_with_its_qkv_split_on_tile_rows(monkeypatch, tmp_path) -> None:- """Comfy's nvfp4 Z-Image build quantizes the fused `attention.qkv` and names its layers only in the- safetensors header. The packed tensors have to leave the state dict before the key conversion and the- scaled-fp8 extraction -- which drops block scales whose weight is not float8 -- follow the QKV split on- whole tile rows, and come back as `NVFP4Linear` modules for the strict load. The timestep embedder is- decoded to the compute dtype instead, since its forward picks its activation dtype off its weight, and a- bundled encoder's layers are dropped with everything else the transformer does not hold."""+def _bf16_nvfp4_header(monkeypatch, header: dict) -> None:+ """The header naming the nvfp4 layers, and bf16 rather than the driver's float32, so a layer decoded or charged at+ any other width shows."""+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.z_image.read_safetensors_metadata",+ lambda _path, _logger: {"_quantization_metadata": json.dumps({"layers": header})},+ )+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.z_image.TorchDevice.choose_bfloat16_safe_dtype",+ lambda _device: torch.bfloat16,+ )+++def _nvfp4_checkpoint() -> tuple[dict[str, torch.Tensor], dict, tuple[torch.Tensor, ...], torch.Tensor, torch.Tensor]:+ """Comfy's native nvfp4 layout with the header naming its layers: the state dict, the header, the sign grids of the+ four quantized layers (qkv, modulation, timestep embedder, a bundled encoder's), the modulation bias, and the+ dense embedder."""torch.manual_seed(4)qkv, modulation, timestep, bundled = (torch.randint(0, 2, (rows, 64), dtype=torch.bool) for rows in (384, 128, 128, 128)@@ -313,16 +328,19 @@ def test_an_nvfp4_checkpoint_loads_packed_with_its_qkv_split_on_tile_rows(monkey"text_encoders.qwen3.layers.0.mlp.up_proj",)}+ return state_dict, header, (qkv, modulation, timestep, bundled), modulation_bias, embedder+++def test_an_nvfp4_checkpoint_loads_packed_with_its_qkv_split_on_tile_rows(monkeypatch, tmp_path) -> None:+ """Comfy's nvfp4 Z-Image build quantizes the fused `attention.qkv` and names its layers only in the+ safetensors header. The packed tensors have to leave the state dict before the key conversion and the+ scaled-fp8 extraction -- which drops block scales whose weight is not float8 -- follow the QKV split on+ whole tile rows, and come back as `NVFP4Linear` modules for the strict load. The timestep embedder is+ decoded to the compute dtype instead, since its forward picks its activation dtype off its weight, and a+ bundled encoder's layers are dropped with everything else the transformer does not hold."""+ state_dict, header, (qkv, modulation, timestep, _bundled), modulation_bias, embedder = _nvfp4_checkpoint()run, config = _driver(monkeypatch, tmp_path, state_dict, model_class=_TinyNativeZImage)- monkeypatch.setattr(- "invokeai.backend.model_manager.load.model_loaders.z_image.read_safetensors_metadata",- lambda _path, _logger: {"_quantization_metadata": json.dumps({"layers": header})},- )- # bf16 rather than the driver's float32, so a layer decoded or charged at any other width shows.- monkeypatch.setattr(- "invokeai.backend.model_manager.load.model_loaders.z_image.TorchDevice.choose_bfloat16_safe_dtype",- lambda _device: torch.bfloat16,- )+ _bf16_nvfp4_header(monkeypatch, header)model = run.load(config)@@ -434,3 +452,89 @@ def test_an_nvfp4_layer_missing_its_global_scale_is_refused_before_the_cache_is_run.load(config)assert run.reserved == []+++class _TinyZImageWithCastableLayer(_TinyZImageWithTimestepEmbedder):+ """Adds a dense layer no skip pattern protects, which is the one a storage cast would reach."""++ def __init__(self, **kwargs) -> None:+ super().__init__(**kwargs)+ self.all_x_embedder = torch.nn.ModuleDict({"2-1": torch.nn.Linear(8, 4)})+++def _storage_config(config: Main_Checkpoint_ZImage_Config, fp8_storage: bool) -> Main_Checkpoint_ZImage_Config:+ return Main_Checkpoint_ZImage_Config.model_construct(+ path=config.path, name="z-image", default_settings=MainModelDefaultSettings(fp8_storage=fp8_storage)+ )+++def _load_with_storage(monkeypatch, tmp_path, build) -> dict:+ """The loads of one build with FP8 Storage off and on: `{fp8_storage: (model, run)}`. `build` returns the state+ dict, the model class and an optional header naming nvfp4 layers."""+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda _device, _logger=None: True)+ loads = {}+ for fp8_storage in (False, True):+ state_dict, model_class, header = build()+ run, config = _driver(monkeypatch, tmp_path, state_dict, model_class=model_class, seam=STORAGE_SEAM)+ if header is not None:+ _bf16_nvfp4_header(monkeypatch, header)+ loads[fp8_storage] = (run.load(_storage_config(config, fp8_storage)), run)+ return loads+++def test_fp8_storage_leaves_an_int8_build_as_loaded(monkeypatch, tmp_path) -> None:+ """The dense layers keep the precision the build chose -- the decoded timestep embedder, and a layer that no skip+ pattern protects, which a cast that only logged would still convert: no float8 tensor, and every tensor equal to+ the load without FP8 Storage."""++ def build():+ torch.manual_seed(3)+ sensitive, ordinary = (quantize_convrot(torch.randn(4, CONVROT_GROUP_SIZE)) for _ in range(2))+ state_dict = {+ "t_embedder.mlp.0.weight": sensitive.codes,+ "t_embedder.mlp.0.weight_scale": sensitive.scale,+ "t_embedder.mlp.0.comfy_quant": comfy_quant_marker(MARKER),+ "layers.0.proj.weight": ordinary.codes,+ "layers.0.proj.weight_scale": ordinary.scale,+ "layers.0.proj.comfy_quant": comfy_quant_marker(MARKER),+ "x_embedder.weight": torch.randn(4, 8),+ "x_embedder.bias": torch.randn(4),+ }+ return state_dict, _TinyZImageWithCastableLayer, None++ loads = _load_with_storage(monkeypatch, tmp_path, build)++ model, run = loads[True]+ assert any(isinstance(module, Int8ConvrotLinear) for module in model.modules())+ assert_fp8_storage_declined(model, loads[False][0], logged_info(run.loader._logger), "z-image")+++def test_fp8_storage_casts_the_dense_layers_of_an_nvfp4_build_and_leaves_its_nvfp4_buffers(+ monkeypatch, tmp_path+) -> None:+ """Turned on, FP8 Storage stores the dense layers in fp8. The nvfp4 layers are buffers, so they stay as stored."""++ def build():+ state_dict, header, *_ = _nvfp4_checkpoint()+ return state_dict, _TinyNativeZImage, header++ loads = _load_with_storage(monkeypatch, tmp_path, build)++ (plain, _), (stored, run) = loads[False], loads[True]+ packed = [name for name, module in stored.named_modules() if isinstance(module, NVFP4Linear)]+ assert packed+ for name in packed:+ for key, buffer in stored.get_submodule(name).state_dict().items():+ reference = plain.get_submodule(name).state_dict()[key]+ assert buffer.dtype is reference.dtype, (name, key)+ assert torch.equal(buffer.float(), reference.float()), (name, key)+ dense = [+ name+ for name, module in stored.named_modules()+ if isinstance(module, torch.nn.Linear) and not isinstance(module, NVFP4Linear)+ ]+ assert dense+ assert any(stored.get_submodule(name).weight.dtype is torch.float8_e4m3fn for name in dense)+ lines = logged_info(run.loader._logger)+ assert any(line.startswith("FP8 layerwise casting enabled for z-image") for line in lines)+ assert not any("FP8 Storage skipped" in line for line in lines)diff --git a/tests/fixtures/loader_seams.py b/tests/fixtures/loader_seams.pyindex e4f918c9f8..5342b70aee 100644--- a/tests/fixtures/loader_seams.py+++ b/tests/fixtures/loader_seams.py@@ -22,6 +22,9 @@ and ``order`` make the ordering constraint visible -- room has to be reserved *bwiden, or the reservation is for a smaller model than the one about to exist -- and that constraintis held at every seam today by the order the calls happen to be written in. An end-state assertioncannot see it. These can.++:func:`assert_fp8_storage_declined` is the shared assertion for a quantized build that FP8 Storage must+leave as loaded."""from collections.abc import Callable, Mapping@@ -173,3 +176,36 @@ def prepare(monkeypatch.setattr(seam.module, name, step)return run+++FP8_STORAGE_SKIPPED = (+ "FP8 Storage skipped for {name} - this quantized build keeps its quantized layers as stored and its other "+ "layers in the precision the build chose."+)+++def logged_info(logger: MagicMock) -> list[str]:+ """The messages a loader's mocked logger received at INFO."""+ return [call.args[0] for call in logger.info.call_args_list]+++def assert_fp8_storage_declined(+ stored: torch.nn.Module,+ plain: torch.nn.Module,+ info: list[str],+ name: str,+) -> None:+ """``stored`` is the load with FP8 Storage on, ``plain`` the same load with it off.++ A quantized build is left exactly as loaded: same keys, same dtypes, same values, and one notice saying so.+ """+ stored_state, plain_state = stored.state_dict(), plain.state_dict()+ assert stored_state.keys() == plain_state.keys()+ for key, tensor in stored_state.items():+ assert tensor.dtype is plain_state[key].dtype, key+ # Widened where the dtype has no equality kernel (float8); the dtype itself is asserted above.+ widen = tensor.dtype.is_floating_point+ assert torch.equal(+ tensor.float() if widen else tensor, plain_state[key].float() if widen else plain_state[key]+ ), key+ assert info.count(FP8_STORAGE_SKIPPED.format(name=name)) == 1