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.

fix(fp8): apply the keep-fp8 filters to raw weights only, probe the device

Alexander Eichhorn526cb3689023
diff --git a/docs/src/content/docs/configuration/fp8-storage.mdx b/docs/src/content/docs/configuration/fp8-storage.mdx
index 2e0595c914..fe1ac4d687 100644
--- a/docs/src/content/docs/configuration/fp8-storage.mdx
+++ b/docs/src/content/docs/configuration/fp8-storage.mdx
@@ -98,29 +98,31 @@ If you see unexpected quality regressions, disable FP8 Storage on the affected m
## FP8 Compute
-Everything above describes FP8 *Storage*: a per-model toggle that changes how weights are **stored**, while the math still runs in BF16. `fp8_compute` is a separate, global setting in `invokeai.yaml` that changes how they are **multiplied** — ComfyUI "scaled fp8" checkpoints stay quantized and their matmuls run on the FP8 tensor cores via `torch._scaled_mm`, instead of being dequantized at load time.
+Everything above describes FP8 *Storage*, which changes how weights are **stored** while the math still runs in BF16. `fp8_compute` is a separate, global setting in `invokeai.yaml` that also does the **math** in FP8, on GPUs that have hardware for it. That makes generation faster, not just smaller.
-It needs an Ada (SM 8.9) or newer NVIDIA GPU and falls back to the dequantized path automatically on anything older. It applies to checkpoints that already ship quantized; FP8 Storage is the toggle for full-precision ones.
+It is for models that were **already saved in FP8** by whoever published them — you'll often see these labelled "fp8" or "fp8_scaled" in the filename. Normally InvokeAI unpacks them back to BF16 while loading; with `fp8_compute` on, they stay as they are and run directly on the GPU's FP8 hardware. FP8 Storage is the toggle for the other case: a full-precision model you want to shrink yourself.
+
+Not every part of a model stays in FP8 — the small, precision-sensitive pieces are always unpacked. Those are a tiny share of the weights, so you still get nearly the full VRAM saving.
+
+You need an FP8-capable GPU: RTX 40-series or newer, the datacenter cards of those generations, or AMD MI300 and newer. InvokeAI checks your card the first time it needs to — by actually trying a small FP8 operation rather than going by the model name — so a card that can't do it quietly falls back to the normal path instead of failing partway through a generation.
:::danger[Reproducibility requires the model to be fully in VRAM]
With `fp8_compute` enabled, **the same seed only reproduces the same image if the model is 100% resident in VRAM.**
-The FP8 matmul needs both operands on the same device, so a layer whose weights are still in RAM cannot use it and silently falls back to the dequantized BF16 path. That fallback is numerically different — and *which* layers it hits depends on how much of the model happened to fit at that moment, which shifts between runs as VRAM pressure changes.
-
-Measured on a 24 GB card with a ~12 GB transformer sitting at 88–95% residency: two runs with an identical seed and identical settings differed in **98.7% of all pixels**. With the model fully resident, repeated runs were **bit-identical**.
+FP8 math only happens for the parts of the model that are actually on the GPU. Anything still sitting in system RAM takes the normal path instead, which gives slightly different numbers — and *which* parts that affects depends on how much of the model happened to fit at that moment, which changes from run to run.
-A *constant* residency fraction would in principle be reproducible too, but nothing guarantees one in practice — other resident models, per-node working-memory reservations and allocator state all move the line between runs.
+Measured on a 24 GB card with a ~12 GB model at 88–95% loaded: two runs with an identical seed and identical settings differed in **98.7% of all pixels**. With the model fully loaded, repeated runs came out **identical**.
-To get repeatable output, check the model's load line in the log for `VRAM: … (100.0%)`. If it is below that, free up VRAM (lower resolution, fewer resident models, a smaller text encoder) or set `enable_partial_loading: false`.
+To get repeatable output, check the model's load line in the log for `VRAM: … (100.0%)`. If it is below that, free up VRAM (lower resolution, fewer models loaded at once, a smaller text encoder) or set `enable_partial_loading: false`.
:::
-Keeping the model fully resident is worth it for speed as well: on the same 24 GB card, streaming the last 5–12% of the transformer over PCIe cost **+47% per step** (1.03 → 1.51 s/it at 1024², 8 steps).
+Keeping the whole model on the GPU is worth it for speed as well: on the same 24 GB card, having to stream the last 5–12% of the model over PCIe cost **+47% per step** (1.03 → 1.51 s/it at 1024², 8 steps).
-### Layers the checkpoint marks as full-precision
+### When the model asks for full precision
-Some scaled-fp8 checkpoints mark individual layers with `full_precision_matrix_mult`, meaning the producer measured them as unsafe to multiply in FP8. InvokeAI honors those markers by default, which means those layers dequantize on every forward instead of using the tensor cores. On checkpoints that mark many layers this can cost a large part of the FP8 Compute speedup.
+Some FP8 models come with a note from whoever made them, marking certain layers as ones that should not use FP8 math. InvokeAI follows those notes by default, so those layers run the slower way. On a model that marks a lot of layers, this can eat much of the FP8 Compute speedup.
-`fp8_compute_full_precision_hints: false` overrides the markers and runs every quantized layer on the tensor cores. It is faster, but you are deliberately going against the checkpoint author's instruction — the marked layers were flagged as numerically sensitive, so compare output before settling on it.
+Setting `fp8_compute_full_precision_hints: false` ignores the notes and runs everything on the FP8 hardware. It is faster, but you are overriding the model author's judgement about which layers are sensitive — so compare a few images before sticking with it.
## Troubleshooting
diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.py
index 16aeaa6379..6fdaa96091 100644
--- a/invokeai/backend/model_manager/load/model_loaders/flux.py
+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py
@@ -74,7 +74,12 @@ from invokeai.backend.model_manager.taxonomy import (
from invokeai.backend.model_manager.util.model_util import (
convert_bundle_to_flux_transformer_checkpoint,
)
-from invokeai.backend.quantization.fp8_scaled import FP8_DTYPE, cast_state_dict, should_keep_fp8_weights
+from invokeai.backend.quantization.fp8_scaled import (
+ can_stay_quantized,
+ cast_state_dict,
+ predict_cast_state_dict_size,
+ should_keep_fp8_weights,
+)
from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader
from invokeai.backend.quantization.gguf.utils import TORCH_COMPATIBLE_QTYPES
from invokeai.backend.util.silence_warnings import SilenceWarnings
@@ -655,11 +660,7 @@ class FluxCheckpointModel(ModelLoader):
# fp8 matmul is available; casting them to bf16 here would throw away both the VRAM saving
# and the tensor cores before the model is ever built.
keep_fp8 = should_keep_fp8_weights(self._torch_device)
- new_sd_size = sum(
- ten.nelement() * (ten.element_size() if keep_fp8 and ten.dtype is FP8_DTYPE else torch.bfloat16.itemsize)
- for ten in sd.values()
- )
- self._ram_cache.make_room(new_sd_size)
+ self._ram_cache.make_room(predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=keep_fp8, model=model))
# Everything else is cast to bfloat16, the only dtype currently supported for inference.
kept = cast_state_dict(sd, torch.bfloat16, keep_fp8=keep_fp8, model=model)
if kept:
@@ -915,7 +916,8 @@ class Flux2CheckpointModel(ModelLoader):
# Handle FP8 quantized weights (ComfyUI-style or scaled FP8)
# These store weights as: layer.weight (FP8) + layer.weight_scale (FP32 scalar)
- sd = self._dequantize_fp8_weights(sd)
+ keep_fp8 = should_keep_fp8_weights(self._torch_device)
+ sd = self._dequantize_fp8_weights(sd, keep_fp8=keep_fp8)
# Check if keys have ComfyUI-style prefix and strip if needed
prefix_to_strip = None
@@ -1014,7 +1016,7 @@ class Flux2CheckpointModel(ModelLoader):
kept = cast_state_dict(
converted_sd,
torch.bfloat16,
- keep_fp8=should_keep_fp8_weights(self._torch_device),
+ keep_fp8=keep_fp8,
model=model,
skip_patterns=getattr(model, "_skip_layerwise_casting_patterns", None) or (),
)
@@ -1026,7 +1028,7 @@ class Flux2CheckpointModel(ModelLoader):
return model
- def _dequantize_fp8_weights(self, sd: dict) -> dict:
+ def _dequantize_fp8_weights(self, sd: dict, keep_fp8: bool = False) -> dict:
"""Dequantize FP8 quantized weights in the state dict.
ComfyUI and some FLUX.2 models store quantized weights as:
@@ -1036,6 +1038,18 @@ class Flux2CheckpointModel(ModelLoader):
Dequantization formula: dequantized = weight.to(float) * weight_scale
Also handles FP8 tensors stored with float8_e4m3fn dtype by converting to float.
+
+ ``keep_fp8`` spares the *raw* fp8 weights (fp8 with no ``weight_scale``) that trailing
+ conversion, so they survive to `cast_state_dict` and reach the tensor cores. Without it this
+ method converts every float8 tensor unconditionally and nothing fp8 is left downstream — the
+ FLUX.2 half of the raw-fp8 path would never execute. Scaled weights are always folded here:
+ they have already had their scale applied a few lines up, so they are no longer float8 by
+ the time the loop below runs.
+
+ The test is deliberately the model-less form of :func:`can_stay_quantized` — the module tree
+ does not exist yet at this point, and the keys are still in checkpoint naming. It is a
+ superset: `cast_state_dict` re-applies the same predicate later *with* the model and casts
+ whatever turns out not to be an ``nn.Linear`` weight.
"""
# Check for ComfyUI-style scale factors
weight_scale_keys = [k for k in sd.keys() if isinstance(k, str) and k.endswith(".weight_scale")]
@@ -1089,6 +1103,8 @@ class Flux2CheckpointModel(ModelLoader):
# 0-dimensional tensor (scalar) - likely metadata, remove it
keys_to_remove_scalars.append(key)
elif hasattr(tensor, "dtype") and "float8" in str(tensor.dtype):
+ if keep_fp8 and can_stay_quantized(key, tensor, None):
+ continue
# Native FP8 tensor - mark for conversion
keys_to_convert.append(key)
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.py
index c18743aafd..ecb1cb336a 100644
--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py
+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py
@@ -29,13 +29,15 @@ from invokeai.backend.quantization.fp8_scaled import (
attach_fp8_scales,
cast_state_dict,
dequantize_fp8_scaled,
- device_supports_fp8_matmul,
extract_comfy_quant_hints,
extract_fp8_scaled_layers,
full_precision_hints_respected,
- is_fp8_matmul_enabled,
parse_quantization_metadata,
+ predict_cast_state_dict_size,
+ read_safetensors_metadata,
should_keep_fp8_weights,
+ split_fp8_scaled_layers,
+ warn_on_unattached_scales,
)
from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader
from invokeai.backend.util.devices import TorchDevice
@@ -141,24 +143,6 @@ def _dequantize_scaled_fp8(sd: dict[str, Any], dtype: "torch.dtype") -> dict[str
return out
-def _read_safetensors_metadata(path: Path, logger: Any = 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.
- """
- try:
- from safetensors import safe_open
-
- with safe_open(path, framework="pt") as f:
- 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.")
- return None
-
-
def _remap_native_layer_paths(layer_names: Any) -> dict[str, str]:
"""Map native/ComfyUI layer paths to their diffusers equivalents.
@@ -407,7 +391,7 @@ class Krea2CheckpointModel(ModelLoader):
model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
sd = load_file(model_path)
- metadata = _read_safetensors_metadata(model_path, self._logger)
+ metadata = read_safetensors_metadata(model_path, self._logger)
sd = _strip_comfyui_prefix(sd)
# Native/ComfyUI key naming → diffusers Krea2Transformer2DModel keys. Done *before* the fp8
# scales are pulled out: the renames are substring-based on ".weight", so a sibling
@@ -428,31 +412,36 @@ class Krea2CheckpointModel(ModelLoader):
# ComfyUI 'scaled fp8' checkpoints (fp8 weight + .weight_scale, optionally .input_scale).
fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)
- if fp8_layers and not is_fp8_matmul_enabled():
+ keep_fp8 = should_keep_fp8_weights(target_device)
+ if fp8_layers and not keep_fp8:
# Legacy behavior: fold the scales into the weights. Keeping them quantized without the
# fp8 matmul would halve VRAM but run slower, so both are tied to the same setting.
dequantize_fp8_scaled(sd, fp8_layers, model_dtype)
fp8_layers = {}
-
with accelerate.init_empty_weights():
model = Krea2Transformer2DModel(**KREA2_TRANSFORMER_CONFIG)
- # fp8 weights keep their own (1-byte) footprint; everything else lands in model_dtype.
- new_sd_size = sum(
- ten.nelement() * (ten.element_size() if ten.dtype == FP8_DTYPE else model_dtype.itemsize)
- for ten in sd.values()
+ skip_patterns = tuple(getattr(model, "_skip_layerwise_casting_patterns", None) or ())
+ # Scaled layers the cast would dequantize anyway (skip patterns, non-Linear weights) are
+ # folded here, with their scale applied. Left to `cast_state_dict` they would be cast
+ # *without* it and `attach_fp8_scales` would then skip them for no longer being fp8 —
+ # a weight silently off by 1/weight_scale. Krea-2's `time_embed.linear_1/linear_2` are
+ # ordinary quantized Linears in a ComfyUI export and match the model's `time_embed` pattern.
+ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)
+
+ self._ram_cache.make_room(
+ predict_cast_state_dict_size(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)
)
- self._ram_cache.make_room(new_sd_size)
- # `keep_fp8` covers the scaled path decided above; a checkpoint with raw fp8 weights (fp8
- # tensors and no weight_scale) yields no fp8_layers at all, but its weights are still usable
- # on the tensor cores, so they are kept whenever the matmul is available.
+ # A checkpoint with raw fp8 weights (fp8 tensors and no weight_scale) yields no fp8_layers at
+ # all, but its weights are still usable on the tensor cores, so the same `keep_fp8` covers
+ # both kinds.
kept = cast_state_dict(
sd,
model_dtype,
- keep_fp8=bool(fp8_layers) or should_keep_fp8_weights(target_device),
+ keep_fp8=keep_fp8,
model=model,
- skip_patterns=getattr(model, "_skip_layerwise_casting_patterns", None) or (),
+ skip_patterns=skip_patterns,
)
model.load_state_dict(sd, assign=True, strict=False)
@@ -469,6 +458,7 @@ class Krea2CheckpointModel(ModelLoader):
if fp8_layers:
attached = attach_fp8_scales(model, fp8_layers)
self._logger.info(f"Krea-2: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, fp8_compute enabled)")
+ warn_on_unattached_scales(self._logger, "Krea-2", attached, fp8_layers)
# Marked layers dequantize on every forward instead of using the tensor cores, which is
# the single biggest lever on how much fp8_compute actually buys for a given checkpoint.
# Surface it: otherwise "fp8_compute is on but barely faster" has no visible cause.
@@ -716,7 +706,7 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):
model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
sd = load_file(str(model_path))
- metadata = _read_safetensors_metadata(model_path, self._logger)
+ metadata = read_safetensors_metadata(model_path, self._logger)
# Per-layer markers must be read before extract_fp8_scaled_layers() drops them, and before
# the key remap, which would not carry a ".comfy_quant" suffix to a sensible destination.
layer_hints = {**extract_comfy_quant_hints(sd), **parse_quantization_metadata(metadata)}
@@ -733,8 +723,7 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):
source_is_fp8 = bool(fp8_layers) or any(
getattr(t, "dtype", None) in (torch.float8_e4m3fn, torch.float8_e5m2) for t in sd.values()
)
- keep_fp8 = bool(fp8_layers) and is_fp8_matmul_enabled() and device_supports_fp8_matmul(target_device)
- if fp8_layers and not keep_fp8:
+ if fp8_layers and not should_keep_fp8_weights(target_device):
# Legacy behavior: fold the scales into the weights. Without the fp8 matmul, staying
# quantized would save VRAM but cost speed, so the two are tied to the same setting.
dequantize_fp8_scaled(sd, fp8_layers, model_dtype)
@@ -762,6 +751,7 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):
# cores. Same resident VRAM as the layerwise-casting path below, but without paying a
# fp8->bf16 round trip on every forward.
attached = attach_fp8_scales(model, fp8_layers)
+ warn_on_unattached_scales(self._logger, f"Qwen3-VL encoder '{config.name}'", attached, fp8_layers)
# The checkpoint quantizes only the language-model linears; the visual tower ships bf16
# and would make the encoder ~0.4GB larger resident than the plain fp8_storage path. On a
# GPU already holding a ~12GB transformer that is enough to push the transformer into
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 045564678a..9e390c5beb 100644
--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py
@@ -27,11 +27,75 @@ from invokeai.backend.model_manager.taxonomy import (
ModelType,
SubModelType,
)
-from invokeai.backend.quantization.fp8_scaled import FP8_DTYPE, cast_state_dict, should_keep_fp8_weights
+from invokeai.backend.quantization.fp8_scaled import (
+ attach_fp8_scales,
+ cast_state_dict,
+ dequantize_fp8_scaled,
+ extract_comfy_quant_hints,
+ extract_fp8_scaled_layers,
+ full_precision_hints_respected,
+ parse_quantization_metadata,
+ predict_cast_state_dict_size,
+ read_safetensors_metadata,
+ should_keep_fp8_weights,
+ split_fp8_scaled_layers,
+ warn_on_unattached_scales,
+)
from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader
from invokeai.backend.qwen3.qwen3_tokenizer import load_bundled_qwen3_tokenizer
from invokeai.backend.util.devices import TorchDevice
+# Per-layer quantization side-channel entries that sit next to a fused `qkv.weight` and therefore
+# have to be split along with it. The scale spellings are the ones `fp8_scaled` accepts; the marker
+# is a JSON blob describing the layer, identical for all three halves of the split.
+_QKV_SPLIT_SIDECHANNEL_SUFFIXES = ("weight_scale", "scale_weight", "input_scale", "scale_input", "comfy_quant")
+
+
+def _split_qkv_sidechannel(key: str, value: Any) -> tuple[Any, Any, Any]:
+ """Split a fused-QKV scale/marker into the parts belonging to Q, K and V.
+
+ A per-tensor scale (and any marker blob) describes the whole fused tensor, so each third
+ inherits it unchanged. A per-output-channel scale has one entry per row and is split exactly
+ like the weight.
+ """
+ tensor = torch.as_tensor(value) if hasattr(value, "shape") else value
+ if not hasattr(tensor, "shape") or tensor.dim() == 0 or tensor.shape[0] == 1:
+ return (tensor, tensor, tensor)
+ if tensor.numel() == 1 or key.endswith(("comfy_quant", "input_scale", "scale_input")):
+ # A marker blob is a 1-D byte string, not a per-channel vector — never split it.
+ return (tensor, tensor, tensor)
+ if tensor.shape[0] % 3 != 0:
+ raise ValueError(
+ f"Cannot split fused QKV quantization data '{key}': first dimension ({tensor.shape[0]}) is "
+ "neither 1 nor divisible by 3, so it matches neither a per-tensor nor a per-channel scale."
+ )
+ third = tensor.shape[0] // 3
+ return (tensor[:third], tensor[third : 2 * third], tensor[2 * third :])
+
+
+def _remap_z_image_layer_paths(layer_names: Any) -> dict[str, list[str]]:
+ """Map native Z-Image layer paths to their diffusers equivalents.
+
+ ``_quantization_metadata`` names its layers in the checkpoint's own scheme, but the scales are
+ extracted after the state dict has been renamed. Rather than restating the rename rules — which
+ would drift — each name is pushed through the real converter as a lone ``<name>.weight`` entry
+ and the resulting keys are read back. A fused ``qkv`` maps to *three* diffusers layers, so the
+ mapping is one-to-many.
+ """
+ mapping: dict[str, list[str]] = {}
+ for name in layer_names:
+ if not isinstance(name, str):
+ continue
+ try:
+ # 3 rows so the qkv split is well-defined; the values themselves are never read.
+ converted = _convert_z_image_gguf_to_diffusers({f"{name}.weight": torch.empty(3, 1)})
+ except Exception:
+ continue
+ targets = [k[: -len(".weight")] for k in converted if isinstance(k, str) and k.endswith(".weight")]
+ if targets:
+ mapping[name] = targets
+ return mapping
+
def _convert_z_image_gguf_to_diffusers(sd: dict[str, Any]) -> dict[str, Any]:
"""Convert Z-Image GGUF state dict keys to diffusers format.
@@ -89,9 +153,15 @@ def _convert_z_image_gguf_to_diffusers(sd: dict[str, Any]) -> dict[str, Any]:
prefix = key.rsplit(".attention.qkv.", 1)[0]
suffix = key.rsplit(".attention.qkv.", 1)[1] # "weight" or "bias"
- # Skip non-weight/bias tensors (e.g., FP8 scale_weight tensors)
- # These are quantization metadata and should not be split
if suffix not in ("weight", "bias"):
+ # Quantization side-channel for the fused weight. It has to travel with the split,
+ # or the recovered scale is keyed on `...attention.qkv`, a module path that no
+ # longer exists — `attach_fp8_scales` then finds nothing and the three split
+ # weights stay quantized but *unscaled*, i.e. off by 1/weight_scale.
+ if suffix in _QKV_SPLIT_SIDECHANNEL_SUFFIXES:
+ for name, part in zip(("to_q", "to_k", "to_v"), _split_qkv_sidechannel(key, value), strict=True):
+ new_sd[f"{prefix}.attention.{name}.{suffix}"] = part
+ continue
new_sd[key] = value
continue
@@ -223,6 +293,11 @@ class ZImageCheckpointModel(ModelLoader):
stripped_sd[key] = value
sd = stripped_sd
+ # 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.
+ header_hints = parse_quantization_metadata(read_safetensors_metadata(model_path, self._logger))
+
# 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))
@@ -230,6 +305,10 @@ class ZImageCheckpointModel(ModelLoader):
if needs_conversion:
# Convert from original format to diffusers format
sd = _convert_z_image_gguf_to_diffusers(sd)
+ path_map = _remap_z_image_layer_paths(header_hints.keys())
+ header_hints = {
+ target: hints for name, hints in header_hints.items() for target in path_map.get(name, [name])
+ }
# Create an empty model with the default Z-Image config
# Z-Image-Turbo uses these default parameters from diffusers
@@ -259,7 +338,8 @@ class ZImageCheckpointModel(ModelLoader):
# Filter out keys that don't belong to the ZImageTransformer2DModel.
# Merged checkpoints (e.g. LoRA-baked models) may bundle text encoder weights
# (text_encoders.*) or other non-transformer keys alongside the transformer weights.
- # Also filter FP8 quantization metadata (scale_weight, scaled_fp8).
+ # This runs *before* the scales are extracted so a bundled encoder's own scale keys are
+ # dropped here rather than being recovered as transformer layers that resolve to nothing.
valid_prefixes = (
"all_x_embedder.",
"all_final_layer.",
@@ -271,41 +351,63 @@ class ZImageCheckpointModel(ModelLoader):
"rope_embedder.",
)
valid_exact = {"x_pad_token", "cap_pad_token"}
- keys_to_remove = [
- k
- for k in sd.keys()
- if not (k.startswith(valid_prefixes) or k in valid_exact)
- or k.endswith(".scale_weight")
- or k == "scaled_fp8"
- ]
+ 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]
+ # ComfyUI 'scaled fp8' (fp8 weight + .weight_scale/.scale_weight). Until now the loader
+ # deleted those scales and cast the weight — silently producing a weight off by
+ # 1/weight_scale — and had no way to tell such a checkpoint from a raw fp8 one.
+ layer_hints = {**extract_comfy_quant_hints(sd), **header_hints}
+ fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)
+
# Handle memory management and dtype conversion. A checkpoint that ships raw fp8 weights
# (fp8 tensors, no weight_scale) keeps them when the fp8 matmul is available — casting 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)
- new_sd_size = sum(
- ten.nelement() * (ten.element_size() if keep_fp8 and ten.dtype is FP8_DTYPE else model_dtype.itemsize)
- for ten in sd.values()
- )
- self._ram_cache.make_room(new_sd_size)
+ 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 = tuple(getattr(model, "_skip_layerwise_casting_patterns", None) or ())
+ # 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)
+
+ self._ram_cache.make_room(
+ predict_cast_state_dict_size(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)
+ )
kept = cast_state_dict(
sd,
model_dtype,
keep_fp8=keep_fp8,
model=model,
- skip_patterns=getattr(model, "_skip_layerwise_casting_patterns", None) or (),
+ skip_patterns=skip_patterns,
)
- if kept:
- self._logger.info(f"Z-Image: kept {kept} raw fp8 weight(s) quantized for the fp8 tensor cores.")
model.load_state_dict(sd, assign=True)
+
+ if fp8_layers:
+ attached = attach_fp8_scales(model, fp8_layers)
+ self._logger.info(f"Z-Image: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, fp8_compute enabled)")
+ warn_on_unattached_scales(self._logger, "Z-Image", attached, fp8_layers)
+ marked = sum(1 for layer in fp8_layers.values() if layer.full_precision_matmul)
+ if marked and full_precision_hints_respected():
+ self._logger.info(
+ f"Z-Image: {marked} of {len(fp8_layers)} layer(s) are marked full_precision_matrix_mult "
+ "and will dequantize per forward. Set fp8_compute_full_precision_hints=false to run "
+ "them on the fp8 tensor cores instead."
+ )
+ elif kept:
+ self._logger.info(
+ f"Z-Image: kept {kept} raw fp8 weight(s) quantized (no weight_scale in the checkpoint); "
+ "they will run on the fp8 tensor cores with unit scaling."
+ )
return model
diff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.py
index 36ae6f7f6f..df245316b2 100644
--- a/invokeai/backend/quantization/fp8_scaled.py
+++ b/invokeai/backend/quantization/fp8_scaled.py
@@ -18,6 +18,8 @@ that :class:`CustomLinear` can decide per forward what to do with it.
"""
from dataclasses import dataclass
+from logging import Logger
+from pathlib import Path
from typing import Any, Iterable, Mapping
import torch
@@ -56,6 +58,24 @@ class Fp8ScaledLayer:
return self.weight_scale.numel() == 1
+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.
+ """
+ try:
+ from safetensors import safe_open
+
+ with safe_open(path, framework="pt") as f:
+ 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.")
+ return None
+
+
def parse_quantization_metadata(metadata: Mapping[str, Any] | None) -> dict[str, dict[str, Any]]:
"""Parse the safetensors ``_quantization_metadata`` header entry into a per-layer mapping.
@@ -243,7 +263,8 @@ def attach_fp8_scales(
parse time, so the recovered metadata stays inspectable, and are suppressed when the user has
turned the hints off (see :func:`full_precision_hints_respected`).
- Returns the number of modules that were annotated.
+ Returns the number of modules that were annotated. A caller that expects *every* recovered
+ layer to be annotated should check that count with :func:`warn_on_unattached_scales`.
"""
wanted = set(module_paths) if module_paths is not None else None
respect_hints = full_precision_hints_respected()
@@ -266,6 +287,24 @@ def attach_fp8_scales(
return count
+def warn_on_unattached_scales(logger: Logger, what: str, attached: int, layers: Mapping[str, Any]) -> None:
+ """Complain when :func:`attach_fp8_scales` annotated fewer modules than there were layers.
+
+ Every recovered layer should reach a module: :func:`split_fp8_scaled_layers` has already folded
+ the ones that cannot stay quantized. A shortfall therefore means a scale went nowhere, and a
+ weight is now off by ``1/weight_scale`` — visually a broken or washed-out generation, with
+ nothing in the log to point at it. Loaders otherwise report ``attached`` as if it were the whole
+ story, which reads as success.
+ """
+ missing = len(layers) - attached
+ if missing > 0:
+ logger.warning(
+ f"{what}: {missing} of {len(layers)} scaled fp8 layer(s) did not receive their weight_scale. "
+ "Those weights are quantized but unscaled, which will degrade output. This is a bug — "
+ "please report the checkpoint."
+ )
+
+
# ----------------------------------------------------------------------------------- runtime path
FP8_MAX = torch.finfo(FP8_DTYPE).max
@@ -333,18 +372,48 @@ def full_precision_hints_respected() -> bool:
return True
+def _probe_fp8_matmul(index: int) -> bool:
+ """Run one minimal ``_scaled_mm`` on device ``index`` and report whether it worked.
+
+ Asking the device is the only reliable test. ``get_device_capability`` reports the *gfx arch*
+ on ROCm, not an SM version, so an RDNA3 card (gfx1100) answers ``(11, 0)`` and sails past a
+ ``>= (8, 9)`` check — then every forward raises ``torch._scaled_mm is only supported on CUDA
+ devices with compute capability >= 9.0 or 8.9, or ROCm MI300+``. The whole point of the
+ capability gate is to *fall back* rather than raise mid-generation, so it must not itself be a
+ guess. The probe is one 16x16 matmul, run once per device and cached.
+ """
+ try:
+ device = torch.device("cuda", index)
+ # Column-major right operand, i.e. exactly the layout `scaled_mm_linear` feeds it.
+ lhs = torch.zeros((_MM_ALIGNMENT, _MM_ALIGNMENT), device=device, dtype=FP8_DTYPE)
+ rhs = torch.zeros((_MM_ALIGNMENT, _MM_ALIGNMENT), device=device, dtype=FP8_DTYPE).t()
+ scale = torch.ones((1, 1), device=device, dtype=torch.float32)
+ torch._scaled_mm(lhs, rhs, scale, scale, out_dtype=torch.bfloat16)
+ except Exception:
+ return False
+ return True
+
+
def device_supports_fp8_matmul(device: torch.device) -> bool:
- """Whether ``torch._scaled_mm`` can run on this device (Ada/SM 8.9 and newer)."""
+ """Whether ``torch._scaled_mm`` can run on this device (Ada/SM 8.9 and newer, or MI300+)."""
if device.type != "cuda" or not torch.cuda.is_available():
return False
index = device.index if device.index is not None else torch.cuda.current_device()
cached = _fp8_mm_supported.get(index)
if cached is None:
- cached = torch.cuda.get_device_capability(index) >= (8, 9)
+ # The capability check is only a cheap pre-filter that spares older CUDA cards the probe;
+ # it is deliberately not trusted on its own (see `_probe_fp8_matmul`).
+ supported = torch.version.hip is not None or torch.cuda.get_device_capability(index) >= (8, 9)
+ cached = supported and _probe_fp8_matmul(index)
_fp8_mm_supported[index] = cached
return cached
+def reset_fp8_matmul_support_cache() -> None:
+ """Forget the probed per-device support. For tests; the answer cannot change at runtime."""
+ _fp8_mm_supported.clear()
+
+
def should_keep_fp8_weights(device: torch.device) -> bool:
"""Whether fp8 weights in a checkpoint should survive the load instead of being dequantized.
@@ -377,6 +446,37 @@ def _is_fp8_matmul_weight(key: str, tensor: Any, model: torch.nn.Module | None)
return isinstance(module, torch.nn.Linear)
+def can_stay_quantized(
+ key: str,
+ tensor: Any,
+ model: torch.nn.Module | None,
+ skip_patterns: Iterable[str] = (),
+) -> bool:
+ """Whether this state-dict entry may be left in fp8 by :func:`cast_state_dict`.
+
+ Single source of truth for that decision: the loaders reserve RAM against it
+ (:func:`predict_cast_state_dict_size`) and decide which scaled layers survive with it
+ (:func:`split_fp8_scaled_layers`), so the three must never drift apart.
+
+ Only ``float8_e4m3fn`` qualifies. ``float8_e5m2`` is always cast because
+ :func:`scaled_mm_linear` cannot use it as the weight operand on Ada, so keeping it quantized
+ would buy VRAM at the cost of a per-forward dequantize.
+
+ ``skip_patterns`` are substrings of the state-dict key whose weights must be dequantized even
+ when the rest stays fp8. Pass the model's ``_skip_layerwise_casting_patterns``: diffusers uses
+ it to mark precision-sensitive modules, and some of them *read their own weight's dtype and cast
+ their activations to it*. Z-Image's ``TimestepEmbedder.forward`` does exactly that
+ (``t_freq.to(self.mlp[0].weight.dtype)``), so leaving its weight in fp8 hands the next Linear an
+ fp8 activation and the forward dies in ``x.abs()`` with
+ ``"abs_cuda" not implemented for 'Float8_e4m3fn'``.
+ """
+ return (
+ getattr(tensor, "dtype", None) is FP8_DTYPE
+ and _is_fp8_matmul_weight(key, tensor, model)
+ and not any(pattern in key for pattern in skip_patterns)
+ )
+
+
def cast_state_dict(
sd: dict[str, Any],
dtype: torch.dtype,
@@ -391,17 +491,10 @@ def cast_state_dict(
checkpoint that ships raw fp8 weights (fp8 tensors with no ``weight_scale`` alongside them) —
the VRAM saving and the tensor cores are both thrown away before the model is ever built.
- Only ``float8_e4m3fn`` is preserved. ``float8_e5m2`` is left to be cast because
- :func:`scaled_mm_linear` cannot use it as the weight operand on Ada, so keeping it quantized
- would buy VRAM at the cost of a per-forward dequantize.
-
- ``skip_patterns`` are substrings of the state-dict key whose weights must be dequantized even
- when the rest stays fp8. Pass the model's ``_skip_layerwise_casting_patterns``: diffusers uses
- it to mark precision-sensitive modules, and some of them *read their own weight's dtype and cast
- their activations to it*. Z-Image's ``TimestepEmbedder.forward`` does exactly that
- (``t_freq.to(self.mlp[0].weight.dtype)``), so leaving its weight in fp8 hands the next Linear an
- fp8 activation and the forward dies in ``x.abs()`` with
- ``"abs_cuda" not implemented for 'Float8_e4m3fn'``.
+ A *scaled* fp8 weight must never reach this function still carrying an unapplied scale: the
+ plain ``tensor.to(dtype)`` below drops the scale silently, leaving the weight off by
+ ``1/weight_scale``. Run :func:`split_fp8_scaled_layers` first — it folds the scale into exactly
+ those layers this function would cast.
Returns the number of tensors left in fp8.
"""
@@ -409,18 +502,76 @@ def cast_state_dict(
kept = 0
for key in sd:
tensor = sd[key]
- if (
- keep_fp8
- and getattr(tensor, "dtype", None) is FP8_DTYPE
- and _is_fp8_matmul_weight(key, tensor, model)
- and not any(pattern in key for pattern in patterns)
- ):
+ if keep_fp8 and can_stay_quantized(key, tensor, model, patterns):
kept += 1
continue
sd[key] = tensor.to(dtype)
return kept
+def predict_cast_state_dict_size(
+ sd: Mapping[str, Any],
+ dtype: torch.dtype,
+ *,
+ keep_fp8: bool,
+ model: torch.nn.Module | None = None,
+ skip_patterns: Iterable[str] = (),
+) -> int:
+ """Bytes the state dict will occupy once :func:`cast_state_dict` has run over it.
+
+ Loaders call this to size their ``make_room()`` reservation. Charging 1 byte/element for every
+ fp8 tensor is wrong in the direction that hurts: only 2-D ``nn.Linear`` weights outside the skip
+ patterns stay quantized, and everything else — biases, norms, learned pad tokens, the
+ deliberately-dequantized precision-sensitive Linears — lands at ``dtype.itemsize``. On a
+ checkpoint that quantized all 453 of its tensors that under-count is most of the difference.
+ """
+ patterns = tuple(skip_patterns)
+ total = 0
+ for key, tensor in sd.items():
+ if keep_fp8 and can_stay_quantized(key, tensor, model, patterns):
+ total += tensor.nelement() * tensor.element_size()
+ else:
+ total += tensor.nelement() * dtype.itemsize
+ return total
+
+
+def split_fp8_scaled_layers(
+ sd: dict[str, Any],
+ layers: Mapping[str, Fp8ScaledLayer],
+ dtype: torch.dtype,
+ *,
+ model: torch.nn.Module | None = None,
+ skip_patterns: Iterable[str] = (),
+) -> dict[str, Fp8ScaledLayer]:
+ """Dequantize the scaled layers that cannot stay quantized; return the ones that can.
+
+ Every filter that keeps a weight *out* of fp8 — a skip pattern, a weight that is not a 2-D
+ ``nn.Linear.weight`` — is a filter that would otherwise let :func:`cast_state_dict` do a plain
+ ``.to(dtype)`` on a scaled weight, i.e. drop its ``weight_scale`` and leave the weight off by
+ ``1/weight_scale``. :func:`attach_fp8_scales` cannot repair that afterwards: it skips any module
+ whose weight is no longer fp8, so the scale is lost for good. Krea-2 hits this on ordinary
+ ComfyUI exports, where ``time_embed.linear_1/linear_2`` are quantized like any other Linear and
+ match the model's ``time_embed`` skip pattern.
+
+ So the filters are applied here instead, *before* the cast, and the affected layers go through
+ :func:`dequantize_fp8_scaled`, which applies the scale properly. They are then dropped from the
+ returned mapping — they are no longer fp8, so there is nothing left to attach.
+ """
+ patterns = tuple(skip_patterns)
+ usable: dict[str, Fp8ScaledLayer] = {}
+ unusable: dict[str, Fp8ScaledLayer] = {}
+ for path, layer in layers.items():
+ key = f"{path}.weight"
+ tensor = sd.get(key)
+ if tensor is not None and can_stay_quantized(key, tensor, model, patterns):
+ usable[path] = layer
+ else:
+ unusable[path] = layer
+ if unusable:
+ dequantize_fp8_scaled(sd, unusable, dtype)
+ return usable
+
+
def count_fp8_weights(model: torch.nn.Module) -> int:
"""Number of parameters already stored as ``float8_e4m3fn``.
diff --git a/tests/backend/model_manager/load/test_flux2_state_dict_utils.py b/tests/backend/model_manager/load/test_flux2_state_dict_utils.py
index 8425118af1..dc817cd672 100644
--- a/tests/backend/model_manager/load/test_flux2_state_dict_utils.py
+++ b/tests/backend/model_manager/load/test_flux2_state_dict_utils.py
@@ -99,3 +99,46 @@ class TestSwapScaleShift:
def test_leaves_malformed_tensor_untouched(self):
weight = torch.ones(3) # odd length -> cannot be split
assert torch.allclose(_flux2_swap_scale_shift(weight), weight)
+
+
+class TestFlux2RawFp8Gate:
+ """`_dequantize_fp8_weights` runs before `cast_state_dict`, so anything it converts is gone.
+
+ Its trailing loop used to cast *every* float8 tensor unconditionally, which meant nothing fp8
+ ever reached `cast_state_dict` and the FLUX.2 half of the raw-fp8 path could not execute.
+ """
+
+ def _dequantize(self, sd, keep_fp8):
+ from invokeai.backend.model_manager.load.model_loaders.flux import Flux2CheckpointModel
+
+ # The method does not touch `self`; calling it unbound avoids building a whole loader.
+ return Flux2CheckpointModel._dequantize_fp8_weights(None, sd, keep_fp8=keep_fp8)
+
+ def test_raw_fp8_linear_weights_survive_when_kept(self):
+ sd = {
+ "double_blocks.0.img_attn.qkv.weight": torch.zeros(48, 16).to(torch.float8_e4m3fn),
+ "double_blocks.0.img_attn.qkv.bias": torch.zeros(48).to(torch.float8_e4m3fn),
+ "double_blocks.0.img_norm.scale": torch.ones(16).to(torch.float8_e4m3fn),
+ }
+ out = self._dequantize(sd, keep_fp8=True)
+ assert out["double_blocks.0.img_attn.qkv.weight"].dtype is torch.float8_e4m3fn
+ # 1-D tensors are never usable on the tensor cores and must not stay quantized.
+ assert out["double_blocks.0.img_attn.qkv.bias"].dtype is torch.bfloat16
+ assert out["double_blocks.0.img_norm.scale"].dtype is torch.bfloat16
+
+ def test_everything_is_dequantized_when_not_kept(self):
+ sd = {"double_blocks.0.img_attn.qkv.weight": torch.zeros(48, 16).to(torch.float8_e4m3fn)}
+ out = self._dequantize(sd, keep_fp8=False)
+ assert out["double_blocks.0.img_attn.qkv.weight"].dtype is torch.bfloat16
+
+ def test_scaled_fp8_is_still_folded_even_when_keeping(self):
+ """A weight with a `weight_scale` is dequantized *with* its scale, as before — only
+ scale-less fp8 is kept, because only that is safe to hand to `_scaled_mm` unscaled."""
+ sd = {
+ "double_blocks.0.img_attn.qkv.weight": torch.ones(48, 16).to(torch.float8_e4m3fn),
+ "double_blocks.0.img_attn.qkv.weight_scale": torch.tensor(4.0),
+ }
+ out = self._dequantize(sd, keep_fp8=True)
+ assert out["double_blocks.0.img_attn.qkv.weight"].dtype is torch.bfloat16
+ assert torch.allclose(out["double_blocks.0.img_attn.qkv.weight"], torch.full((48, 16), 4.0).bfloat16())
+ assert "double_blocks.0.img_attn.qkv.weight_scale" not in out
diff --git a/tests/backend/model_manager/load/test_z_image_state_dict_utils.py b/tests/backend/model_manager/load/test_z_image_state_dict_utils.py
index 37e113d857..42b43c70ce 100644
--- a/tests/backend/model_manager/load/test_z_image_state_dict_utils.py
+++ b/tests/backend/model_manager/load/test_z_image_state_dict_utils.py
@@ -1,8 +1,12 @@
"""Unit tests for the Z-Image GGUF/ComfyUI -> diffusers state-dict converter."""
+import pytest
import torch
-from invokeai.backend.model_manager.load.model_loaders.z_image import _convert_z_image_gguf_to_diffusers
+from invokeai.backend.model_manager.load.model_loaders.z_image import (
+ _convert_z_image_gguf_to_diffusers,
+ _remap_z_image_layer_paths,
+)
from tests.backend.model_manager.load.state_dicts.utils import keys_to_mock_state_dict
from tests.backend.model_manager.load.state_dicts.z_image_transformer_comfyui_keys import (
state_dict_keys as z_image_keys,
@@ -64,3 +68,83 @@ class TestConvertZImageGgufToDiffusers:
assert torch.allclose(out["blk.attention.to_q.weight"], qkv[0:2])
assert torch.allclose(out["blk.attention.to_k.weight"], qkv[2:4])
assert torch.allclose(out["blk.attention.to_v.weight"], qkv[4:6])
+
+
+class TestQkvQuantizationSideChannel:
+ """A scaled-fp8 checkpoint puts a `scale_weight` next to the fused `qkv.weight`.
+
+ Left on `...attention.qkv`, the recovered scale is keyed on a module path the diffusers model
+ does not have, so `attach_fp8_scales` finds nothing and the three split weights stay quantized
+ but *unscaled* — off by 1/weight_scale, with no error anywhere.
+ """
+
+ def test_per_tensor_scale_reaches_all_three_projections(self):
+ out = _convert_z_image_gguf_to_diffusers(
+ {
+ "blk.attention.qkv.weight": torch.arange(12, dtype=torch.float32).reshape(6, 2),
+ "blk.attention.qkv.scale_weight": torch.tensor(0.25),
+ }
+ )
+ assert not any(".attention.qkv." in k for k in out)
+ for name in ("to_q", "to_k", "to_v"):
+ assert torch.equal(out[f"blk.attention.{name}.scale_weight"], torch.tensor(0.25))
+
+ def test_per_channel_scale_is_split_like_the_weight(self):
+ out = _convert_z_image_gguf_to_diffusers(
+ {
+ "blk.attention.qkv.weight": torch.arange(12, dtype=torch.float32).reshape(6, 2),
+ "blk.attention.qkv.weight_scale": torch.arange(6, dtype=torch.float32),
+ }
+ )
+ assert torch.equal(out["blk.attention.to_q.weight_scale"], torch.tensor([0.0, 1.0]))
+ assert torch.equal(out["blk.attention.to_k.weight_scale"], torch.tensor([2.0, 3.0]))
+ assert torch.equal(out["blk.attention.to_v.weight_scale"], torch.tensor([4.0, 5.0]))
+
+ def test_marker_blob_is_copied_not_split(self):
+ # `.comfy_quant` is a 1-D JSON byte string describing the layer, not a per-channel vector.
+ blob = torch.frombuffer(b'{"format":"float8_e4m3fn"}', dtype=torch.uint8).clone()
+ out = _convert_z_image_gguf_to_diffusers(
+ {
+ "blk.attention.qkv.weight": torch.arange(12, dtype=torch.float32).reshape(6, 2),
+ "blk.attention.qkv.comfy_quant": blob,
+ }
+ )
+ for name in ("to_q", "to_k", "to_v"):
+ assert torch.equal(out[f"blk.attention.{name}.comfy_quant"], blob)
+
+ def test_unknown_suffix_is_left_alone(self):
+ out = _convert_z_image_gguf_to_diffusers(
+ {
+ "blk.attention.qkv.weight": torch.arange(12, dtype=torch.float32).reshape(6, 2),
+ "blk.attention.qkv.something_else": torch.tensor(1.0),
+ }
+ )
+ assert "blk.attention.qkv.something_else" in out
+
+ def test_undivisible_scale_is_rejected_rather_than_mis_split(self):
+ with pytest.raises(ValueError, match="Cannot split fused QKV quantization data"):
+ _convert_z_image_gguf_to_diffusers(
+ {
+ "blk.attention.qkv.weight": torch.arange(12, dtype=torch.float32).reshape(6, 2),
+ "blk.attention.qkv.weight_scale": torch.arange(4, dtype=torch.float32),
+ }
+ )
+
+
+class TestMetadataPathRemap:
+ """`_quantization_metadata` names layers in the checkpoint's scheme; the scales are recovered
+ after the rename, so the per-layer hints have to follow the same route."""
+
+ def test_renamed_layers_map_one_to_one(self):
+ mapping = _remap_z_image_layer_paths(["x_embedder", "final_layer.linear", "layers.0.attention.out"])
+ assert mapping["x_embedder"] == ["all_x_embedder.2-1"]
+ assert mapping["final_layer.linear"] == ["all_final_layer.2-1.linear"]
+ assert mapping["layers.0.attention.out"] == ["layers.0.attention.to_out.0"]
+
+ def test_fused_qkv_maps_to_all_three_projections(self):
+ mapping = _remap_z_image_layer_paths(["layers.0.attention.qkv"])
+ assert mapping["layers.0.attention.qkv"] == [
+ "layers.0.attention.to_q",
+ "layers.0.attention.to_k",
+ "layers.0.attention.to_v",
+ ]
diff --git a/tests/backend/quantization/test_fp8_scaled.py b/tests/backend/quantization/test_fp8_scaled.py
index e10e71e92f..df2e109f29 100644
--- a/tests/backend/quantization/test_fp8_scaled.py
+++ b/tests/backend/quantization/test_fp8_scaled.py
@@ -1,3 +1,6 @@
+import logging
+from unittest import mock
+
import pytest
import torch
@@ -13,9 +16,13 @@ from invokeai.backend.quantization.fp8_scaled import (
extract_comfy_quant_hints,
extract_fp8_scaled_layers,
parse_quantization_metadata,
+ predict_cast_state_dict_size,
+ reset_fp8_matmul_support_cache,
scaled_mm_linear,
set_fp8_matmul_enabled,
set_full_precision_hints_respected,
+ split_fp8_scaled_layers,
+ warn_on_unattached_scales,
)
cuda_fp8 = pytest.mark.skipif(
@@ -360,6 +367,137 @@ class TestKrea2MetadataRemap:
assert mapping["txtfusion.refiner_blocks.1.attn.wk"] == "text_fusion.refiner_blocks.1.attn.to_k"
+class TestSplitScaledLayers:
+ """A scaled layer must never reach `cast_state_dict` still holding an unapplied scale."""
+
+ def _model(self):
+ model = torch.nn.Sequential()
+ model.add_module("time_embed", torch.nn.Sequential())
+ model.time_embed.add_module("linear_2", torch.nn.Linear(16, 32))
+ model.add_module("attn", torch.nn.Linear(16, 32))
+ return model
+
+ def test_skip_pattern_layer_is_dequantized_with_its_scale(self):
+ """The Krea-2 regression: `time_embed` matches the model's skip patterns, so the cast would
+ turn its fp8 weight into bf16 *codes* — the scale silently dropped, the weight off by
+ 1/weight_scale, and `attach_fp8_scales` unable to repair it afterwards."""
+ model = self._model()
+ w = torch.randn(32, 16, dtype=torch.bfloat16) * 0.02
+ scale = (w.abs().amax() / torch.finfo(FP8_DTYPE).max).float().clamp(min=1e-12)
+ q = (w / scale).to(FP8_DTYPE)
+ sd = {"time_embed.linear_2.weight": q, "attn.weight": q.clone()}
+ layers = {
+ "time_embed.linear_2": Fp8ScaledLayer(weight_scale=scale),
+ "attn": Fp8ScaledLayer(weight_scale=scale),
+ }
+
+ remaining = split_fp8_scaled_layers(
+ sd, layers, torch.bfloat16, model=model, skip_patterns=["time_embed", "norm"]
+ )
+
+ assert set(remaining) == {"attn"}, "only the layer that can stay quantized is left to attach"
+ assert sd["time_embed.linear_2.weight"].dtype is torch.bfloat16
+ rel = ((sd["time_embed.linear_2.weight"].float() - w.float()).norm() / w.float().norm()).item()
+ assert rel < 0.05, f"the scale was not applied on the way down: rel-err {rel:.4f}"
+
+ # And the survivor is untouched by the subsequent cast, so its scale still attaches.
+ assert cast_state_dict(sd, torch.bfloat16, keep_fp8=True, model=model, skip_patterns=["time_embed"]) == 1
+ model.load_state_dict(sd, assign=True, strict=False)
+ assert attach_fp8_scales(model, remaining) == 1
+ assert torch.equal(model.attn.weight_scale, scale)
+
+ def test_non_linear_scaled_weight_is_dequantized_with_its_scale(self):
+ """Same failure without any skip pattern: a scaled tensor that is not an nn.Linear weight
+ fails `_is_fp8_matmul_weight`, so the cast would strip its scale."""
+ model = self._model()
+ q, scale = _fp8_weight(32, 16)
+ sd = {"pad_token.weight": q}
+ remaining = split_fp8_scaled_layers(
+ sd, {"pad_token": Fp8ScaledLayer(weight_scale=scale)}, torch.bfloat16, model=model
+ )
+ assert remaining == {}
+ assert torch.equal(sd["pad_token.weight"], dequantize_weight(q, scale, torch.bfloat16))
+
+ def test_warns_when_a_scale_finds_no_module(self):
+ logger = logging.getLogger("fp8-test")
+ with mock.patch.object(logger, "warning") as warn:
+ warn_on_unattached_scales(logger, "Krea-2", 1, {"a": object(), "b": object()})
+ assert warn.call_count == 1
+ assert "1 of 2" in warn.call_args[0][0]
+
+ def test_silent_when_every_scale_landed(self):
+ logger = logging.getLogger("fp8-test")
+ with mock.patch.object(logger, "warning") as warn:
+ warn_on_unattached_scales(logger, "Krea-2", 2, {"a": object(), "b": object()})
+ assert warn.call_count == 0
+
+
+class TestPredictedSize:
+ def test_matches_what_cast_state_dict_actually_leaves(self):
+ """`make_room` reserves against this, so a mismatch is a silent under-reservation."""
+ model = torch.nn.Sequential()
+ model.add_module("lin", torch.nn.Linear(16, 32))
+ model.add_module("t_embedder", torch.nn.Linear(16, 32))
+ model.add_module("norm", torch.nn.LayerNorm(32))
+ q, _ = _fp8_weight(32, 16)
+ sd = {
+ "lin.weight": q,
+ "lin.bias": torch.zeros(32).to(FP8_DTYPE),
+ "t_embedder.weight": q.clone(),
+ "norm.weight": torch.ones(32).to(FP8_DTYPE),
+ "pad_token": torch.zeros(1, 32).to(FP8_DTYPE),
+ }
+ kwargs = {"model": model, "skip_patterns": ["t_embedder"]}
+ # What the loaders used to reserve: 1 byte/element for *every* fp8 tensor.
+ naive = sum(t.nelement() * (t.element_size() if t.dtype is FP8_DTYPE else 2) for t in sd.values())
+
+ predicted = predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=True, **kwargs)
+ cast_state_dict(sd, torch.bfloat16, keep_fp8=True, **kwargs)
+ actual = sum(t.nelement() * t.element_size() for t in sd.values())
+ assert predicted == actual
+
+ # Only `lin.weight` stays 1 byte/element; the rest lands at 2, so the old sum under-counted.
+ assert naive < actual
+
+ def test_all_dequantized_when_keep_fp8_is_off(self):
+ q, _ = _fp8_weight(32, 16)
+ sd = {"lin.weight": q}
+ assert predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=False) == q.nelement() * 2
+
+
+class TestDeviceSupport:
+ def test_probe_decides_rather_than_the_capability_number(self):
+ """ROCm reports the gfx arch from `get_device_capability`, so RDNA3 (gfx1100 -> (11, 0))
+ passes a `>= (8, 9)` test and then raises on every forward. The probe is what decides."""
+ reset_fp8_matmul_support_cache()
+ with mock.patch("torch.cuda.is_available", return_value=True):
+ with mock.patch("torch.cuda.get_device_capability", return_value=(11, 0)):
+ with mock.patch(
+ "invokeai.backend.quantization.fp8_scaled._probe_fp8_matmul", return_value=False
+ ) as probe:
+ assert device_supports_fp8_matmul(torch.device("cuda", 0)) is False
+ assert probe.called
+ reset_fp8_matmul_support_cache()
+
+ def test_probe_result_is_cached_per_device(self):
+ reset_fp8_matmul_support_cache()
+ with mock.patch("torch.cuda.is_available", return_value=True):
+ with mock.patch("torch.cuda.get_device_capability", return_value=(8, 9)):
+ with mock.patch(
+ "invokeai.backend.quantization.fp8_scaled._probe_fp8_matmul", return_value=True
+ ) as probe:
+ assert device_supports_fp8_matmul(torch.device("cuda", 0)) is True
+ assert device_supports_fp8_matmul(torch.device("cuda", 0)) is True
+ assert probe.call_count == 1
+ reset_fp8_matmul_support_cache()
+
+ def test_non_cuda_never_probes(self):
+ reset_fp8_matmul_support_cache()
+ with mock.patch("invokeai.backend.quantization.fp8_scaled._probe_fp8_matmul") as probe:
+ assert device_supports_fp8_matmul(torch.device("cpu")) is False
+ assert not probe.called
+
+
class TestDequantize:
@pytest.mark.parametrize("per_channel", [False, True])
def test_roundtrip_close_to_original(self, per_channel: bool):