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(wan): keep ComfyUI fp8_scaled checkpoints packed instead of folding them to bf16 (#10262)
Alexander Eichhorn672c724c8292
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.mdxindex 445304e0ca..ddaa50fcf1 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@@ -51,7 +51,7 @@ InvokeAI recognizes the format from the file's contents, so you install them lik- **int4** (`convrot_w4a4` or `int4_tensorwise`, ComfyUI repackages that usually keep some layers int8): the weights stay packed in memory at half a byte each and are unpacked per layer, on every device. This saves memory, not time: InvokeAI unpacks the weights for every step rather than running 4-bit matrix kernels, and 4-bit weights keep less detail than int8. Supported for the Krea-2 transformer.- **nvfp4** (4-bit, in ComfyUI's checkpoint format, such as Comfy-Org's builds; other nvfp4 exports such as AWQ are refused): the weights stay packed in memory and are unpacked per layer, so no special GPU is needed. Supported for the FLUX.3, Z-Image, Krea-2, Qwen-Image and LTX-2 transformers and for the Qwen3, Qwen3-VL 4B/8B, Qwen2.5-VL and FLUX.2 Mistral encoders; for FLUX.3 also Black Forest Labs' own nvfp4 build, in NVIDIA ModelOpt's layout. The Ideogram 4 and Qwen-Image-2.1 nvfp4 transformer files are refused at install.- **fp8** (plain or `fp8_scaled`): InvokeAI keeps the weights in fp8 when [FP8 Storage](/configuration/optimization/fp8-storage/) is on, which installation does for you, or when `fp8_compute` is enabled.-- **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/).+- **MXFP8** (fp8 with one scale per block of 32 weights): loaded by unpacking to BF16. Turn FP8 Storage off for these, except on Wan 2.2; see the [FP8 Storage caution](/configuration/optimization/fp8-storage/).Text encoders for T5, Qwen-Image, Z-Image, Krea-2, FLUX.3, Ideogram 4, Qwen-Image-2.1 and MOSS-Image bring their tokenizer and configuration with InvokeAI, so single-file and GGUF encoders load without network access.diff --git a/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdx b/docs/src/content/docs/Users Guide/03.Models/03.model-format-support.mdxindex 02f8cfe133..408600fee4 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@@ -48,7 +48,7 @@ reader's error; if the file is incomplete or corrupt, download it again.| [Ideogram 4](/users-guide/models/local-models/ideogram4/) | ✓ | ✓ | ✓ | ✓ | R | R | ✓ | ✓ | ✗ | inside the Diffusers folder || [ERNIE-Image](/users-guide/models/local-models/ernie-image/) | ✓ | ✓ | L | L | L | L | ✗ | ✓ | ✗ | ✗ || [MOSS-Image](/users-guide/models/local-models/moss-image/) | ✓ | ✓ | R | ✓ | R | R | R | ✓ | ✗ | ✗ |-| [Wan 2.2](/users-guide/video-generation/wan-22/) | ✓ | ✓ | ✓ | ✓ | R | L | L | ✓ | ✗ | ✗ |+| [Wan 2.2](/users-guide/video-generation/wan-22/) | ✓ | ✓ | ✓ | ✓ | R | L | ✓ | ✓ | ✗ | ✗ || [LTX-2](/users-guide/video-generation/ltx-2/) (2.5 only) | official layout ✓, Diffusers layout ✗ | ✓ | L | ✓ | L | ✓ | ✗ | ✓ | ✗ | ✗ || [MiniMax H3](/users-guide/video-generation/minimax-h3/) | ✓ | ✓ | L | ✓ | L | L | ✗ | ✗ | ✗ | ✗ |diff --git a/docs/src/content/docs/Users Guide/05.Video Generation/wan-2.2.mdx b/docs/src/content/docs/Users Guide/05.Video Generation/wan-2.2.mdxindex 16f607b35c..d12f802e8f 100644--- a/docs/src/content/docs/Users Guide/05.Video Generation/wan-2.2.mdx+++ b/docs/src/content/docs/Users Guide/05.Video Generation/wan-2.2.mdx@@ -61,8 +61,14 @@ The UMT5-XXL encoder also comes as a GGUF file: **Wan T5 Encoder (UMT5-XXL, GGUF**On a 12 GB VRAM card**: use TI2V-5B — it covers both text-to-video and image-to-video and fits comfortably. The bundle includes it; to skip the A14B downloads, install the **Wan 2.2 TI2V-5B (Q4_K_M)** starter model on its own, which brings its VAE and the UMT5-XXL encoder. The A14B variants will technically run via aggressive offloading but are slow and prone to OOM.:::+#### ComfyUI fp8 scaled builds++Single-file A14B and TI2V-5B transformers in ComfyUI's `fp8_scaled` format load like any other single file, with the same two-expert setup for A14B. With [FP8 Storage](/configuration/optimization/fp8-storage/) on, which installing such a file switches on by itself, or with [FP8 Compute](/configuration/optimization/fp8-compute/) on a GPU that supports it, the scaled layers stay fp8 in memory with the scale the file shipped, so an A14B expert takes about half the memory of a bf16 one (a 14.3 GB file instead of about 28 GB). LoRAs, including Lightning, are applied alongside the fp8 weights rather than merged into them. Layers that cannot stay fp8 are widened to the compute dtype at load, with their scale applied, and FP8 Storage leaves them there: the condition embedder, which the model reads outside a matrix multiply, float8_e5m2 layers, and layers with a per-block scale (MXFP8 files). With neither setting on, the file is widened to the compute dtype at load, and an expert takes the same memory as a bf16 file.++On one Windows machine with an RTX 4090 and the default cache settings (T2V A14B `fp8_scaled` pair, 832x480, 17 frames, 8 steps), keeping the layers fp8 peaked at about 16 GB of RAM and 18.5 GB of VRAM at about 72 s per clip, against about 40 GB of RAM, 22.8 GB of VRAM and about 102 s with the file widened to bf16. Other systems will differ.+#### ComfyUI int8 buildsSingle-file A14B and TI2V-5B transformers in ComfyUI's `int8_tensorwise` (convrot) format load like any other single file, with the same two-expert setup for A14B. The attention and feed-forward weights stay int8 in memory, which saves memory. By default they are dequantized per layer on each forward pass; [int8 Compute](/configuration/optimization/int8-compute/) can instead run them on NVIDIA int8 tensor cores. LoRAs, including Lightning, are applied alongside the int8 weights rather than merged into them. Files marked only `{"convrot": true}`, without a `format` entry, and the int4 builds are refused when you install them.-On one Windows machine with an RTX 4090 (T2V A14B, 832x480, 17 frames), an int8 expert file is about 14.5 GB against about 28.6 GB for a bf16 expert. With both experts and the UMT5 encoder kept in the RAM cache, the int8 build peaked at about 41 GB of RAM. With `max_cache_ram_gb: 16` it still runs but reloads the experts for each clip, and peaked at about 30 GB of RAM, because both experts are held in memory during the swap. Windows also counts VRAM toward a process's committed memory, so that figure reads higher than the RAM in use. int8 mainly saves memory; how much speed it changes depends on whether the model otherwise fits in VRAM. Other systems will differ.+On one Windows machine with an RTX 4090 (T2V A14B, 832x480, 17 frames), an int8 expert file is about 14.5 GB against about 28.6 GB for a bf16 expert. With both experts and the UMT5 encoder kept in the RAM cache, the int8 build peaked at about 41 GB of RAM. With `max_cache_ram_gb: 16` it still runs but reloads the experts for each clip, and peaked at about 16 GB of RAM, since the outgoing expert is released before the next one loads. These figures are the process working set; Windows also counts VRAM toward a process's committed memory, so the commit reads higher than the RAM in use. int8 mainly saves memory; how much speed it changes depends on whether the model otherwise fits in VRAM. Other systems will differ.diff --git a/docs/src/content/docs/configuration/Optimization/fp8-storage.mdx b/docs/src/content/docs/configuration/Optimization/fp8-storage.mdxindex 0f98c364f2..29ace3e58b 100644--- a/docs/src/content/docs/configuration/Optimization/fp8-storage.mdx+++ b/docs/src/content/docs/configuration/Optimization/fp8-storage.mdx@@ -21,7 +21,9 @@ To also run the math in FP8 on the GPU's FP8 hardware, see [FP8 Compute](/config:::caution[Turn it off for MXFP8 checkpoints]Installing switches FP8 Storage on for every checkpoint that stores FP8 weights, MXFP8 included. For MXFP8 it costs-quality: see [By file format](#by-file-format). Turn it off under **Default Settings** after installing one.+quality: see [By file format](#by-file-format). Turn it off under **Default Settings** after installing one. Wan 2.2 is+the exception: its loader leaves at the compute dtype every layer it unpacks with its scale, so on an MXFP8 Wan file+the setting only stores the layers that shipped without a scale as fp8, as it does for any other checkpoint.:::## What it applies to@@ -36,7 +38,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. |+| 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. || GGUF, NF4 and [SDNQ](/configuration/optimization/sdnq-quantization/) | **No**: already quantized. The setting is not shown. |@@ -52,7 +54,7 @@ If your model is quantized, its full-precision variant gets the full effect of F| 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 |-| Wan (checkpoint and Diffusers) | Yes, except ComfyUI `fp8_scaled` files, which load at BF16 |+| Wan (checkpoint and Diffusers) | Yes || ControlNet (SD1, SD2, SDXL), T2I-Adapter | Yes || VAE | No: visible decode-quality regression || Text encoders, tokenizers | No: small models, and FP8 rounding costs text quality. The FLUX.2 Mistral encoder keeps its scaled fp8 weights packed on any GPU that passes the FP8 test, with no setting. |@@ -146,8 +148,7 @@ 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 MXFP8 checkpoint | **On automatically, but turn it off**: it costs quality (see [By file format](#by-file-format)). |-| A Wan checkpoint in ComfyUI's `fp8_scaled` format | Shows as on, but the Wan loader cannot keep these packed yet: it declines, logs `FP8 Storage not applied to …`, and loads the model at BF16. |+| 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. |Either way the setting stays editable under **Default Settings**, and re-identifying a model keeps it.@@ -171,7 +172,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 keeps its 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.</details>@@ -194,7 +195,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)), a Wan `fp8_scaled` checkpoint (the log says why), 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)), or already FP8 (`FP8 storage skipped … already fp8`: nothing needed re-encoding). || `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/app/invocations/wan/wan_denoise.py b/invokeai/app/invocations/wan/wan_denoise.pyindex 4a46247ad5..6468a8dae3 100644--- a/invokeai/app/invocations/wan/wan_denoise.py+++ b/invokeai/app/invocations/wan/wan_denoise.py@@ -53,6 +53,7 @@ from invokeai.backend.rectified_flow.rectified_flow_inpaint_extension import Recfrom invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateStatefrom invokeai.backend.stable_diffusion.diffusion.conditioning_data import WanConditioningInfofrom invokeai.backend.util.devices import TorchDevice+from invokeai.backend.util.fp8 import peak_fp8_cast_transient_bytesfrom invokeai.backend.util.sage_attention import sage_attention_scopefrom invokeai.backend.wan.memory_optimization import wan_memory_optimizationfrom invokeai.backend.wan.sampling_utils import get_spatial_scale_factor, make_noise@@ -256,10 +257,12 @@ class _ExpertSwapper:info = self._context.models.load(model_id)supports_partial_loading = getattr(info, "supports_partial_loading", None)if self._working_mem_bytes is None or supports_partial_loading is False:- # No estimate to add it to, so a quantized expert's per-forward dequantization transient is passed- # alone; the cache floors it at `device_working_mem_gb`, so zero asks for the default.+ # No estimate to add it to, so a quantized expert's per-forward dequantization transient (module-level+ # schemes and GGUF, then the float8 widening of FP8 Storage and kept scaled fp8) is passed alone;+ # the cache floors it at `device_working_mem_gb`, so zero asks for the default.device_ctx = info.model_on_device(working_mem_bytes=peak_dequant_transient_bytes(info.model, self._inference_dtype)+ + peak_fp8_cast_transient_bytes(info.model, self._inference_dtype))else:device_ctx = info.model_on_device(working_mem_bytes=self._working_mem_bytes)diff --git a/invokeai/backend/model_manager/load/model_loaders/comfyui_state_dict_utils.py b/invokeai/backend/model_manager/load/model_loaders/comfyui_state_dict_utils.pyindex 4f16025d3c..cc0a11b99b 100644--- a/invokeai/backend/model_manager/load/model_loaders/comfyui_state_dict_utils.py+++ b/invokeai/backend/model_manager/load/model_loaders/comfyui_state_dict_utils.py@@ -6,8 +6,8 @@ an optional ``model.diffusion_model.`` key prefix, and optional fp8 weightspaired with per-tensor scale factors. These helpers undo both so a state dictcan be handed to a plain diffusers module.-Originally written for the Qwen Image loader; shared so the Wan loader doesn't-need a second copy.+Now used by the Qwen2.5-VL encoder loader only; the transformer loaders read the same+conventions through ``quantization/fp8_scaled.py``."""from typing import Any, Mapping@@ -88,8 +88,8 @@ def _strip_quantization_metadata(sd: dict) -> None:Through the shared predicate rather than a second list of suffixes. The list that used to standhere was a clause-for-clause copy of it that had fallen one spelling behind: it dropped- ``.scale_input`` but not ``.input_scale``, which is the spelling Comfy actually writes, so on- the Wan path an ordinary scaled-fp8 checkpoint was rejected outright by+ ``.scale_input`` but not ``.input_scale``, which is the spelling Comfy actually writes, so an+ ordinary scaled-fp8 checkpoint was rejected outright by`_raise_for_incompatible_keys` as an unsupported variant. A copy that has to be kept in step byhand will fall behind again the next time a spelling is added."""diff --git a/invokeai/backend/model_manager/load/model_loaders/wan.py b/invokeai/backend/model_manager/load/model_loaders/wan.pyindex 668e7cdb6b..71fb2d44e7 100644--- a/invokeai/backend/model_manager/load/model_loaders/wan.py+++ b/invokeai/backend/model_manager/load/model_loaders/wan.py@@ -14,7 +14,7 @@ Currently covers:from itertools import chainfrom pathlib import Path-from typing import Any, Callable, Optional+from typing import Any, Callable, Iterable, Mapping, Optionalimport torch@@ -30,11 +30,6 @@ from invokeai.backend.model_manager.configs.main import (from invokeai.backend.model_manager.configs.wan_t5_encoder import WanT5Encoder_GGUF_Configfrom invokeai.backend.model_manager.load.load_default import ModelLoader, _model_declared_skip_patternsfrom invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistry-from invokeai.backend.model_manager.load.model_loaders.comfyui_state_dict_utils import (- _strip_quantization_metadata,- fold_comfyui_fp8_scale,- reject_layers_the_fold_cannot_decode,-)from invokeai.backend.model_manager.load.model_loaders.generic_diffusers import GenericDiffusersLoaderfrom invokeai.backend.model_manager.model_on_disk import safetensors_meta_state_dictfrom invokeai.backend.model_manager.taxonomy import (@@ -52,12 +47,25 @@ from invokeai.backend.model_manager.util.llamacpp_t5 import ()from invokeai.backend.quantization.fp8_scaled import (COMFY_QUANT_SUFFIX,+ FP8_WEIGHT_DTYPES,+ INPUT_SCALE_SUFFIXES,+ Fp8ScaledLayer,+ attach_fp8_scales,+ cast_state_dict,+ dequantize_fp8_scaled,+ extract_comfy_quant_hints,+ extract_fp8_scaled_layers,+ fold_transient_bytes,is_scale_metadata_key,iter_weight_scale_pairs,parse_quantization_metadata,- predict_cast_state_dict_size,read_safetensors_metadata,+ reject_undecoded_mx_scale,+ split_fp8_scaled_layers,strip_layer_path_prefix,+ survives_split_and_cast,+ unparsed_fp8_scale_keys,+ warn_on_unattached_scales,)from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensorfrom invokeai.backend.quantization.gguf.loaders import gguf_sd_loader, unpack_ggml_at_load@@ -68,6 +76,8 @@ from invokeai.backend.quantization.int8_convrot import (reject_unmarked_int8_weights,resolve_quantized_module_paths,)+from invokeai.backend.quantization.load_plan import reserve_for_load+from invokeai.backend.quantization.nvfp4 import reject_nvfp4_layers_a_plain_fold_cannot_decodefrom invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.state_dict_loading import load_state_dict_ignoring_extras, reject_incomplete_load@@ -433,35 +443,95 @@ class WanGGUFCheckpointModel(ModelLoader):return model-def _predict_folded_cast_size(sd: dict, dtype: torch.dtype) -> int:- """Bytes the state dict occupies once the scale fold and the cast to ``dtype`` have run.+def _planned_fp8_layers(+ layer_keys: Mapping[str, list[str]], side_channel: Mapping[str, torch.Tensor]+) -> dict[str, Fp8ScaledLayer]:+ """The scaled layers as the header describes them, for a reservation made before any scale is read.++ Each scale is a float32 ``meta`` tensor in its stored layout, which is all `reserve_for_load` reads of a layer: the+ layout decides whether the split keeps it fp8 (`is_matmul_usable_scale` answers the same for the stored and the+ normalized shape), and float32 is the width `extract_fp8_scaled_layers` gives every scale, a decoded MXFP8 grid+ included. A one-element input scale is counted even where the extraction drops it as an uncalibrated placeholder:+ four bytes over rather than under.+ """+ planned: dict[str, Fp8ScaledLayer] = {}+ for path, (scale_key, *input_keys) in layer_keys.items():+ inputs = [side_channel[key] for key in input_keys if side_channel[key].numel() == 1]+ planned[path] = Fp8ScaledLayer(+ weight_scale=side_channel[scale_key].to(torch.float32),+ input_scale=inputs[0].to(torch.float32).reshape(()) if inputs else None,+ )+ return planned+++def _fold_in_flight_bytes(sd: Mapping[str, torch.Tensor], folded_scales: Mapping[str, torch.Tensor]) -> int:+ """The most a fold holds at once beyond the state dict a reservation sizes, from the header's ``meta`` tensors.- The fold consumes and strips the scale tensors, and it widens every weight that has a sibling- scale to ``dtype`` whatever its stored dtype, so those are charged at ``dtype`` too.+ The layers fold one at a time, each as it is read, so this is the largest single layer's: its scale at the float32+ width the fold multiplies by (a decoded MXFP8 grid included), and the fold's own transient. The stored weight in+ flight is not counted, as for any tensor the read casts. Neither is the MXFP8 decode, which holds a few copies of+ the grid before the fold and stays below the fold's transient for any layer under about 400M weights."""- kept = {k: v for k, v in sd.items() if not is_scale_metadata_key(k)}- folded = {weight_key for weight_key, _ in iter_weight_scale_pairs(sd)}- total = predict_cast_state_dict_size({k: v for k, v in kept.items() if k not in folded}, dtype, keep_fp8=False)- return total + sum(kept[k].nelement() * dtype.itemsize for k in folded)+ return max(+ (+ scale.numel() * torch.float32.itemsize + fold_transient_bytes(sd[f"{path}.weight"], scale)+ for path, scale in folded_scales.items()+ ),+ default=0,+ )-def _read_folded_and_cast(sd: dict[str, torch.Tensor], read: Callable[[str], torch.Tensor], dtype: torch.dtype) -> int:+def _read_converted(+ sd: dict[str, torch.Tensor],+ read: Callable[[str], torch.Tensor],+ layer_keys: Mapping[str, list[str]],+ hints: Mapping[str, Mapping[str, Any]],+ dtype: torch.dtype,+ *,+ keep_fp8: bool,+ model: torch.nn.Module,+ skip_patterns: Iterable[str],+) -> dict[str, Fp8ScaledLayer]:"""Fill ``sd``'s header entries from ``read`` one tensor at a time, each converted as it arrives.- A ComfyUI weight scale is folded into its weight and dropped with the rest of the quantization metadata;- every other float tensor is cast to ``dtype``. Converted on arrival, the peak is the finished state dict plus- the tensor in flight rather than the whole source. Returns the number of folds.+ A scaled weight arrives with the side-channel keys ``layer_keys`` names for its module. An fp8 one goes through the+ shared extraction: where ``keep_fp8`` holds and the split lets it, it stays as stored with its float32 scale;+ otherwise it is folded with its scale applied. One that is not fp8 is always folded. Every other float tensor is+ cast to ``dtype``, except a plain fp8 weight the cast keeps under ``keep_fp8``. Each runs as a one-entry state+ dict, so the shared split and cast decide a tensor exactly as they would over the whole dict, and the peak is the+ finished state dict plus the layer in flight rather than the whole source. Returns the layers kept fp8, keyed by+ module path."""- scales = dict(iter_weight_scale_pairs(sd))- _strip_quantization_metadata(sd)+ kept: dict[str, Fp8ScaledLayer] = {}for key in sd:- tensor = read(key)- if key in scales:- tensor = fold_comfyui_fp8_scale(tensor, read(scales[key]), key, dtype)- elif tensor.is_floating_point():- tensor = tensor.to(dtype)- sd[key] = tensor- return len(scales)+ path = key[: -len(".weight")] if key.endswith(".weight") else None+ one = {key: read(key)}+ layers: dict[str, Fp8ScaledLayer] = {}+ if path in layer_keys:+ one.update({side_key: read(side_key) for side_key in layer_keys[path]})+ if one[key].dtype not in FP8_WEIGHT_DTYPES:+ # Scaled all the same: ComfyUI's legacy `scaled_fp8` ops apply `scale_weight` whatever the weight's+ # dtype, so "scaled" checkpoints are not all fp8. The extraction would drop such a scale, so it is+ # folded here, through the same fold, and never kept.+ scale = one.pop(layer_keys[path][0])+ reject_undecoded_mx_scale(path, scale)+ layers = {path: Fp8ScaledLayer(weight_scale=scale.float())}+ # Only the float32 scale is in flight during the fold, as the reservation counts it.+ del scale+ dequantize_fp8_scaled(one, layers, dtype)+ layers = {}+ else:+ layers = extract_fp8_scaled_layers(one, layer_hints={path: hints[path]} if path in hints else {})+ if keep_fp8:+ layers = split_fp8_scaled_layers(one, layers, dtype, model=model, skip_patterns=skip_patterns)+ else:+ dequantize_fp8_scaled(one, layers, dtype)+ layers = {}+ cast_state_dict(one, dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)+ kept.update(layers)+ # No local keeps the stored tensor: it would stay alive through the next read.+ sd[key] = one.pop(key)+ return kept@ModelLoaderRegistry.register(base=BaseModelType.Wan, type=ModelType.Main, format=ModelFormat.Checkpoint)@@ -469,13 +539,12 @@ class WanCheckpointModel(ModelLoader):"""Loader for single-file Wan 2.2 transformer checkpoints (safetensors).This is what CivitAI fine-tunes and ComfyUI-oriented Hugging Face repos ship.- Handles the full matrix of community conventions: the optional- ``model.diffusion_model.`` key prefix, the native upstream key layout as well- as the diffusers one, ComfyUI ``fp8_scaled`` weights (dequantized to the- compute dtype at load time), and plain ``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 dequantize them per forward; layers the model- reads outside a matmul (``condition_embedder``) are widened at load instead.+ Handles the full matrix of community conventions: the optional ``model.diffusion_model.`` key prefix, the native+ upstream key layout as well as the diffusers one, ComfyUI ``fp8_scaled`` weights (kept packed with their own scale+ when FP8 Storage or the fp8 matmul uses them, folded into the compute dtype otherwise), and plain+ ``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 dequantize+ them per forward; layers the model reads outside a matmul (``condition_embedder``) are widened at load instead.Like the GGUF loader, one file is one expert; A14B pairing happens at theWanModelLoaderInvocation layer.@@ -539,17 +608,22 @@ class WanCheckpointModel(ModelLoader):int8_markers = extract_int8_convrot_markers(sd, header_layers=header_layers)reject_unmarked_int8_weights(sd, int8_markers, f"Wan 2.2 ({model_path.name})", header_layers=header_layers)- dequantized = 0+ hints: dict[str, dict[str, Any]] = {}if int8_markers:# Still the header's tensors: `install_int8_convrot_layers` reads them once it has reserved.sd = drop_unconsumed_quantization_sidecars(sd)else:- reject_layers_the_fold_cannot_decode(sd, f"Wan checkpoint {model_path.name}")- # Before the first read: the reservation is the state dict after the fold and the cast.- self._ram_cache.make_room(_predict_folded_cast_size(sd, model_dtype))- dequantized = _read_folded_and_cast(sd, read, model_dtype)- if dequantized > 0:- logger.info(f"Dequantized {dequantized} ComfyUI-quantized weights")+ reject_nvfp4_layers_a_plain_fold_cannot_decode(sd, f"Wan checkpoint {model_path.name}")+ # Asked before the rename, in the namespace the scales were written in (see `unparsed_fp8_scale_keys`).+ unparsed = unparsed_fp8_scale_keys(sd)+ if unparsed:+ raise NotImplementedError(+ f"Wan checkpoint {model_path.name}: {len(unparsed)} fp8 weight scale(s) use a spelling "+ f"InvokeAI does not read (e.g. '{unparsed[0]}'), so their weights would load unscaled. Use "+ "the scaled-fp8 or bf16 build of this checkpoint."+ )+ # ComfyUI 'scaled fp8' hints, from the marker tensors and the header, named as the file names them.+ hints = {**extract_comfy_quant_hints(sd), **header_layers}# Community releases ship the native upstream Wan key layout# (text_embedding.0, self_attn/cross_attn, ffn.0/2, head.head, ...);@@ -560,11 +634,15 @@ class WanCheckpointModel(ModelLoader):key_map = {key: _rename_wan_native_key(key) for key in sd if isinstance(key, str)}sd = _convert_wan_native_to_diffusers(sd)file_keys = _convert_wan_native_to_diffusers(file_keys)+ # The hints follow their weight's rename, as the int8 markers do. The rename replaces substrings of whole+ # keys, so a layer's scales are renamed with its weight.+ hints = resolve_quantized_module_paths(hints, key_map)model_config = _build_wan_transformer_config(sd, source="checkpoint state dict")with accelerate.init_empty_weights():model = WanTransformer3DModel(**model_config)+ skip_patterns = _model_declared_skip_patterns(model)if int8_markers:# Casts only the dense tensors: the blanket cast below would also cast the fp32 scales. The skip@@ -577,7 +655,7 @@ class WanCheckpointModel(ModelLoader):model_dtype,architecture="Wan 2.2",reserve=self._ram_cache.make_room,- skip_patterns=_model_declared_skip_patterns(model),+ skip_patterns=skip_patterns,read=read,)# Metadata the fp8 branch strips: a stray `scaled_fp8` flag, or a weight scale beside a dense weight.@@ -589,37 +667,112 @@ class WanCheckpointModel(ModelLoader):f"Wan 2.2: kept {len(quantized)} of {len(int8_markers)} layer(s) in int8 ""(int8_tensorwise checkpoint, dequantized per forward)")+ fp8_layers: dict[str, Fp8ScaledLayer] = {}+ scaled_paths: set[str] = set()+ use_fp8_storage = False+ else:+ # Every module whose weight has a scale beside it, fp8 or not, including the ones the split will fold.+ # Under FP8 Storage none of them may take the layerwise cast: a folded weight has no scale to re-encode+ # it with, and a weight stored scaled is one whose producer needed the scale for its range.+ weight_scales = {+ weight_key[: -len(".weight")]: scale_key for weight_key, scale_key in iter_weight_scale_pairs(sd)+ }+ scaled_paths = set(weight_scales)+ fp8_scaled = {path for path in weight_scales if sd[f"{path}.weight"].dtype in FP8_WEIGHT_DTYPES}+ # Kept fp8 only when something uses it: the fp8 matmul, or fp8 storage the user asked of this model,+ # where the checkpoint's own scale is exact and the layerwise cast of a folded weight has none.+ use_fp8_storage = bool(scaled_paths) and self._should_use_fp8(config, SubModelType.Transformer)+ keep_fp8 = bool(fp8_scaled) and self._keep_fp8_weights(config, SubModelType.Transformer)+ # The side channel leaves `sd`, so the reservation and the read cover the layers' own tensors. A scale+ # is read with its weight, an input scale only where an fp8 layer may stay fp8: a folded one has no use+ # for it. The rest, such as the `scaled_fp8` flag, is never read.+ side_channel = {key: sd.pop(key) for key in [k for k in sd if is_scale_metadata_key(k)]}+ layer_keys = {+ path: [scale_key]+ + [+ f"{path}{suffix}"+ for suffix in INPUT_SCALE_SUFFIXES+ if keep_fp8 and path in fp8_scaled and f"{path}{suffix}" in side_channel+ ]+ for path, scale_key in weight_scales.items()+ }+ # Which layers stay fp8, decided as the split will decide it.+ planned = _planned_fp8_layers({p: layer_keys[p] for p in fp8_scaled}, side_channel) if keep_fp8 else {}+ kept = {+ path: layer+ for path, layer in planned.items()+ if survives_split_and_cast(f"{path}.weight", sd[f"{path}.weight"], model, skip_patterns, layer)+ }+ folded = [path for path in weight_scales if path not in kept]+ # One reservation, before the first read: kept layers at their stored width with their float32 scales,+ # which stay resident, everything else at the compute dtype, and the largest fold in flight. Folded+ # weights are planned at the compute dtype they end at, so only the kept layers' scales are charged in+ # full: a folded layer's scale lives only through its own fold.+ in_flight = _fold_in_flight_bytes(sd, {path: side_channel[weight_scales[path]] for path in folded})+ planned_sd = {+ **sd,+ **{+ f"{path}.weight": torch.empty(sd[f"{path}.weight"].shape, dtype=model_dtype, device="meta")+ for path in folded+ },+ }+ reserve_for_load(+ lambda planned_bytes: self._ram_cache.make_room(planned_bytes + in_flight),+ planned_sd,+ model_dtype,+ keep_fp8=keep_fp8,+ model=model,+ fp8_layers=kept,+ nvfp4_payloads={},+ skip_patterns=skip_patterns,+ )+ del planned_sd+ fp8_layers = _read_converted(+ sd,+ read,+ layer_keys,+ hints,+ model_dtype,+ keep_fp8=keep_fp8,+ model=model,+ skip_patterns=skip_patterns,+ )+ if weight_scales and not keep_fp8:+ logger.info(f"Wan 2.2: folded {len(weight_scales)} scaled layer(s) into {model_dtype}.")incompatible_keys = model.load_state_dict(sd, strict=False, assign=True)_raise_for_incompatible_keys(incompatible_keys, source="Wan checkpoint")- # A checkpoint that shipped per-tensor scales must not take the cast. The fold above consumed- # those scales and `_strip_quantization_metadata` dropped them, so re-encoding the result as- # *unscaled* fp8 would flush the low end of every tensor to zero -- 3.4% of the weights on- # `flux-2-klein-4b-fp8`, for the byte count the file already had. `configs/factory.py` enables- # FP8 Storage by itself for a float8 denoiser, on the stated grounds that the loaders keep such- # a file in its own scaled form; this loader does not do that yet (the scaled-fp8 treatment the- # FLUX and Krea-2 paths received never reached here), so it declines rather than quietly- # trading quality the user did not offer. A plain fp8 checkpoint with no scales is unaffected:- # its round trip through the compute dtype and back is exact.- if dequantized > 0:- if self._should_use_fp8(config, SubModelType.Transformer):- logger.info(- f"FP8 Storage not applied to {model_path.name}: its {dequantized} scaled weight(s) were folded "- "with the per-tensor scales the file shipped, and re-encoding them as unscaled fp8 would lose "- "the low end of every tensor. Keeping them packed instead is the fix, and this loader does not "- "implement it yet."- )- return model-# `assign=True` aliases every param to its `sd` tensor; drop the dict's references before the# FP8 cast or each original stays reachable while its fp8 copy is allocated (see `ltx2.py`,# which learned this the same way).sd.clear()- # FP8 Storage, which this path ignored until now although the control was offered for it and- # identification switched it on by itself for any float8 denoiser -- a 14B transformer loaded- # at bf16 size while the record said it was halved.+ attached = 0+ if fp8_layers:+ attached = attach_fp8_scales(model, fp8_layers)+ warn_on_unattached_scales(logger, "Wan 2.2", attached, fp8_layers)+ if use_fp8_storage:+ # The dense remainder goes to fp8 storage. Scaled layers are left alone, kept or folded: the cast hooks+ # would upcast a kept one without its scale, and re-encode a folded one (float8_e5m2, block-wise scales,+ # the embedders) as unscaled fp8. Entered whenever the file was scaled, so that a file whose layers were+ # all folded does not fall through to the generic cast either.+ self._apply_fp8_to_nn_module(+ model,+ storage_dtype=torch.float8_e4m3fn,+ compute_dtype=model_dtype,+ extra_skip_patterns=skip_patterns,+ skip=lambda name, module: name in scaled_paths or getattr(module, "weight_scale", None) is not None,+ )+ logger.info(+ f"FP8 layerwise casting enabled for {config.name} (storage=float8_e4m3fn, compute={model_dtype}); "+ f"kept {attached} of {len(scaled_paths)} scaled layer(s) fp8 with their own scale."+ )+ return model+ if attached:+ logger.info(f"Wan 2.2: kept {attached} scaled fp8 layer(s) fp8 for fp8 compute.")+ return model+return self._apply_fp8_layerwise_casting(model, config, SubModelType.Transformer)diff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.pyindex 672fdda1f6..fb248ffbf3 100644--- a/invokeai/backend/quantization/fp8_scaled.py+++ b/invokeai/backend/quantization/fp8_scaled.py@@ -809,6 +809,29 @@ def _fold_scale(weight: torch.Tensor, scale: torch.Tensor, dtype: torch.dtype, preturn out+def fold_transient_bytes(weight: Any, scale: Any) -> int:+ """The most :func:`dequantize_fp8_scaled` holds beside its result while folding ``scale`` into ``weight``.++ That is the float32 copy of the weight and the product, each over the whole weight or one slab of rows+ (`_fold_scale`), plus, for a block-wise scale, its widened copy over the same rows and, in slabs, the row index+ that picks each slab's scale rows. Exact in slabs; folded whole it is over by the result, which does not exist yet+ while the multiply holds its copies. Reads shapes only, so a loader can reserve for it from a header's ``meta``+ tensors before anything is read. ``scale`` is in the layout the fold receives, so a stored MXFP8 grid stands for+ its decoded one. The result, the stored weight and the scale itself are the caller's to count.+ """+ numel = weight.numel()+ rows = weight.shape[0] if weight.dim() else 1+ block_wise = scale.numel() > 1 and scale.dim() > 1+ index_bytes = 0+ if numel > _FOLD_SLAB_ELEMENTS:+ columns = numel // rows+ slab_rows = min(rows, max(1, _FOLD_SLAB_ELEMENTS // columns))+ numel = slab_rows * columns+ if block_wise:+ index_bytes = slab_rows * torch.int64.itemsize+ return numel * torch.float32.itemsize * (3 if block_wise else 2) + index_bytes++def attach_fp8_scales(model: torch.nn.Module,layers: Mapping[str, Fp8ScaledLayer],diff --git a/invokeai/backend/quantization/int8_convrot.py b/invokeai/backend/quantization/int8_convrot.pyindex 43666a0d2c..b8c8669a2a 100644--- a/invokeai/backend/quantization/int8_convrot.py+++ b/invokeai/backend/quantization/int8_convrot.py@@ -53,7 +53,7 @@ import structfrom collections.abc import Callable, Iterable, Mappingfrom dataclasses import dataclassfrom pathlib import Path-from typing import Any+from typing import Any, TypeVarimport torch@@ -77,6 +77,8 @@ from invokeai.backend.util.logging import InvokeAILoggerlogger = InvokeAILogger.get_logger(__name__)+_T = TypeVar("_T")+CONVROT_GROUP_SIZE = 256_HADAMARD_SEED = ((1, 1, 1, -1), (1, 1, -1, 1), (1, -1, 1, 1), (-1, 1, 1, 1))@@ -833,17 +835,15 @@ def drop_unconsumed_quantization_sidecars(sd: dict[str, Any]) -> dict[str, Any]:return {k: v for k, v in sd.items() if not (isinstance(k, str) and k.endswith(_UNCONSUMED_SIDECAR_SUFFIXES))}-def resolve_quantized_module_paths(- markers: dict[str, dict[str, Any]], key_map: dict[str, str]-) -> dict[str, dict[str, Any]]:- """Re-key markers from the checkpoint's names to the built model's names.+def resolve_quantized_module_paths(markers: dict[str, _T], key_map: dict[str, str]) -> dict[str, _T]:+ """Re-key per-layer entries (int8 markers, scaled-fp8 layers) from the checkpoint's names to the built model's names.The markers are read in the checkpoint's key space, because that is the only place where amarker and its weight are reliably paired: the key conversions rename `.weight` (and, bysubstring, `.weight_scale`) but leave `.comfy_quant` behind on the old name. Following theweight's own rename is therefore the only mapping that cannot drift from the conversion."""- resolved: dict[str, dict[str, Any]] = {}+ resolved: dict[str, _T] = {}for path, marker in markers.items():weight_key = key_map.get(f"{path}.weight", f"{path}.weight")resolved[weight_key[: -len(".weight")]] = markerdiff --git a/tests/app/invocations/test_wan_expert_swapper.py b/tests/app/invocations/test_wan_expert_swapper.pyindex 2ac9099dbd..eae75946ea 100644--- a/tests/app/invocations/test_wan_expert_swapper.py+++ b/tests/app/invocations/test_wan_expert_swapper.py@@ -735,3 +735,37 @@ def test_outgoing_expert_is_collectable_when_the_next_expert_loads():swapper.close()assert outgoing_collected == [True]+++def test_float8_weights_are_counted_in_the_working_memory_asked_for_the_expert():+ """A kept scaled-fp8 layer is widened per forward with its scale applied: the widened weight and its product with the+ scale are alive at once. The expert's working memory has to cover that largest layer, or the cache plans for a+ dense one."""+ log: list[str] = []+ expert = nn.Sequential(nn.Linear(8, 16, bias=False), nn.Linear(16, 4, bias=False))+ expert[0].weight = nn.Parameter(expert[0].weight.detach().to(torch.float8_e4m3fn), requires_grad=False)+ expert[0].register_buffer("weight_scale", torch.tensor(2.0), persistent=False)+ expert[1].weight = nn.Parameter(expert[1].weight.detach().to(torch.float8_e4m3fn), requires_grad=False)+ asked: list[int | None] = []++ class _RecordingInfo(_FakeInfo):+ def model_on_device(self, working_mem_bytes=None):+ asked.append(working_mem_bytes)+ return super().model_on_device(working_mem_bytes)++ ctx = _FakeContext({"high": _RecordingInfo("HIGH", expert, log)}, log)+ stub, _calls = _stub_lora_context_manager(log)+ with patch("invokeai.app.invocations.wan.wan_denoise.LayerPatcher.apply_smart_model_patches", side_effect=stub):+ swapper = _ExpertSwapper(+ context=ctx,+ high_model="high",+ low_model=None,+ inference_dtype=torch.bfloat16,+ high_lora_factory=_make_factory(log, "HIGH"),+ low_lora_factory=None,+ )+ swapper.get(_ExpertSwapper.HIGH)+ swapper.close()++ # The scaled layer: two bf16 copies of 8 * 16 weights. The unscaled one (16 * 4) is smaller either way.+ assert asked == [2 * 8 * 16 * torch.bfloat16.itemsize]diff --git a/tests/backend/model_manager/load/test_int8_through_the_fp8_fold.py b/tests/backend/model_manager/load/test_int8_through_the_fp8_fold.pyindex 3b50a8910a..a5cda20701 100644--- a/tests/backend/model_manager/load/test_int8_through_the_fp8_fold.py+++ b/tests/backend/model_manager/load/test_int8_through_the_fp8_fold.py@@ -91,8 +91,8 @@ def test_an_int8_weight_with_no_marker_is_refused() -> None:def test_a_scaled_fp8_layer_is_untouched_by_the_check() -> None:"""The population this fold exists for. The guard keys on the int8 dtype, so an fp8 layer never- reaches it -- asserted, because a guard that fired here would break every Wan and Qwen-Image- scaled-fp8 checkpoint."""+ reaches it -- asserted, because a guard that fired here would break every Qwen2.5-VL+ encoder scaled-fp8 checkpoint."""payload = quantize_scaled_fp8(torch.randn(8, 16))state_dict = {"lin.weight": payload.codes, "lin.weight_scale": payload.scale}diff --git a/tests/backend/model_manager/load/test_scaled_fp8_fold_axis.py b/tests/backend/model_manager/load/test_scaled_fp8_fold_axis.pyindex e82b77d463..44b75a88e8 100644--- a/tests/backend/model_manager/load/test_scaled_fp8_fold_axis.py+++ b/tests/backend/model_manager/load/test_scaled_fp8_fold_axis.py@@ -135,8 +135,8 @@ class TestZImageQwen3EncoderFold:class TestSharedComfyFold:- """`_dequantize_comfyui_fp8`, the copy the Wan (`wan.py:511`) and Qwen-Image- (`qwen_image.py:520`) loaders reach. Its local loop compared `scale.shape[dim] !=+ """`_dequantize_comfyui_fp8`, the copy the Qwen2.5-VL encoder loader+ (`qwen_image.py`) reaches. Its local loop compared `scale.shape[dim] !=weight.shape[dim]`, so a per-output-channel scale -- whose length already equals the row count-- was expanded by nothing and left to broadcasting."""@@ -212,9 +212,8 @@ class TestSharedComfyFold:_dequantize_comfyui_fp8(tensors, torch.float32)def test_a_layer_whose_packed_payload_was_taken_out_first_still_folds(self) -> None:- """Two loaders reach this fold: Wan, which has no nvfp4 support at all, and the Qwen2.5-VL- encoder, which calls `pop_nvfp4_layers` first (`qwen_image.py:473`) and ships the layers- packed. That pop takes the weight and both scales out together, so by the time the fold runs+ """The Qwen2.5-VL encoder reaches this fold. It calls `pop_nvfp4_layers` first (`qwen_image.py`)+ and ships the layers packed. That pop takes the weight and both scales out together, so by the time the fold runsthere is nothing for the guard to see -- asserted, because a guard that fired here anywaywould break the one supported nvfp4 build that passes through."""tensors, _ = nvfp4_signed_tensors("packed", torch.randint(0, 2, (128, 64), dtype=torch.bool))diff --git a/tests/backend/model_manager/load/test_wan_checkpoint_loader.py b/tests/backend/model_manager/load/test_wan_checkpoint_loader.pyindex 6469cfe65e..076821b886 100644--- a/tests/backend/model_manager/load/test_wan_checkpoint_loader.py+++ b/tests/backend/model_manager/load/test_wan_checkpoint_loader.py@@ -18,15 +18,21 @@ import safetensors.torchimport torchfrom safetensors.torch import save_file+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.wan import (_WAN_NATIVE_TO_DIFFUSERS_RENAMES,WanCheckpointModel,_build_wan_transformer_config,)from invokeai.backend.model_manager.taxonomy import SubModelType, WanVariantType+from invokeai.backend.quantization.fp8_scaled import is_scale_metadata_key, set_full_precision_hints_respectedfrom invokeai.backend.quantization.int8_convrot import Int8ConvrotLinearfrom tests.fixtures.quantized_payloads import (comfy_quant_marker,+ mxfp8_tensors,nvfp4_signed_tensors,quantize_convrot,quantize_scaled_fp8,@@ -98,6 +104,7 @@ def _recording_model() -> tuple[MagicMock, dict[str, torch.Tensor]]:def _make_loader() -> WanCheckpointModel:loader = object.__new__(WanCheckpointModel)loader._ram_cache = MagicMock()+ loader._torch_device = torch.device("cpu")return loader@@ -240,7 +247,7 @@ class TestEndToEnd:assert on what the loader actually hands over rather than on the result."""target = "blocks.0.attn1.to_q.weight"sd = _tiny_model().state_dict()- sd[target] = torch.full_like(sd[target], 0.5)+ sd[target] = torch.full_like(sd[target], 0.5).to(torch.float8_e4m3fn)sd["blocks.0.attn1.to_q.scale_weight"] = torch.tensor([4.0])sd["blocks.0.attn1.to_q.scale_input"] = torch.tensor([1.0])sd["scaled_fp8"] = torch.zeros(1, dtype=torch.float8_e4m3fn)@@ -249,16 +256,15 @@ class TestEndToEnd:save_file(sd, path)model, handed_over = _recording_model()+ loader = _make_loader()+ loader._should_use_fp8 = lambda *_args: Falsewith patch("diffusers.WanTransformer3DModel", return_value=model):- _load(path)+ _load(path, loader=loader)assert not [k for k in handed_over if k.endswith((".scale_weight", ".scale_input")) or k == "scaled_fp8"]# ...without eating scale_shift_table, which is a real Wan parameter.assert "scale_shift_table" in handed_over- # The scale is applied whatever the weight's dtype — `_dequantize_comfyui_fp8`- # has no fp8 gate, deliberately, because "scaled" checkpoints are not all fp8.- # Asserted rather than left implicit: this fixture's weight is bf16, so without- # this line the test would construct a 4x-scaled weight and say nothing about it.+ # Folded with its scale: 0.5 * 4.0.assert torch.allclose(handed_over[target].float(), torch.full_like(handed_over[target].float(), 2.0))def test_extra_modules_are_refused_not_dropped(self, tmp_path: Path) -> None:@@ -388,23 +394,25 @@ class TestHeaderFirstRead:"""What the header settles before any payload is read, and what the loaded model still holds of the file."""@staticmethod- def _load_recording(path: Path) -> tuple[torch.nn.Module, list[tuple], list[int]]:+ def _load_recording(+ path: Path, loader: WanCheckpointModel | None = None+ ) -> tuple[torch.nn.Module, list[tuple], list[set[str]]]:"""Load through the real reader, logging each payload it hands out and each reservation, in order.- Also returns, per read, how many earlier payloads that are not bf16 were still alive: source tensors that a- conversion on arrival has already replaced by then.+ Also returns, per read, the earlier payloads that are not bf16 and were still alive: source tensors that a+ conversion on arrival has already replaced by then, unless the load keeps them as stored."""events: list[tuple] = []- alive_at_read: list[int] = []- sources: list[weakref.ref] = []+ alive_at_read: list[set[str]] = []+ sources: list[tuple[str, weakref.ref]] = []real_safe_open = safetensors.safe_opendef handed_out(key: str, tensor: torch.Tensor) -> torch.Tensor:events.append(("read", key))- alive = [ref() for ref in sources]- alive_at_read.append(sum(1 for t in alive if t is not None and t.dtype != torch.bfloat16))+ alive = [(source, ref()) for source, ref in sources]+ alive_at_read.append({source for source, t in alive if t is not None and t.dtype != torch.bfloat16})del alive- sources.append(weakref.ref(tensor))+ sources.append((key, weakref.ref(tensor)))return tensorclass Handle:@@ -426,7 +434,7 @@ class TestHeaderFirstRead:with real_safe_open(*args, **kwargs) as handle:yield Handle(handle)- loader = _make_loader()+ loader = loader or _make_loader()loader._ram_cache.make_room.side_effect = lambda size: events.append(("reserve", size))dtype = torch.float32 if "int8" in path.name else torch.bfloat16with patch.object(safetensors, "safe_open", safe_open), patch.object(safetensors.torch, "safe_open", safe_open):@@ -480,7 +488,7 @@ class TestHeaderFirstRead:_, _, alive_at_read = self._load_recording(path)assert len(alive_at_read) > 2- assert max(alive_at_read) == 0+ assert not set().union(*alive_at_read)def test_scaled_fp8_room_is_the_folded_size_and_its_metadata_is_never_read(self, tmp_path: Path) -> None:reference = _tiny_model()@@ -495,11 +503,13 @@ class TestHeaderFirstRead:model, events, alive_at_read = self._load_recording(path)- assert events[0] == ("reserve", sum(v.numel() for v in reference.state_dict().values()) * 2)+ # The folded size, plus the one fold in flight: the weight's float32 copy and product, and its float32 scale.+ in_flight = 2 * 128 * 128 * torch.float32.itemsize + 128 * torch.float32.itemsize+ assert events[0] == ("reserve", sum(v.numel() for v in reference.state_dict().values()) * 2 + in_flight)read = {key for kind, key in events if kind == "read"}assert read == set(reference.state_dict()) | {"blocks.0.attn1.to_q.scale_weight"}# Only the fp8 weight is still alive while its scale is read; it is folded right after.- assert max(alive_at_read) == 1+ assert max(len(alive) for alive in alive_at_read) == 1folded = model.state_dict()[target]assert folded.dtype == torch.bfloat16assert torch.equal(folded.float(), torch.full_like(folded.float(), 2.0))@@ -820,3 +830,449 @@ class TestInt8Convrot:with pytest.raises(ValueError, match="mixing convrot layers with scaled fp8"):_load(path)+++# --- ComfyUI fp8_scaled ------------------------------------------------------------------------------------------++FP8_MARKER = {"format": "float8_e4m3fn"}+E5M2_MAX = 57344.0+# MXFP8 scales sit in cuBLAS tiles of 128 rows by 4 blocks of 32 weights; only the 128x128 attention projections fit.+MX_BLOCK = 32+++def hints_respected():+ set_full_precision_hints_respected(True)+ yield+ set_full_precision_hints_respected(None)+++def _scaled_fp8_checkpoint(+ layers: list[str],+ *,+ markers: bool = True,+ e5m2: tuple[str, ...] = (),+ hinted: tuple[str, ...] = (),+) -> tuple[torch.nn.Module, dict[str, torch.Tensor], dict[str, torch.Tensor]]:+ """A diffusers-layout state dict with ``layers`` stored as ComfyUI scaled fp8, and the dense model it decodes to.++ The reference carries each layer's round trip (codes times scale) from the fixture's own quantizer, which is+ what a correct loader must reconstruct. The third value is the scales by layer path. ``e5m2`` layers are stored in+ that float8 flavour, ``hinted`` ones carry a per-layer ``full_precision_matrix_mult`` marker.+ """+ torch.manual_seed(0)+ reference = _tiny_model().float()+ sd = {key: value.detach().clone() for key, value in reference.state_dict().items()}+ scales: dict[str, torch.Tensor] = {}+ for path in layers:+ weight = reference.get_submodule(path).weight+ if path in e5m2:+ scale = (weight.detach().abs().max() / E5M2_MAX).float()+ codes = (weight.detach() / scale).to(torch.float8_e5m2)+ decoded = codes.float() * scale+ else:+ payload = quantize_scaled_fp8(weight.detach().float())+ scale, codes, decoded = payload.scale, payload.codes, payload.dequantized+ with torch.no_grad():+ weight.copy_(decoded)+ sd[f"{path}.weight"] = codes+ sd[f"{path}.weight_scale"] = scale+ scales[path] = scale+ if markers:+ extra = {"full_precision_matrix_mult": True} if path in hinted else {}+ sd[f"{path}.comfy_quant"] = comfy_quant_marker({**FP8_MARKER, **extra})+ sd["scaled_fp8"] = torch.zeros(1, dtype=torch.float8_e4m3fn)+ return reference, sd, scales+++def _mxfp8_checkpoint(layers: list[str]) -> tuple[torch.nn.Module, dict[str, torch.Tensor]]:+ """``layers`` (128x128 projections) stored as MXFP8 with all-ones codes and a varied exponent grid, plus the dense+ model they decode to. The expected weight is the grid itself, expanded over its blocks of 32."""+ torch.manual_seed(0)+ reference = _tiny_model().float()+ sd = {key: value.detach().clone() for key, value in reference.state_dict().items()}+ for path in layers:+ tensors, block_scale = mxfp8_tensors(path, torch.randint(120, 128, (128, 128 // MX_BLOCK)).float())+ sd.update(tensors)+ sd[f"{path}.comfy_quant"] = comfy_quant_marker({"format": "mxfp8"})+ with torch.no_grad():+ reference.get_submodule(path).weight.copy_(block_scale.repeat_interleave(MX_BLOCK, dim=1))+ return reference, sd+++def _storage_loader(monkeypatch: pytest.MonkeyPatch, *, storage: bool, fp8_matmul: bool = False) -> WanCheckpointModel:+ """A loader whose settings are as given and whose FP8 Storage cast is the real one."""+ loader = _make_loader()+ loader._should_use_fp8 = lambda *_args: storage+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _device: fp8_matmul)+ return loader+++def _round_trip_through_fp8_storage(reference: torch.nn.Module, layers: list[str]) -> None:+ """Make ``reference`` hold what FP8 Storage leaves behind in the layers the checkpoint shipped dense (biases too)."""+ for path in layers:+ for param in reference.get_submodule(path).parameters():+ with torch.no_grad():+ param.copy_(param.to(torch.float8_e4m3fn).to(param.dtype))+++def _assert_forwards_like(model: torch.nn.Module, reference: torch.nn.Module, **tolerance) -> None:+ expected = _forward(reference)+ assert expected.abs().max() > 0, "reference output is degenerate, the comparison would pass vacuously"+ torch.testing.assert_close(_forward(model), expected, **tolerance)+++class TestScaledFp8:+ @pytest.mark.parametrize("native", [True, False], ids=["native-keys", "diffusers-keys"])+ @pytest.mark.parametrize("prefix", ["", "model.diffusion_model."], ids=["bare", "comfyui-prefix"])+ def test_fp8_storage_keeps_the_scaled_layers_packed_and_forwards_like_the_folded_model(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, native: bool, prefix: str+ ) -> None:+ reference, sd, scales = _scaled_fp8_checkpoint(ATTENTION)+ path = _write(tmp_path, sd, native=native, prefix=prefix)++ model = _load(path, loader=_storage_loader(monkeypatch, storage=True), dtype=torch.float32)++ for name in ATTENTION:+ layer = model.get_submodule(name)+ assert layer.weight.dtype is torch.float8_e4m3fn, name+ # The file's own scale, on the module the weight landed in rather than the one it was named after.+ torch.testing.assert_close(layer.weight_scale, scales[name], rtol=0, atol=0)+ for name in FFN:+ layer = model.get_submodule(name)+ assert layer.weight.dtype is torch.float8_e4m3fn, name+ assert getattr(layer, "weight_scale", None) is None, name+ _round_trip_through_fp8_storage(reference, FFN)+ apply_custom_layers_to_model(model)+ _assert_forwards_like(model, reference, rtol=1e-3, atol=1e-4)++ def test_scale_keys_never_reach_the_model(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """An unexpected key is blamed on an Animate/S2V variant, and `strict=False` would drop it silently+ otherwise, so assert on what the loader hands over."""+ _, sd, _ = _scaled_fp8_checkpoint(ATTENTION)+ for layer in ATTENTION:+ sd[f"{layer}.input_scale"] = torch.ones(())+ path = _write(tmp_path, sd)+ model, handed_over = _recording_model()+ with patch("diffusers.WanTransformer3DModel", return_value=model):+ _load(path, loader=_storage_loader(monkeypatch, storage=False), dtype=torch.float32)++ assert not [k for k in handed_over if is_scale_metadata_key(k)]+ assert "scale_shift_table" in handed_over++ def test_without_fp8_storage_or_the_fp8_matmul_the_file_is_folded(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ reference, sd, _ = _scaled_fp8_checkpoint(ATTENTION)+ path = _write(tmp_path, sd)++ model = _load(path, loader=_storage_loader(monkeypatch, storage=False), dtype=torch.float32)++ assert not any(p.dtype is torch.float8_e4m3fn for p in model.parameters())+ assert not any(name.endswith("weight_scale") for name, _ in model.named_buffers())+ _assert_forwards_like(model, reference, rtol=1e-4, atol=1e-5)++ def test_the_fp8_matmul_keeps_the_layers_packed_without_casting_the_rest(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ reference, sd, _ = _scaled_fp8_checkpoint(ATTENTION)+ path = _write(tmp_path, sd)++ model = _load(path, loader=_storage_loader(monkeypatch, storage=False, fp8_matmul=True), dtype=torch.float32)++ for name in ATTENTION:+ assert model.get_submodule(name).weight.dtype is torch.float8_e4m3fn, name+ for name in FFN:+ assert model.get_submodule(name).weight.dtype is torch.float32, name+ apply_custom_layers_to_model(model)+ _assert_forwards_like(model, reference, rtol=1e-3, atol=1e-4)++ def test_quantized_embedders_are_folded_so_the_condition_embedder_can_read_its_dtype(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """`condition_embedder` is a model-declared skip pattern: a scaled layer there cannot stay fp8, and has to be+ folded with its scale rather than cast without it."""+ reference, sd, _ = _scaled_fp8_checkpoint(ATTENTION + EMBEDDERS)+ path = _write(tmp_path, sd)++ model = _load(path, loader=_storage_loader(monkeypatch, storage=True), dtype=torch.float32)++ for name in EMBEDDERS:+ layer = model.get_submodule(name)+ assert layer.weight.dtype is torch.float32, name+ torch.testing.assert_close(layer.weight, reference.get_submodule(name).weight, rtol=1e-6, atol=1e-7)+ _round_trip_through_fp8_storage(reference, FFN)+ apply_custom_layers_to_model(model)+ _assert_forwards_like(model, reference, rtol=1e-3, atol=1e-4)++ def test_a_scaled_layer_the_split_folds_is_not_re_encoded_unscaled_by_fp8_storage(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """float8_e5m2 cannot stay packed, so its layer is folded with its scale. It then has no `weight_scale` and+ matches no skip pattern, which is exactly what the layerwise cast would otherwise take for a dense weight and+ store as unscaled e4m3: roughly 1% of its weights flushed to zero."""+ folded = "blocks.0.attn1.to_q"+ reference, sd, scales = _scaled_fp8_checkpoint(ATTENTION, e5m2=(folded,))+ path = _write(tmp_path, sd)++ model = _load(path, loader=_storage_loader(monkeypatch, storage=True), dtype=torch.float32)++ layer = model.get_submodule(folded)+ assert layer.weight.dtype is torch.float32+ torch.testing.assert_close(layer.weight, reference.get_submodule(folded).weight, rtol=1e-6, atol=1e-7)+ for name in ATTENTION:+ if name != folded:+ kept = model.get_submodule(name)+ assert kept.weight.dtype is torch.float8_e4m3fn, name+ torch.testing.assert_close(kept.weight_scale, scales[name], rtol=0, atol=0)+ _round_trip_through_fp8_storage(reference, FFN)+ apply_custom_layers_to_model(model)+ _assert_forwards_like(model, reference, rtol=1e-3, atol=1e-4)++ def test_a_file_whose_scaled_layers_are_all_folded_still_gets_no_unscaled_cast(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """With nothing left to attach, the load must not fall through to the generic cast, which would store every+ folded layer unscaled. The dense remainder still goes to fp8."""+ reference, sd, _ = _scaled_fp8_checkpoint(ATTENTION, e5m2=tuple(ATTENTION))+ path = _write(tmp_path, sd)++ model = _load(path, loader=_storage_loader(monkeypatch, storage=True), dtype=torch.float32)++ for name in ATTENTION:+ assert model.get_submodule(name).weight.dtype is torch.float32, name+ torch.testing.assert_close(+ model.get_submodule(name).weight, reference.get_submodule(name).weight, rtol=1e-6, atol=1e-7+ )+ for name in FFN:+ assert model.get_submodule(name).weight.dtype is torch.float8_e4m3fn, name+ _round_trip_through_fp8_storage(reference, FFN)+ apply_custom_layers_to_model(model)+ _assert_forwards_like(model, reference, rtol=1e-3, atol=1e-4)++ @pytest.mark.parametrize("storage", [False, True], ids=["storage-off", "storage-on"])+ def test_an_mxfp8_file_is_decoded_and_its_layers_stay_at_the_compute_dtype(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, storage: bool+ ) -> None:+ """A block-wise scale has no fp8 matmul to feed, so those layers are folded at load. Under FP8 Storage they+ must not then be re-encoded without it: blocks whose scale is far below 1 would flush to zero."""+ reference, sd = _mxfp8_checkpoint(ATTENTION)+ path = _write(tmp_path, sd)++ model = _load(path, loader=_storage_loader(monkeypatch, storage=storage), dtype=torch.float32)++ for name in ATTENTION:+ weight = model.get_submodule(name).weight+ assert weight.dtype is torch.float32, name+ torch.testing.assert_close(weight, reference.get_submodule(name).weight, rtol=0, atol=0)+ if storage:+ _round_trip_through_fp8_storage(reference, FFN)+ apply_custom_layers_to_model(model)+ _assert_forwards_like(model, reference, rtol=1e-3, atol=1e-4)++ @pytest.mark.parametrize("header_prefix", ["", "model.diffusion_model."], ids=["bare-header", "prefixed-header"])+ def test_a_precision_hint_declared_only_in_the_header_reaches_the_renamed_module(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, hints_respected: None, header_prefix: str+ ) -> None:+ """Header entries name layers natively. The flag has to land on the layer it was written for, in the model's+ own names, and on no other."""+ _, sd, _ = _scaled_fp8_checkpoint(ATTENTION, markers=False)+ hinted = ATTENTION[0]+ native_name = next(iter(_to_native_layout({f"{hinted}.weight": torch.empty(0)}))).removesuffix(".weight")+ header = {+ "_quantization_metadata": json.dumps(+ {+ "format_version": "1.0",+ "layers": {f"{header_prefix}{native_name}": {**FP8_MARKER, "full_precision_matrix_mult": True}},+ }+ )+ }+ path = tmp_path / "wan2.2_t2v_high_noise_14B_fp8_scaled.safetensors"+ save_file(+ {f"model.diffusion_model.{k}": v.contiguous() for k, v in _to_native_layout(sd).items()},+ path,+ metadata=header,+ )++ model = _load(path, loader=_storage_loader(monkeypatch, storage=True), dtype=torch.float32)++ assert model.get_submodule(hinted)._fp8_full_precision_matmul is True+ assert not any(model.get_submodule(name)._fp8_full_precision_matmul for name in ATTENTION[1:])++ @pytest.mark.parametrize("native", [True, False], ids=["native-keys", "diffusers-keys"])+ def test_a_precision_hint_carried_by_the_layers_own_marker_reaches_the_renamed_module(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, hints_respected: None, native: bool+ ) -> None:+ """The marker tensors are deleted by the extraction, so their hints have to be read first, in the file's names,+ and then follow the weight's rename."""+ hinted = ATTENTION[-1]+ _, sd, _ = _scaled_fp8_checkpoint(ATTENTION, hinted=(hinted,))+ path = _write(tmp_path, sd, native=native)++ model = _load(path, loader=_storage_loader(monkeypatch, storage=True), dtype=torch.float32)++ assert model.get_submodule(hinted)._fp8_full_precision_matmul is True+ assert not any(model.get_submodule(name)._fp8_full_precision_matmul for name in ATTENTION[:-1])++ def test_the_reservation_charges_kept_layers_one_byte_and_the_rest_the_compute_width(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Kept: one byte per code plus the float32 scale. Folded, the same layers would be charged the compute+ width, which is what made a 14B expert reserve twice what it holds."""+ _, sd, _ = _scaled_fp8_checkpoint(ATTENTION)+ path = _write(tmp_path, sd)+ loader = _storage_loader(monkeypatch, storage=True)++ _load(path, loader=loader, dtype=torch.float32)++ kept = set(ATTENTION)+ expected = 0+ for key, tensor in _tiny_model().state_dict().items():+ if key.endswith(".weight") and key[: -len(".weight")] in kept:+ expected += tensor.numel() * 1 + torch.float32.itemsize+ else:+ expected += tensor.numel() * torch.float32.itemsize+ loader._ram_cache.make_room.assert_called_once_with(expected)++ def test_kept_layers_are_read_after_the_one_reservation_and_stay_as_stored(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Kept or not, the reservation is settled from the header: only the markers are read before it. A kept layer's+ codes and float32 scale arrive as stored and are never widened or copied, and its input scale is read only+ because the layer stays fp8. What is folded or cast is dead by the next read."""+ _, sd, scales = _scaled_fp8_checkpoint(ATTENTION + EMBEDDERS)+ calibrated = ATTENTION[0]+ # The spelling ComfyUI's own fp8_scaled files carry.+ sd[f"{calibrated}.scale_input"] = torch.tensor(0.5)+ codes = {name: sd[f"{name}.weight"].clone() for name in ATTENTION}+ path = _write(tmp_path, sd, native=False)+ path = path.rename(path.with_name("wan2.2_t2v_high_noise_14B_fp8_scaled.safetensors"))++ model, events, alive_at_read = TestHeaderFirstRead._load_recording(+ path, loader=_storage_loader(monkeypatch, storage=True)+ )++ reserves = [index for index, event in enumerate(events) if event[0] == "reserve"]+ assert len(reserves) == 1+ assert all(key.endswith(".comfy_quant") for _, key in events[: reserves[0]])+ read = {key for kind, key in events[reserves[0] + 1 :] if kind == "read"}+ assert read == (+ set(_tiny_model().state_dict())+ | {f"{name}.weight_scale" for name in ATTENTION + EMBEDDERS}+ | {f"{calibrated}.scale_input"}+ )+ # At each weight read, the earlier payloads still alive (bf16 aside) are the kept codes and at most their+ # scales: the folded embedders' codes and scales and the cast float32 sources are gone.+ kept_codes = {f"{name}.weight" for name in ATTENTION}+ kept_scales = {f"{name}.weight_scale" for name in ATTENTION} | {f"{calibrated}.scale_input"}+ reads = [key for kind, key in events if kind == "read"]+ weight_reads = 0+ for index, (key, alive) in enumerate(zip(reads, alive_at_read, strict=True)):+ if key in sd and not is_scale_metadata_key(key):+ assert {source for source in alive if not is_scale_metadata_key(source)} == kept_codes & set(+ reads[:index]+ ), key+ assert {source for source in alive if is_scale_metadata_key(source)} <= kept_scales, key+ weight_reads += 1+ assert weight_reads == len(_tiny_model().state_dict())+ for name in ATTENTION:+ layer = model.get_submodule(name)+ assert layer.weight.dtype is torch.float8_e4m3fn, name+ # Its own storage, one byte per code: neither a widened copy nor a slice of a larger buffer.+ assert layer.weight.untyped_storage().nbytes() == layer.weight.numel(), name+ assert torch.equal(layer.weight.view(torch.uint8), codes[name].view(torch.uint8)), name+ assert layer.weight_scale.dtype is torch.float32, name+ torch.testing.assert_close(layer.weight_scale, scales[name], rtol=0, atol=0)+ assert model.get_submodule(calibrated).input_scale.item() == 0.5+ for name in EMBEDDERS:+ assert model.get_submodule(name).weight.dtype is torch.bfloat16, name++ @pytest.mark.parametrize("storage", [False, True], ids=["storage-off", "storage-on"])+ def test_a_scale_beside_a_weight_that_is_not_fp8_is_folded_into_it(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, storage: bool+ ) -> None:+ """ComfyUI's legacy `scaled_fp8` ops apply `scale_weight` whatever the weight's dtype: a "scaled" checkpoint is+ not all fp8. Such a layer is folded, and FP8 Storage leaves it at the compute dtype like any other folded+ scaled layer rather than re-encoding it without its scale."""+ target = ATTENTION[0]+ sd = {key: value.detach().clone() for key, value in _tiny_model().state_dict().items()}+ stored = sd[f"{target}.weight"].to(torch.bfloat16)+ sd[f"{target}.weight"] = stored+ sd[f"{target}.scale_weight"] = torch.tensor([0.25])+ path = _write(tmp_path, sd)++ model = _load(path, loader=_storage_loader(monkeypatch, storage=storage), dtype=torch.float32)++ loaded = model.get_submodule(target).weight+ assert loaded.dtype is torch.float32+ # A power-of-two scale, so the product is exact.+ torch.testing.assert_close(loaded, stored.float() * 0.25, rtol=0, atol=0)+ if storage:+ assert model.get_submodule(FFN[0]).weight.dtype is torch.float8_e4m3fn++ @pytest.mark.parametrize(+ ("storage", "fp8_matmul"),+ [(False, False), (False, True), (True, False)],+ ids=["folded", "fp8-matmul", "fp8-storage"],+ )+ def test_the_reservation_covers_what_the_load_holds_within_a_few_scalars(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, storage: bool, fp8_matmul: bool+ ) -> None:+ """The reservation is planned from the header, before any scale is read, so it has to agree with what the read+ ends up holding: kept per-tensor layers with both input-scale spellings, an e5m2 layer and the embedders the+ split folds, a scaled weight that is not fp8, and dense float32 tensors. Measured before the FP8 Storage cast,+ which shrinks the model afterwards. The slack is exactly the largest fold in flight, here the 768x128+ `time_proj` with its float32 copy and product and its scalar scale, and, where the layers are kept, the+ placeholder input scale the plan counts and the extraction drops."""+ e5m2 = ATTENTION[1]+ _, sd, _ = _scaled_fp8_checkpoint(ATTENTION + EMBEDDERS, e5m2=(e5m2,))+ sd[f"{ATTENTION[0]}.scale_input"] = torch.tensor(0.5)+ # An uncalibrated placeholder, which the extraction drops.+ sd[f"{ATTENTION[2]}.input_scale"] = torch.tensor(1.0)+ sd[f"{FFN[0]}.weight"] = sd[f"{FFN[0]}.weight"].to(torch.bfloat16)+ sd[f"{FFN[0]}.scale_weight"] = torch.tensor([0.5])+ path = _write(tmp_path, sd)+ loader = _storage_loader(monkeypatch, storage=storage, fp8_matmul=fp8_matmul)+ loader._apply_fp8_to_nn_module = lambda *_args, **_kwargs: None++ model = _load(path, loader=loader, dtype=torch.float32)++ held = sum(t.nelement() * t.element_size() for t in model.parameters()) + sum(+ b.nelement() * b.element_size()+ for name, b in model.named_buffers()+ if name.endswith((".weight_scale", ".input_scale"))+ )+ reserved = loader._ram_cache.make_room.call_args_list+ assert len(reserved) == 1+ in_flight = 2 * 768 * 128 * torch.float32.itemsize + torch.float32.itemsize+ placeholder = torch.float32.itemsize if storage or fp8_matmul else 0+ assert reserved[0].args[0] - held == in_flight + placeholder+ if storage or fp8_matmul:+ assert model.get_submodule(ATTENTION[0]).weight.dtype is torch.float8_e4m3fn++ @pytest.mark.parametrize("storage", [False, True], ids=["storage-off", "storage-on"])+ @pytest.mark.parametrize("slab_rows", [None, 32], ids=["whole", "slabs"])+ def test_an_mxfp8_file_reserves_for_its_largest_grid_in_flight(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, slab_rows: int | None, storage: bool+ ) -> None:+ """Every MXFP8 layer is folded, with FP8 Storage or without, so no grid stays resident, but each is alive+ through its own fold, and the fold widens it across the weight. The reservation covers what the model holds+ plus one such layer, not every grid at once: its float32 grid, and the fold's float32 weight copy, product and+ widened grid over the rows it folds at once (with the row index that picks a slab's grid rows). Measured before+ the FP8 Storage cast, which shrinks the dense layers afterwards."""+ from invokeai.backend.quantization import fp8_scaled++ if slab_rows is not None:+ monkeypatch.setattr(fp8_scaled, "_FOLD_SLAB_ELEMENTS", slab_rows * 128)+ _, sd = _mxfp8_checkpoint(ATTENTION)+ path = _write(tmp_path, sd)+ loader = _storage_loader(monkeypatch, storage=storage)+ loader._apply_fp8_to_nn_module = lambda *_args, **_kwargs: None++ model = _load(path, loader=loader, dtype=torch.float32)++ held = sum(t.nelement() * t.element_size() for t in model.parameters())+ grid = 128 * (128 // MX_BLOCK) * torch.float32.itemsize+ rows = 128 if slab_rows is None else slab_rows+ fold = 3 * rows * 128 * torch.float32.itemsize + (0 if slab_rows is None else rows * torch.int64.itemsize)+ loader._ram_cache.make_room.assert_called_once_with(held + grid + fold)diff --git a/tests/backend/model_manager/load/test_wan_fp8_wiring.py b/tests/backend/model_manager/load/test_wan_fp8_wiring.pyindex 198330c717..9c35448217 100644--- a/tests/backend/model_manager/load/test_wan_fp8_wiring.py+++ b/tests/backend/model_manager/load/test_wan_fp8_wiring.py@@ -9,11 +9,12 @@ Three behaviours are pinned here, and each of them is a decision this loader makmachinery it inherits:- a plain checkpoint reaches the cast;-- a Comfy `fp8_scaled` checkpoint does *not*, and says why. Its per-tensor scales were folded into the- weights and dropped, so re-encoding the result as unscaled fp8 would flush the low end of every- tensor to zero -- 3.4% of the weights on `flux-2-klein-4b-fp8`. Identification switches FP8 Storage- on by itself for a float8 denoiser, so this is the default path for such a file, not a road less- travelled;+- a Comfy `fp8_scaled` checkpoint with FP8 Storage on does *not* take that cast. Its scaled layers stay+ fp8 with the file's own scale, and the cast the rest of the model gets skips them: the layerwise cast+ would upcast them without the scale, and re-encoding a folded weight as unscaled fp8 flushes the low+ end of every tensor to zero -- 3.4% of the weights on `flux-2-klein-4b-fp8`. Identification switches+ FP8 Storage on by itself for a float8 denoiser, so this is the default path for such a file. (With the+ setting off the file is folded; `TestEndToEnd` covers that);- the state dict is released first, or the bf16 originals stay reachable beside their fp8 copies whilethe reservation covers only one of the two."""@@ -22,7 +23,6 @@ from pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import MagicMock, patch-import pytestimport torchfrom safetensors.torch import save_file@@ -43,18 +43,23 @@ TINY_MODEL_KWARGS = {}+SCALE = 4.0++def _tiny_state_dict() -> dict[str, torch.Tensor]:from diffusers import WanTransformer3DModel+ torch.manual_seed(0)return WanTransformer3DModel(**TINY_MODEL_KWARGS).state_dict()def _checkpoint(path: Path, scaled: bool) -> Path:sd = _tiny_state_dict()if scaled:- # What Comfy's `fp8_scaled` repack looks like: a per-tensor scale beside the weight, and the- # marker tensor that names the convention.- sd["blocks.0.attn1.to_q.scale_weight"] = torch.tensor([4.0])+ # What Comfy's `fp8_scaled` repack looks like: an fp8 weight with a per-tensor scale beside it, and+ # the marker tensor that names the convention.+ sd["blocks.0.attn1.to_q.weight"] = (sd["blocks.0.attn1.to_q.weight"] / SCALE).to(torch.float8_e4m3fn)+ sd["blocks.0.attn1.to_q.scale_weight"] = torch.tensor([SCALE])sd["scaled_fp8"] = torch.zeros(1, dtype=torch.float8_e4m3fn)save_file(sd, path)return path@@ -63,8 +68,8 @@ def _checkpoint(path: Path, scaled: bool) -> Path:def _loader(cast_calls: list, *, asks_for_fp8: bool = True) -> WanCheckpointModel:loader = object.__new__(WanCheckpointModel)loader._ram_cache = MagicMock()- # The branch under test consults the gate to decide whether the decline is worth reporting; the- # gate itself has its own cells in `test_load_default_fp8.py`.+ loader._torch_device = torch.device("cpu")+ # The gate itself has its own cells in `test_load_default_fp8.py`.loader._should_use_fp8 = lambda *_args, **_kwargs: asks_for_fp8loader._apply_fp8_layerwise_casting = lambda model, config, submodel: (cast_calls.append((config, submodel)),@@ -99,35 +104,23 @@ class TestTheCheckpointLoader:assert len(cast_calls) == 1assert cast_calls[0][1] is SubModelType.Transformer- def test_a_scaled_checkpoint_is_declined_and_the_reason_is_logged(- self, tmp_path: Path, caplog: pytest.LogCaptureFixture- ) -> None:+ def test_a_scaled_checkpoint_keeps_its_layers_packed_and_skips_the_unscaled_cast(self, tmp_path: Path) -> None:"""The case identification turns on by itself, and the one where the cast would cost quality.- Folding happened before this point and the scales are gone, so the cast could only re-encode- the result unscaled. Declining leaves the model where it already is -- correct, at bf16 size.+ The scaled layer stays fp8 with its checkpoint scale; the rest of the model is cast in the same+ pass, so the loader's trailing cast, which would see the scaled layer too, is not reached."""cast_calls: list = []loader = _loader(cast_calls)- with caplog.at_level("INFO"):- model = _load(loader, _checkpoint(tmp_path / "Wan2.2-A14B-HighNoise-fp8_scaled.safetensors", scaled=True))-- assert cast_calls == []- assert model is not None- assert "FP8 Storage not applied" in caplog.text- assert "unscaled fp8" in caplog.text-- def test_the_decline_is_silent_when_nobody_asked(self, tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:- """Most loads of a scaled file have the setting off, and they have nothing to be told."""- cast_calls: list = []- loader = _loader(cast_calls, asks_for_fp8=False)-- with caplog.at_level("INFO"):- _load(loader, _checkpoint(tmp_path / "Wan2.2-A14B-HighNoise-fp8_scaled.safetensors", scaled=True))+ model = _load(loader, _checkpoint(tmp_path / "Wan2.2-A14B-HighNoise-fp8_scaled.safetensors", scaled=True))assert cast_calls == []- assert "FP8 Storage" not in caplog.text+ scaled = model.get_submodule("blocks.0.attn1.to_q")+ assert scaled.weight.dtype is torch.float8_e4m3fn+ assert scaled.weight_scale.item() == SCALE+ assert model.get_submodule("blocks.0.ffn.net.2").weight.dtype is torch.float8_e4m3fn+ assert getattr(model.get_submodule("blocks.0.ffn.net.2"), "weight_scale", None) is Nonedef test_the_state_dict_is_released_before_the_cast(self, tmp_path: Path) -> None:"""Peak RAM must not overshoot the `make_room()` reservation.diff --git a/tests/backend/quantization/test_fp8_scaled.py b/tests/backend/quantization/test_fp8_scaled.pyindex b888683fd9..1af4c7eaaa 100644--- a/tests/backend/quantization/test_fp8_scaled.py+++ b/tests/backend/quantization/test_fp8_scaled.py@@ -1,6 +1,7 @@import contextlibimport jsonimport logging+import weakreffrom unittest import mockimport pytest@@ -24,6 +25,7 @@ from invokeai.backend.quantization.fp8_scaled import (extract_comfy_quant_hints,extract_fp8_scaled_layers,find_torchao_fp8_problem,+ fold_transient_bytes,forget_inconclusive_fp8_matmul_probe,is_matmul_usable_scale,is_scale_metadata_key,@@ -958,6 +960,64 @@ class TestFoldInSlabs:assert max(event.cpu_memory_usage for event in profiler.events()) == result_bytes+ @pytest.mark.parametrize(+ "scale",+ [+ pytest.param(torch.tensor(0.37), id="per_tensor"),+ pytest.param(torch.rand(256) + 0.5, id="per_row"),+ pytest.param(torch.rand(16, 4) + 0.5, id="row_and_column_blocks"),+ pytest.param(torch.rand(256, 16) + 0.5, id="column_blocks"),+ ],+ )+ @pytest.mark.parametrize("slab_elements", [None, 8 * 512], ids=["whole", "slabs"])+ def test_the_transient_a_loader_reserves_for_covers_what_the_fold_holds(+ self, monkeypatch: pytest.MonkeyPatch, scale: torch.Tensor, slab_elements: int | None+ ) -> None:+ """`fold_transient_bytes` is what a loader adds to its reservation for the layer in flight, so it must not fall+ short of the live bytes the fold allocates beyond its result. Counted by storage, from allocation until the+ last tensor on it dies. In slabs it is exact; folded whole it is over by the result, which does not yet exist+ while the multiply holds its two float32 copies."""+ from torch.utils._python_dispatch import TorchDispatchMode+ from torch.utils._pytree import tree_leaves++ class LiveBytes(TorchDispatchMode):+ def __init__(self) -> None:+ super().__init__()+ self.live = 0+ self.peak = 0++ def _free(self, size: int) -> None:+ self.live -= size++ def __torch_dispatch__(self, func, types, args=(), kwargs=None):+ kwargs = kwargs or {}+ inputs = {t.untyped_storage().data_ptr() for t in tree_leaves((args, kwargs)) if torch.is_tensor(t)}+ out = func(*args, **kwargs)+ for tensor in tree_leaves(out):+ storage = tensor.untyped_storage() if torch.is_tensor(tensor) else None+ if storage is None or storage.nbytes() == 0 or storage.data_ptr() in inputs:+ continue+ inputs.add(storage.data_ptr())+ self.live += storage.nbytes()+ self.peak = max(self.peak, self.live)+ weakref.finalize(tensor, self._free, storage.nbytes())+ return out++ if slab_elements is not None:+ monkeypatch.setattr(fp8_scaled, "_FOLD_SLAB_ELEMENTS", slab_elements)+ sd = {"lin.weight": torch.randn(256, 512).to(FP8_DTYPE)}+ bound = fold_transient_bytes(torch.empty(256, 512, dtype=FP8_DTYPE, device="meta"), scale)++ with LiveBytes() as live:+ dequantize_fp8_scaled(sd, {"lin": Fp8ScaledLayer(weight_scale=scale)}, torch.bfloat16)++ beyond_result = live.peak - 256 * 512 * torch.bfloat16.itemsize+ assert beyond_result > 0, "the tracker saw no allocation, so the comparison would pass vacuously"+ if slab_elements is None:+ assert beyond_result <= bound+ else:+ assert beyond_result == bound+def test_a_block_scale_that_does_not_tile_the_rows_names_the_layer(self) -> None:# Left to the multiply: "The size of tensor a (39) must match the size of tensor b (36)", naming nothing.sd = {"blocks.0.lin.weight": torch.randn(39, 48).to(FP8_DTYPE)}