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.

Revert "feat(krea2): load NVFP4 checkpoints and stream fp8 storage" and MXFP8 fix

joshistoast93edeb034c01
diff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.py
index dd348780a5..040b55cb6e 100644
--- a/invokeai/backend/model_manager/load/load_default.py
+++ b/invokeai/backend/model_manager/load/load_default.py
@@ -20,7 +20,6 @@ from invokeai.backend.model_manager.taxonomy import (
AnyModel,
SubModelType,
)
-from invokeai.backend.quantization.dequantize_common import FP8_STORAGE_SKIP_PATTERNS
from invokeai.backend.util.devices import TorchDevice
# Layer classes that benefit from FP8 storage. Mirrors diffusers'
@@ -39,10 +38,18 @@ _FP8_SUPPORTED_PYTORCH_LAYERS: tuple[type[torch.nn.Module], ...] = (
torch.nn.Embedding,
)
-# Re-exported under the historical name; defined in the quantization layer because single-file
-# loaders apply the same skip list when they cast weights to FP8 during dequantization (which keeps
-# peak host RAM at the FP8 model size rather than the full bf16 one).
-_FP8_DEFAULT_SKIP_PATTERNS = FP8_STORAGE_SKIP_PATTERNS
+# Module-path regexes (matched against `named_modules()` dotted paths) for precision-sensitive
+# layers that should never be cast to FP8. Mirrors diffusers' `DEFAULT_SKIP_MODULES_PATTERN`
+# — without these, FLUX RMSNorm.scale and similar tiny learned scalars get crushed to FP8 and
+# inference quality degrades. Includes anything named `norm`, position/patch embeddings, and
+# the in/out projection of transformer blocks.
+_FP8_DEFAULT_SKIP_PATTERNS: tuple[str, ...] = (
+ "pos_embed",
+ "patch_embed",
+ "norm",
+ r"^proj_in$",
+ r"^proj_out$",
+)
# TO DO: The loader is not thread safe!
@@ -206,15 +213,10 @@ class ModelLoader(ModelLoaderBase):
# Detect the model's current dtype to use as compute dtype, since models
# (e.g. Flux) may require a specific dtype (bf16) that differs from the global torch dtype (fp16).
- # Params that are *already* fp8 are skipped: a loader may have stored weights at fp8 directly
- # (streaming the cast during dequantization, to avoid a full-bf16 peak in host RAM), and
- # adopting fp8 as the compute dtype would make the upcast hooks no-ops and run the forward
- # pass in fp8.
if isinstance(model, torch.nn.Module):
- compute_dtype = next(
- (p.dtype for p in model.parameters() if p.dtype not in (torch.float8_e4m3fn, torch.float8_e5m2)),
- compute_dtype,
- )
+ first_param = next(model.parameters(), None)
+ if first_param is not None:
+ compute_dtype = first_param.dtype
# We use our own hook-based path for every nn.Module — including diffusers ModelMixin —
# rather than `model.enable_layerwise_casting()`. Diffusers' LayerwiseCastingHook installs
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.py
index a1a201b514..98cd4a2dec 100644
--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py
+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py
@@ -5,7 +5,6 @@ from pathlib import Path
from typing import Any, Optional
import accelerate
-import torch
from transformers import AutoConfig, AutoTokenizer
from invokeai.backend.model_manager.configs.base import Checkpoint_Config_Base, Diffusers_Config_Base
@@ -25,13 +24,7 @@ from invokeai.backend.model_manager.taxonomy import (
ModelType,
SubModelType,
)
-from invokeai.backend.quantization.dequantize_common import (
- FP8_STORAGE_SKIP_PATTERNS,
- read_declared_quantization_formats,
-)
from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader
-from invokeai.backend.quantization.nvfp4 import dequantize_nvfp4, is_nvfp4_state_dict
-from invokeai.backend.quantization.scaled_fp8 import dequantize_scaled_fp8
from invokeai.backend.util.devices import TorchDevice
@@ -96,59 +89,27 @@ def _is_native_krea2_format(sd: dict[str, Any]) -> bool:
)
-def _is_supported_quantization_format(fmt: str) -> bool:
- """Whether a format string from a checkpoint's ``_quantization_metadata`` is one we dequantize.
+def _dequantize_scaled_fp8(sd: dict[str, Any]) -> dict[str, Any]:
+ """Dequantize ComfyUI 'scaled fp8' weights: ``dequant = weight.float() * weight_scale``.
- Matches any fp8 spelling (``fp8``, ``mxfp8``, ``scaled_fp8``, ``fp8_e4m3``, ...) plus NVFP4.
- Deliberately does *not* match bare ``fp4``/``mxfp4``: those pack two 4-bit values per byte like
- NVFP4 but carry a single block scale and no ``.weight_scale_2``, so NVFP4 detection would miss
- them and the scaled-fp8 path would silently multiply a packed weight by a block scale.
+ Each quantized layer stores an fp8 ``<name>.weight`` plus a (usually scalar) ``<name>.weight_scale``.
+ Returns a new dict with the weights dequantized to float and the ``.weight_scale`` keys removed.
+ No-op if there are no scale keys.
"""
- return fmt == "nvfp4" or "fp8" in fmt
-
-
-def _reject_unsupported_quantization(model_path: Path, *, what: str) -> None:
- """Raise on a checkpoint that declares a quantization format we cannot dequantize.
-
- Without this, an unsupported format reaches ``load_state_dict`` as a wrongly-shaped state dict
- and fails with one "size mismatch for ..." line per quantized layer — hundreds of lines that
- name every tensor in the model and identify neither the format nor the fix.
- """
- unsupported = sorted(
- f for f in read_declared_quantization_formats(model_path) if not _is_supported_quantization_format(f)
- )
- if unsupported:
- raise RuntimeError(
- f"{what}: checkpoint declares quantization format(s) {', '.join(unsupported)}, which "
- f"InvokeAI cannot dequantize. Supported single-file formats are NVFP4, fp8 variants "
- f"(ComfyUI 'scaled fp8' / MXFP8) and unquantized bf16/fp16; GGUF is supported as its own "
- f"model format. Re-download this model in one of those formats."
- )
-
-
-def _dequantize_quantized_weights(
- sd: dict[str, Any],
- compute_dtype: torch.dtype,
- *,
- storage_dtype: torch.dtype | None = None,
-) -> dict[str, Any]:
- """Fold single-file quantization scales into the weights in place, returning the same dict.
-
- Dispatches on the format actually present. NVFP4 has to be tested first: it uses the same
- ``.weight_scale`` key as ComfyUI 'scaled fp8' and is distinguished only by its per-tensor
- ``.weight_scale_2``, so the scaled-fp8 path would otherwise multiply a *packed* 4-bit weight by
- an NVFP4 block scale and hand ``load_state_dict`` a half-width tensor.
+ import torch
- Both branches delegate to shared implementations so this stays in step with the Qwen-Image
- loader; the two previously had independent copies of the fp8 path, and this one had drifted — it
- multiplied by the raw scale (crashing on the block-wise scales real checkpoints ship) and
- dequantized via float32 (spiking peak RAM to ~4 bytes/param). No-op when there are no scale keys.
- """
- if is_nvfp4_state_dict(sd):
- dequantize_nvfp4(sd, compute_dtype, storage_dtype=storage_dtype, skip_patterns=FP8_STORAGE_SKIP_PATTERNS)
- else:
- dequantize_scaled_fp8(sd, compute_dtype, storage_dtype=storage_dtype, skip_patterns=FP8_STORAGE_SKIP_PATTERNS)
- return sd
+ scale_keys = [k for k in sd if isinstance(k, str) and k.endswith(".weight_scale")]
+ if not scale_keys:
+ return sd
+ out = dict(sd)
+ for scale_key in scale_keys:
+ weight_key = scale_key.replace(".weight_scale", ".weight")
+ if weight_key in out:
+ weight = torch.as_tensor(_to_plain_tensor(out[weight_key])).float()
+ scale = torch.as_tensor(_to_plain_tensor(out[scale_key])).float()
+ out[weight_key] = weight * scale
+ del out[scale_key]
+ return out
def _convert_krea2_native_to_diffusers(sd: dict[str, Any]) -> dict[str, Any]:
@@ -370,42 +331,24 @@ class Krea2CheckpointModel(ModelLoader):
raise TypeError(f"Expected Main_Checkpoint_Krea2_Config, got {type(config).__name__}.")
model_path = Path(config.path)
- target_device = TorchDevice.choose_torch_device()
- model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
-
- _reject_unsupported_quantization(model_path, what="Krea-2 single-file checkpoint")
-
- # Resolved before dequantizing, not after loading: with fp8 storage on, each weight is cast
- # to fp8 as it is dequantized, so the state dict never holds the full bf16 model. Dequantizing
- # everything to bf16 first and letting `_apply_fp8_layerwise_casting` re-quantize afterwards
- # is numerically identical but transiently needs 23.9 GiB for a 12.8 B-parameter transformer,
- # which does not fit on a 32 GB host that also has to hold a ~5 GiB text encoder.
- storage_dtype = torch.float8_e4m3fn if self._should_use_fp8(config, SubModelType.Transformer) else None
-
sd = load_file(model_path)
sd = _strip_comfyui_prefix(sd)
- # NVFP4 or ComfyUI 'scaled fp8': fold the scales into the weights. Dequantized straight to
- # the storage dtype — via float32 this needs ~4 bytes/param of host RAM, which for a 12.5 GB
- # fp8 transformer is 50 GB and unloadable on a 32 GB machine.
- sd = _dequantize_quantized_weights(sd, model_dtype, storage_dtype=storage_dtype)
+ # ComfyUI 'scaled fp8' checkpoints: fold the per-tensor weight_scale into the weights (→ float).
+ sd = _dequantize_scaled_fp8(sd)
# Native/ComfyUI key naming → diffusers Krea2Transformer2DModel keys.
if _is_native_krea2_format(sd):
sd = _convert_krea2_native_to_diffusers(sd)
+ target_device = TorchDevice.choose_torch_device()
+ model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
+
with accelerate.init_empty_weights():
model = Krea2Transformer2DModel(**KREA2_TRANSFORMER_CONFIG)
- # Leave already-fp8 weights alone; casting them up to `model_dtype` here would undo the
- # streaming above and reintroduce the full-bf16 peak this path exists to avoid.
- preserved_dtypes = (torch.float8_e4m3fn, torch.float8_e5m2) if storage_dtype is not None else ()
- new_sd_size = sum(
- ten.nelement() * (ten.element_size() if ten.dtype in preserved_dtypes else model_dtype.itemsize)
- for ten in sd.values()
- )
+ new_sd_size = sum(ten.nelement() * model_dtype.itemsize for ten in sd.values())
self._ram_cache.make_room(new_sd_size)
for k in sd.keys():
- if sd[k].dtype not in preserved_dtypes:
- sd[k] = sd[k].to(model_dtype)
+ sd[k] = sd[k].to(model_dtype)
model.load_state_dict(sd, assign=True, strict=False)
_reject_incomplete_load(model, what="Krea-2 single-file checkpoint")
@@ -617,20 +560,15 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):
target_device = TorchDevice.choose_torch_device()
model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
- _reject_unsupported_quantization(model_path, what="Qwen3-VL encoder checkpoint")
-
sd = load_file(str(model_path))
- # Detect a quantized source (NVFP4 / ComfyUI 'scaled fp8' scale keys, or raw float8 weights)
- # BEFORE dequantizing. A quantized-on-disk encoder is kept fp8-resident with layerwise
- # upcasting below, so it occupies ~half the VRAM of the dequantized bf16 model (the whole
- # point of shipping it quantized).
+ # Detect an fp8 source (ComfyUI 'scaled fp8' weight_scale keys, or raw float8 weights) BEFORE
+ # dequantizing. An fp8-on-disk encoder is kept fp8-resident with layerwise upcasting below, so
+ # it occupies ~half the VRAM of the dequantized bf16 model (the whole point of shipping fp8).
source_is_fp8 = any(isinstance(k, str) and k.endswith(".weight_scale") for k in sd) or any(
getattr(t, "dtype", None) in (torch.float8_e4m3fn, torch.float8_e5m2) for t in sd.values()
)
- # NVFP4 or ComfyUI 'scaled fp8': fold the scales into the weights, then drop quantization
- # metadata. Dequantized straight to the model dtype rather than via float32, which would
- # double peak host RAM for an 8.9 GB encoder.
- sd = _dequantize_quantized_weights(sd, model_dtype)
+ # ComfyUI 'scaled fp8': fold weight_scale into the weights, then drop quantization metadata.
+ sd = _dequantize_scaled_fp8(sd)
for k in list(sd.keys()):
if isinstance(k, str) and (k.endswith(".comfy_quant") or "scale_input" in k):
del sd[k]
diff --git a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py b/invokeai/backend/model_manager/load/model_loaders/qwen_image.py
index 2e572dbdde..9091979499 100644
--- a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/qwen_image.py
@@ -27,7 +27,6 @@ from invokeai.backend.model_manager.taxonomy import (
)
from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader
-from invokeai.backend.quantization.scaled_fp8 import dequantize_scaled_fp8
from invokeai.backend.util.devices import TorchDevice
@@ -52,10 +51,40 @@ def _strip_comfyui_prefix(sd: dict) -> dict:
def _dequantize_comfyui_fp8(sd: dict, compute_dtype: torch.dtype) -> int:
"""Dequantize ComfyUI-style fp8_scaled weights in-place. Returns count of dequantized tensors.
- Thin wrapper over the shared implementation, which this function's logic was extracted into so
- the Krea-2 loader could stop carrying a divergent copy.
+ Weights are dequantized directly to `compute_dtype` (typically bf16) instead of via a
+ full-precision float32 intermediate. The previous float32 path materialised a complete
+ 4-byte/param copy of the model before a separate downcast pass, spiking peak RAM to ~2x the
+ final bf16 size (~80GB for the 20B Qwen-Image transformer). Multiplying in the target dtype
+ keeps the dict at the bf16 model size plus a single transient tensor. fp8 has only 3 mantissa
+ bits and bf16 shares float32's exponent range, so the bf16 multiply loses no meaningful
+ precision here.
+
+ Two key naming schemes are in the wild:
+ - `<path>.weight` + `<path>.weight_scale` (FLUX, Z-Image style)
+ - `<path>.weight` + `<path>.scale_weight` (Qwen2.5-VL fp8_scaled style, also
+ emits `<path>.scale_input` for activation scaling that we discard).
"""
- return dequantize_scaled_fp8(sd, compute_dtype)
+ scale_suffixes = (".weight_scale", ".scale_weight")
+ weight_scale_keys = [k for k in sd.keys() if isinstance(k, str) and k.endswith(scale_suffixes)]
+ count = 0
+ for scale_key in weight_scale_keys:
+ for suffix in scale_suffixes:
+ if scale_key.endswith(suffix):
+ weight_key = scale_key[: -len(suffix)] + ".weight"
+ break
+ if weight_key not in sd:
+ continue
+ weight = sd[weight_key].to(compute_dtype)
+ scale = sd[scale_key].to(compute_dtype)
+ if scale.shape != weight.shape and scale.numel() > 1:
+ for dim in range(len(weight.shape)):
+ if dim < len(scale.shape) and scale.shape[dim] != weight.shape[dim]:
+ block_size = weight.shape[dim] // scale.shape[dim]
+ if block_size > 1:
+ scale = scale.repeat_interleave(block_size, dim=dim)
+ sd[weight_key] = weight * scale
+ count += 1
+ return count
def _remap_qwen_vl_checkpoint_keys(sd: dict) -> dict:
diff --git a/invokeai/backend/quantization/dequantize_common.py b/invokeai/backend/quantization/dequantize_common.py
deleted file mode 100644
index 04c4961cf2..0000000000
--- a/invokeai/backend/quantization/dequantize_common.py
+++ /dev/null
@@ -1,106 +0,0 @@
-"""Shared helpers for folding single-file checkpoint quantization scales into weights.
-
-Both scaled formats we support - ComfyUI "scaled fp8" / MXFP8 (:mod:`.scaled_fp8`) and NVFP4
-(:mod:`.nvfp4`) - dequantize by multiplying a low-precision weight by one or more scale tensors.
-They share three concerns, collected here: reading tensors that may still be GGML-wrapped, choosing
-the dtype the dequantized result is *stored* at, and reporting what a checkpoint says it contains.
-"""
-
-import json
-import re
-from collections.abc import Sequence
-from pathlib import Path
-from typing import Any
-
-import torch
-
-#: Metadata key ComfyUI/ModelOpt exports use to declare per-layer quantization.
-QUANTIZATION_METADATA_KEY = "_quantization_metadata"
-
-#: Module-path regexes for precision-sensitive layers that should never be stored as fp8. Mirrors
-#: diffusers' ``DEFAULT_SKIP_MODULES_PATTERN`` - without these, FLUX RMSNorm.scale and similar tiny
-#: learned scalars get crushed to fp8 and inference quality degrades. Matched both against
-#: ``named_modules()`` dotted paths by the layerwise-casting pass and against state-dict key prefixes
-#: by the dequantizers here, so that both routes to fp8 storage make the same exclusions.
-FP8_STORAGE_SKIP_PATTERNS: tuple[str, ...] = (
- "pos_embed",
- "patch_embed",
- "norm",
- r"^proj_in$",
- r"^proj_out$",
-)
-
-
-def to_plain_tensor(value: Any) -> Any:
- """Dequantize a GGMLTensor to a plain tensor; pass anything else through."""
- if hasattr(value, "get_dequantized_tensor"):
- return value.get_dequantized_tensor()
- return value
-
-
-def resolve_target_dtype(
- name: str,
- compute_dtype: torch.dtype,
- storage_dtype: torch.dtype | None,
- skip_patterns: Sequence[str],
-) -> torch.dtype:
- """Pick the dtype a dequantized weight should be *stored* at.
-
- ``storage_dtype`` is how the caller intends to keep the weight resident - fp8, for the
- fp8-storage setting. Casting to it here, one tensor at a time as it is dequantized, is what
- keeps peak host RAM at the fp8 model size. Dequantizing the whole checkpoint to
- ``compute_dtype`` and re-quantizing afterwards transiently needs the full bf16 model, which for
- a 12.8 B-parameter Krea-2 transformer is 23.9 GiB - unloadable on a 32 GB host, which also has
- to hold a ~5 GiB text encoder. The two are numerically equivalent: both round the same
- dequantized value to fp8 once.
-
- ``skip_patterns`` mirrors the caller's layerwise-casting skip list, so a weight it would have
- deliberately preserved at full precision (norms and embeddings, whose tiny learned scalars are
- crushed by fp8) is not pre-emptively downcast here instead.
- """
- if storage_dtype is None:
- return compute_dtype
- if any(re.search(pattern, name) for pattern in skip_patterns):
- return compute_dtype
- return storage_dtype
-
-
-def read_declared_quantization_formats(model_path: Path) -> set[str]:
- """Return the lower-cased quantization formats a safetensors file declares, if any.
-
- ComfyUI and NVIDIA TensorRT Model Optimizer both stamp a ``_quantization_metadata`` JSON blob
- into the safetensors header, mapping each quantized layer to a ``format`` (``"nvfp4"``,
- ``"mxfp8"``, ...). Reading it lets a loader reject a format it cannot handle with the format's
- name, instead of letting a wrongly-shaped state dict reach ``load_state_dict`` and emit one
- "size mismatch for ..." line per quantized layer - hundreds of lines that name every tensor and
- diagnose nothing.
-
- Returns an empty set for unquantized checkpoints, for quantized ones that ship no metadata, and
- for files that are not safetensors at all (an empty set means "nothing declared", never "nothing
- quantized" - detection still has to be driven by the actual keys, so this is only ever used to
- reject, never to accept).
- """
- from safetensors import safe_open
-
- if model_path.suffix != ".safetensors":
- return set()
-
- # Best-effort throughout: this only ever *rejects* a load, so an unreadable or malformed header
- # must fall through to the normal path rather than become a new failure mode of its own. Whatever
- # is actually wrong with the file will surface with a better message from the real load.
- try:
- with safe_open(model_path, framework="pt") as f:
- metadata = f.metadata() or {}
- parsed = json.loads(metadata.get(QUANTIZATION_METADATA_KEY) or "")
- except Exception:
- return set()
-
- layers = parsed.get("layers") if isinstance(parsed, dict) else None
- if not isinstance(layers, dict):
- return set()
-
- return {
- str(info["format"]).lower()
- for info in layers.values()
- if isinstance(info, dict) and info.get("format") is not None
- }
diff --git a/invokeai/backend/quantization/nvfp4.py b/invokeai/backend/quantization/nvfp4.py
deleted file mode 100644
index 30948068cc..0000000000
--- a/invokeai/backend/quantization/nvfp4.py
+++ /dev/null
@@ -1,176 +0,0 @@
-"""NVFP4 dequantization for single-file checkpoints.
-
-NVFP4 is NVIDIA's 4-bit float format, as produced by TensorRT Model Optimizer and re-exported by
-ComfyUI. Each quantized layer ships three tensors::
-
- <path>.weight uint8 two packed FP4 values per byte, along the last dim
- <path>.weight_scale float8_e4m3fn one scale per block of 16 values along the last dim
- <path>.weight_scale_2 float32 one scalar scale for the whole tensor
-
-Dequantizing is ``fp4_value * weight_scale * weight_scale_2``. Three details are easy to get wrong,
-and only the first fails loudly:
-
-**The weight is 4-bit packed, so its stored last dim is half the logical one.** A ``(6144, 6144)``
-weight is stored as ``(6144, 3072)`` uint8. Passing that to ``load_state_dict`` unmodified produces
-a wall of "copying a param with shape torch.Size([6144, 3072]) ... the shape in current model is
-torch.Size([6144, 6144])" - one line per quantized layer, naming every tensor and diagnosing
-nothing.
-
-**The high nibble is the even element.** Byte ``j`` holds logical elements ``2j`` (high nibble) and
-``2j + 1`` (low nibble), and consecutive elements are adjacent - not split into low-nibble and
-high-nibble halves. Getting the nibble order backwards swaps every adjacent pair, which does not
-crash and leaves the weight histogram identical, so it is only detectable by comparing against the
-same weights quantized another way. Both facts were established against Krea-2 Turbo, which ships
-an MXFP8 export of bit-identical weights (all 174 unquantized tensors compare equal):
-
-=================== ============== =================
-nibble order sign agreement per-block cosine
-=================== ============== =================
-high nibble first 100.00% +0.996
-low nibble first 49.95% -0.004
-=================== ============== =================
-
-The interleaved (rather than split-halves) layout is independently confirmed without any reference:
-under it, 100% of scale blocks contain the maximum FP4 code, which is what a block scale of
-``amax / 6`` guarantees. Under a split-halves layout only ~85% do.
-
-**FP4 codes are not integers.** The three magnitude bits are E2M1 - two exponent, one mantissa - so
-the representable magnitudes are 0, 0.5, 1, 1.5, 2, 3, 4, 6, not 0-7. Treating a code as its own
-value distorts the top half of every block.
-
-Note that ``.weight_scale`` is *also* the scale key used by ComfyUI "scaled fp8" (see
-:mod:`.scaled_fp8`), so a loader handling both must test for NVFP4 first - the distinguishing key is
-``.weight_scale_2``. Feeding an NVFP4 checkpoint to the scaled-fp8 path silently multiplies a packed
-4-bit weight by an NVFP4 block scale and yields a half-width tensor.
-"""
-
-from collections.abc import Sequence
-from typing import Any
-
-import torch
-
-from invokeai.backend.quantization.dequantize_common import (
- resolve_target_dtype,
- to_plain_tensor,
-)
-
-#: Values per NVFP4 block scale, along the last dim.
-NVFP4_BLOCK_SIZE = 16
-
-#: Distinguishes NVFP4 from ComfyUI "scaled fp8", which has no equivalent per-tensor scale.
-GLOBAL_SCALE_SUFFIX = ".weight_scale_2"
-BLOCK_SCALE_SUFFIX = ".weight_scale"
-
-#: FP4 E2M1 magnitudes, indexed by the low 3 bits of a code.
-_E2M1_MAGNITUDES = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0)
-
-#: Largest representable FP4 magnitude; a block scale is chosen as ``amax / 6``.
-FP4_E2M1_MAX = _E2M1_MAGNITUDES[-1]
-
-
-def fp4_e2m1_lut(dtype: torch.dtype, device: torch.device) -> torch.Tensor:
- """Build the 16-entry FP4 E2M1 code-to-value table (bit 3 is the sign, so 8-15 are negative)."""
- magnitudes = torch.tensor(_E2M1_MAGNITUDES, dtype=dtype, device=device)
- return torch.cat((magnitudes, -magnitudes))
-
-
-def is_nvfp4_state_dict(sd: dict[str, Any]) -> bool:
- """True if ``sd`` carries NVFP4 weights, identified by the per-tensor global-scale keys."""
- return any(isinstance(k, str) and k.endswith(GLOBAL_SCALE_SUFFIX) for k in sd)
-
-
-def unpack_fp4_e2m1(packed: torch.Tensor, lut: torch.Tensor) -> torch.Tensor:
- """Expand packed FP4 pairs into values, doubling the last dim.
-
- The high nibble of each byte is the even element and the low nibble the odd one - see the module
- docstring for how that was established. Written into a preallocated buffer rather than built with
- ``stack`` so only one half-width intermediate exists at a time; these tensors reach 16384 columns.
- """
- if packed.dtype != torch.uint8:
- raise ValueError(f"NVFP4 packed weights must be uint8, got {packed.dtype}.")
-
- unpacked = torch.empty(
- (*packed.shape[:-1], packed.shape[-1] * 2),
- dtype=lut.dtype,
- device=packed.device,
- )
- unpacked[..., 0::2] = lut[(packed >> 4).long()]
- unpacked[..., 1::2] = lut[(packed & 0x0F).long()]
- return unpacked
-
-
-def expand_block_scale(block_scale: torch.Tensor, logical_last_dim: int, *, name: str) -> torch.Tensor:
- """Broadcast a per-block scale up to one entry per weight element along the last dim."""
- blocks = block_scale.shape[-1]
- if blocks == logical_last_dim:
- return block_scale
-
- block_size, remainder = divmod(logical_last_dim, blocks)
- if remainder or block_size < 1:
- raise ValueError(
- f"{name}: NVFP4 block scale has {blocks} blocks along the last dim, which does not "
- f"evenly divide the {logical_last_dim} unpacked weight columns (expected one scale per "
- f"{NVFP4_BLOCK_SIZE} values)."
- )
- return block_scale.repeat_interleave(block_size, dim=-1)
-
-
-def dequantize_nvfp4_tensor(
- packed: torch.Tensor,
- block_scale: torch.Tensor,
- global_scale: torch.Tensor,
- compute_dtype: torch.dtype,
- *,
- name: str = "weight",
-) -> torch.Tensor:
- """Dequantize one NVFP4 weight to ``compute_dtype``."""
- lut = fp4_e2m1_lut(compute_dtype, packed.device)
- values = unpack_fp4_e2m1(packed, lut)
-
- # Fold the global scale into the (16x smaller) block scale in float32 before downcasting: the
- # product is what actually multiplies the weights, and bf16 has 8 mantissa bits, so scaling
- # twice in bf16 rounds twice for no benefit.
- scale = (block_scale.float() * global_scale.float()).to(compute_dtype)
- scale = expand_block_scale(scale, values.shape[-1], name=name)
-
- values *= scale
- return values
-
-
-def dequantize_nvfp4(
- sd: dict[str, Any],
- compute_dtype: torch.dtype,
- *,
- storage_dtype: torch.dtype | None = None,
- skip_patterns: Sequence[str] = (),
-) -> int:
- """Dequantize NVFP4 weights in ``sd`` in place; returns the number converted.
-
- Scale keys are removed, including orphans with no matching weight - nothing can be multiplied by
- those, and leaving them behind would inflate the caller's size accounting and reach
- ``load_state_dict`` as unexpected keys. See :func:`resolve_target_dtype` for ``storage_dtype``
- and ``skip_patterns``.
- """
- global_scale_keys = [k for k in sd if isinstance(k, str) and k.endswith(GLOBAL_SCALE_SUFFIX)]
- count = 0
-
- for global_scale_key in global_scale_keys:
- base = global_scale_key[: -len(GLOBAL_SCALE_SUFFIX)]
- weight_key = base + ".weight"
- block_scale_key = base + BLOCK_SCALE_SUFFIX
-
- if weight_key in sd and block_scale_key in sd:
- target_dtype = resolve_target_dtype(base, compute_dtype, storage_dtype, skip_patterns)
- sd[weight_key] = dequantize_nvfp4_tensor(
- to_plain_tensor(sd[weight_key]),
- to_plain_tensor(sd[block_scale_key]),
- to_plain_tensor(sd[global_scale_key]),
- compute_dtype,
- name=weight_key,
- ).to(target_dtype)
- count += 1
-
- sd.pop(block_scale_key, None)
- del sd[global_scale_key]
-
- return count
diff --git a/invokeai/backend/quantization/scaled_fp8.py b/invokeai/backend/quantization/scaled_fp8.py
deleted file mode 100644
index d3f59480e6..0000000000
--- a/invokeai/backend/quantization/scaled_fp8.py
+++ /dev/null
@@ -1,116 +0,0 @@
-"""Dequantization for scaled-fp8 single-file checkpoints (ComfyUI "scaled fp8" and MXFP8).
-
-A quantized layer stores an fp8 ``<name>.weight`` alongside a scale tensor. Dequantizing is
-``weight * scale``, but three details make a naive implementation wrong, each in a different way:
-
-**E8M0 (microscaling) scales are exponents, not multipliers.** MXFP8 checkpoints store the scale
-as a ``uint8`` biased power-of-two exponent, so the multiplier is ``2 ** (scale - 127)``. Treating
-the raw byte as the multiplier does not crash — it silently scales weights by ~10^6 (a real
-Krea-2 MXFP8 transformer goes from std 0.03 to std 14000), so the model loads and generates
-garbage. Distinguished here by dtype: an integer scale is an exponent, a float scale is a
-multiplier. A linear scale is never stored as an integer.
-
-**Block-wise scales.** The scale is often not a scalar. Microscaling uses one scale per block of
-32 values along the last dim, so a ``(6144, 6144)`` weight carries a ``(6144, 192)`` scale. Plain
-multiplication cannot broadcast that and raises "The size of tensor a (3072) must match the size
-of tensor b (384)". The scale has to be expanded with ``repeat_interleave`` first.
-
-**Dequantizing straight to the target dtype.** Going via ``.float()`` materialises a complete
-4-byte/param copy of the model before a separate downcast pass, spiking peak host RAM to ~2x the
-final bf16 size — 50 GB for a 12.5 GB fp8 Krea-2 transformer, which is unloadable on a 32 GB
-machine. Multiplying in the target dtype keeps the dict at the bf16 model size plus one transient
-tensor. fp8 has only 3 mantissa bits and bf16 shares float32's exponent range, so the bf16
-multiply loses no meaningful precision.
-
-This lives here rather than in a loader because the Krea-2 and Qwen-Image loaders both need it,
-and two independent copies had already drifted: the Krea-2 copy lacked every fix above.
-
-Two scale-key naming schemes are in the wild:
- - ``<path>.weight`` + ``<path>.weight_scale`` (FLUX, Z-Image, Krea-2 style)
- - ``<path>.weight`` + ``<path>.scale_weight`` (Qwen2.5-VL fp8_scaled style, which also emits
- ``<path>.scale_input`` for activation scaling that we discard)
-"""
-
-from collections.abc import Sequence
-from typing import Any
-
-import torch
-
-from invokeai.backend.quantization.dequantize_common import (
- resolve_target_dtype,
- to_plain_tensor,
-)
-
-SCALE_SUFFIXES = (".weight_scale", ".scale_weight")
-
-#: Exponent bias for OCP Microscaling E8M0 scale bytes.
-E8M0_EXPONENT_BIAS = 127
-
-
-def to_scale_multiplier(scale: torch.Tensor, compute_dtype: torch.dtype) -> torch.Tensor:
- """Resolve a stored scale tensor to the multiplier to apply to the weights.
-
- An integer scale is an E8M0 biased exponent (microscaling), so it becomes ``2 ** (s - 127)``.
- A float scale is already a linear multiplier and is only cast. ``exp2`` is evaluated in float32
- before the cast so the intermediate cannot overflow a narrow dtype; every result is an exact
- power of two and so is representable in bf16/fp16 without rounding.
- """
- if not scale.dtype.is_floating_point:
- return torch.exp2(scale.float() - E8M0_EXPONENT_BIAS).to(compute_dtype)
-
- return scale.to(compute_dtype)
-
-
-def expand_scale_to_weight(weight: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
- """Broadcast a possibly block-wise ``scale`` up to ``weight``'s shape.
-
- A scalar scale is returned untouched — it broadcasts natively. A block-wise scale is repeated
- along each mismatched dimension by the block size implied by the shape ratio (32 for MXFP8).
- """
- if scale.shape == weight.shape or scale.numel() == 1:
- return scale
-
- for dim in range(len(weight.shape)):
- if dim < len(scale.shape) and scale.shape[dim] != weight.shape[dim]:
- block_size = weight.shape[dim] // scale.shape[dim]
- if block_size > 1:
- scale = scale.repeat_interleave(block_size, dim=dim)
-
- return scale
-
-
-def dequantize_scaled_fp8(
- sd: dict[str, Any],
- compute_dtype: torch.dtype,
- *,
- storage_dtype: torch.dtype | None = None,
- skip_patterns: Sequence[str] = (),
-) -> int:
- """Dequantize scaled-fp8 weights in ``sd`` in place; returns the number converted.
-
- Weights are dequantized directly to ``compute_dtype`` (see the module docstring on why not via
- float32), then stored at ``storage_dtype`` when one is given — see
- :func:`~invokeai.backend.quantization.dequantize_common.resolve_target_dtype`. Scale keys are
- removed, including orphans with no matching weight — nothing can be multiplied by those, and
- leaving them behind would inflate the caller's size accounting.
- """
- scale_keys = [k for k in sd if isinstance(k, str) and k.endswith(SCALE_SUFFIXES)]
- count = 0
-
- for scale_key in scale_keys:
- for suffix in SCALE_SUFFIXES:
- if scale_key.endswith(suffix):
- base = scale_key[: -len(suffix)]
- weight_key = base + ".weight"
- break
-
- if weight_key in sd:
- target_dtype = resolve_target_dtype(base, compute_dtype, storage_dtype, skip_patterns)
- weight = torch.as_tensor(to_plain_tensor(sd[weight_key])).to(compute_dtype)
- scale = to_scale_multiplier(torch.as_tensor(to_plain_tensor(sd[scale_key])), compute_dtype)
- sd[weight_key] = (weight * expand_scale_to_weight(weight, scale)).to(target_dtype)
- count += 1
-
- del sd[scale_key]
-
- return count
diff --git a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py
index dbce2eb032..cb8dfe21d7 100644
--- a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py
+++ b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py
@@ -36,10 +36,6 @@ def test_single_file_loader_constructs_and_materializes_model(monkeypatch, tmp_p
ram_cache = SimpleNamespace(make_room=MagicMock())
loader = object.__new__(Krea2CheckpointModel)
loader._ram_cache = ram_cache
- # The loader resolves the fp8-storage decision itself (to stream the cast during dequantization
- # rather than re-quantize a full bf16 state dict), and `_should_use_fp8` reads `_torch_device`.
- # CPU means fp8 storage is off, so this exercises the plain bf16 path.
- loader._torch_device = torch.device("cpu")
loader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: model
monkeypatch.setattr(diffusers, "Krea2Transformer2DModel", _TinyKrea2Transformer, raising=False)
diff --git a/tests/backend/model_manager/load/test_krea2_state_dict_utils.py b/tests/backend/model_manager/load/test_krea2_state_dict_utils.py
index 9b6feed807..c75873a8fd 100644
--- a/tests/backend/model_manager/load/test_krea2_state_dict_utils.py
+++ b/tests/backend/model_manager/load/test_krea2_state_dict_utils.py
@@ -17,7 +17,7 @@ import torch
from invokeai.backend.model_manager.load.model_loaders.krea2 import (
KREA2_TRANSFORMER_CONFIG,
_convert_krea2_native_to_diffusers,
- _dequantize_quantized_weights,
+ _dequantize_scaled_fp8,
_is_native_krea2_format,
_normalize_qwen3vl_rope_config,
_reject_incomplete_load,
@@ -90,101 +90,22 @@ class TestDequantizeScaledFp8:
"layer.weight": torch.tensor([2.0, 4.0]),
"layer.weight_scale": torch.tensor(0.5),
}
- out = _dequantize_quantized_weights(sd, torch.float32)
+ out = _dequantize_scaled_fp8(sd)
assert "layer.weight_scale" not in out
assert torch.allclose(out["layer.weight"], torch.tensor([1.0, 2.0]))
def test_noop_without_scale_keys(self) -> None:
sd = {"layer.weight": torch.tensor([2.0, 4.0])}
- out = _dequantize_quantized_weights(sd, torch.float32)
+ out = _dequantize_scaled_fp8(sd)
assert out is sd
def test_orphan_scale_key_is_dropped(self) -> None:
# A scale key with no matching weight is simply removed (nothing to multiply).
sd = {"other.weight": torch.tensor([1.0]), "layer.weight_scale": torch.tensor(0.5)}
- out = _dequantize_quantized_weights(sd, torch.float32)
+ out = _dequantize_scaled_fp8(sd)
assert "layer.weight_scale" not in out
assert "other.weight" in out
- def test_expands_block_wise_scales(self) -> None:
- """Regression: real Krea-2 fp8 checkpoints carry one scale per block of rows.
-
- A (4, 2) weight with a (2, 1) scale used to raise "The size of tensor a (4) must match the
- size of tensor b (2) at non-singleton dimension 0" because the raw scale was multiplied in
- directly. Each scale must cover its block of rows.
- """
- sd = {
- "layer.weight": torch.tensor([[2.0, 2.0], [4.0, 4.0], [6.0, 6.0], [8.0, 8.0]]),
- "layer.weight_scale": torch.tensor([[0.5], [2.0]]),
- }
-
- out = _dequantize_quantized_weights(sd, torch.float32)
-
- expected = torch.tensor([[1.0, 1.0], [2.0, 2.0], [12.0, 12.0], [16.0, 16.0]])
- assert torch.allclose(out["layer.weight"], expected)
-
- def test_dequantizes_to_the_requested_dtype_without_a_float32_detour(self) -> None:
- """The dtype is the whole point: a float32 intermediate doubles peak host RAM.
-
- A 12.5 GB fp8 transformer needs ~50 GB via float32 versus ~25 GB straight to bf16, which is
- the difference between loadable and OOM-killed on a 32 GB machine.
- """
- sd = {
- "layer.weight": torch.tensor([2.0, 4.0], dtype=torch.float32),
- "layer.weight_scale": torch.tensor(0.5, dtype=torch.float32),
- }
-
- out = _dequantize_quantized_weights(sd, torch.bfloat16)
-
- assert out["layer.weight"].dtype is torch.bfloat16
-
- def test_decodes_e8m0_microscaling_exponents_rather_than_multiplying_the_byte(self) -> None:
- """Regression: MXFP8 stores the scale as a uint8 biased power-of-two exponent.
-
- Multiplying by the raw byte does not crash — it scales weights by ~10^6, so the model loads
- and silently generates garbage. A real Krea-2 MXFP8 transformer goes from std ~0.03 to
- ~14000 that way, which is exactly the failure this guards.
- """
- # Byte 127 is 2**0, so it must leave the weight untouched; 128 is 2**1 and 126 is 2**-1.
- sd = {
- "layer.weight": torch.tensor([[4.0], [4.0], [4.0]]),
- "layer.weight_scale": torch.tensor([[127], [128], [126]], dtype=torch.uint8),
- }
-
- out = _dequantize_quantized_weights(sd, torch.float32)
-
- assert torch.allclose(out["layer.weight"], torch.tensor([[4.0], [8.0], [2.0]]))
-
- def test_treats_a_float_scale_as_a_plain_multiplier(self) -> None:
- # ComfyUI scaled-fp8 (FLUX / Z-Image / Qwen style) stores a linear float scale, which must
- # not be reinterpreted as an exponent.
- sd = {"layer.weight": torch.tensor([4.0]), "layer.weight_scale": torch.tensor(2.0)}
-
- out = _dequantize_quantized_weights(sd, torch.float32)
-
- assert torch.allclose(out["layer.weight"], torch.tensor([8.0]))
-
- def test_expands_a_block_wise_e8m0_scale_over_its_block(self) -> None:
- # The combination that actually ships: block-wise scales that are also E8M0 exponents.
- sd = {
- "layer.weight": torch.tensor([[2.0, 2.0, 2.0, 2.0]]),
- "layer.weight_scale": torch.tensor([[128, 126]], dtype=torch.uint8),
- }
-
- out = _dequantize_quantized_weights(sd, torch.float32)
-
- # First block doubles, second halves.
- assert torch.allclose(out["layer.weight"], torch.tensor([[4.0, 4.0, 1.0, 1.0]]))
-
- def test_supports_the_scale_weight_naming_variant(self) -> None:
- # Qwen2.5-VL fp8_scaled exports use `.scale_weight` rather than `.weight_scale`.
- sd = {"layer.weight": torch.tensor([2.0]), "layer.scale_weight": torch.tensor(3.0)}
-
- out = _dequantize_quantized_weights(sd, torch.float32)
-
- assert "layer.scale_weight" not in out
- assert torch.allclose(out["layer.weight"], torch.tensor([6.0]))
-
class TestConvertKrea2NativeToDiffusers:
def test_top_level_module_renames(self) -> None:
@@ -436,38 +357,3 @@ class TestConvertedShapesMatchRealKrea2Transformer:
for name in table_keys:
if name.startswith(("transformer_blocks.", "text_fusion.")):
assert expected[name][0] == 6, f"{name} expected 6 modulation rows, got {expected[name]}"
-
-
-class TestDequantCallSites:
- """Guards the arity of every `_dequantize_quantized_weights` call inside the Krea-2 loader.
-
- The loader dequantizes in two places — the transformer single-file path and the Qwen3-VL
- encoder single-file path — and only the first is covered by a functional test. When the
- function gained its `compute_dtype` parameter, the encoder call site was missed and shipped a
- TypeError that only surfaced at generation time.
-
- mypy would catch this (`strict = true` flags a missing positional argument), but the module
- already carries hundreds of pre-existing errors, so it cannot serve as a gate. This asserts the
- property directly and cheaply instead.
- """
-
- def test_every_call_site_passes_a_compute_dtype(self) -> None:
- import ast
- import inspect
-
- from invokeai.backend.model_manager.load.model_loaders import krea2
-
- tree = ast.parse(inspect.getsource(krea2))
- calls = [
- node
- for node in ast.walk(tree)
- if isinstance(node, ast.Call)
- and isinstance(node.func, ast.Name)
- and node.func.id == "_dequantize_quantized_weights"
- ]
-
- # Both single-file paths must be present; a dropped call site is as much a bug as a
- # miscalled one.
- assert len(calls) == 2, f"expected 2 call sites, found {len(calls)}"
- for call in calls:
- assert len(call.args) == 2, f"call at line {call.lineno} passes {len(call.args)} args, expected 2"
diff --git a/tests/backend/quantization/test_nvfp4.py b/tests/backend/quantization/test_nvfp4.py
deleted file mode 100644
index 7328438b93..0000000000
--- a/tests/backend/quantization/test_nvfp4.py
+++ /dev/null
@@ -1,267 +0,0 @@
-import pytest
-import torch
-
-from invokeai.backend.quantization.dequantize_common import (
- FP8_STORAGE_SKIP_PATTERNS,
- read_declared_quantization_formats,
- resolve_target_dtype,
-)
-from invokeai.backend.quantization.nvfp4 import (
- FP4_E2M1_MAX,
- NVFP4_BLOCK_SIZE,
- dequantize_nvfp4,
- expand_block_scale,
- fp4_e2m1_lut,
- is_nvfp4_state_dict,
- unpack_fp4_e2m1,
-)
-from invokeai.backend.quantization.scaled_fp8 import dequantize_scaled_fp8
-
-#: The 16 FP4 E2M1 code values, in code order. Bit 3 is the sign.
-EXPECTED_LUT = [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]
-
-
-def _pack(codes: torch.Tensor) -> torch.Tensor:
- """Pack FP4 codes (0-15) along the last dim, high nibble first — the layout NVFP4 uses."""
- even, odd = codes[..., 0::2], codes[..., 1::2]
- return ((even << 4) | odd).to(torch.uint8)
-
-
-def _nvfp4_sd(weight: torch.Tensor, *, name: str = "layer") -> dict[str, torch.Tensor]:
- """Encode ``weight`` as an NVFP4 state dict the way a real exporter does.
-
- Per block of 16 along the last dim, the block scale is ``amax / 6`` so the largest magnitude maps
- to the largest FP4 code; the global scale carries whatever the E4M3 block scale cannot represent.
- """
- rows, cols = weight.shape
- blocks = weight.reshape(rows, cols // NVFP4_BLOCK_SIZE, NVFP4_BLOCK_SIZE)
- amax = blocks.abs().amax(-1, keepdim=True)
- block_scale = (amax / FP4_E2M1_MAX).clamp_min(torch.finfo(torch.float32).tiny)
-
- lut = fp4_e2m1_lut(torch.float32, weight.device)
- normalized = blocks / block_scale
- codes = (normalized[..., None] - lut).abs().argmin(-1).to(torch.uint8)
-
- return {
- f"{name}.weight": _pack(codes.reshape(rows, cols)),
- f"{name}.weight_scale": block_scale.squeeze(-1).to(torch.float8_e4m3fn),
- f"{name}.weight_scale_2": torch.tensor(1.0),
- }
-
-
-class TestFp4E2m1Lut:
- def test_lut_matches_the_ocp_e2m1_encoding(self) -> None:
- assert fp4_e2m1_lut(torch.float32, torch.device("cpu")).tolist() == EXPECTED_LUT
-
- def test_max_magnitude_constant_matches_the_lut(self) -> None:
- assert FP4_E2M1_MAX == max(EXPECTED_LUT)
-
- def test_codes_are_not_their_own_values(self) -> None:
- # The E2M1 magnitudes are 0, .5, 1, 1.5, 2, 3, 4, 6 — not 0-7. Treating a code as its own
- # value silently distorts the top half of every block, so pin the divergence.
- assert EXPECTED_LUT[5] == 3.0
- assert EXPECTED_LUT[7] == 6.0
-
-
-class TestUnpackFp4E2m1:
- def test_high_nibble_is_the_even_element(self) -> None:
- """The whole-model failure mode: reversing this swaps every adjacent pair without crashing.
-
- Verified against Krea-2 Turbo's bit-identical MXFP8 export — high-nibble-first gives 100%
- sign agreement and +0.996 per-block cosine, low-nibble-first gives 49.95% and -0.004.
- """
- lut = fp4_e2m1_lut(torch.float32, torch.device("cpu"))
- # 0x2A -> high nibble 0x2 (= 1.0), low nibble 0xA (= -1.0)
- unpacked = unpack_fp4_e2m1(torch.tensor([[0x2A]], dtype=torch.uint8), lut)
- assert unpacked.tolist() == [[1.0, -1.0]]
-
- def test_doubles_the_last_dim(self) -> None:
- lut = fp4_e2m1_lut(torch.float32, torch.device("cpu"))
- packed = torch.zeros((3, 8), dtype=torch.uint8)
- assert unpack_fp4_e2m1(packed, lut).shape == (3, 16)
-
- def test_consecutive_elements_are_adjacent_not_split_into_halves(self) -> None:
- # A split-halves layout (all low nibbles, then all high) would put these values in a
- # different order; independently confirmed on a real checkpoint, where the interleaved
- # layout puts the max code in 100% of scale blocks vs ~85% for split halves.
- lut = fp4_e2m1_lut(torch.float32, torch.device("cpu"))
- packed = torch.tensor([[0x12, 0x34]], dtype=torch.uint8)
- assert unpack_fp4_e2m1(packed, lut).tolist() == [[0.5, 1.0, 1.5, 2.0]]
-
- def test_rejects_non_uint8_weights(self) -> None:
- lut = fp4_e2m1_lut(torch.float32, torch.device("cpu"))
- with pytest.raises(ValueError, match="must be uint8"):
- unpack_fp4_e2m1(torch.zeros((2, 2), dtype=torch.int8), lut)
-
-
-class TestExpandBlockScale:
- def test_expands_one_scale_per_block(self) -> None:
- scale = torch.tensor([[1.0, 2.0]])
- expanded = expand_block_scale(scale, 4, name="w")
- assert expanded.tolist() == [[1.0, 1.0, 2.0, 2.0]]
-
- def test_passes_through_a_fully_expanded_scale(self) -> None:
- scale = torch.tensor([[1.0, 2.0, 3.0]])
- assert expand_block_scale(scale, 3, name="w") is scale
-
- def test_rejects_a_scale_that_does_not_divide_the_weight(self) -> None:
- with pytest.raises(ValueError, match="does not evenly divide"):
- expand_block_scale(torch.ones((1, 3)), 8, name="some.weight")
-
-
-class TestIsNvfp4StateDict:
- def test_detects_the_per_tensor_global_scale(self) -> None:
- assert is_nvfp4_state_dict({"a.weight": None, "a.weight_scale": None, "a.weight_scale_2": None})
-
- def test_does_not_match_scaled_fp8(self) -> None:
- # Both formats use `.weight_scale`; only NVFP4 adds `.weight_scale_2`. Misdetecting here is
- # what would send a packed 4-bit weight through the scaled-fp8 path.
- assert not is_nvfp4_state_dict({"a.weight": None, "a.weight_scale": None})
- assert not is_nvfp4_state_dict({"a.weight": None, "a.scale_weight": None})
-
- def test_tolerates_non_string_keys(self) -> None:
- assert not is_nvfp4_state_dict({0: None})
-
-
-class TestDequantizeNvfp4:
- def test_round_trips_values_that_lie_on_the_fp4_grid(self) -> None:
- # Every value is exactly representable, so dequantization must reproduce it bit-for-bit.
- row = torch.tensor([[0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0, -0.5]])
- sd = _nvfp4_sd(row)
- assert dequantize_nvfp4(sd, torch.float32) == 1
- torch.testing.assert_close(sd["layer.weight"], row)
-
- def test_restores_the_logical_shape(self) -> None:
- weight = torch.randn(8, 32)
- sd = _nvfp4_sd(weight)
- assert sd["layer.weight"].shape == (8, 16) # packed: half width
- dequantize_nvfp4(sd, torch.float32)
- assert sd["layer.weight"].shape == (8, 32)
-
- def test_approximates_arbitrary_weights_and_stays_finite(self) -> None:
- torch.manual_seed(0)
- weight = torch.randn(16, 64) * 0.05
- sd = _nvfp4_sd(weight)
- dequantize_nvfp4(sd, torch.float32)
- out = sd["layer.weight"]
- assert torch.isfinite(out).all()
- # 1 mantissa bit -> coarse, but the per-block direction must be preserved.
- cosine = torch.nn.functional.cosine_similarity(out.flatten(), weight.flatten(), dim=0)
- assert cosine > 0.99
-
- def test_applies_the_global_scale(self) -> None:
- sd = _nvfp4_sd(torch.tensor([[6.0] * 16]))
- sd["layer.weight_scale_2"] = torch.tensor(3.0)
- dequantize_nvfp4(sd, torch.float32)
- torch.testing.assert_close(sd["layer.weight"], torch.tensor([[18.0] * 16]))
-
- def test_removes_all_scale_keys(self) -> None:
- sd = _nvfp4_sd(torch.randn(4, 16))
- dequantize_nvfp4(sd, torch.float32)
- assert set(sd) == {"layer.weight"}
-
- def test_removes_orphan_scales_with_no_matching_weight(self) -> None:
- # Nothing can be multiplied by these, and leaving them behind would inflate the caller's
- # size accounting and reach load_state_dict as unexpected keys.
- sd = {"ghost.weight_scale": torch.ones(1), "ghost.weight_scale_2": torch.tensor(1.0)}
- assert dequantize_nvfp4(sd, torch.float32) == 0
- assert sd == {}
-
- def test_is_a_no_op_without_nvfp4_keys(self) -> None:
- sd = {"a.weight": torch.ones(2, 2)}
- assert dequantize_nvfp4(sd, torch.float32) == 0
- assert set(sd) == {"a.weight"}
-
- def test_honors_the_compute_dtype(self) -> None:
- sd = _nvfp4_sd(torch.randn(4, 16))
- dequantize_nvfp4(sd, torch.bfloat16)
- assert sd["layer.weight"].dtype == torch.bfloat16
-
-
-class TestFp8StorageStreaming:
- """Dequantizing straight to fp8 is what keeps peak host RAM at the fp8 model size.
-
- Dequantizing everything to bf16 and re-quantizing afterwards is numerically identical but
- transiently needs the full bf16 model — 23.9 GiB for a 12.8 B-parameter Krea-2 transformer.
- """
-
- def test_nvfp4_stores_at_the_storage_dtype(self) -> None:
- sd = _nvfp4_sd(torch.randn(4, 16))
- dequantize_nvfp4(sd, torch.bfloat16, storage_dtype=torch.float8_e4m3fn)
- assert sd["layer.weight"].dtype == torch.float8_e4m3fn
-
- def test_scaled_fp8_stores_at_the_storage_dtype(self) -> None:
- sd = {
- "layer.weight": torch.randn(4, 8).to(torch.float8_e4m3fn),
- "layer.weight_scale": torch.tensor(2.0),
- }
- dequantize_scaled_fp8(sd, torch.bfloat16, storage_dtype=torch.float8_e4m3fn)
- assert sd["layer.weight"].dtype == torch.float8_e4m3fn
-
- def test_skip_patterns_preserve_precision_sensitive_weights(self) -> None:
- sd = {
- **_nvfp4_sd(torch.randn(4, 16), name="attn.to_q"),
- **_nvfp4_sd(torch.randn(4, 16), name="norm_out.linear"),
- }
- dequantize_nvfp4(sd, torch.bfloat16, storage_dtype=torch.float8_e4m3fn, skip_patterns=FP8_STORAGE_SKIP_PATTERNS)
- assert sd["attn.to_q.weight"].dtype == torch.float8_e4m3fn
- assert sd["norm_out.linear.weight"].dtype == torch.bfloat16
-
- def test_defaults_to_the_compute_dtype(self) -> None:
- sd = _nvfp4_sd(torch.randn(4, 16))
- dequantize_nvfp4(sd, torch.bfloat16)
- assert sd["layer.weight"].dtype == torch.bfloat16
-
-
-class TestResolveTargetDtype:
- def test_returns_compute_dtype_when_no_storage_dtype_is_requested(self) -> None:
- assert resolve_target_dtype("a.b", torch.bfloat16, None, FP8_STORAGE_SKIP_PATTERNS) == torch.bfloat16
-
- def test_returns_storage_dtype_for_an_unskipped_name(self) -> None:
- target = resolve_target_dtype(
- "blocks.0.attn.wq", torch.bfloat16, torch.float8_e4m3fn, FP8_STORAGE_SKIP_PATTERNS
- )
- assert target == torch.float8_e4m3fn
-
- @pytest.mark.parametrize("name", ["blocks.0.prenorm", "pos_embed.proj", "patch_embed.proj", "proj_in"])
- def test_skips_precision_sensitive_names(self, name: str) -> None:
- target = resolve_target_dtype(name, torch.bfloat16, torch.float8_e4m3fn, FP8_STORAGE_SKIP_PATTERNS)
- assert target == torch.bfloat16
-
-
-class TestReadDeclaredQuantizationFormats:
- def test_reads_the_declared_formats(self, tmp_path) -> None:
- import json
-
- from safetensors.torch import save_file
-
- path = tmp_path / "m.safetensors"
- metadata = {
- "_quantization_metadata": json.dumps(
- {"layers": {"blocks.0.attn.wq": {"format": "nvfp4"}, "blocks.1.mlp.up": {"format": "MXFP8"}}}
- )
- }
- save_file({"a": torch.ones(2)}, path, metadata=metadata)
- assert read_declared_quantization_formats(path) == {"nvfp4", "mxfp8"}
-
- def test_returns_empty_for_a_file_without_metadata(self, tmp_path) -> None:
- from safetensors.torch import save_file
-
- path = tmp_path / "m.safetensors"
- save_file({"a": torch.ones(2)}, path)
- assert read_declared_quantization_formats(path) == set()
-
- @pytest.mark.parametrize("name", ["empty.safetensors", "model.gguf", "missing.safetensors"])
- def test_never_raises_on_an_unreadable_file(self, tmp_path, name: str) -> None:
- # This only ever rejects a load, so it must not become a failure mode of its own.
- path = tmp_path / name
- if "missing" not in name:
- path.touch()
- assert read_declared_quantization_formats(path) == set()
-
- def test_returns_empty_for_malformed_metadata(self, tmp_path) -> None:
- from safetensors.torch import save_file
-
- path = tmp_path / "m.safetensors"
- save_file({"a": torch.ones(2)}, path, metadata={"_quantization_metadata": "{not json"})
- assert read_declared_quantization_formats(path) == set()