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): ignore uncalibrated input_scale placeholders, read both spellings

Alexander Eichhorncfd8a05ab65a
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.py
index 6eeb4eecd5..082e918a0c 100644
--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py
+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py
@@ -686,10 +686,6 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):
# 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)}
- # A legacy activation-scale marker this loader has never consumed.
- for k in list(sd.keys()):
- if isinstance(k, str) and "scale_input" in k:
- del sd[k]
# Remap BEFORE pulling the scales out. The remap rewrites whole keys, so each
# ".weight_scale" travels with its ".weight" and the recovered layer paths already match the
diff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.py
index 54067dcc4e..3c8a823f28 100644
--- a/invokeai/backend/quantization/fp8_scaled.py
+++ b/invokeai/backend/quantization/fp8_scaled.py
@@ -25,7 +25,10 @@ import torch
FP8_DTYPE = torch.float8_e4m3fn
WEIGHT_SCALE_SUFFIXES = (".weight_scale", ".scale_weight")
-INPUT_SCALE_SUFFIX = ".input_scale"
+# Both spellings occur, exactly as for the weight scale. ComfyUI normalizes `.scale_input` to
+# `.input_scale` on load (comfy/utils.py, convert_old_quants); reading only one of them means a
+# calibrated activation scale is silently discarded and every forward pays the amax reduction.
+INPUT_SCALE_SUFFIXES = (".input_scale", ".scale_input")
QUANT_METADATA_KEY = "_quantization_metadata"
@@ -118,15 +121,36 @@ def extract_comfy_quant_hints(sd: dict[str, Any]) -> dict[str, dict[str, Any]]:
return hints
-def _strip_scale_suffix(key: str) -> tuple[str, str] | None:
+def _strip_scale_suffix(key: str) -> tuple[str, bool] | None:
+ """Return ``(module path, is_input_scale)``, or None if ``key`` is not a scale key."""
for suffix in WEIGHT_SCALE_SUFFIXES:
if key.endswith(suffix):
- return key[: -len(suffix)], suffix
- if key.endswith(INPUT_SCALE_SUFFIX):
- return key[: -len(INPUT_SCALE_SUFFIX)], INPUT_SCALE_SUFFIX
+ return key[: -len(suffix)], False
+ for suffix in INPUT_SCALE_SUFFIXES:
+ if key.endswith(suffix):
+ return key[: -len(suffix)], True
return None
+def _usable_input_scale(scale: torch.Tensor | None) -> torch.Tensor | None:
+ """A calibrated static activation scale, or None to fall back to per-forward ``amax`` scaling.
+
+ An ``input_scale`` of exactly 1.0 is a placeholder: the producer wrote the field without
+ calibrating it. Taking it at face value replaces the dynamic scale with *no scaling at all*, so
+ every activation above the fp8 maximum saturates — far worse than the dynamic path it
+ suppresses. ComfyUI drops the key in exactly this case (comfy/utils.py, convert_old_quants).
+
+ 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.
+ """
+ if scale is None:
+ return None
+ scale = scale.float().reshape(())
+ if not torch.isfinite(scale) or scale <= 0 or scale.item() == 1.0:
+ return None
+ return scale
+
+
def extract_fp8_scaled_layers(
sd: dict[str, Any],
metadata: Mapping[str, Any] | None = None,
@@ -155,8 +179,8 @@ def extract_fp8_scaled_layers(
parsed = _strip_scale_suffix(key)
if parsed is None:
continue
- path, suffix = parsed
- if suffix == INPUT_SCALE_SUFFIX:
+ path, is_input_scale = parsed
+ if is_input_scale:
input_scales[path] = sd.pop(key)
else:
weight_scales[path] = sd.pop(key)
@@ -175,7 +199,7 @@ def extract_fp8_scaled_layers(
hints = layer_meta.get(path, {})
layers[path] = Fp8ScaledLayer(
weight_scale=scale.float().reshape(()) if scale.numel() == 1 else scale.float().flatten(),
- input_scale=input_scales.get(path).float().reshape(()) if path in input_scales else None,
+ input_scale=_usable_input_scale(input_scales.get(path)),
full_precision_matmul=bool(hints.get("full_precision_matrix_mult", False)),
)
return layers
diff --git a/tests/backend/quantization/test_fp8_scaled.py b/tests/backend/quantization/test_fp8_scaled.py
index 03a6729888..4e8028c6bb 100644
--- a/tests/backend/quantization/test_fp8_scaled.py
+++ b/tests/backend/quantization/test_fp8_scaled.py
@@ -102,6 +102,59 @@ def _comfy_quant_blob(full_precision: bool):
return torch.tensor(list(payload.encode("utf-8")), dtype=torch.uint8)
+class TestInputScale:
+ def test_calibrated_scale_is_kept(self):
+ q, scale = _fp8_weight(32, 16)
+ sd = {"lin.weight": q, "lin.weight_scale": scale, "lin.input_scale": torch.tensor(0.017)}
+ layer = extract_fp8_scaled_layers(sd)["lin"]
+ assert layer.input_scale is not None
+ assert pytest.approx(layer.input_scale.item()) == 0.017
+ assert "lin.input_scale" not in sd
+
+ def test_scale_input_spelling_is_accepted(self):
+ """`.scale_input` is the other spelling in the wild; ignoring it discards the calibration."""
+ q, scale = _fp8_weight(32, 16)
+ sd = {"lin.weight": q, "lin.scale_weight": scale, "lin.scale_input": torch.tensor(0.017)}
+ layer = extract_fp8_scaled_layers(sd)["lin"]
+ assert pytest.approx(layer.input_scale.item()) == 0.017
+ assert not [k for k in sd if "scale_input" in k], "must be popped, not left for load_state_dict"
+
+ @pytest.mark.parametrize(
+ "value", [1.0, 0.0, -0.5, float("nan"), float("inf")], ids=["placeholder", "zero", "negative", "nan", "inf"]
+ )
+ def test_unusable_scales_fall_back_to_dynamic(self, value: float):
+ """A 1.0 input_scale is an uncalibrated placeholder. Using it means *no* activation scaling,
+ so everything above the fp8 max saturates -- strictly worse than the per-forward amax it
+ would replace. Zero/negative/non-finite cannot be a divisor at all."""
+ q, scale = _fp8_weight(32, 16)
+ sd = {"lin.weight": q, "lin.weight_scale": scale, "lin.input_scale": torch.tensor(value)}
+ assert extract_fp8_scaled_layers(sd)["lin"].input_scale is None
+
+ @cuda_fp8
+ def test_placeholder_scale_saturates_activations_above_the_fp8_range(self):
+ """End-to-end cost of trusting a 1.0 placeholder.
+
+ fp8_e4m3 is a floating-point format, so a scale factor does not buy relative precision the
+ way it would for int8 — for activations inside +/-448 both paths are equivalent. The damage
+ appears only above the representable range, where an unscaled cast clamps hard while the
+ dynamic amax scale maps the whole tensor into range. Transformer activations do reach that
+ regime, which is why a calibrated input_scale exists at all.
+ """
+ torch.manual_seed(0)
+ q, scale = _fp8_weight(64, 64)
+ q, scale = q.cuda(), scale.cuda()
+ x = (torch.randn(32, 64, dtype=torch.bfloat16, device="cuda") * 2000.0).unsqueeze(0)
+ assert x.abs().max() > 448, "test must exercise the saturating regime"
+ reference = torch.nn.functional.linear(x, dequantize_weight(q, scale, x.dtype))
+
+ def err(got: torch.Tensor) -> float:
+ return ((got.float() - reference.float()).norm() / reference.float().norm()).item()
+
+ dynamic = scaled_mm_linear(x, q, scale, None, input_scale=None)
+ unscaled = scaled_mm_linear(x, q, scale, None, input_scale=torch.tensor(1.0, device="cuda"))
+ assert err(dynamic) < err(unscaled) / 2, f"dynamic={err(dynamic):.4f} unscaled={err(unscaled):.4f}"
+
+
class TestComfyQuantHints:
def test_reads_per_layer_markers_and_pops_them(self):
sd = {