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): address round-3 review — Qwen3-VL split, scale-axis and probe caching

Alexander Eichhorn6fa8ac8e216b
diff --git a/invokeai/backend/model_manager/load/model_loaders/anima.py b/invokeai/backend/model_manager/load/model_loaders/anima.py
index c5cf39ce5e..4c38b41e6a 100644
--- a/invokeai/backend/model_manager/load/model_loaders/anima.py
+++ b/invokeai/backend/model_manager/load/model_loaders/anima.py
@@ -206,11 +206,15 @@ class AnimaCheckpointModel(ModelLoader):
skip_patterns = tuple(getattr(model, "_skip_layerwise_casting_patterns", None) or ())
# Layers the cast would dequantize anyway are folded here, scale applied, so the cast never
# strips a scale that can no longer be put back.
- fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)
-
+ # Reserve before the split, not after: `split_fp8_scaled_layers` dequantizes its unusable
+ # subset through fp32, so reserving afterwards lets that transient peak land on an
+ # unreserved cache. The prediction is unaffected by the split -- it applies the same
+ # `can_stay_quantized` predicate, so those layers are already counted at `dtype.itemsize`.
self._ram_cache.make_room(
predict_cast_state_dict_size(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)
)
+
+ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)
kept = cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)
load_result = model.load_state_dict(sd, assign=True, strict=False)
diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.py
index 7374729570..ed33a1582f 100644
--- a/invokeai/backend/model_manager/load/model_loaders/flux.py
+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py
@@ -770,13 +770,17 @@ class FluxCheckpointModel(ModelLoader):
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 that can no longer be put back.
- fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, torch.bfloat16, model=model, skip_patterns=skip_patterns)
-
+ # Reserve before the split, not after: `split_fp8_scaled_layers` dequantizes its unusable
+ # subset through fp32, so reserving afterwards lets that transient peak land on an
+ # unreserved cache. The prediction is unaffected by the split -- it applies the same
+ # `can_stay_quantized` predicate, so those layers are already counted at `dtype.itemsize`.
self._ram_cache.make_room(
predict_cast_state_dict_size(
sd, torch.bfloat16, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns
)
)
+
+ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, torch.bfloat16, model=model, skip_patterns=skip_patterns)
# 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, skip_patterns=skip_patterns)
model.load_state_dict(sd, assign=True)
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.py
index 7feb9951a6..34d9ee90f0 100644
--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py
+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py
@@ -25,7 +25,6 @@ from invokeai.backend.model_manager.taxonomy import (
SubModelType,
)
from invokeai.backend.quantization.fp8_scaled import (
- FP8_DTYPE,
attach_fp8_scales,
cast_state_dict,
dequantize_fp8_scaled,
@@ -380,7 +379,9 @@ class Krea2CheckpointModel(ModelLoader):
path_map = _remap_native_layer_paths({*detached, *layer_hints})
orphaned = reattach_layer_sidechannel(sd, detached, path_map)
if orphaned:
- self._logger.debug(
+ # INFO, not DEBUG: a dropped scale leaves its weight off by 1/weight_scale with no
+ # other symptom, so the one line that mentions it must be visible by default.
+ self._logger.info(
f"Krea-2: dropped quantization side-channel for {len(orphaned)} module(s) with no "
f"diffusers counterpart (e.g. {orphaned[0]})."
)
@@ -404,11 +405,15 @@ class Krea2CheckpointModel(ModelLoader):
# *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)
-
+ # Reserve before the split, not after: `split_fp8_scaled_layers` dequantizes its unusable
+ # subset through fp32, so reserving afterwards lets that transient peak land on an
+ # unreserved cache. The prediction is unaffected by the split -- it applies the same
+ # `can_stay_quantized` predicate, so those layers are already counted at `dtype.itemsize`.
self._ram_cache.make_room(
predict_cast_state_dict_size(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)
)
+
+ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)
# 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.
@@ -709,15 +714,25 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):
with accelerate.init_empty_weights():
model = Qwen3VLModel._from_config(te_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()
- )
- self._ram_cache.make_room(new_sd_size)
- for k in sd.keys():
- if sd[k].dtype is not FP8_DTYPE:
- sd[k] = sd[k].to(model_dtype)
+ # Same ordering contract as every other loader in this series: split *before* the cast.
+ # A per-key `if dtype is not FP8_DTYPE` cast looks equivalent and is not — it keeps every
+ # fp8 tensor quantized, including the ones that must not stay:
+ #
+ # - a 1-D fp8 norm (checkpoints that "quantize everything" ship these) would keep its
+ # scale as an unused buffer on a non-Linear and the forward would compute on the raw
+ # fp8 codes, i.e. off by 1/weight_scale with nothing logged;
+ # - an e5m2 scaled weight would be cast *without* its scale, since only e4m3fn is spared;
+ # - a block-wise scale would reach `scaled_mm_linear` unchecked and raise mid-generation.
+ #
+ # `split_fp8_scaled_layers` applies exactly those filters and dequantizes the affected
+ # layers *with* their scale, so what remains is what the matmul can actually consume.
+ keep_fp8 = should_keep_fp8_weights(target_device)
+ # Reserve before the split: it dequantizes its unusable subset through fp32, so reserving
+ # afterwards lets that transient peak land on an unreserved cache. The prediction is
+ # unaffected -- it applies the same `can_stay_quantized` predicate.
+ self._ram_cache.make_room(predict_cast_state_dict_size(sd, model_dtype, keep_fp8=keep_fp8, model=model))
+ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model)
+ cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model)
model.load_state_dict(sd, assign=True, strict=False)
_reject_incomplete_load(model, what="Qwen3-VL encoder checkpoint")
diff --git a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
index 0c30c2932f..d751a209e6 100644
--- a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
+++ b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
@@ -38,8 +38,10 @@ from invokeai.backend.model_manager.taxonomy import (
SubModelType,
)
from invokeai.backend.quantization.fp8_scaled import (
+ TRANSFORMER_KEY_PREFIXES,
attach_fp8_scales,
cast_state_dict,
+ expand_weight_scale,
extract_comfy_quant_hints,
extract_fp8_scaled_layers,
full_precision_hints_respected,
@@ -204,6 +206,13 @@ def _read_gguf_metadata_int(path: Path, key: str) -> int | None:
return int(value) if isinstance(value, (int, float)) else None
+# Wrapper prefixes this loader strips from the state dict. Kept as a named constant because the
+# `_quantization_metadata` header names its layers *before* the strip, so the hints have to be
+# re-keyed with exactly the same list -- see `_load_text_encoder`. Restating it there would be a
+# second copy free to drift.
+MISTRAL_KEY_PREFIXES = ("text_encoder.", "language_model.")
+
+
def _strip_known_prefixes(sd: dict[str, Any]) -> dict[str, Any]:
"""Strip wrapper prefixes used by some FLUX.2 single-file redistributions.
@@ -217,7 +226,7 @@ def _strip_known_prefixes(sd: dict[str, Any]) -> dict[str, Any]:
out[key] = value
continue
new_key = key
- for prefix in ("text_encoder.", "language_model."):
+ for prefix in MISTRAL_KEY_PREFIXES:
if new_key.startswith(prefix):
new_key = new_key[len(prefix) :]
break
@@ -375,13 +384,10 @@ def _drop_quantization_metadata(sd: dict[str, Any], logger, target_dtype: torch.
dequantized = 0
for weight_key, scale_key in list(iter_weight_scale_pairs(sd)):
weight = sd[weight_key].float()
- scale = sd[scale_key].float()
- 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 = weight.shape[dim] // scale.shape[dim]
- if block > 1:
- scale = scale.repeat_interleave(block, dim=dim)
+ # `expand_weight_scale` rather than a local broadcast: a per-output-channel scale is 1-D of
+ # length `out`, and `(out, in) * (out,)` aligns on the *last* axis, so it scales input
+ # channels instead of output channels -- wrong on a square weight, a shape error otherwise.
+ scale = expand_weight_scale(weight, sd[scale_key].float())
result = weight * scale
sd[weight_key] = result.to(target_dtype) if target_dtype is not None else result
dequantized += 1
@@ -949,8 +955,13 @@ class MistralEncoderCheckpointLoader(ModelLoader):
keep_fp8 = should_keep_fp8_weights(target_device)
fp8_layers: dict[str, Any] = {}
if keep_fp8:
+ # This loader strips its own wrapper prefixes on top of the generic ones, so the hints
+ # need both lists. With only the generic tuple, a `language_model.`-prefixed
+ # redistribution keeps its hint names while the sd keys lose the prefix, and every
+ # `full_precision_matrix_mult` is silently ignored.
header_hints = strip_layer_path_prefix(
- parse_quantization_metadata(read_safetensors_metadata(model_path, logger))
+ parse_quantization_metadata(read_safetensors_metadata(model_path, logger)),
+ prefixes=(*MISTRAL_KEY_PREFIXES, *TRANSFORMER_KEY_PREFIXES),
)
layer_hints = {**extract_comfy_quant_hints(sd), **header_hints}
fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)
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 47a6f010d1..b460332ccc 100644
--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py
@@ -39,6 +39,7 @@ from invokeai.backend.quantization.fp8_scaled import (
attach_fp8_scales,
cast_state_dict,
dequantize_fp8_scaled,
+ expand_weight_scale,
extract_comfy_quant_hints,
extract_fp8_scaled_layers,
full_precision_hints_respected,
@@ -551,11 +552,15 @@ class ZImageCheckpointModel(ModelLoader):
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)
-
+ # Reserve before the split, not after: `split_fp8_scaled_layers` dequantizes its unusable
+ # subset through fp32, so reserving afterwards lets that transient peak land on an
+ # unreserved cache. The prediction is unaffected by the split -- it applies the same
+ # `can_stay_quantized` predicate, so those layers are already counted at `dtype.itemsize`.
self._ram_cache.make_room(
predict_cast_state_dict_size(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)
)
+
+ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)
kept = cast_state_dict(
sd,
model_dtype,
@@ -1079,16 +1084,12 @@ class Qwen3EncoderCheckpointLoader(ModelLoader):
# Note: Float8 types (e.g., float8_e4m3fn) require .float() instead of .to(torch.float32)
# as PyTorch doesn't support direct type promotion for Float8 types
weight_float = weight.float()
- scale = scale.float()
- if scale.shape != weight_float.shape and scale.numel() > 1:
- # Block-wise quantization: need to expand scale to match weight shape
- # Find which dimension differs and repeat scale along that dimension
- for dim in range(len(weight_float.shape)):
- if dim < len(scale.shape) and scale.shape[dim] != weight_float.shape[dim]:
- block_size = weight_float.shape[dim] // scale.shape[dim]
- if block_size > 1:
- # Repeat scale along this dimension to match weight shape
- scale = scale.repeat_interleave(block_size, dim=dim)
+ # `expand_weight_scale` handles all three layouts (per-tensor, per-output-channel,
+ # block-wise). The local loop it replaces left a 1-D per-channel scale untouched, and
+ # `(out, in) * (out,)` then broadcasts on the *last* axis -- scaling input channels
+ # instead of output channels, which is wrong on a square weight and a shape error on
+ # any other.
+ scale = expand_weight_scale(weight_float, scale.float())
# Multiply in float32 for precision, but store the compute dtype immediately so the
# *whole model* is never materialized in float32. Keeping every dequantized weight as
# float32 until the caller's later cast quadruples the per-parameter cost (4 bytes vs
diff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.py
index afe64d82e0..d9e3a32991 100644
--- a/invokeai/backend/quantization/fp8_scaled.py
+++ b/invokeai/backend/quantization/fp8_scaled.py
@@ -221,11 +221,19 @@ def reattach_layer_sidechannel(
destination in the converted state dict — usually because the converter drops that module
outright — so its scale is dropped with it. Returning them rather than swallowing them lets the
caller say so: a *silently* dropped scale is exactly the failure this pair exists to prevent.
+
+ A destination counts as present when *any* tensor sits under it, not specifically a
+ ``<path>.weight``. Requiring that name assumes every quantizable module stores its parameter as
+ ``weight``, which is not true of the norms: a producer that quantizes them (the
+ "quantizes everything" class documented in :func:`can_stay_quantized`) writes ``<path>.scale``,
+ and the guard would reject the destination for the wrong reason and drop a scale it could have
+ placed.
"""
+ present_modules = {key.rsplit(".", 1)[0] for key in sd if isinstance(key, str) and "." in key}
orphaned: list[str] = []
for path, entries in detached.items():
destination = path_map.get(path, path)
- if f"{destination}.weight" not in sd:
+ if destination not in present_modules:
orphaned.append(path)
continue
for suffix, value in entries:
@@ -323,10 +331,20 @@ def _usable_input_scale(scale: torch.Tensor | None) -> torch.Tensor | None:
Non-finite and non-positive scales are rejected for the same reason: they cannot be a valid
divisor, and using one would produce inf/NaN activations instead of a slightly worse image.
+
+ A multi-element ``input_scale`` is dropped rather than raising. ``scaled_mm_linear`` scales the
+ activations by a single value, so there is nothing to do with a per-channel or per-block
+ activation scale, and the dynamic per-forward ``amax`` path is a correct fallback. Reshaping it
+ to a scalar unconditionally turned such a checkpoint into a `RuntimeError: shape '[]' is invalid
+ for input of size N` at load time -- the one malformed side-channel in this module that neither
+ skipped nor explained itself.
"""
if scale is None:
return None
- scale = scale.float().reshape(())
+ scale = scale.float()
+ if scale.numel() != 1:
+ return None
+ scale = scale.reshape(())
if not torch.isfinite(scale) or scale <= 0 or scale.item() == 1.0:
return None
return scale
@@ -615,6 +633,18 @@ def full_precision_hints_respected() -> bool:
return True
+# Wordings torch uses when `_scaled_mm` is genuinely unavailable on the hardware, as opposed to
+# having failed under load. Kept narrow on purpose: anything not matched here is treated as
+# transient and re-probed, which is the safe direction (see `_probe_fp8_matmul`).
+_UNSUPPORTED_MM_MARKERS = ("compute capability", "not supported", "no kernel image", "not implemented")
+
+
+def _is_definitive_unsupported_error(exc: BaseException) -> bool:
+ """Whether ``exc`` says the device cannot do fp8 matmul at all, rather than not right now."""
+ message = str(exc).lower()
+ return any(marker in message for marker in _UNSUPPORTED_MM_MARKERS)
+
+
def _probe_fp8_matmul(index: int) -> bool | None:
"""Run one minimal ``_scaled_mm`` on device ``index`` and report whether it worked.
@@ -625,11 +655,21 @@ def _probe_fp8_matmul(index: int) -> bool | None:
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.
- Returns ``None`` when the probe could not be *carried out* — an allocation failure rather than
- an unsupported operation. The probe runs during a model load, i.e. under real VRAM pressure, and
- caching a momentary OOM as "this GPU cannot do fp8" would disable the fp8 matmul for the rest of
- the process. Same reasoning as `_device_supports_fp8_storage`, which also refuses to cache a
- transient failure.
+ Returns ``None`` when the probe could not be *carried out* rather than having established that
+ the operation is unsupported. The probe runs during a model load, i.e. under real VRAM pressure
+ and alongside whatever else the driver is doing, and caching a momentary failure as "this GPU
+ cannot do fp8" would disable the fp8 matmul for the rest of the process. Same reasoning as
+ `_device_supports_fp8_storage`, which also refuses to cache a transient failure.
+
+ A ``RuntimeError`` is therefore treated as inconclusive *unless* it names the support
+ constraint. Listing the transient wordings instead would be the wrong way round: an OOM and a
+ cuBLAS workspace failure are only two of the ways a loaded machine can fail this call, and every
+ wording not on such a list would be cached as permanent. The definitive answer has one stable
+ shape — torch says the op needs a given compute capability — so match that and treat the open
+ set as inconclusive.
+
+ An inconclusive answer costs one 16x16 matmul on the next load; a wrongly cached one costs the
+ fp8 path for the lifetime of the process.
"""
try:
device = torch.device("cuda", index)
@@ -641,11 +681,10 @@ def _probe_fp8_matmul(index: int) -> bool | None:
except torch.OutOfMemoryError:
return None
except RuntimeError as e:
- # cuBLAS reports a failed workspace allocation as a plain RuntimeError, not an OOM.
- if "out of memory" in str(e).lower() or "ALLOC_FAILED" in str(e):
- return None
- return False
+ return False if _is_definitive_unsupported_error(e) else None
except Exception:
+ # Not a RuntimeError: a missing op or a rejected dtype, i.e. structural rather than
+ # situational. Those do not become true on a less busy machine.
return False
return True
diff --git a/tests/backend/model_manager/load/test_fp8_hint_prefixes.py b/tests/backend/model_manager/load/test_fp8_hint_prefixes.py
new file mode 100644
index 0000000000..3c93e7349a
--- /dev/null
+++ b/tests/backend/model_manager/load/test_fp8_hint_prefixes.py
@@ -0,0 +1,92 @@
+"""Layer hints must survive each loader's own key rewrites.
+
+`_quantization_metadata` names its layers in the checkpoint's scheme, while the scales are read
+after the loader has stripped whatever prefix that checkpoint carries. A hint whose name still
+carries the prefix matches no layer, so `full_precision_matrix_mult` is silently ignored and the
+producer's "do not multiply this one in fp8" instruction is disregarded -- the exact failure the
+hint plumbing exists to prevent. It has now been found twice (FLUX/Krea-2/Z-Image/Anima in round 2,
+Mistral in round 3), so each loader's own prefix list gets a pin.
+"""
+
+import torch
+
+from invokeai.backend.model_manager.load.model_loaders.mistral_encoder import (
+ MISTRAL_KEY_PREFIXES,
+ _strip_known_prefixes,
+)
+from invokeai.backend.quantization.fp8_scaled import (
+ FP8_DTYPE,
+ TRANSFORMER_KEY_PREFIXES,
+ extract_fp8_scaled_layers,
+ strip_layer_path_prefix,
+)
+
+
+def _quantized(path: str) -> dict[str, torch.Tensor]:
+ return {
+ f"{path}.weight": torch.zeros(16, 16, dtype=torch.float32).to(FP8_DTYPE),
+ f"{path}.weight_scale": torch.tensor(2.0),
+ }
+
+
+class TestMistralHintPrefixes:
+ """The Mistral loader strips wrapper prefixes the generic tuple does not know about."""
+
+ def test_its_own_prefixes_are_not_covered_by_the_generic_tuple(self) -> None:
+ """If this ever becomes false the extra argument at the call site is dead weight."""
+ assert not set(MISTRAL_KEY_PREFIXES) & set(TRANSFORMER_KEY_PREFIXES)
+
+ def test_a_language_model_prefixed_hint_reaches_its_layer(self) -> None:
+ """Multimodal Mistral3 redistributions prefix every key with `language_model.`.
+
+ The sd loses that prefix in `_strip_known_prefixes`; the header does not. Passing only the
+ generic tuple leaves the hint keyed on `language_model.model.layers.0.…` while the layer is
+ `model.layers.0.…`, and the flag is dropped in silence.
+ """
+ sd = _strip_known_prefixes(_quantized("language_model.model.layers.0.self_attn.q_proj"))
+ header = {"language_model.model.layers.0.self_attn.q_proj": {"full_precision_matrix_mult": True}}
+
+ hints = strip_layer_path_prefix(header, prefixes=(*MISTRAL_KEY_PREFIXES, *TRANSFORMER_KEY_PREFIXES))
+ layers = extract_fp8_scaled_layers(sd, layer_hints=hints)
+
+ assert set(layers) == {"model.layers.0.self_attn.q_proj"}
+ assert layers["model.layers.0.self_attn.q_proj"].full_precision_matmul is True
+
+ def test_the_generic_tuple_alone_would_have_lost_the_flag(self) -> None:
+ """Pins the failure mode itself, so the fix cannot be reverted unnoticed."""
+ sd = _strip_known_prefixes(_quantized("language_model.model.layers.0.self_attn.q_proj"))
+ header = {"language_model.model.layers.0.self_attn.q_proj": {"full_precision_matrix_mult": True}}
+
+ hints = strip_layer_path_prefix(header)
+ layers = extract_fp8_scaled_layers(sd, layer_hints=hints)
+
+ assert layers["model.layers.0.self_attn.q_proj"].full_precision_matmul is False
+
+
+class TestFluxHintPrefixes:
+ """FLUX.1's hint plumbing had no test at all.
+
+ ComfyUI FLUX.1 redistributions prefix their keys with `model.diffusion_model.`, which the
+ bundle conversion strips before the scales are read.
+ """
+
+ def test_a_prefixed_hint_lands_on_the_renamed_layer(self) -> None:
+ sd = {
+ k[len("model.diffusion_model.") :]: v
+ for k, v in _quantized("model.diffusion_model.double_blocks.0.img_attn.qkv").items()
+ }
+ header = {"model.diffusion_model.double_blocks.0.img_attn.qkv": {"full_precision_matrix_mult": True}}
+
+ layers = extract_fp8_scaled_layers(sd, layer_hints=strip_layer_path_prefix(header))
+
+ assert set(layers) == {"double_blocks.0.img_attn.qkv"}
+ assert layers["double_blocks.0.img_attn.qkv"].full_precision_matmul is True
+
+ def test_an_unprefixed_hint_is_passed_through_unchanged(self) -> None:
+ """A partially-prefixed header must not have its plain names dropped."""
+ sd = _quantized("double_blocks.0.img_attn.qkv")
+ header = {"double_blocks.0.img_attn.qkv": {"full_precision_matrix_mult": True}}
+
+ layers = extract_fp8_scaled_layers(sd, layer_hints=strip_layer_path_prefix(header))
+
+ assert layers["double_blocks.0.img_attn.qkv"].full_precision_matmul is True
diff --git a/tests/backend/model_manager/load/test_load_default_fp8.py b/tests/backend/model_manager/load/test_load_default_fp8.py
index 4b63597a57..fe7aa3f6fb 100644
--- a/tests/backend/model_manager/load/test_load_default_fp8.py
+++ b/tests/backend/model_manager/load/test_load_default_fp8.py
@@ -34,6 +34,7 @@ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch
apply_custom_layers_to_model,
)
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType, SubModelType
+from invokeai.backend.util.fp8 import FP8_COMPUTE_DTYPE_ATTR
def _make_loader(device: str = "cuda") -> ModelLoader:
@@ -692,3 +693,89 @@ def test_device_supports_fp8_storage_is_cached_per_device():
# xpu:1 has not been probed, so a failing probe there must be observed, not short-circuited.
with patch("torch.zeros", side_effect=RuntimeError("no float8 on this device")):
assert _device_supports_fp8_storage(torch.device("xpu", 1)) is False
+
+
+class TestAlreadyFp8StorageGuard:
+ """FP8 storage must not run over weights that are already fp8 and headed for the tensor cores.
+
+ Layerwise casting installs a pre-hook that restores the compute dtype before every forward. On
+ a scaled-fp8 checkpoint that hook does two things at once: `_can_use_fp8_matmul` no longer sees
+ an fp8 weight, so the matmul silently falls back, and the hook upcasts the weight *without*
+ applying its `weight_scale`, i.e. a weight off by `1/weight_scale`. Neither is visible in the
+ output of a successful generation, so the guard is load-bearing and needs a test that fails if
+ it is reverted.
+ """
+
+ def _model(self) -> torch.nn.Module:
+ model = torch.nn.Sequential(torch.nn.Linear(16, 32))
+ model[0].weight = torch.nn.Parameter(
+ torch.zeros(32, 16, dtype=torch.float32).to(torch.float8_e4m3fn), requires_grad=False
+ )
+ return model
+
+ def test_a_model_whose_weights_are_already_fp8_is_left_alone(self) -> None:
+ loader = _make_loader("cuda")
+ model = self._model()
+
+ with patch("invokeai.backend.model_manager.load.load_default.should_keep_fp8_weights", return_value=True):
+ result = loader._apply_fp8_layerwise_casting(model, _make_config(ModelType.Main, fp8=True))
+
+ assert result is model
+ # No compute-dtype marker means `_apply_fp8_to_nn_module` never ran over it.
+ assert getattr(model, FP8_COMPUTE_DTYPE_ATTR, None) is None
+ assert model[0].weight.dtype is torch.float8_e4m3fn
+
+ def test_a_full_precision_model_is_still_cast(self) -> None:
+ """The guard must key on the weights, not merely on fp8_compute being enabled."""
+ loader = _make_loader("cuda")
+ model = torch.nn.Sequential(torch.nn.Linear(16, 32))
+
+ with patch("invokeai.backend.model_manager.load.load_default.should_keep_fp8_weights", return_value=True):
+ loader._apply_fp8_layerwise_casting(model, _make_config(ModelType.Main, fp8=True))
+
+ assert model[0].weight.dtype is torch.float8_e4m3fn
+ assert getattr(model, FP8_COMPUTE_DTYPE_ATTR, None) is not None
+
+ def test_ordinary_storage_casting_is_unaffected_when_the_matmul_is_unavailable(self) -> None:
+ """The guard must not become a blanket "skip fp8 storage" once fp8_compute is off.
+
+ Only the already-fp8 case is protected. A full-precision model still gets the storage cast,
+ which is the entire point of the toggle on a card without the fp8 matmul.
+
+ (The mirror case -- an already-fp8 model with the matmul *off* -- is unreachable: every
+ loader either folds the scales or casts raw fp8 away when `should_keep_fp8_weights` is
+ False, so nothing fp8 survives to reach this method. `set_fp8_compute_dtype` refuses it
+ outright rather than recording float8 as a compute dtype.)
+ """
+ loader = _make_loader("cuda")
+ model = torch.nn.Sequential(torch.nn.Linear(16, 32))
+
+ with patch("invokeai.backend.model_manager.load.load_default.should_keep_fp8_weights", return_value=False):
+ loader._apply_fp8_layerwise_casting(model, _make_config(ModelType.Main, fp8=True))
+
+ assert model[0].weight.dtype is torch.float8_e4m3fn
+
+
+class TestApplyFp8SkipCallback:
+ """The `skip=` callback keeps scaled-fp8 layers out of the storage cast.
+
+ Its one caller (the Qwen3-VL encoder) casts the *unquantized* remainder of a partly-quantized
+ checkpoint to fp8 storage while leaving the scaled layers on the matmul path. Without the
+ callback those layers would be cast without their scale.
+ """
+
+ def test_a_module_the_callback_rejects_is_not_cast(self) -> None:
+ model = torch.nn.Sequential()
+ model.add_module("keep", torch.nn.Linear(16, 32))
+ model.add_module("cast", torch.nn.Linear(16, 32))
+ model.keep.weight_scale = torch.tensor(2.0)
+
+ ModelLoader._apply_fp8_to_nn_module(
+ model,
+ storage_dtype=torch.float8_e4m3fn,
+ compute_dtype=torch.bfloat16,
+ skip=lambda _name, module: getattr(module, "weight_scale", None) is not None,
+ )
+
+ assert model.keep.weight.dtype is not torch.float8_e4m3fn
+ assert model.cast.weight.dtype is torch.float8_e4m3fn
diff --git a/tests/backend/quantization/test_fp8_scaled.py b/tests/backend/quantization/test_fp8_scaled.py
index c6efaa0120..fe2d92acc8 100644
--- a/tests/backend/quantization/test_fp8_scaled.py
+++ b/tests/backend/quantization/test_fp8_scaled.py
@@ -15,8 +15,10 @@ from invokeai.backend.quantization.fp8_scaled import (
dequantize_weight,
detach_layer_sidechannel,
device_supports_fp8_matmul,
+ expand_weight_scale,
extract_comfy_quant_hints,
extract_fp8_scaled_layers,
+ is_matmul_usable_scale,
is_scale_metadata_key,
iter_weight_scale_pairs,
parse_quantization_metadata,
@@ -592,6 +594,17 @@ class TestScaledMm:
class TestCustomLinearIntegration:
"""The fp8 matmul must be opt-in and must degrade to the dequantized path, never raise."""
+ @pytest.fixture(autouse=True)
+ def _restore_matmul_override(self):
+ """Clear the override after each test, rather than leaving it pinned to ``False``.
+
+ These tests reset with ``set_fp8_matmul_enabled(False)``, which is not the neutral state --
+ it is an explicit "off" that outlives the class and silently overrides the config for
+ anything that runs later in the same process.
+ """
+ yield
+ set_fp8_matmul_enabled(None)
+
def _module(self, device: torch.device, in_f=64, out_f=128, device_autocasting: bool = False):
from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (
apply_custom_layers_to_model,
@@ -1024,3 +1037,136 @@ class TestMxfp8IsRefused:
layers = extract_fp8_scaled_layers(sd)
assert tuple(layers["lin"].weight_scale.shape) == (4, 2)
+
+
+class TestNonScalarInputScale:
+ """A multi-element ``input_scale`` is dropped, not raised on.
+
+ `scaled_mm_linear` scales activations by one value, so there is nothing to do with a
+ per-channel or per-block activation scale -- but reshaping it to a scalar unconditionally
+ turned such a checkpoint into a shape error at load time. Every other malformed side-channel in
+ this module is either skipped or refused with an actionable message; this one was neither.
+ """
+
+ def _sd(self, input_scale: torch.Tensor) -> dict[str, torch.Tensor]:
+ return {
+ "blocks.0.attn.weight": torch.zeros(16, 16, dtype=torch.float32).to(FP8_DTYPE),
+ "blocks.0.attn.weight_scale": torch.tensor(2.0),
+ "blocks.0.attn.input_scale": input_scale,
+ }
+
+ def test_a_per_channel_input_scale_does_not_abort_the_load(self) -> None:
+ layers = extract_fp8_scaled_layers(self._sd(torch.full((16,), 0.5)))
+
+ assert set(layers) == {"blocks.0.attn"}
+ # Dropped, so the forward falls back to the dynamic amax path -- which is correct.
+ assert layers["blocks.0.attn"].input_scale is None
+ # The weight scale is unaffected by the unusable activation scale.
+ assert layers["blocks.0.attn"].weight_scale is not None
+
+ def test_a_scalar_input_scale_is_still_kept(self) -> None:
+ layers = extract_fp8_scaled_layers(self._sd(torch.tensor(0.5)))
+
+ assert layers["blocks.0.attn"].input_scale is not None
+
+
+class TestMatmulUsableScale:
+ """`is_matmul_usable_scale` decides what may reach `_scaled_mm` un-dequantized."""
+
+ def test_a_per_tensor_scale_is_usable(self) -> None:
+ assert is_matmul_usable_scale(torch.zeros(32, 16), torch.tensor(2.0)) is True
+
+ def test_a_per_output_channel_scale_is_usable(self) -> None:
+ assert is_matmul_usable_scale(torch.zeros(32, 16), torch.full((32,), 2.0)) is True
+
+ def test_a_one_dimensional_scale_of_the_wrong_length_is_not(self) -> None:
+ """The branch that keeps a mislabelled scale out of the kernel.
+
+ A 1-D scale whose length is not the row count is neither per-tensor nor
+ per-output-channel. Letting it through raises inside `_scaled_mm` mid-generation instead of
+ dequantizing the layer up front, which is the whole point of asking.
+ """
+ assert is_matmul_usable_scale(torch.zeros(32, 16), torch.full((16,), 2.0)) is False
+
+ def test_a_block_wise_scale_is_not(self) -> None:
+ assert is_matmul_usable_scale(torch.zeros(32, 16), torch.full((4, 2), 2.0)) is False
+
+
+class TestReattachToNonWeightDestination:
+ """The reattach guard must not assume every module stores its parameter as ``weight``.
+
+ A producer that quantizes norms -- the "quantizes everything" class this module documents --
+ writes ``<path>.scale``. Testing for ``<destination>.weight`` rejects such a destination for the
+ wrong reason and drops a scale it could have placed, with only a log line to show for it.
+ """
+
+ def test_a_destination_whose_tensor_is_not_named_weight_still_receives_its_scale(self) -> None:
+ sd = {"blocks.0.norm_q.scale": torch.zeros(16, dtype=torch.float32).to(FP8_DTYPE)}
+ detached = {"blocks.0.qnorm": [(".weight_scale", torch.tensor(2.0))]}
+
+ orphaned = reattach_layer_sidechannel(sd, detached, {"blocks.0.qnorm": "blocks.0.norm_q"})
+
+ assert orphaned == []
+ assert "blocks.0.norm_q.weight_scale" in sd
+
+ def test_a_destination_absent_from_the_state_dict_is_still_reported(self) -> None:
+ sd = {"blocks.0.attn.weight": torch.zeros(4, 4)}
+ detached = {"blocks.0.dropped": [(".weight_scale", torch.tensor(2.0))]}
+
+ orphaned = reattach_layer_sidechannel(sd, detached, {})
+
+ assert orphaned == ["blocks.0.dropped"]
+ assert not [k for k in sd if k.endswith(".weight_scale")]
+
+
+class TestProbeTransientFailures:
+ """Only a definitively unsupported device may be cached; everything else re-probes.
+
+ Listing the transient wordings is the wrong way round: an OOM and a cuBLAS workspace failure
+ are two of the ways a loaded machine can fail this call, and any wording not on the list would
+ be cached as permanent -- reproducing the failure the OOM branch was written to avoid.
+ """
+
+ def test_an_unrecognized_runtime_error_is_not_cached(self) -> None:
+ reset_fp8_matmul_support_cache()
+ device = torch.device("cuda", 0)
+ with _probe_on_cpu():
+ with mock.patch("torch._scaled_mm", side_effect=RuntimeError("CUDA driver reset")):
+ assert device_supports_fp8_matmul(device) is False
+ # Inconclusive, so the next load re-probes rather than the process losing fp8.
+ with mock.patch("torch._scaled_mm", return_value=torch.zeros(1)):
+ assert device_supports_fp8_matmul(device) is True
+ reset_fp8_matmul_support_cache()
+
+ def test_a_capability_error_is_cached(self) -> None:
+ reset_fp8_matmul_support_cache()
+ device = torch.device("cuda", 0)
+ message = "torch._scaled_mm is only supported on CUDA devices with compute capability >= 8.9"
+ with _probe_on_cpu():
+ with mock.patch("torch._scaled_mm", side_effect=RuntimeError(message)):
+ assert device_supports_fp8_matmul(device) is False
+ with mock.patch("torch._scaled_mm", side_effect=AssertionError("must not be probed again")):
+ assert device_supports_fp8_matmul(device) is False
+ reset_fp8_matmul_support_cache()
+
+
+class TestExpandWeightScaleAxis:
+ """A per-output-channel scale must scale rows, not columns.
+
+ `(out, in) * (out,)` broadcasts on the *last* axis, so a bare multiply scales input channels --
+ wrong on a square weight, a shape error on any other. Both legacy folds used to do exactly that.
+ """
+
+ def test_a_per_channel_scale_lines_up_with_the_rows(self) -> None:
+ weight = torch.ones(3, 2)
+ scale = torch.tensor([1.0, 2.0, 3.0])
+
+ result = weight * expand_weight_scale(weight, scale)
+
+ assert torch.equal(result, torch.tensor([[1.0, 1.0], [2.0, 2.0], [3.0, 3.0]]))
+
+ def test_a_non_square_weight_no_longer_raises(self) -> None:
+ weight = torch.ones(4, 2)
+
+ # Without the expansion this is a broadcast error, not merely a wrong number.
+ assert (weight * expand_weight_scale(weight, torch.arange(4, dtype=torch.float32))).shape == (4, 2)