Skip to content

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

feat(quantization): keep Z-Image nvfp4 layers packed

Alexander Eichhornc69a999eaae7
diff --git a/docs/src/content/docs/configuration/fp8-storage.mdx b/docs/src/content/docs/configuration/fp8-storage.mdx
index 89d4db6399..95a2bb00b0 100644
--- a/docs/src/content/docs/configuration/fp8-storage.mdx
+++ b/docs/src/content/docs/configuration/fp8-storage.mdx
@@ -11,7 +11,7 @@ FP8 Storage cuts a model's VRAM footprint roughly in half by keeping weights on
It pairs well with [Low-VRAM mode](/configuration/low-vram-mode/): low-VRAM mode streams layers between RAM and VRAM, while FP8 Storage shrinks the layers themselves.
:::caution[For full precision models only]
-FP8 Storage only applies to **full precision** checkpoints (FP16 / BF16 / FP32). It is **silently a no-op** for already-quantized formats — **GGUF**, **NF4**, **int8**, and [**SDNQ**](/configuration/sdnq-quantization/) checkpoints carry their own storage precision and the loader returns a different module type that the FP8 layer cast does not touch. If your model is already quantized, the toggle has no effect; use the full-precision variant of the model if you want to enable FP8 Storage.
+FP8 Storage is meant for **full precision** checkpoints (FP16 / BF16 / FP32). It is **silently a no-op** for **GGUF**, **NF4** and [**SDNQ**](/configuration/sdnq-quantization/) checkpoints, which carry their own storage precision. **int8** and **nvfp4** single-file checkpoints keep their quantized layers as they are — the loader returns a module type the FP8 layer cast does not touch — so there the toggle only reaches the layers the build ships in full precision. If your model is already quantized, use its full-precision variant to get the full effect of FP8 Storage.
:::
## Requirements
@@ -109,7 +109,7 @@ If you see unexpected quality regressions, disable FP8 Storage on the affected m
**FP8 Compute + partial loading** is a different story — it still works, but it costs both speed and reproducibility. See [FP8 Compute](#fp8-compute) below.
-(For why FP8 Storage doesn't stack on top of GGUF / NF4 / int8 checkpoints, see the callout at the top of this page.)
+(For how FP8 Storage interacts with GGUF / NF4 / SDNQ / int8 / nvfp4 checkpoints, see the callout at the top of this page.)
## FP8 Compute
@@ -163,7 +163,7 @@ You're on a PyTorch version that predates FP8 support. Reinstall InvokeAI using
If FP8 Storage misbehaves — crash, quality regression, OOM that shouldn't happen — please [open a GitHub issue](https://github.com/invoke-ai/InvokeAI/issues/new/choose) and include:
- **What you did**: the workflow / generation step that triggered the problem, and whether it reproduces every time.
-- **Model**: exact name and variant (e.g. "FLUX.2 Klein 9B Diffusers", "SDXL Base 1.0 single-file"), and whether the file is a full-precision checkpoint or already quantized (GGUF / NF4 / int8).
+- **Model**: exact name and variant (e.g. "FLUX.2 Klein 9B Diffusers", "SDXL Base 1.0 single-file"), and whether the file is a full-precision checkpoint or already quantized (GGUF / NF4 / SDNQ / int8 / nvfp4).
- **LoRAs**: whether any LoRAs (or ControlLoRAs) are stacked on the model, and how many.
- **Other toggles**: Low-VRAM mode on/off, any `cpu_only` text encoder setting, configured VRAM limit.
- **GPU**: model and VRAM size (e.g. "RTX 3090 24 GB", "RTX 4070 Ti 12 GB").
diff --git a/invokeai/app/invocations/krea2/krea2_denoise.py b/invokeai/app/invocations/krea2/krea2_denoise.py
index fbf8baf4df..5e7aee2be0 100644
--- a/invokeai/app/invocations/krea2/krea2_denoise.py
+++ b/invokeai/app/invocations/krea2/krea2_denoise.py
@@ -53,10 +53,7 @@ from invokeai.backend.model_manager.taxonomy import BaseModelType
from invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpec
from invokeai.backend.patches.lora_conversions.krea2_lora_constants import KREA2_LORA_TRANSFORMER_PREFIX
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
-from invokeai.backend.quantization.int8_convrot import (
- peak_int8_dequant_transient_bytes,
- requires_sidecar_patching,
-)
+from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes, requires_sidecar_patching
from invokeai.backend.rectified_flow.rectified_flow_inpaint_extension import RectifiedFlowInpaintExtension
from invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateState
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import Krea2ConditioningInfo
@@ -507,7 +504,7 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
# derotated weight per forward call. That transient is alive alongside the activations above,
# so it is added rather than compared -- and it is invisible to an activation estimate, which
# is how a model that loaded comfortably OOMs in its first step. Zero for any other format.
- estimated_working_memory += peak_int8_dequant_transient_bytes(transformer_info.model, inference_dtype)
+ estimated_working_memory += peak_dequant_transient_bytes(transformer_info.model, inference_dtype)
# Once per device per process, and from here rather than from startup: the probe allocates,
# so on the boot path it would create a CUDA context on an idle server -- and on `cuda:0`,
diff --git a/invokeai/app/invocations/minimax_h3/minimax_h3_denoise.py b/invokeai/app/invocations/minimax_h3/minimax_h3_denoise.py
index 89c9d81378..1023577506 100644
--- a/invokeai/app/invocations/minimax_h3/minimax_h3_denoise.py
+++ b/invokeai/app/invocations/minimax_h3/minimax_h3_denoise.py
@@ -74,10 +74,7 @@ from invokeai.backend.patches.lora_conversions.minimax_h3_lora_conversion_utils
is_minimax_h3_adaln_layer_path,
)
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
-from invokeai.backend.quantization.int8_convrot import (
- peak_int8_dequant_transient_bytes,
- requires_sidecar_patching,
-)
+from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes, requires_sidecar_patching
from invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateState
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import MiniMaxH3ConditioningInfo
from invokeai.backend.util.devices import TorchDevice
@@ -477,7 +474,7 @@ class MiniMaxH3DenoiseInvocation(BaseInvocation):
# Added to the activation estimate rather than compared against it: the transient is alive
# inside the same forward. Zero on a bf16 build. Read from the unlocked model, before the
# VRAM lock the reservation applies to.
- estimated_working_memory += peak_int8_dequant_transient_bytes(transformer_info.model, torch.bfloat16)
+ estimated_working_memory += peak_dequant_transient_bytes(transformer_info.model, torch.bfloat16)
# LoRA patches are materialized (RAM cache) before any VRAM locks. On the AdaLN-pruned
# transformer the AdaLN layers cannot be weight patches (their 2688-dim input space was
diff --git a/invokeai/app/invocations/z_image/z_image_denoise.py b/invokeai/app/invocations/z_image/z_image_denoise.py
index f913120301..3d011994ca 100644
--- a/invokeai/app/invocations/z_image/z_image_denoise.py
+++ b/invokeai/app/invocations/z_image/z_image_denoise.py
@@ -32,10 +32,7 @@ from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat
from invokeai.backend.patches.layer_patcher import LayerPatcher, PatchSpec
from invokeai.backend.patches.lora_conversions.z_image_lora_constants import Z_IMAGE_LORA_TRANSFORMER_PREFIX
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
-from invokeai.backend.quantization.int8_convrot import (
- peak_int8_dequant_transient_bytes,
- requires_sidecar_patching,
-)
+from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes, requires_sidecar_patching
from invokeai.backend.rectified_flow.rectified_flow_inpaint_extension import RectifiedFlowInpaintExtension
from invokeai.backend.stable_diffusion.diffusers_pipeline import PipelineIntermediateState
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import ZImageConditioningInfo
@@ -446,29 +443,28 @@ class ZImageDenoiseInvocation(BaseInvocation):
):
raise ValueError(f"Unsupported Z-Image model format: {transformer_config.format}")
- # An int8_tensorwise build materializes each linear's dequantized, derotated weight per
- # forward. That transient is not part of the model's resident size, so the cache has to
- # be told to keep room for it or the first forward competes with weights it just placed.
- # Read from the unlocked model, before the VRAM lock the reservation applies to; zero
- # for every other build.
+ # An int8_tensorwise or nvfp4 build materializes each quantized linear's weight per forward.
+ # That transient is not part of the model's resident size, so the cache has to be told to
+ # keep room for it or the first forward competes with weights it just placed. Read from the
+ # unlocked model, before the VRAM lock the reservation applies to; zero for every other build.
#
# Passed alone rather than added to an activation estimate because this node has none --
# the cache's `device_working_mem_gb` floor is what covers activations here, as it did
- # before. That floor (3 GiB by default) is 20x Z-Image's largest int8 transient, so this
- # only ever raises the reservation; a node that grows a real activation estimate should
- # add the two, since the transient is alive alongside the activations.
- int8_dequant_bytes = peak_int8_dequant_transient_bytes(transformer_info.model, inference_dtype)
+ # before. That floor (3 GiB by default) is about 20x Z-Image's largest transient under either
+ # scheme, so this only ever raises the reservation; a node that grows a real activation
+ # estimate should add the two, since the transient is alive alongside the activations.
+ dequant_bytes = peak_dequant_transient_bytes(transformer_info.model, inference_dtype)
# Load transformer - always use base transformer, control is handled via extension
(cached_weights, transformer) = exit_stack.enter_context(
- transformer_info.model_on_device(working_mem_bytes=int8_dequant_bytes)
+ transformer_info.model_on_device(working_mem_bytes=dequant_bytes)
)
# Whether LoRA has to go on as a sidecar. Asked of the loaded module tree, not the
- # format: a `checkpoint` Z-Image may be an int8_tensorwise build, whose Linears are
- # Int8ConvrotLinear. Those carry their weights as buffers rather than parameters, so
- # the fallbacks inside the patcher -- which iterate `module.parameters()` -- find
- # nothing and choose direct patching on a module that has no patchable weights.
+ # format: a `checkpoint` Z-Image may be an int8_tensorwise or nvfp4 build, whose quantized
+ # Linears carry their weights as buffers rather than parameters, so the fallbacks inside
+ # the patcher -- which iterate `module.parameters()` -- find nothing and choose direct
+ # patching on a module that has no patchable weights.
model_is_quantized = requires_sidecar_patching(transformer, transformer_config.format)
# Prepare control extension if control is provided
diff --git a/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_dequantizing_linear.py b/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_dequantizing_linear.py
new file mode 100644
index 0000000000..eeab7e927f
--- /dev/null
+++ b/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_dequantizing_linear.py
@@ -0,0 +1,65 @@
+import torch
+
+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.cast_to_device import cast_to_device
+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_linear import (
+ autocast_linear_forward_sidecar_patches,
+)
+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_module_mixin import (
+ CustomModuleMixin,
+)
+from invokeai.backend.quantization.dequantizing_linear import DequantizingLinear
+from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
+from invokeai.backend.quantization.nvfp4 import NVFP4Linear
+
+
+class CustomDequantizingLinear(DequantizingLinear, CustomModuleMixin):
+ """Sidecar patches (LoRA) and device autocast for a ``DequantizingLinear``, subclassed once per scheme below.
+
+ The weight lives in quantized buffers and is dequantized per forward, so a patch cannot be written into
+ it: patches ride as sidecars. The scheme's own forward runs unchanged, and a LoRA's low-rank residual is
+ added in activation space at full compute precision -- the delta is never rounded into the quantized
+ grid. Callers must pass ``force_sidecar_patching=True`` to the ``LayerPatcher`` when a model contains
+ these modules (see ``requires_sidecar_patching``): the smart patcher's heuristics look at parameters,
+ and these modules have none.
+
+ Device autocast falls out of the base forward, which already moves the buffers to the input's device
+ per call, so a partially loaded module left on the CPU streams its quantized payload on demand.
+ """
+
+ def _cast_tensor_for_input(self, tensor: torch.Tensor | None, input: torch.Tensor) -> torch.Tensor | None:
+ tensor = cast_to_device(tensor, input.device)
+ if (
+ tensor is not None
+ and input.is_floating_point()
+ and tensor.is_floating_point()
+ and tensor.dtype != input.dtype
+ ):
+ tensor = tensor.to(dtype=input.dtype)
+ return tensor
+
+ def _cast_weight_bias_for_input(self, input: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor | None]:
+ # A meta tensor lets patch types without an optimized sidecar path read the weight's shape but never its
+ # quantized values; LoRA layers take the residual path and never get here. Patches are reshaped to this
+ # shape, so it has to be the unpacked one, which the weight buffer's is not for nvfp4.
+ weight = torch.empty((self.out_features, self.in_features), device="meta")
+ bias = self._cast_tensor_for_input(self.bias, input)
+ return weight, bias
+
+ def _autocast_forward_with_patches(self, input: torch.Tensor) -> torch.Tensor:
+ return autocast_linear_forward_sidecar_patches(self, input, self._patches_and_weights)
+
+ def _autocast_forward(self, input: torch.Tensor) -> torch.Tensor:
+ return DequantizingLinear.forward(self, input)
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
+ if len(self._patches_and_weights) > 0:
+ return self._autocast_forward_with_patches(input)
+ return self._autocast_forward(input)
+
+
+class CustomInt8ConvrotLinear(CustomDequantizingLinear, Int8ConvrotLinear):
+ pass
+
+
+class CustomNVFP4Linear(CustomDequantizingLinear, NVFP4Linear):
+ pass
diff --git a/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_int8_convrot_linear.py b/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_int8_convrot_linear.py
deleted file mode 100644
index 3cac78415b..0000000000
--- a/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_int8_convrot_linear.py
+++ /dev/null
@@ -1,61 +0,0 @@
-import torch
-
-from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.cast_to_device import cast_to_device
-from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_linear import (
- autocast_linear_forward_sidecar_patches,
-)
-from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_module_mixin import (
- CustomModuleMixin,
-)
-from invokeai.backend.patches.layers.param_shape_utils import get_param_shape
-from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
-
-
-class CustomInt8ConvrotLinear(Int8ConvrotLinear, CustomModuleMixin):
- """Custom wrapper for ``Int8ConvrotLinear`` enabling sidecar patches (LoRA) and device autocast.
-
- The base module stores an int8 weight plus a per-output-channel scale as buffers and
- dequantizes per forward. Direct (in-place) weight patching is impossible on int8 storage,
- so LoRAs are applied as sidecar patches: the base module's own quantized forward runs
- unchanged, and the low-rank residual is added in activation space at full compute
- precision — the delta is never rounded into the int8 grid. Callers must pass
- ``force_sidecar_patching=True`` to the ``LayerPatcher`` when a model contains these
- modules (the smart patcher's device heuristics would otherwise try direct patching).
-
- Device autocast falls out of the base implementation: ``Int8ConvrotLinear.forward``
- already moves its buffers to the input's device per call, so a partially-loaded module
- left on the CPU streams its (int8, i.e. half-bf16-sized) weight on demand.
- """
-
- def _cast_tensor_for_input(self, tensor: torch.Tensor | None, input: torch.Tensor) -> torch.Tensor | None:
- tensor = cast_to_device(tensor, input.device)
- if (
- tensor is not None
- and input.is_floating_point()
- and tensor.is_floating_point()
- and tensor.dtype != input.dtype
- ):
- tensor = tensor.to(dtype=input.dtype)
- return tensor
-
- def _cast_weight_bias_for_input(self, input: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor | None]:
- # Substitute a meta tensor for the weight so patch types without an optimized sidecar
- # path can read its *shape* but never the quantized int8 values (same convention as
- # CustomInvokeLinear8bitLt). LoRA layers take the optimized residual path and never
- # get here.
- weight = torch.empty(get_param_shape(self.weight), device="meta")
- bias = self._cast_tensor_for_input(self.bias, input)
- return weight, bias
-
- def _autocast_forward_with_patches(self, input: torch.Tensor) -> torch.Tensor:
- return autocast_linear_forward_sidecar_patches(self, input, self._patches_and_weights)
-
- def _autocast_forward(self, input: torch.Tensor) -> torch.Tensor:
- # The base forward dequantizes into the input's device and dtype per call, which is
- # already autocast-safe.
- return Int8ConvrotLinear.forward(self, input)
-
- def forward(self, input: torch.Tensor) -> torch.Tensor:
- if len(self._patches_and_weights) > 0:
- return self._autocast_forward_with_patches(input)
- return self._autocast_forward(input)
diff --git a/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/torch_module_autocast.py b/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/torch_module_autocast.py
index c01d789310..116983f15e 100644
--- a/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/torch_module_autocast.py
+++ b/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/torch_module_autocast.py
@@ -10,6 +10,10 @@ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custo
from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_conv2d import (
CustomConv2d,
)
+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_dequantizing_linear import (
+ CustomInt8ConvrotLinear,
+ CustomNVFP4Linear,
+)
from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_diffusers_rms_norm import (
CustomDiffusersRMSNorm,
)
@@ -22,9 +26,6 @@ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custo
from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_group_norm import (
CustomGroupNorm,
)
-from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_int8_convrot_linear import (
- CustomInt8ConvrotLinear,
-)
from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_layer_norm import (
CustomLayerNorm,
)
@@ -35,6 +36,7 @@ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custo
CustomModuleMixin,
)
from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
+from invokeai.backend.quantization.nvfp4 import NVFP4Linear
AUTOCAST_MODULE_TYPE_MAPPING: dict[type[torch.nn.Module], type[torch.nn.Module]] = {
torch.nn.Linear: CustomLinear,
@@ -46,6 +48,7 @@ AUTOCAST_MODULE_TYPE_MAPPING: dict[type[torch.nn.Module], type[torch.nn.Module]]
FluxRMSNorm: CustomFluxRMSNorm,
DiffusersRMSNorm: CustomDiffusersRMSNorm,
Int8ConvrotLinear: CustomInt8ConvrotLinear,
+ NVFP4Linear: CustomNVFP4Linear,
}
try:
diff --git a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
index 499014e0d8..0f0cd1e915 100644
--- a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
+++ b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
@@ -948,11 +948,22 @@ class MistralEncoderCheckpointLoader(ModelLoader):
sd = load_file(model_path)
sd = _strip_known_prefixes(sd)
+ # The header names layers before this loader strips its own wrapper prefixes on top of the generic ones,
+ # so the names need both lists. With only the generic tuple, a `language_model.`-prefixed redistribution
+ # keeps its names while the sd keys lose the prefix: every `full_precision_matrix_mult` is silently
+ # ignored, and nvfp4 layers only the header names are refused as unnamed.
+ header_hints = strip_layer_path_prefix(
+ parse_quantization_metadata(read_safetensors_metadata(model_path, logger)),
+ prefixes=(*MISTRAL_KEY_PREFIXES, *TRANSFORMER_KEY_PREFIXES),
+ )
+
# Comfy's fp4_mixed build keeps most projections in nvfp4 beside scaled fp8. Decode those first:
# the keep-fp8 branch below pops every `weight_scale` and discards the ones whose weight is not
# float8, nvfp4's block scales included, and the dequantizing branch would stretch them over the
# packed weight.
- nvfp4_layers = dequantize_nvfp4_layers(sd, model_dtype, reserve=self._ram_cache.make_room)
+ nvfp4_layers = dequantize_nvfp4_layers(
+ sd, model_dtype, reserve=self._ram_cache.make_room, header_layers=header_hints
+ )
if nvfp4_layers:
logger.info(
f"Mistral encoder: decoded {nvfp4_layers} nvfp4 layer(s) to {model_dtype}. They are not kept packed, "
@@ -970,14 +981,6 @@ class MistralEncoderCheckpointLoader(ModelLoader):
keep_fp8 = should_keep_fp8_weights(target_device)
fp8_layers: dict[str, Any] = {}
if keep_fp8:
- # This loader strips its own wrapper prefixes on top of the generic ones, so the hints
- # need both lists. With only the generic tuple, a `language_model.`-prefixed
- # redistribution keeps its hint names while the sd keys lose the prefix, and every
- # `full_precision_matrix_mult` is silently ignored.
- header_hints = strip_layer_path_prefix(
- parse_quantization_metadata(read_safetensors_metadata(model_path, logger)),
- prefixes=(*MISTRAL_KEY_PREFIXES, *TRANSFORMER_KEY_PREFIXES),
- )
layer_hints = {**extract_comfy_quant_hints(sd), **header_hints}
fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)
if not fp8_layers:
diff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.py
index 980e37dcc7..595218f8fc 100644
--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py
@@ -68,7 +68,13 @@ from invokeai.backend.quantization.int8_convrot import (
split_int8_convrot_layers,
swap_in_int8_linears,
)
-from invokeai.backend.quantization.nvfp4 import dequantize_nvfp4_layers
+from invokeai.backend.quantization.nvfp4 import (
+ NVFP4Payload,
+ install_nvfp4_layers,
+ pop_nvfp4_layers,
+ predict_nvfp4_install_size,
+ split_nvfp4_rows,
+)
from invokeai.backend.quantization.sdnq.detection import is_sdnq_folder
from invokeai.backend.quantization.sdnq.loaders import raise_on_incomplete_sdnq_load, sdnq_sd_loader
from invokeai.backend.qwen3.qwen3_tokenizer import load_bundled_qwen3_tokenizer
@@ -99,6 +105,17 @@ def _remap_z_image_layer_paths(layer_names: Any) -> dict[str, list[str]]:
return mapping
+def _remap_nvfp4_payloads(payloads: dict[str, NVFP4Payload]) -> dict[str, NVFP4Payload]:
+ """Move packed nvfp4 layers to their diffusers paths, splitting a fused QKV's tensors the way the converter
+ splits its weight: into equal thirds by rows, which the block scales only survive on whole tile rows."""
+ path_map = _remap_z_image_layer_paths(payloads.keys())
+ remapped: dict[str, NVFP4Payload] = {}
+ for name, payload in payloads.items():
+ targets = path_map.get(name, [name])
+ remapped.update(zip(targets, split_nvfp4_rows(name, payload, len(targets)), strict=True))
+ return remapped
+
+
def _convert_z_image_gguf_to_diffusers(sd: dict[str, Any]) -> dict[str, Any]:
"""Convert Z-Image GGUF state dict keys to diffusers format.
@@ -486,24 +503,20 @@ class ZImageCheckpointModel(ModelLoader):
target_device = TorchDevice.choose_torch_device()
model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
- # Before anything below reads the quantization side channel: the scaled-fp8 extraction pops every
- # `weight_scale` and drops the ones whose weight is not float8, nvfp4's block scales included, and
- # the fused-QKV split has no destination for `weight_scale_2`.
- nvfp4_layers = dequantize_nvfp4_layers(sd, model_dtype, reserve=self._ram_cache.make_room)
- if nvfp4_layers:
- self._logger.info(
- f"Z-Image: decoded {nvfp4_layers} nvfp4 layer(s) to {model_dtype}. They are not kept packed, so the "
- "model needs as much memory as its bf16 build."
- )
-
- # Per-layer `full_precision_matrix_mult` hints, from the safetensors header and/or the
- # per-tensor `.comfy_quant` markers. The header names layers in the checkpoint's own scheme,
- # so it is remapped below; the markers ride along through the key conversion instead.
- # The names in the header still carry the checkpoint prefix stripped off `sd` above.
+ # Per-layer hints from the safetensors header and/or the per-tensor `.comfy_quant` markers:
+ # `full_precision_matrix_mult` for scaled fp8, and for nvfp4 the evidence that a layer follows
+ # ComfyUI's conventions. The header names layers in the checkpoint's own scheme, so it is remapped
+ # below; the markers ride along through the key conversion instead. The names in the header still
+ # carry the checkpoint prefix stripped off `sd` above.
header_hints = strip_layer_path_prefix(
parse_quantization_metadata(read_safetensors_metadata(model_path, self._logger))
)
+ # Out of the state dict before anything below reads the quantization side channel: the scaled-fp8
+ # extraction pops every `weight_scale` and drops the ones whose weight is not float8, nvfp4's block
+ # scales included, and the casts would widen the packed payload.
+ nvfp4_payloads = pop_nvfp4_layers(sd, header_layers=header_hints)
+
# Check if the state dict is in original format (not diffusers format)
# Original format has keys like "x_embedder.weight" instead of "all_x_embedder.2-1.weight"
needs_conversion = any(k.startswith("x_embedder.") for k in sd.keys() if isinstance(k, str))
@@ -515,6 +528,7 @@ class ZImageCheckpointModel(ModelLoader):
header_hints = {
target: hints for name, hints in header_hints.items() for target in path_map.get(name, [name])
}
+ nvfp4_payloads = _remap_nvfp4_payloads(nvfp4_payloads)
# Create an empty model with the default Z-Image config
# Z-Image-Turbo uses these default parameters from diffusers
@@ -556,6 +570,20 @@ class ZImageCheckpointModel(ModelLoader):
keys_to_remove = [k for k in sd.keys() if not (k.startswith(valid_prefixes) or k in valid_exact)]
for k in keys_to_remove:
del sd[k]
+ # A bundled encoder's nvfp4 layers go the same way.
+ nvfp4_payloads = {path: payload for path, payload in nvfp4_payloads.items() if path.startswith(valid_prefixes)}
+
+ # Honor the model's own precision-sensitive list on every path below. Z-Image declares
+ # ["t_embedder", "cap_embedder"] because `ZImageTimestepEmbedder.forward` reads
+ # `self.mlp[0].weight.dtype` to pick the dtype it casts its activations to, and a quantized
+ # weight there breaks that branch whichever scheme it comes from: an fp8 weight turns the
+ # activations fp8 and the forward dies in `x.abs()`; an `Int8ConvrotLinear` or `NVFP4Linear`
+ # reports an integer dtype, the forward falls through to a `compute_dtype` attribute these
+ # modules do not have, and the timestep branch silently runs in float32 into a bf16 model.
+ skip_patterns = _model_declared_skip_patterns(model)
+ # What the nvfp4 layers will occupy, packed or decoded. Both branches reserve it together with the
+ # rest of the state dict: a reservation makes that much room, it does not add to an earlier one.
+ nvfp4_bytes = predict_nvfp4_install_size(model, nvfp4_payloads, model_dtype, skip_patterns)
# Two ComfyUI side-channel formats reach this loader, and a checkpoint carries one or the
# other: `comfy_quant` names its format per layer, and `int8_tensorwise` never appears in a
@@ -582,14 +610,6 @@ class ZImageCheckpointModel(ModelLoader):
sd.update(kept_sd)
del kept_sd
- # Honor the model's own precision-sensitive list here too, not only on the fp8 side.
- # Z-Image declares ["t_embedder", "cap_embedder"] because
- # `ZImageTimestepEmbedder.forward` reads `self.mlp[0].weight.dtype` to pick the dtype
- # it casts its activations to; on an `Int8ConvrotLinear` that reads `torch.int8`, the
- # forward falls through to a `compute_dtype` attribute these modules do not have, and
- # the timestep branch silently runs in float32 into a bf16 model.
- skip_patterns = _model_declared_skip_patterns(model)
-
# Reserve before the split, not after: the split dequantizes the layers it widens, so
# reserving afterwards lets that transient land on an unreserved cache. The prediction
# is given the same inputs, so it charges those layers the compute dtype's width and
@@ -597,6 +617,7 @@ class ZImageCheckpointModel(ModelLoader):
# memory this load never uses.
self._ram_cache.make_room(
predict_int8_cast_size(sd, model_dtype, int8_markers, model=model, skip_patterns=skip_patterns)
+ + nvfp4_bytes
)
quantized = split_int8_convrot_layers(
@@ -619,24 +640,14 @@ class ZImageCheckpointModel(ModelLoader):
# them here would discard both the VRAM saving and the tensor cores before the model is
# built.
keep_fp8 = should_keep_fp8_weights(self._torch_device)
- if fp8_layers and not keep_fp8:
- # Legacy behavior, but now with the scale actually applied: fold it into the weight.
- dequantize_fp8_scaled(sd, fp8_layers, model_dtype)
- fp8_layers = {}
- # Honor the model's own precision-sensitive list. Z-Image declares
- # ["t_embedder", "cap_embedder"], and `TimestepEmbedder.forward` casts its activations to
- # `self.mlp[0].weight.dtype` — an fp8 weight there turns the activations fp8 and the
- # forward dies in `x.abs()`. Those layers must be dequantized even though the rest stays
- # quantized.
- skip_patterns = _model_declared_skip_patterns(model)
- # Scaled layers that the cast would dequantize anyway are folded here, scale applied, so
- # `cast_state_dict` never strips a scale it cannot put back.
- # Reserve before the split, not after: `split_fp8_scaled_layers` dequantizes its unusable
- # subset through fp32, so reserving afterwards lets that transient peak land on an
- # unreserved cache. `scaled_layers` is what keeps that honest: the split also widens
- # layers whose scale layout `scaled_mm` cannot apply, and without the mapping the
- # prediction would charge those 1 byte/element and arrive at 2.
+ # Reserve before anything below widens a weight, not after: without fp8 compute the fold right
+ # after this widens every scaled layer, and `split_fp8_scaled_layers` dequantizes its unusable
+ # subset through fp32 -- reserving afterwards lets either peak land on an unreserved cache.
+ # Without fp8 compute the prediction charges every float at `model_dtype`, folded yet or not.
+ # With it, `scaled_layers` is what keeps the prediction honest: the split also widens layers
+ # whose scale layout `scaled_mm` cannot apply, and without the mapping the prediction would
+ # charge those 1 byte/element and arrive at 2.
self._ram_cache.make_room(
predict_cast_state_dict_size(
sd,
@@ -646,8 +657,17 @@ class ZImageCheckpointModel(ModelLoader):
skip_patterns=skip_patterns,
scaled_layers=fp8_layers,
)
+ + nvfp4_bytes
)
+ if fp8_layers and not keep_fp8:
+ # Legacy behavior, but now with the scale actually applied: fold it into the weight.
+ dequantize_fp8_scaled(sd, fp8_layers, model_dtype)
+ fp8_layers = {}
+
+ # Scaled layers that the cast would dequantize anyway are folded here, scale applied, so
+ # `cast_state_dict` never strips a scale it cannot put back.
+
fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)
kept = cast_state_dict(
sd,
@@ -657,6 +677,18 @@ class ZImageCheckpointModel(ModelLoader):
skip_patterns=skip_patterns,
)
+ if nvfp4_payloads:
+ packed = install_nvfp4_layers(model, sd, nvfp4_payloads, model_dtype, skip_patterns)
+ decoded = len(nvfp4_payloads) - packed
+ self._logger.info(
+ f"Z-Image: kept {packed} nvfp4 layer(s) packed"
+ + (
+ f" and decoded {decoded} to {model_dtype} (precision-sensitive or not a Linear)."
+ if decoded
+ else "."
+ )
+ )
+
model.load_state_dict(sd, assign=True)
# `assign=True` aliases every param to its `sd` tensor, so the dict keeps the whole model
# alive a second time. The FP8 cast below allocates the fp8 copy per param while the
diff --git a/invokeai/backend/quantization/dequantizing_linear.py b/invokeai/backend/quantization/dequantizing_linear.py
new file mode 100644
index 0000000000..9ae2bf3ee9
--- /dev/null
+++ b/invokeai/backend/quantization/dequantizing_linear.py
@@ -0,0 +1,85 @@
+"""Linears that keep their weight quantized in buffers and materialize it on every forward.
+
+Two schemes store their Linears this way, ``int8_convrot`` and ``nvfp4``, and the code around them
+needs the same two answers about either: 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,
+so they live here beside the base class the modules share rather than inside either scheme -- a new
+scheme answers them by subclassing instead of every caller learning its name.
+"""
+
+import abc
+from typing import Any
+
+import torch
+import torch.nn.functional as F
+
+from invokeai.backend.model_manager.taxonomy import ModelFormat
+
+
+class DequantizingLinear(torch.nn.Module, abc.ABC):
+ """A Linear whose weight is kept quantized as buffers and dequantized on every forward.
+
+ Subclasses register their payload as persistent buffers under the checkpoint's own key names, so
+ ``load_state_dict`` assigns the quantized tensors straight into them and the model cache moves them
+ between devices like any other weight. ``bias`` is a buffer as well, or ``None``.
+
+ ``forward`` takes the weight from :meth:`_dequantized_weight` on the input's device and in its dtype,
+ so a partial load that left the buffers on the CPU streams them per call instead of failing. The model
+ cache wraps these modules for sidecar patches (see ``AUTOCAST_MODULE_TYPE_MAPPING``).
+
+ Both methods are abstract so that a scheme missing one fails where its modules are built, at load,
+ rather than in the denoise node that sizes its working memory from them.
+ """
+
+ in_features: int
+ out_features: int
+ bias: torch.Tensor | None
+
+ @abc.abstractmethod
+ def _dequantized_weight(self, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
+ """The weight as ``[out_features, in_features]`` in ``dtype`` on ``device``, for one forward."""
+
+ @abc.abstractmethod
+ def dequant_transient_bytes(self, compute_dtype: torch.dtype) -> int:
+ """Peak bytes one forward of this layer allocates beyond its resident buffers."""
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ weight = self._dequantized_weight(x.device, x.dtype)
+ bias = self.bias.to(device=x.device, dtype=x.dtype) if self.bias is not None else None
+ return F.linear(x, weight, bias)
+
+
+def requires_sidecar_patching(model: Any, model_format: ModelFormat) -> bool:
+ """Whether LoRA has to be applied as a sidecar rather than written into the weights.
+
+ The format alone does not answer this. A plain ``checkpoint`` may still hold
+ :class:`DequantizingLinear` modules -- an ``int8_tensorwise`` or ``nvfp4`` build whose Linears the
+ loader replaced -- and those keep their weights as quantized *buffers*, which a direct patch cannot
+ write into. Worse, the patcher's own fallbacks iterate ``module.parameters()``, and these modules have
+ none, so they answer "not quantized" and direct patching is chosen. So the loaded module tree is
+ consulted, not just the config.
+ """
+ if model_format in (ModelFormat.GGUFQuantized, ModelFormat.SDNQQuantized):
+ return True
+ return any(isinstance(module, DequantizingLinear) for module in model.modules())
+
+
+def peak_dequant_transient_bytes(model: torch.nn.Module, compute_dtype: torch.dtype) -> int:
+ """Peak bytes one forward transiently needs to dequantize this model's quantized linears.
+
+ A :class:`DequantizingLinear` materializes its weight per forward, so that allocation is not covered
+ by the model's resident size and has to fit inside the calling node's working-memory reservation. The
+ layers run one after another and free their weight before the next one allocates, so the peak is the
+ largest single layer's transient. Zero when the model holds no such layer.
+
+ Not covered: the matmul's own cuBLAS workspace, which a dense Linear of the same shape allocates too
+ and which a node's activation estimate already includes.
+ """
+ return max(
+ (
+ module.dequant_transient_bytes(compute_dtype)
+ for module in model.modules()
+ if isinstance(module, DequantizingLinear)
+ ),
+ default=0,
+ )
diff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.py
index b59a03a45e..34bb98df36 100644
--- a/invokeai/backend/quantization/fp8_scaled.py
+++ b/invokeai/backend/quantization/fp8_scaled.py
@@ -67,9 +67,10 @@ class Fp8ScaledLayer:
def read_safetensors_metadata(path: Path, logger: Logger | None = None) -> dict[str, str] | None:
"""Read the safetensors header metadata, or None if it cannot be read.
- Only used to enrich fp8 handling (per-layer ``full_precision_matrix_mult`` hints), so an
- unreadable header must not fail the model load. It is warned about rather than swallowed: without
- the hints, layers the quantizer marked as unsafe would silently be multiplied in fp8.
+ Only used for per-layer quantization hints, so an unreadable header must not fail the model load
+ by itself. It is warned about rather than swallowed: without the hints, layers the quantizer marked
+ as unsafe would silently be multiplied in fp8, and nvfp4 layers that only the header names are
+ refused as unnamed.
"""
try:
from safetensors import safe_open
@@ -78,7 +79,9 @@ def read_safetensors_metadata(path: Path, logger: Logger | None = None) -> dict[
return f.metadata()
except Exception as e:
if logger is not None:
- logger.warning(f"Could not read safetensors metadata from {path.name} ({e}); fp8 layer hints unavailable.")
+ logger.warning(
+ f"Could not read safetensors metadata from {path.name} ({e}); per-layer quantization hints unavailable."
+ )
return None
diff --git a/invokeai/backend/quantization/int8_convrot.py b/invokeai/backend/quantization/int8_convrot.py
index a505661ebc..3887c22ed2 100644
--- a/invokeai/backend/quantization/int8_convrot.py
+++ b/invokeai/backend/quantization/int8_convrot.py
@@ -30,8 +30,8 @@ dequantized, derotated bf16 weight per forward call. The derotation is a
``[out, in/256, 256] @ [256, 256]`` matmul — a rounding error next to the
transformer forward itself — and the transient bf16 weight (<= ~310 MB for H3's
largest layer) has to fit inside the calling node's working-memory reservation:
-``peak_int8_dequant_transient_bytes`` is what a denoise node adds to its estimate
-for that, since the model's resident size does not account for it.
+``dequantizing_linear.peak_dequant_transient_bytes`` is what a denoise node adds to
+its estimate for that, since the model's resident size does not account for it.
"""
import json
@@ -39,9 +39,8 @@ from collections.abc import Iterable, Mapping
from typing import Any
import torch
-import torch.nn.functional as F
-from invokeai.backend.model_manager.taxonomy import ModelFormat
+from invokeai.backend.quantization.dequantizing_linear import DequantizingLinear
from invokeai.backend.quantization.fp8_scaled import (
COMFY_QUANT_SUFFIX,
FP8_WEIGHT_DTYPES,
@@ -191,23 +190,22 @@ def dequantize_convrot_weight(
return w.to(dtype)
-class Int8ConvrotLinear(torch.nn.Module):
+class Int8ConvrotLinear(DequantizingLinear):
"""A linear layer storing Comfy int8_tensorwise(+convrot) weights, dequantized per forward.
The int8 weight and fp32 scale are registered as PERSISTENT buffers named ``weight`` and
``weight_scale`` — exactly the converted checkpoint's key names — so ``load_state_dict``
consumes the quantized tensors directly and the model cache moves them between devices
like any other weight. The Hadamard matrix is neither loaded nor held per module: it is a
- constant of the scheme, so ``forward`` takes it from :func:`shared_regular_hadamard`, which
- keeps one per ``(size, device, dtype)`` for every layer in the model.
+ constant of the scheme, so the dequantization takes it from :func:`shared_regular_hadamard`,
+ which keeps one per ``(size, device, dtype)`` for every layer in the model.
The model cache wraps this module as ``CustomInt8ConvrotLinear`` (see
``AUTOCAST_MODULE_TYPE_MAPPING``), which enables sidecar LoRA patches and lets a partial
- load leave some int8 buffers on the CPU — ``forward``'s per-call ``.to(device)`` then
- streams them (at half the bf16 byte count) instead of failing outright. Fully-resident
- operation remains the intended regime (~20 GiB free VRAM for H3's pruned transformer);
- streamed layers pay a per-forward PCIe cost, and an unquantized model is still the better
- citizen on small cards.
+ load leave some int8 buffers on the CPU — the per-call ``.to(device)`` then streams them
+ (at half the bf16 byte count) instead of failing outright. Fully-resident operation remains
+ the intended regime (~20 GiB free VRAM for H3's pruned transformer); streamed layers pay a
+ per-forward PCIe cost, and an unquantized model is still the better citizen on small cards.
"""
def __init__(
@@ -255,10 +253,20 @@ class Int8ConvrotLinear(torch.nn.Module):
).view(self.out_features, self.in_features)
return w
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- weight = self._dequantized_weight(x.device, x.dtype)
- bias = self.bias.to(device=x.device, dtype=x.dtype) if self.bias is not None else None
- return F.linear(x, weight, bias)
+ def dequant_transient_bytes(self, compute_dtype: torch.dtype) -> int:
+ """Two weight-sized tensors in the compute dtype.
+
+ Both halves of ``_dequantized_weight`` peak at two: the dtype cast of the int8 weight is alive
+ alongside the product it is multiplied into, and that product is then alive alongside the
+ derotation matmul's output. Each pair is freed before the next allocates.
+
+ Under partial load the int8 weight is additionally streamed to the device per call, adding up to
+ half a weight again; the resident-model regime this scheme targets pays nothing for that. Verified
+ against the real `z_image_turbo_int8_convrot` checkpoint: exact for most shapes, and 2 MiB under on
+ the two that make cuBLAS take a workspace (10240x3840 and 3840x10240), against a 3 GiB reservation
+ floor.
+ """
+ return 2 * self.out_features * self.in_features * compute_dtype.itemsize
def extra_repr(self) -> str:
return f"in_features={self.in_features}, out_features={self.out_features}, convrot={self.convrot}"
@@ -344,25 +352,6 @@ def reject_unmarked_int8_weights(sd: dict[str, Any], markers: Mapping[str, Any],
)
-def requires_sidecar_patching(transformer: Any, model_format: ModelFormat) -> bool:
- """Whether LoRA has to be applied as a sidecar rather than written into the weights.
-
- The format alone does not answer this. A plain ``checkpoint`` may still be an
- ``int8_tensorwise`` build, whose Linears the loader replaced with :class:`Int8ConvrotLinear` --
- those hold their weights as int8 *buffers*, which a direct patch cannot write into (and which
- could not represent the patched values anyway, the rotation having mixed 256 of them). Worse,
- the fallbacks that would otherwise catch this iterate ``module.parameters()``, and these modules
- have none, so they answer "not quantized" and direct patching is chosen. So the loaded module
- tree is consulted, not just the config.
-
- Lives here rather than beside one denoise node because every architecture this scheme reaches
- needs the same answer, and getting it from the config alone is wrong in the same way for each.
- """
- if model_format in (ModelFormat.GGUFQuantized, ModelFormat.SDNQQuantized):
- return True
- return any(isinstance(module, Int8ConvrotLinear) for module in transformer.modules())
-
-
def drop_unconsumed_quantization_sidecars(sd: dict[str, Any]) -> dict[str, Any]:
"""Remove quantization metadata no loader here consumes.
@@ -670,31 +659,3 @@ def reject_foreign_quantization_scales(
f"`int8_tensorwise` marker claims, e.g. {orphans[:3]}. A file mixing int8_tensorwise "
"with scaled fp8 is not supported: the fp8 weights would load unscaled."
)
-
-
-def peak_int8_dequant_transient_bytes(model: torch.nn.Module, compute_dtype: torch.dtype) -> int:
- """Peak bytes one forward transiently needs to dequantize this model's int8 linears.
-
- ``Int8ConvrotLinear`` keeps its weight int8 and materializes the dequantized, derotated weight
- per forward, so that transient is *not* covered by the model's resident size and has to fit
- inside the calling node's working-memory reservation. Zero when the model holds no such layer.
-
- Two weight-sized tensors in the compute dtype, over the largest such layer. Both halves of
- ``_dequantized_weight`` peak at two: the dtype cast of the int8 weight is alive alongside the
- product it is multiplied into, and that product is then alive alongside the derotation matmul's
- output. Each pair is freed before the next allocates, and the layers run one at a time.
-
- Under partial load the int8 weight is additionally streamed to the device per call, adding up to
- half a weight again; the resident-model regime this scheme targets pays nothing for that.
-
- What it does not cover is the matmul's own cuBLAS workspace, which is not a property of this
- scheme -- a dense Linear of the same shape allocates it too, and the node's activation estimate
- is measured with it included. Verified against the real `z_image_turbo_int8_convrot` checkpoint:
- exact for most shapes, and 2 MiB under on the two that make cuBLAS take a workspace
- (10240x3840 and 3840x10240), against a 3 GiB reservation floor.
- """
- largest = 0
- for module in model.modules():
- if isinstance(module, Int8ConvrotLinear):
- largest = max(largest, module.in_features * module.out_features)
- return 2 * largest * compute_dtype.itemsize
diff --git a/invokeai/backend/quantization/nvfp4.py b/invokeai/backend/quantization/nvfp4.py
index b7ab8f7381..12327233bd 100644
--- a/invokeai/backend/quantization/nvfp4.py
+++ b/invokeai/backend/quantization/nvfp4.py
@@ -1,4 +1,4 @@
-"""Load-time support for Comfy "nvfp4" quantized linears.
+"""Comfy "nvfp4" quantized linears: packed storage decoded per forward, or a decode at load.
``nvfp4`` is a ComfyUI-wide scheme, not one architecture's format: Comfy-Org ships it for Z-Image,
Krea-2, Qwen-Image, the FLUX.2 Mistral encoder and more, often beside scaled fp8 and plain bf16 in the
@@ -14,27 +14,37 @@ A quantized linear ``[out, in]`` is stored as:
- ``<layer>.weight_scale_2``: a float32 scalar, multiplied in:
``W = E2M1[codes] * block_scale * weight_scale_2``.
- optionally ``<layer>.input_scale``, an activation scale for fp4 compute, and a ``.comfy_quant``
- marker. Some producers name their layers in the ``_quantization_metadata`` header instead; detection
- here is structural -- a ``weight_scale_2`` beside the weight -- so it needs neither.
-
-These facts were established against real checkpoints, not a specification: decoding every nvfp4
-tensor of the Mistral FLUX.2 encoder and Z-Image Turbo builds reaches cosine 0.995 against the bf16
-build in the same repository, the floor of 4-bit block quantization. Reading the scale grid row by row
-instead still loads without an error and reaches 0.68-0.95 -- a model that runs and follows its
-conditioning slightly worse. That silence is why tests pin the layout against the measured index
-formula and against a slice of a real checkpoint.
-
-The weights are dequantized to the compute dtype at load, so an nvfp4 checkpoint loads correctly but
-occupies as much memory as its bf16 build. AWQ builds (``pre_quant_scale``) are refused: their input
-channels were rescaled before quantization, so a plain decode would produce wrong weights.
+ marker. Some producers name their layers in the ``_quantization_metadata`` header instead.
+
+These are ComfyUI's conventions, established against real checkpoints rather than a specification:
+decoding every nvfp4 tensor of the Mistral FLUX.2 encoder and Z-Image Turbo builds reaches cosine 0.995
+against the bf16 build in the same repository, the floor of 4-bit block quantization. Reading the scale
+grid row by row instead loads without an error and reaches 0.68-0.95 -- a model that runs and follows
+its conditioning slightly worse -- which is why tests pin the layout against the measured index formula
+and a slice of a real checkpoint. Nothing guarantees that another producer writing the same key names
+shares these conventions, so a layer is only read when a Comfy marker or header entry names it nvfp4.
+
+Loaders take one of two routes:
+
+- Keep the layers packed: :func:`pop_nvfp4_layers` takes them out of the state dict before any fp8
+ handling, and :func:`install_nvfp4_layers` swaps :class:`NVFP4Linear` modules in before the load. A
+ layer then occupies about 0.56 bytes per weight element against bf16's 2 and dequantizes per forward.
+- Decode at load with :func:`dequantize_nvfp4_layers`. The model then needs as much memory as its bf16
+ build.
+
+AWQ builds (``pre_quant_scale``) are refused either way: their input channels were rescaled before
+quantization, so a plain decode would produce wrong weights.
"""
-from collections.abc import Callable
+import functools
+from collections.abc import Callable, Iterable, Mapping
+from dataclasses import dataclass
from typing import Any
import torch
import torch.nn.functional as F
+from invokeai.backend.quantization.dequantizing_linear import DequantizingLinear
from invokeai.backend.quantization.fp8_scaled import COMFY_QUANT_SUFFIX, INPUT_SCALE_SUFFIXES, iter_weight_scale_pairs
from invokeai.backend.quantization.int8_convrot import parse_comfy_quant_marker
@@ -44,7 +54,7 @@ NVFP4_BLOCK_SIZE = 16
WEIGHT_SCALE_2_SUFFIX = ".weight_scale_2"
PRE_QUANT_SCALE_SUFFIX = ".pre_quant_scale"
-# What a decoded layer no longer needs besides its weight.
+# Everything a layer carries besides its weight.
_SIDE_CHANNEL_SUFFIXES = (".weight_scale", WEIGHT_SCALE_2_SUFFIX, COMFY_QUANT_SUFFIX, *INPUT_SCALE_SUFFIXES)
# cuBLAS block-scale tiles span 128 rows and 4 blocks.
@@ -53,7 +63,23 @@ _TILE_BLOCKS = 4
_E2M1_VALUES = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0])
# Both decoded elements of every possible byte, upper nibble first: one lookup per byte.
-_E2M1_BYTE_PAIRS = torch.stack([_E2M1_VALUES[torch.arange(256) >> 4], _E2M1_VALUES[torch.arange(256) & 0x0F]], dim=1)
+_E2M1_PAIRS_BY_BYTE = torch.stack([_E2M1_VALUES[torch.arange(256) >> 4], _E2M1_VALUES[torch.arange(256) & 0x0F]], dim=1)
+# Every float8_e4m3fn value by its bit pattern. Block scales are widened through this rather than cast, so the
+# decode needs no float8 kernel, and a packed layer can hold its scales as plain bytes: MPS has no float8 tensors.
+_E4M3_BY_BYTE = torch.arange(256, dtype=torch.uint8).view(torch.float8_e4m3fn).to(torch.float32).unsqueeze(1)
+
+
+# The tables on each device, shared by every layer and read-only. Held per module they would be copied to the
+# device on every lock and cast on every forward -- the lesson of int8_convrot's Hadamard matrix. Bounded by the
+# devices and compute dtypes in use, at 512 values each.
+def _e2m1_pairs_on(device: torch.device, dtype: torch.dtype) -> torch.Tensor:
+ return _E2M1_PAIRS_BY_BYTE.to(device=device, dtype=dtype)
+
+
+def _e4m3_values_on(device: torch.device) -> torch.Tensor:
+ return _E4M3_BY_BYTE.to(device)
def _check_tile_layout(rows: int, blocks: int) -> None:
@@ -72,7 +98,8 @@ def unblock_scale_grid(scale: torch.Tensor) -> torch.Tensor:
``row % 32``, then ``row // 32``, then the block. Producers write that layout into a tensor of the
row-major shape, so nothing about the shape gives it away. It is a permutation, and inverting it is
a reshape: stored ``(tile row, tile column, row % 32, row // 32, block)`` becomes
- ``(tile row, row // 32, row % 32, tile column, block)``.
+ ``(tile row, row // 32, row % 32, tile column, block)``. Tile row ``r`` therefore occupies stored rows
+ ``[128 r, 128 (r + 1))``.
The MXFP8 scales ``fp8_scaled._reject_mx_scale`` refuses are stored reordered too; whether in these
tiles, with their 32-element blocks, has not been measured.
@@ -86,7 +113,7 @@ def unblock_scale_grid(scale: torch.Tensor) -> torch.Tensor:
def _check_layout(weight: torch.Tensor | None, weight_scale: torch.Tensor | None, weight_scale_2: torch.Tensor) -> None:
- """Refuse tensors this decode would misread. Reads dtypes and shapes only."""
+ """Refuse checkpoint tensors this decode would misread. Reads dtypes and shapes only."""
if weight is None or weight_scale is None:
raise ValueError(f"has a weight_scale_2 but no {'weight' if weight is None else 'weight_scale'}")
if weight.dtype is not torch.uint8 or weight.dim() != 2:
@@ -110,40 +137,107 @@ def _check_layout(weight: torch.Tensor | None, weight_scale: torch.Tensor | None
def dequantize_nvfp4_weight(
weight: torch.Tensor, weight_scale: torch.Tensor, weight_scale_2: torch.Tensor, dtype: torch.dtype
) -> torch.Tensor:
- """Decode one nvfp4 weight to ``[out, in]`` in ``dtype``, on the weight's device.
+ """Decode one nvfp4 weight, as the checkpoint stores it, to ``[out, in]`` in ``dtype`` on the weight's device."""
+ _check_layout(weight, weight_scale, weight_scale_2)
+ return _decode(weight, weight_scale.view(torch.uint8), weight_scale_2, dtype)
+
+
+def _decode(
+ weight: torch.Tensor, scale_bytes: torch.Tensor, weight_scale_2: torch.Tensor, dtype: torch.dtype
+) -> torch.Tensor:
+ """The decode behind :func:`dequantize_nvfp4_weight` and :class:`NVFP4Linear`, over the block scales' bytes.
- Decodes in ``dtype`` directly. The E2M1 values and the e4m3 block scales are exact in bf16, and the
- rounding the float32 global scale introduces is far below the 4-bit quantization error. That keeps
- the transient at the result plus an int32 byte index, two bytes per weight element each, instead of
- adding a float32 copy on top.
+ Works in ``dtype`` directly. The E2M1 values and the e4m3 block scales are exact in bf16, and the rounding
+ the float32 global scale introduces is far below the 4-bit quantization error. The scale grid is reordered
+ while still one byte per entry and widened before the weight is, so the weight's decode allocates only its
+ result and an int32 byte index beside that grid (see :meth:`NVFP4Linear.dequant_transient_bytes`).
"""
- _check_layout(weight, weight_scale, weight_scale_2)
- out_features, blocks = weight_scale.shape
device = weight.device
- global_scale = weight_scale_2.to(device=device, dtype=torch.float32).reshape(())
- grid = unblock_scale_grid(weight_scale.to(device=device, dtype=torch.float32)) * global_scale
- values = F.embedding(weight.to(torch.int32), _E2M1_BYTE_PAIRS.to(device=device, dtype=dtype))
- values = values.view(out_features, blocks, NVFP4_BLOCK_SIZE).mul_(grid.to(dtype).unsqueeze(-1))
+ out_features, blocks = scale_bytes.shape
+ grid = F.embedding(unblock_scale_grid(scale_bytes.to(device)).to(torch.int32), _e4m3_values_on(device))
+ grid = grid.mul_(weight_scale_2.to(device=device, dtype=torch.float32).reshape(())).to(dtype)
+ values = F.embedding(weight.to(torch.int32), _e2m1_pairs_on(device, dtype))
+ values = values.view(out_features, blocks, NVFP4_BLOCK_SIZE).mul_(grid)
return values.view(out_features, blocks * NVFP4_BLOCK_SIZE)
-def dequantize_nvfp4_layers(
- sd: dict[str, Any], dtype: torch.dtype, reserve: Callable[[int], object] | None = None
-) -> int:
- """Decode every nvfp4 layer in ``sd`` to ``dtype`` in place, drop its side channel, return the count.
+class NVFP4Linear(DequantizingLinear):
+ """A linear layer storing Comfy nvfp4 weights, dequantized per forward.
+
+ Built from the checkpoint's tensors and registered as persistent buffers under their names, so
+ ``load_state_dict`` assigns them as stored. The block scales keep their tiled layout but are held as their
+ bytes: MPS cannot hold a float8 tensor, and the decode reads them through a table either way. Resident, a
+ layer costs about 0.56 bytes per weight element against bf16's 2.
+
+ The model cache wraps this module as ``CustomNVFP4Linear`` (see ``AUTOCAST_MODULE_TYPE_MAPPING``) for
+ sidecar LoRA patches, and a partial load that leaves its buffers on the CPU streams them per forward.
+ """
- Call it before any fp8 handling. The scaled-fp8 extraction pops every ``weight_scale`` in the file
- and discards those whose weight is not float8 -- nvfp4's block scales included -- and the folds that
- multiply a scale in would stretch the ``[out, in/16]`` grid over the packed ``[out, in/2]`` weight.
- Decided per layer, never per file: the same checkpoints mix nvfp4 with scaled fp8, whose weights,
- scales and markers are left for that path.
-
- Nothing is widened until everything has been checked: AWQ layers, packed weights with a
- ``weight_scale`` but no ``weight_scale_2``, markers that contradict their tensors and malformed
- layers are refused first, naming the layer. Then ``reserve`` -- a loader's ``make_room`` -- is called
- once with the size ``sd`` will have after decoding. The model cache reserves only the file size
- before a load and decoding more than triples it, so reserving afterwards would let the peak land on
- memory other cached models still hold.
+ def __init__(
+ self,
+ weight: torch.Tensor,
+ weight_scale: torch.Tensor,
+ weight_scale_2: torch.Tensor,
+ bias: torch.Tensor | None = None,
+ ) -> None:
+ super().__init__()
+ _check_layout(weight, weight_scale, weight_scale_2)
+ self.out_features = weight.shape[0]
+ self.in_features = weight.shape[1] * 2
+ self.register_buffer("weight", weight)
+ self.register_buffer("weight_scale", weight_scale.view(torch.uint8))
+ self.register_buffer("weight_scale_2", weight_scale_2)
+ if bias is not None:
+ self.register_buffer("bias", bias)
+ else:
+ self.bias = None
+
+ def _dequantized_weight(self, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
+ # `.to(device)` is a no-op when the module is resident; under partial load it streams the packed payload
+ # to the compute device for this call.
+ return _decode(self.weight.to(device), self.weight_scale, self.weight_scale_2, dtype)
+
+ def dequant_transient_bytes(self, compute_dtype: torch.dtype) -> int:
+ """The weight in the compute dtype, the int32 byte index it is gathered through, and the scale grid.
+
+ The grid's own widening happens first and peaks lower, at half a byte per weight element. Under partial
+ load the packed payload is additionally streamed per call; the resident regime pays nothing for that.
+ """
+ elements = self.out_features * self.in_features
+ return elements * (2 + compute_dtype.itemsize) + elements // NVFP4_BLOCK_SIZE * compute_dtype.itemsize
+
+ def extra_repr(self) -> str:
+ return f"in_features={self.in_features}, out_features={self.out_features}, nvfp4"
+
+
+@dataclass(frozen=True)
+class NVFP4Payload:
+ """One layer's packed tensors, as the checkpoint stores them."""
+
+ weight: torch.Tensor
+ weight_scale: torch.Tensor
+ weight_scale_2: torch.Tensor
+
+ @property
+ def out_features(self) -> int:
+ return self.weight.shape[0]
+
+ @property
+ def in_features(self) -> int:
+ return self.weight.shape[1] * 2
+
+ def nbytes(self) -> int:
+ return sum(t.nelement() * t.element_size() for t in (self.weight, self.weight_scale, self.weight_scale_2))
+
+
+def _find_nvfp4_layers(sd: Mapping[str, Any], header_layers: Mapping[str, Any] | None) -> list[str]:
+ """Every nvfp4 layer in ``sd``, after refusing what this module would read wrong. Mutates nothing.
+
+ Detection is structural -- a ``weight_scale_2`` beside the weight -- and decided per layer, never per
+ file. Refused, naming the layers: AWQ layers; markers that contradict their tensors; packed weights
+ with a ``weight_scale`` but no ``weight_scale_2``; malformed layers; and layers that neither a
+ ``.comfy_quant`` marker nor a ``_quantization_metadata`` entry (``header_layers``, in ``sd``'s key
+ space) names as nvfp4.
"""
layers = sorted(
k[: -len(WEIGHT_SCALE_2_SUFFIX)] for k in sd if isinstance(k, str) and k.endswith(WEIGHT_SCALE_2_SUFFIX)
@@ -158,13 +252,14 @@ def dequantize_nvfp4_layers(
"wrong weights."
)
+ marked: dict[str, Any] = {}
for key in [k for k in sd if isinstance(k, str) and k.endswith(COMFY_QUANT_SUFFIX)]:
path = key[: -len(COMFY_QUANT_SUFFIX)]
- marked = parse_comfy_quant_marker(sd[key]).get("format")
- if marked == NVFP4_FORMAT and path not in claimed:
+ marked[path] = parse_comfy_quant_marker(sd[key]).get("format")
+ if marked[path] == NVFP4_FORMAT and path not in claimed:
raise ValueError(f"nvfp4 layer '{path}' has no weight_scale_2, so it cannot be decoded.")
- if path in claimed and marked not in (None, NVFP4_FORMAT):
- raise ValueError(f"nvfp4 layer '{path}' is marked {marked!r}, which contradicts its tensors.")
+ if path in claimed and marked[path] not in (None, NVFP4_FORMAT):
+ raise ValueError(f"nvfp4 layer '{path}' is marked {marked[path]!r}, which contradicts its tensors.")
half = sorted(
weight_key
@@ -186,6 +281,42 @@ def dequantize_nvfp4_layers(
except ValueError as e:
raise ValueError(f"nvfp4 layer '{path}': {e}") from None
+ headers = header_layers or {}
+ unnamed = [
+ path
+ for path in layers
+ if marked.get(path) != NVFP4_FORMAT
+ and not (isinstance(headers.get(path), Mapping) and headers[path].get("format") == NVFP4_FORMAT)
+ ]
+ if unnamed:
+ raise ValueError(
+ f"Checkpoint has {len(unnamed)} layer(s) laid out like nvfp4 that no ComfyUI `comfy_quant` marker or "
+ f"`_quantization_metadata` entry names, e.g. {unnamed[:3]}. Only ComfyUI's conventions for this layout "
+ "are known here; reading another producer's file by them could load a model that runs and generates "
+ "wrong images. Use a ComfyUI nvfp4 build or the unquantized model. If this file does name its layers, "
+ "look for a warning that its safetensors header could not be read."
+ )
+ return layers
+
+
+def dequantize_nvfp4_layers(
+ sd: dict[str, Any],
+ dtype: torch.dtype,
+ reserve: Callable[[int], object] | None = None,
+ header_layers: Mapping[str, Any] | None = None,
+) -> int:
+ """Decode every nvfp4 layer in ``sd`` to ``dtype`` in place, drop its side channel, return the count.
+
+ For loaders that do not keep the layers packed. Call it before any fp8 handling, for the reasons given
+ at :func:`pop_nvfp4_layers`; the scaled-fp8 weights, scales and markers of a mixed file are left for
+ that path.
+
+ Nothing is widened until every layer has been checked. Then ``reserve`` -- a loader's ``make_room`` --
+ is called once with the size ``sd`` will have after decoding. The model cache reserves only the file
+ size before a load and decoding more than triples it, so reserving afterwards would let the peak land
+ on memory other cached models still hold.
+ """
+ layers = _find_nvfp4_layers(sd, header_layers)
if not layers:
return 0
if reserve is not None:
@@ -198,6 +329,131 @@ def dequantize_nvfp4_layers(
return len(layers)
+def pop_nvfp4_layers(sd: dict[str, Any], header_layers: Mapping[str, Any] | None = None) -> dict[str, NVFP4Payload]:
+ """Take every nvfp4 layer's packed tensors out of ``sd`` and drop the rest of its side channel.
+
+ For loaders that keep the layers packed. Call it before any fp8 handling or cast: the scaled-fp8
+ extraction pops every ``weight_scale`` and discards those whose weight is not float8 -- nvfp4's block
+ scales included -- and a cast would widen the packed payload. Out of ``sd`` they survive both, and
+ :func:`install_nvfp4_layers` puts them back. Whatever a decode would refuse is refused before ``sd``
+ is touched.
+ """
+ payloads: dict[str, NVFP4Payload] = {}
+ for path in _find_nvfp4_layers(sd, header_layers):
+ payloads[path] = NVFP4Payload(
+ weight=sd.pop(f"{path}.weight"),
+ weight_scale=sd.pop(f"{path}.weight_scale"),
+ weight_scale_2=sd.pop(f"{path}{WEIGHT_SCALE_2_SUFFIX}"),
+ )
+ for suffix in _SIDE_CHANNEL_SUFFIXES:
+ sd.pop(f"{path}{suffix}", None)
+ return payloads
+
+
+def split_nvfp4_rows(path: str, payload: NVFP4Payload, parts: int) -> list[NVFP4Payload]:
+ """Split a fused projection's packed tensors into ``parts`` equal row ranges, in order -- a QKV into Q, K, V.
+
+ The block scales split by rows too, but only on whole tile rows (see :func:`unblock_scale_grid`): a part
+ made of whole tile rows is a valid grid of its own, while any other cut hands one part another's scales.
+ That is refused rather than guessed. The global scale belongs to every part.
+ """
+ rows = payload.out_features
+ if rows % parts or (rows // parts) % _TILE_ROWS:
+ raise ValueError(
+ f"nvfp4 layer '{path}': its {rows} rows do not split into {parts} parts of whole {_TILE_ROWS}-row "
+ "scale tiles."
+ )
+ step = rows // parts
+ return [
+ NVFP4Payload(
+ payload.weight[start : start + step], payload.weight_scale[start : start + step], payload.weight_scale_2
+ )
+ for start in range(0, rows, step)
+ ]
+
+
+def predict_nvfp4_install_size(
+ model: torch.nn.Module,
+ payloads: Mapping[str, NVFP4Payload],
+ dtype: torch.dtype,
+ skip_patterns: Iterable[str] = (),
+) -> int:
+ """Bytes the payloads occupy once :func:`install_nvfp4_layers` has run over them with the same arguments.
+
+ The packed tensors for layers that stay packed, the compute dtype for the ones it decodes. Loaders add
+ this to the reservation they make for the rest of the state dict, which no longer holds these layers.
+ """
+ patterns = tuple(skip_patterns)
+ return sum(
+ payload.nbytes()
+ if _stays_packed(model, path, payload, patterns)
+ else payload.out_features * payload.in_features * dtype.itemsize
+ for path, payload in payloads.items()
+ )
+
+
+def install_nvfp4_layers(
+ model: torch.nn.Module,
+ sd: dict[str, Any],
+ payloads: Mapping[str, NVFP4Payload],
+ dtype: torch.dtype,
+ skip_patterns: Iterable[str] = (),
+) -> int:
+ """Put the nvfp4 layers into the built model and ``sd``; return how many stay packed.
+
+ A layer stays packed as an :class:`NVFP4Linear` where the model has an ``nn.Linear`` outside its
+ precision-sensitive modules (``skip_patterns``). Anything else gets its weight decoded to ``dtype``:
+ Z-Image's timestep embedder reads its own weight's dtype to pick the dtype of its activations, and a
+ packed module there would hand it ``torch.uint8``.
+
+ Call it after the state dict's casts and right before a strict ``load_state_dict(sd, assign=True)``,
+ with ``sd`` and ``payloads`` in the model's key space. A packed layer's ``bias`` is taken from ``sd``.
+ """
+ patterns = tuple(skip_patterns)
+ packed = 0
+ for path, payload in payloads.items():
+ if not _stays_packed(model, path, payload, patterns):
+ sd[f"{path}.weight"] = dequantize_nvfp4_weight(
+ payload.weight, payload.weight_scale, payload.weight_scale_2, dtype
+ )
+ continue
+ module = NVFP4Linear(payload.weight, payload.weight_scale, payload.weight_scale_2, bias=sd.get(f"{path}.bias"))
+ # The strict load that follows checks keys against the new module, not the model's Linear, so a bias one of
+ # them has and the other lacks would pass it unnoticed.
+ if (module.bias is None) != (model.get_submodule(path).bias is None):
+ raise ValueError(
+ f"nvfp4 layer '{path}' has {'no' if module.bias is None else 'a'} bias, but the built model's Linear "
+ f"there has {'one' if module.bias is None else 'none'}. The checkpoint is misidentified."
+ )
+ parent_path, _, attribute = path.rpartition(".")
+ setattr(model.get_submodule(parent_path) if parent_path else model, attribute, module)
+ # The strict load assigns every buffer from `sd`, so it has to find them as the module holds them.
+ sd.update(module.state_dict(prefix=f"{path}."))
+ packed += 1
+ return packed
+
+
+def _stays_packed(model: torch.nn.Module, path: str, payload: NVFP4Payload, skip_patterns: tuple[str, ...]) -> bool:
+ """Whether a layer stays packed: the one decision the install and its size prediction share."""
+ try:
+ module = model.get_submodule(path)
+ except AttributeError:
+ raise ValueError(
+ f"nvfp4 layer '{path}' names no module in the built model. The checkpoint is misidentified, or its "
+ "keys need a conversion this loader did not apply."
+ ) from None
+ if not isinstance(module, torch.nn.Linear) or any(pattern in path for pattern in skip_patterns):
+ return False
+ # The strict load checks a decoded weight's shape against its parameter, but assigns packed buffers into a new
+ # module unchecked, so a mismatch would only surface inside the forward.
+ if (module.out_features, module.in_features) != (payload.out_features, payload.in_features):
+ raise ValueError(
+ f"nvfp4 layer '{path}' holds a {payload.out_features}x{payload.in_features} weight, but the built model's "
+ f"Linear there is {module.out_features}x{module.in_features}. The checkpoint is misidentified."
+ )
+ return True
+
+
def _decoded_size(sd: dict[str, Any], layers: list[str], dtype: torch.dtype) -> int:
"""Bytes ``sd`` occupies once ``layers`` are decoded to ``dtype`` and their side channels dropped."""
replaced = {f"{path}{suffix}" for path in layers for suffix in (".weight", *_SIDE_CHANNEL_SUFFIXES)}
diff --git a/tests/app/invocations/test_int8_denoise_working_memory.py b/tests/app/invocations/test_int8_denoise_working_memory.py
index c6e05d3c2f..70add2f220 100644
--- a/tests/app/invocations/test_int8_denoise_working_memory.py
+++ b/tests/app/invocations/test_int8_denoise_working_memory.py
@@ -5,7 +5,7 @@ forward. That allocation is not part of the model's resident size, so unless the
cache to hold room for it, the cache is free to pack the device with weights right up to the
default working memory and the first forward competes with what it just placed.
-`peak_int8_dequant_transient_bytes` is unit-tested next to the module it belongs to. What is
+`peak_dequant_transient_bytes` is unit-tested next to the modules it reads. What is
pinned here is the wire: deleting the `working_mem_bytes=` argument from the node leaves every
other test green. Z-Image only -- MiniMax H3 adds the same term; reaching its `model_on_device()` call needs a packed sequence.
Krea-2's wiring is pinned separately, in `tests/app/invocations/test_krea2_denoise.py`.
diff --git a/tests/app/invocations/test_krea2_denoise.py b/tests/app/invocations/test_krea2_denoise.py
index 28129b7d93..13fac5dbd8 100644
--- a/tests/app/invocations/test_krea2_denoise.py
+++ b/tests/app/invocations/test_krea2_denoise.py
@@ -13,7 +13,8 @@ from invokeai.app.invocations.krea2.krea2_denoise import (
)
from invokeai.app.invocations.model import ModelIdentifierField, TransformerField
from invokeai.backend.model_manager.taxonomy import BaseModelType, Krea2VariantType, ModelFormat, ModelType
-from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear, peak_int8_dequant_transient_bytes
+from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes
+from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData, Krea2ConditioningInfo
@@ -839,6 +840,6 @@ class TestTheInt8DequantTransientReachesTheReservation:
quantized_bytes = self._reservation_for(monkeypatch, tmp_path, quantized)
# `_patch_runtime` pins the compute dtype to float32, which is what the node passes on.
- transient = peak_int8_dequant_transient_bytes(quantized, torch.float32)
+ transient = peak_dequant_transient_bytes(quantized, torch.float32)
assert transient > 0
assert quantized_bytes == dense_bytes + transient
diff --git a/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.py b/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.py
index fc905fce2c..2d98d94e23 100644
--- a/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.py
+++ b/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.py
@@ -40,37 +40,48 @@ def _marker_blob(marker: dict) -> torch.Tensor:
return torch.frombuffer(bytearray(json.dumps(marker).encode("utf-8")), dtype=torch.uint8)
-def _write_checkpoint(tmp_path: Path) -> tuple[Path, dict[str, torch.Tensor], torch.Tensor]:
+def _write_checkpoint(tmp_path: Path, evidence: str) -> tuple[Path, dict[str, torch.Tensor], torch.Tensor]:
"""A Comfy-style fp4_mixed Mistral: nvfp4 projections, one scaled-fp8 projection, bf16 for the rest.
+ The nvfp4 layers are named by per-tensor markers, as in Comfy-Org's build, or -- with `evidence="header"` --
+ only in the `_quantization_metadata` header, with every key under the `language_model.` wrapper prefix some
+ redistributions add. The loader strips that prefix from the keys and has to strip it from the header's
+ names as well, or it refuses the layers as unnamed.
+
Returns the file, the weights the nvfp4 projections must load as, and the fp8 projection's
dequantized weight. Codes 2 and 10 decode to +1.0 and -1.0, so no E2M1 table is needed here.
"""
torch.manual_seed(0)
+ prefix = "language_model." if evidence == "header" else ""
tensors: dict[str, torch.Tensor] = {}
expected: dict[str, torch.Tensor] = {}
+ header: dict[str, dict[str, str]] = {}
for name, shape in NVFP4_PROJECTIONS.items():
positive = torch.randint(0, 2, shape, dtype=torch.bool)
codes = torch.where(positive, 2, 10).to(torch.uint8)
- path = f"model.layers.0.{name}"
+ path = f"{prefix}model.layers.0.{name}"
tensors[f"{path}.weight"] = (codes[:, 0::2] << 4) | codes[:, 1::2]
tensors[f"{path}.weight_scale"] = torch.full((shape[0], shape[1] // 16), 2.0).to(torch.float8_e4m3fn)
tensors[f"{path}.weight_scale_2"] = torch.tensor(0.25)
- tensors[f"{path}.comfy_quant"] = _marker_blob({"format": "nvfp4"})
+ if evidence == "header":
+ header[path] = {"format": "nvfp4"}
+ else:
+ tensors[f"{path}.comfy_quant"] = _marker_blob({"format": "nvfp4"})
expected[f"layers.0.{name}.weight"] = torch.where(positive, 0.5, -0.5)
fp8_values = torch.randint(-8, 9, (HIDDEN, HIDDEN)).float()
- tensors["model.layers.0.self_attn.v_proj.weight"] = fp8_values.to(torch.float8_e4m3fn)
- tensors["model.layers.0.self_attn.v_proj.weight_scale"] = torch.tensor(0.5)
- tensors["model.layers.0.self_attn.v_proj.comfy_quant"] = _marker_blob({"format": "float8_e4m3fn"})
+ tensors[f"{prefix}model.layers.0.self_attn.v_proj.weight"] = fp8_values.to(torch.float8_e4m3fn)
+ tensors[f"{prefix}model.layers.0.self_attn.v_proj.weight_scale"] = torch.tensor(0.5)
+ tensors[f"{prefix}model.layers.0.self_attn.v_proj.comfy_quant"] = _marker_blob({"format": "float8_e4m3fn"})
- tensors["model.embed_tokens.weight"] = torch.randn(VOCAB, HIDDEN)
+ tensors[f"{prefix}model.embed_tokens.weight"] = torch.randn(VOCAB, HIDDEN)
for norm in ("model.layers.0.input_layernorm", "model.layers.0.post_attention_layernorm", "model.norm"):
- tensors[f"{norm}.weight"] = torch.ones(HIDDEN)
+ tensors[f"{prefix}{norm}.weight"] = torch.ones(HIDDEN)
tensors["tekken_model"] = torch.randint(0, 256, (64,), dtype=torch.uint8)
checkpoint = tmp_path / "mistral_3_small_flux2_fp4_mixed.safetensors"
- save_file(tensors, checkpoint)
+ metadata = {"_quantization_metadata": json.dumps({"layers": header})} if header else None
+ save_file(tensors, checkpoint, metadata=metadata)
return checkpoint, expected, fp8_values * 0.5
@@ -83,11 +94,15 @@ def _loader(monkeypatch: pytest.MonkeyPatch, keep_fp8: bool) -> MistralEncoderCh
return loader
[email protected]("keep_fp8", [False, True], ids=["fp8_dequantized", "fp8_kept"])
+ ("keep_fp8", "evidence"),
+ [(False, "marker"), (True, "marker"), (False, "header")],
+ ids=["fp8_dequantized", "fp8_kept", "named_in_prefixed_header"],
+)
def test_an_nvfp4_mixed_checkpoint_loads_under_either_fp8_branch(
- monkeypatch: pytest.MonkeyPatch, tmp_path: Path, keep_fp8: bool
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, keep_fp8: bool, evidence: str
) -> None:
- checkpoint, expected, fp8_dequantized = _write_checkpoint(tmp_path)
+ checkpoint, expected, fp8_dequantized = _write_checkpoint(tmp_path, evidence)
loader = _loader(monkeypatch, keep_fp8)
config = MistralEncoder_Checkpoint_Config.model_construct(path=str(checkpoint), variant=MistralVariantType.Cow)
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.py
index 53acb14bd3..a372e8a26e 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
@@ -16,6 +16,7 @@ import torch
from invokeai.backend.model_manager.configs.main import Main_Checkpoint_ZImage_Config
from invokeai.backend.model_manager.load.model_loaders.z_image import ZImageCheckpointModel
from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, Int8ConvrotLinear, build_regular_hadamard
+from invokeai.backend.quantization.nvfp4 import NVFP4Linear
MARKER = {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": CONVROT_GROUP_SIZE}
@@ -193,57 +194,118 @@ class _TinyAttention(torch.nn.Module):
self.to_v = torch.nn.Linear(64, 128, bias=False)
-class _TinyAttentionBlock(torch.nn.Module):
+class _TinyNativeBlock(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.attention = _TinyAttention()
+ self.adaLN_modulation = torch.nn.Sequential(torch.nn.Linear(64, 128))
+
+
+class _TinyNvfp4TimestepEmbedder(torch.nn.Module):
+ def __init__(self) -> None:
+ super().__init__()
+ self.mlp = torch.nn.ModuleList([torch.nn.Linear(64, 128, bias=False)])
class _TinyNativeZImage(torch.nn.Module):
- """What the native-to-diffusers conversion makes of a checkpoint with a fused `attention.qkv`."""
+ """What the native-to-diffusers conversion makes of a checkpoint with a fused `attention.qkv`, beside the
+ timestep embedder Z-Image declares precision-sensitive."""
+
+ _skip_layerwise_casting_patterns = ["t_embedder", "cap_embedder"]
def __init__(self, **_kwargs) -> None:
super().__init__()
self.all_x_embedder = torch.nn.ModuleDict({"2-1": torch.nn.Linear(4, 4, bias=False)})
- self.layers = torch.nn.ModuleList([_TinyAttentionBlock()])
+ self.t_embedder = _TinyNvfp4TimestepEmbedder()
+ self.layers = torch.nn.ModuleList([_TinyNativeBlock()])
+
+
+def _nvfp4_layer(
+ path: str, positive: torch.Tensor, tile_row_scales: list[float], global_scale: float
+) -> dict[str, torch.Tensor]:
+ """One layer as Comfy stores it. Codes 2 and 10 decode to +1.0 and -1.0, so the expected weight needs no
+ E2M1 table, and a block scale constant over each 128-row tile row reads the same tiled as row by row."""
+ codes = torch.where(positive, 2, 10).to(torch.uint8)
+ scales = torch.tensor(tile_row_scales).repeat_interleave(128).unsqueeze(1).repeat(1, positive.shape[1] // 16)
+ return {
+ f"{path}.weight": (codes[:, 0::2] << 4) | codes[:, 1::2],
+ f"{path}.weight_scale": scales.to(torch.float8_e4m3fn),
+ f"{path}.weight_scale_2": torch.tensor(global_scale),
+ }
-def test_an_nvfp4_checkpoint_is_decoded_before_the_qkv_split(monkeypatch, tmp_path) -> None:
+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 decode has to run before the key conversion and the scaled-fp8 extraction,
- with room reserved for its result first. Without it the strict load meets a packed weight and an
- orphaned `weight_scale_2`; placed after the conversion or the extraction, it finds its layers
- incomplete and refuses them."""
+ 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."""
torch.manual_seed(4)
- # Codes 2 and 10 decode to +1.0 and -1.0, so the expected weight needs no E2M1 table.
- positive = torch.randint(0, 2, (384, 64), dtype=torch.bool)
- codes = torch.where(positive, 2, 10).to(torch.uint8)
+ qkv, modulation, timestep, bundled = (
+ torch.randint(0, 2, (rows, 64), dtype=torch.bool) for rows in (384, 128, 128, 128)
+ )
+ modulation_bias = torch.randn(128)
embedder = torch.randn(4, 4)
state_dict = {
"x_embedder.weight": embedder,
- "layers.0.attention.qkv.weight": (codes[:, 0::2] << 4) | codes[:, 1::2],
- "layers.0.attention.qkv.weight_scale": torch.full((384, 4), 2.0).to(torch.float8_e4m3fn),
- "layers.0.attention.qkv.weight_scale_2": torch.tensor(0.25),
+ **_nvfp4_layer("layers.0.attention.qkv", qkv, [1.0, 2.0, 4.0], global_scale=0.5),
"layers.0.attention.qkv.input_scale": torch.tensor(1.0),
+ **_nvfp4_layer("layers.0.adaLN_modulation.0", modulation, [2.0], global_scale=0.25),
+ "layers.0.adaLN_modulation.0.bias": modulation_bias,
+ **_nvfp4_layer("t_embedder.mlp.0", timestep, [2.0], global_scale=0.25),
+ **_nvfp4_layer("text_encoders.qwen3.layers.0.mlp.up_proj", bundled, [2.0], global_scale=0.25),
+ }
+ header = {
+ path: {"format": "nvfp4"}
+ for path in (
+ "layers.0.attention.qkv",
+ "layers.0.adaLN_modulation.0",
+ "t_embedder.mlp.0",
+ "text_encoders.qwen3.layers.0.mlp.up_proj",
+ )
}
loader, config = _driver(monkeypatch, tmp_path, state_dict)
import diffusers
monkeypatch.setattr(diffusers, "ZImageTransformer2DModel", _TinyNativeZImage, raising=False)
- # The decode works on the very dict `load_file` returned, so the weight's dtype at each reservation
- # tells whether that reservation came before the widening.
- reservations = []
- loader._ram_cache.make_room.side_effect = lambda size: reservations.append(
- (size, state_dict["layers.0.attention.qkv.weight"].dtype)
+ 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,
)
model = loader._load_from_singlefile(config)
- expected = torch.where(positive, 0.5, -0.5)
+ bf16 = torch.bfloat16
+ x = torch.randn(3, 64, dtype=bf16)
attention = model.layers[0].attention
- assert torch.equal(attention.to_q.weight, expected[:128])
- assert torch.equal(attention.to_k.weight, expected[128:256])
- assert torch.equal(attention.to_v.weight, expected[256:])
- assert torch.equal(model.all_x_embedder["2-1"].weight, embedder)
- # First the decoded float32 qkv plus the embedder, asked for while the weight was still packed.
- assert reservations[0] == (384 * 64 * 4 + 4 * 4 * 4, torch.uint8)
+ for projection, signs, magnitude in (
+ (attention.to_q, qkv[:128], 0.5),
+ (attention.to_k, qkv[128:256], 1.0),
+ (attention.to_v, qkv[256:], 2.0),
+ ):
+ assert isinstance(projection, NVFP4Linear)
+ assert projection.weight.dtype is torch.uint8
+ expected = torch.where(signs, magnitude, -magnitude).to(bf16)
+ assert torch.equal(projection(x), torch.nn.functional.linear(x, expected))
+ adaln = model.layers[0].adaLN_modulation[0]
+ assert isinstance(adaln, NVFP4Linear)
+ expected = torch.nn.functional.linear(x, torch.where(modulation, 0.5, -0.5).to(bf16), modulation_bias.to(bf16))
+ assert torch.equal(adaln(x), expected)
+ assert type(model.t_embedder.mlp[0]) is torch.nn.Linear
+ assert torch.equal(model.t_embedder.mlp[0].weight, torch.where(timestep, 0.5, -0.5).to(bf16))
+ assert torch.equal(model.all_x_embedder["2-1"].weight, embedder.to(bf16))
+
+ # One reservation for what the model ends up holding: the packed tensors as stored, and the decoded embedder
+ # and the dense rest at two bytes. Not the bundled layer, and not the packed layers at their decoded size,
+ # which would ask for about 45 KB more.
+ packed = (384 + 128) * 32 + (384 + 128) * 4
+ dense = 128 * 64 * 2 + 128 * 2 + 4 * 4 * 2
+ loader._ram_cache.make_room.assert_called_once()
+ (reserved,), _ = loader._ram_cache.make_room.call_args
+ assert packed + dense <= reserved < packed + dense + 1024
diff --git a/tests/backend/quantization/test_int8_convrot.py b/tests/backend/quantization/test_int8_convrot.py
index 5f74717467..421d5934fa 100644
--- a/tests/backend/quantization/test_int8_convrot.py
+++ b/tests/backend/quantization/test_int8_convrot.py
@@ -12,6 +12,7 @@ import pytest
import torch
from invokeai.backend.model_manager.taxonomy import ModelFormat
+from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes, requires_sidecar_patching
from invokeai.backend.quantization.int8_convrot import (
CONVROT_GROUP_SIZE,
Int8ConvrotLinear,
@@ -19,8 +20,6 @@ from invokeai.backend.quantization.int8_convrot import (
dequantize_convrot_weight,
extract_int8_convrot_markers,
parse_comfy_quant_marker,
- peak_int8_dequant_transient_bytes,
- requires_sidecar_patching,
shared_regular_hadamard,
)
@@ -337,10 +336,10 @@ class TestThePerForwardDequantTransient:
multiplied into, and that product is alive alongside the derotation matmul's output."""
model = self._model((4, CONVROT_GROUP_SIZE), (16, CONVROT_GROUP_SIZE))
- assert peak_int8_dequant_transient_bytes(model, torch.bfloat16) == 2 * 16 * CONVROT_GROUP_SIZE * 2
+ assert peak_dequant_transient_bytes(model, torch.bfloat16) == 2 * 16 * CONVROT_GROUP_SIZE * 2
def test_a_model_with_no_quantized_layers_needs_nothing(self) -> None:
model = torch.nn.Module()
model.dense = torch.nn.Linear(8, 8)
- assert peak_int8_dequant_transient_bytes(model, torch.bfloat16) == 0
+ assert peak_dequant_transient_bytes(model, torch.bfloat16) == 0
diff --git a/tests/backend/quantization/test_nvfp4.py b/tests/backend/quantization/test_nvfp4.py
index e711f9a483..766e8bfdae 100644
--- a/tests/backend/quantization/test_nvfp4.py
+++ b/tests/backend/quantization/test_nvfp4.py
@@ -1,4 +1,4 @@
-"""nvfp4 decode: byte layout, block-scale layout, and the per-layer state-dict pass.
+"""nvfp4: byte layout, block-scale layout, the per-layer state-dict passes and the packed module.
No expected value here comes from `nvfp4.py` itself. Nibble order and the E2M1 table are checked
against literal bytes; the block-scale layout against the index formula measured on real checkpoints,
@@ -14,7 +14,25 @@ import pytest
import torch
from safetensors.torch import load_file
-from invokeai.backend.quantization.nvfp4 import dequantize_nvfp4_layers, dequantize_nvfp4_weight, unblock_scale_grid
+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.taxonomy import ModelFormat
+from invokeai.backend.patches.layer_patcher import LayerPatcher
+from invokeai.backend.patches.layers.full_layer import FullLayer
+from invokeai.backend.patches.layers.lora_layer import LoRALayer
+from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
+from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes, requires_sidecar_patching
+from invokeai.backend.quantization.nvfp4 import (
+ NVFP4Linear,
+ dequantize_nvfp4_layers,
+ dequantize_nvfp4_weight,
+ install_nvfp4_layers,
+ pop_nvfp4_layers,
+ predict_nvfp4_install_size,
+ split_nvfp4_rows,
+ unblock_scale_grid,
+)
FIXTURE = Path(__file__).parent / "data" / "z_image_turbo_nvfp4_slices.safetensors"
@@ -38,13 +56,14 @@ def _stored_layout(grid: torch.Tensor) -> torch.Tensor:
def _nvfp4_tensors(path: str, codes: torch.Tensor, block_scale: float, global_scale: float) -> dict[str, torch.Tensor]:
- """One layer in checkpoint layout. A uniform block scale keeps the expectation independent of the
+ """One marked layer in checkpoint layout. A uniform block scale keeps the expectation independent of the
tile layout, which the tests above pin on their own."""
rows, in_features = codes.shape
return {
f"{path}.weight": (codes[:, 0::2] << 4) | codes[:, 1::2],
f"{path}.weight_scale": torch.full((rows, in_features // 16), block_scale).to(torch.float8_e4m3fn),
f"{path}.weight_scale_2": torch.tensor(global_scale),
+ f"{path}.comfy_quant": _marker_blob({"format": "nvfp4"}),
}
@@ -52,6 +71,17 @@ def _zero_layer(path: str, rows: int = 128) -> dict[str, torch.Tensor]:
return _nvfp4_tensors(path, torch.zeros(rows, 64, dtype=torch.uint8), 1.0, 1.0)
+def _signed_layer(path: str, positive: torch.Tensor) -> dict[str, torch.Tensor]:
+ """Codes 2 and 10 are +1.0 and -1.0; with a block scale of 2 and a global scale of 0.25 the weight is +-0.5."""
+ return _nvfp4_tensors(path, torch.where(positive, 2, 10).to(torch.uint8), block_scale=2.0, global_scale=0.25)
+
+
+def _packed_linear(tensors: dict[str, torch.Tensor], path: str, bias: torch.Tensor | None = None) -> NVFP4Linear:
+ return NVFP4Linear(
+ tensors[f"{path}.weight"], tensors[f"{path}.weight_scale"], tensors[f"{path}.weight_scale_2"], bias=bias
+ )
+
+
def test_the_upper_nibble_is_the_first_element_and_both_scales_multiply() -> None:
weight = torch.zeros(128, 32, dtype=torch.uint8)
# Every code once: 0x7F is 7 then 15, 0x19 is 1 then 9, and so on.
@@ -104,6 +134,11 @@ def test_a_real_checkpoint_slice_decodes_to_its_bf16_build(layer: str) -> None:
naive = dequantize_nvfp4_weight(weight, row_major, scale_2, torch.float32).flatten()
assert torch.cosine_similarity(naive, reference, dim=0).item() < 0.95
+ # The packed module keeps the block scales as bytes and has to compute with exactly this weight.
+ x = torch.randn(2, 128)
+ module = NVFP4Linear(weight, scale, scale_2)
+ assert torch.equal(module(x), torch.nn.functional.linear(x, decoded.view(128, 128)))
+
@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16])
def test_only_nvfp4_layers_are_decoded_and_the_rest_is_left_for_the_fp8_path(dtype: torch.dtype) -> None:
@@ -117,7 +152,6 @@ def test_only_nvfp4_layers_are_decoded_and_the_rest_is_left_for_the_fp8_path(dty
sd = {
**_nvfp4_tensors("blocks.0.mlp", codes, block_scale=2.0, global_scale=0.25),
"blocks.0.mlp.input_scale": torch.tensor(1.0),
- "blocks.0.mlp.comfy_quant": _marker_blob({"format": "nvfp4"}),
"blocks.0.attn.weight": fp8_weight,
"blocks.0.attn.weight_scale": fp8_scale,
"blocks.0.attn.comfy_quant": fp8_marker,
@@ -138,6 +172,45 @@ def test_only_nvfp4_layers_are_decoded_and_the_rest_is_left_for_the_fp8_path(dty
assert sd["tekken_model"] is tekken
+def test_popped_layers_keep_their_tensors_as_stored_and_leave_the_rest_in_place() -> None:
+ fp8_weight = torch.randn(32, 32).to(torch.float8_e4m3fn)
+ sd = {
+ **_zero_layer("blocks.0.mlp"),
+ "blocks.0.mlp.input_scale": torch.tensor(1.0),
+ "blocks.0.mlp.bias": torch.zeros(128),
+ "blocks.0.attn.weight": fp8_weight,
+ "blocks.0.attn.weight_scale": torch.tensor(0.5),
+ }
+ weight, scale = sd["blocks.0.mlp.weight"], sd["blocks.0.mlp.weight_scale"]
+
+ payloads = pop_nvfp4_layers(sd)
+
+ assert list(payloads) == ["blocks.0.mlp"]
+ assert payloads["blocks.0.mlp"].weight is weight
+ assert payloads["blocks.0.mlp"].weight_scale is scale
+ # The bias is an ordinary tensor the loader casts; everything else of the layer is gone.
+ assert sorted(sd) == ["blocks.0.attn.weight", "blocks.0.attn.weight_scale", "blocks.0.mlp.bias"]
+
+
+def test_a_layer_only_the_safetensors_header_names_is_read() -> None:
+ """Comfy's Z-Image build names its nvfp4 layers in `_quantization_metadata` and writes no per-tensor marker."""
+ sd = _zero_layer("layer")
+ del sd["layer.comfy_quant"]
+
+ assert dequantize_nvfp4_layers(sd, torch.float32, header_layers={"layer": {"format": "nvfp4"}}) == 1
+
+
+def test_a_layer_nothing_names_as_nvfp4_is_refused_rather_than_read_by_comfy_conventions() -> None:
+ """Other producers write the same key names, and nothing guarantees they share ComfyUI's nibble order or
+ block-scale layout; a wrong guess loads a model that runs and generates degraded images."""
+ sd = _zero_layer("layer")
+ del sd["layer.comfy_quant"]
+
+ with pytest.raises(ValueError, match="laid out like nvfp4 that no ComfyUI"):
+ pop_nvfp4_layers(sd, header_layers={"other": {"format": "nvfp4"}})
+ assert "layer.weight" in sd
+
+
def test_room_for_the_decoded_state_dict_is_reserved_before_any_layer_is_widened() -> None:
sd = {**_zero_layer("layer", rows=256), "layer.input_scale": torch.tensor(1.0), "norm.weight": torch.zeros(10)}
reservations: list[tuple[int, torch.dtype]] = []
@@ -168,7 +241,7 @@ def test_an_awq_checkpoint_is_refused_before_anything_is_decoded() -> None:
def test_a_packed_weight_without_its_global_scale_is_refused() -> None:
sd = _zero_layer("layer")
- del sd["layer.weight_scale_2"]
+ del sd["layer.weight_scale_2"], sd["layer.comfy_quant"]
with pytest.raises(ValueError, match="with a weight_scale but no weight_scale_2"):
dequantize_nvfp4_layers(sd, torch.float32)
@@ -215,3 +288,130 @@ def test_a_marker_that_contradicts_its_tensors_is_refused(tensors: str, marker:
with pytest.raises(ValueError, match=message):
dequantize_nvfp4_layers(sd, torch.float32)
+
+
+ ("module", "extra", "message"),
+ [
+ (None, {}, "names no module"),
+ (torch.nn.Linear(64, 256, bias=False), {}, "holds a 128x64 weight"),
+ (torch.nn.Linear(64, 128, bias=True), {}, "has no bias"),
+ (torch.nn.Linear(64, 128, bias=False), {"proj.bias": torch.zeros(128)}, "has a bias"),
+ ],
+ ids=["missing_module", "other_shape", "missing_bias", "surplus_bias"],
+)
+def test_a_layer_the_built_model_cannot_hold_is_refused_at_load(
+ module: torch.nn.Module | None, extra: dict[str, torch.Tensor], message: str
+) -> None:
+ """Once a packed module replaces the model's Linear, a strict load checks the new module's keys and assigns
+ its buffers unchecked, so none of these mismatches would stop it; they would surface in the forward, if at
+ all."""
+ model = torch.nn.Module()
+ if module is not None:
+ model.proj = module
+ sd = {**_zero_layer("proj"), **extra}
+ payloads = pop_nvfp4_layers(sd)
+
+ with pytest.raises(ValueError, match=message):
+ predict_nvfp4_install_size(model, payloads, torch.float32)
+ install_nvfp4_layers(model, sd, payloads, torch.float32)
+
+
+def test_a_fused_layer_splits_on_whole_tile_rows_and_each_part_keeps_its_own_scales() -> None:
+ sd = _nvfp4_tensors("fused", torch.full((256, 64), 2, dtype=torch.uint8), block_scale=1.0, global_scale=0.5)
+ # One scale per tile row reads the same tiled as row by row, so each part's scale is known without the layout.
+ tile_row_scales = torch.tensor([[1.0], [4.0]]).repeat_interleave(128, dim=0).repeat(1, 4)
+ sd["fused.weight_scale"] = tile_row_scales.to(torch.float8_e4m3fn)
+ (payload,) = pop_nvfp4_layers(sd).values()
+
+ first, second = split_nvfp4_rows("fused", payload, 2)
+
+ for part, value in ((first, 0.5), (second, 2.0)):
+ decoded = dequantize_nvfp4_weight(part.weight, part.weight_scale, part.weight_scale_2, torch.float32)
+ assert torch.equal(decoded, torch.full((128, 64), value))
+ with pytest.raises(ValueError, match="whole 128-row scale tiles"):
+ split_nvfp4_rows("fused", payload, 4)
+
+
+def test_a_lora_rides_as_a_sidecar_over_the_packed_weight() -> None:
+ """Patches cannot be written into packed buffers, so the model has to be recognised as needing sidecars, and
+ the wrapper has to hand patches that are not LoRAs the unpacked weight shape to be reshaped to."""
+ torch.manual_seed(2)
+ positive = torch.randint(0, 2, (128, 64), dtype=torch.bool)
+ bias = torch.randn(128)
+ model = torch.nn.Module()
+ model.proj = _packed_linear(_signed_layer("proj", positive), "proj", bias=bias)
+ apply_custom_layers_to_model(model)
+ up, down, full = torch.randn(128, 4), torch.randn(4, 64), torch.randn(128, 64)
+ lora = ModelPatchRaw(layers={"lora-proj": LoRALayer(up=up, mid=None, down=down, alpha=None, bias=None)})
+ full_diff = ModelPatchRaw(layers={"lora-proj": FullLayer(weight=full, bias=None)})
+ x = torch.randn(3, 64)
+
+ with LayerPatcher.apply_smart_model_patches(
+ model=model,
+ patches=[(lora, 0.75), (full_diff, 0.5)],
+ prefix="lora-",
+ dtype=torch.float32,
+ force_sidecar_patching=requires_sidecar_patching(model, ModelFormat.Checkpoint),
+ ):
+ patched = model.proj(x)
+
+ dense = torch.where(positive, 0.5, -0.5)
+ expected = torch.nn.functional.linear(x, dense + 0.75 * (up @ down) + 0.5 * full, bias)
+ assert torch.allclose(patched, expected, atol=1e-4)
+ assert model.proj.get_num_patches() == 0
+ assert torch.equal(model.proj(x), torch.nn.functional.linear(x, dense, bias))
+
+
[email protected](not torch.cuda.is_available(), reason="measures CUDA allocations")
[email protected]("dtype", [torch.bfloat16, torch.float32])
+def test_the_transient_estimate_covers_what_the_per_forward_decode_allocates(dtype: torch.dtype) -> None:
+ """The node reserves this much working memory for the decode, and the model's resident size does not include
+ it, so an estimate that falls short lets the first forward compete with weights the cache just placed.
+
+ Measured in requested bytes: peak *allocated* bytes count whole cached blocks, which blocks left over by
+ earlier tests in the same process can inflate."""
+ device = torch.device("cuda")
+ torch.manual_seed(3)
+ tensors = _nvfp4_tensors("proj", torch.randint(0, 16, (1024, 4096), dtype=torch.uint8), 2.0, 0.25)
+ model = torch.nn.Module()
+ model.proj = _packed_linear({k: v.to(device) for k, v in tensors.items()}, "proj")
+ model.proj._dequantized_weight(device, dtype) # Mints the shared byte tables.
+ torch.cuda.synchronize()
+ torch.cuda.reset_peak_memory_stats()
+ baseline = torch.cuda.memory_stats()["requested_bytes.all.current"]
+
+ weight = model.proj._dequantized_weight(device, dtype)
+ torch.cuda.synchronize()
+
+ measured = torch.cuda.memory_stats()["requested_bytes.all.peak"] - baseline
+ estimate = peak_dequant_transient_bytes(model, dtype)
+ assert weight.dtype is dtype
+ assert 0.95 * estimate <= measured <= estimate
+
+
[email protected](not torch.cuda.is_available(), reason="needs a CUDA device")
+def test_buffers_left_in_ram_stream_per_call_and_a_resident_forward_never_waits_on_the_host() -> None:
+ """Partial loading leaves some packed layers in RAM, and their forward has to stream them to the input's
+ device. A resident forward runs 240 times per Z-Image step, so it must not synchronize with the host."""
+ device = torch.device("cuda")
+ torch.manual_seed(4)
+ tensors = _nvfp4_tensors("proj", torch.randint(0, 16, (128, 64), dtype=torch.uint8), 2.0, 0.25)
+ model = torch.nn.Module()
+ model.proj = _packed_linear(tensors, "proj", bias=torch.randn(128))
+ apply_custom_layers_to_model(model, device_autocasting_enabled=True)
+ x = torch.randn(3, 64, device=device, dtype=torch.bfloat16)
+
+ streamed = model.proj(x)
+ model.to(device)
+ torch.cuda.synchronize()
+ torch.cuda.set_sync_debug_mode("error")
+ try:
+ resident = model.proj(x)
+ finally:
+ torch.cuda.set_sync_debug_mode("default")
+
+ assert streamed.device == x.device
+ assert torch.equal(streamed, resident)