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): never apply FP8 storage to already-quantized weights

Alexander Eichhorn3feb027fec20
diff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.py
index cff2f9db54..4d5a315f34 100644
--- a/invokeai/backend/model_manager/load/load_default.py
+++ b/invokeai/backend/model_manager/load/load_default.py
@@ -58,6 +58,32 @@ _FP8_DEFAULT_SKIP_PATTERNS: tuple[str, ...] = (
r"^proj_out$",
)
+# Model formats whose weights are already quantized. FP8 storage is meaningless for them (the
+# payload is packed integers, not values we may re-encode) and actively harmful — see
+# `_should_use_fp8`. Declared as strings to keep this module free of a taxonomy import at module
+# scope; compared against `config.format`, which is a `ModelFormat` str-enum.
+_QUANTIZED_MODEL_FORMATS: frozenset[str] = frozenset(
+ {
+ "gguf_quantized",
+ "bnb_quantized_nf4b",
+ "bnb_quantized_int8b",
+ }
+)
+
+
+def _is_quantized_param(param: torch.nn.Parameter) -> bool:
+ """Whether `param` holds a quantized payload that must not be re-encoded as FP8.
+
+ Two signals, both observed in practice:
+
+ - Not floating point. bnb's NF4/INT8 weights are packed `uint8` (and `bnb.nn.LinearNF4`
+ subclasses `nn.Linear`, so a class check alone does not catch them). Casting those to float8
+ succeeds silently and the layer then returns finite garbage.
+ - A `torch.Tensor` *subclass*, e.g. `GGMLTensor`, which keeps its quantized payload plus
+ metadata and rejects dtype changes outright.
+ """
+ return not param.data.is_floating_point() or type(param.data) is not torch.Tensor
+
# The construction path is not thread-safe on its own; it monkey-patches process-global torch state
# (see MODEL_LOAD_LOCK). Concurrent callers must hold the MODEL_LOAD_LOCK write lock (see
@@ -236,6 +262,16 @@ class ModelLoader(ModelLoaderBase):
from invokeai.backend.model_manager.taxonomy import ModelType
+ # Already-quantized models are excluded. Their weights are packed integer payloads, not
+ # values we may re-encode, and every quantized-format loader reaches this helper. Casting
+ # them is not a no-op:
+ # - GGUF raises `Operation changed the dtype of GGMLTensor unexpectedly` at load time.
+ # - bnb NF4 corrupts *silently* — `bnb.nn.LinearNF4` subclasses `nn.Linear`, so the packed
+ # uint8 payload is cast to float8, inference still returns finite numbers, and the model
+ # just produces garbage.
+ if hasattr(config, "format") and config.format in _QUANTIZED_MODEL_FORMATS:
+ return False
+
# VAEs are excluded — fp8 storage causes noticeable quality degradation in decode.
if hasattr(config, "type") and config.type == ModelType.VAE:
return False
@@ -347,6 +383,11 @@ class ModelLoader(ModelLoaderBase):
`extra_skip_patterns` carries the model's own declared exclusions (diffusers'
`_skip_layerwise_casting_patterns`), which are model-specific and cannot be inferred from
layer types or generic name patterns.
+
+ Modules holding already-quantized weights are skipped regardless of their class. This is a
+ backstop behind the format check in `_should_use_fp8`, which cannot see quantization that
+ is not reflected in the model's format (e.g. a `diffusers`-format checkpoint whose weights
+ were quantized by an external tool).
"""
skip_patterns = _FP8_DEFAULT_SKIP_PATTERNS + tuple(extra_skip_patterns)
for module_name, module in model.named_modules():
@@ -357,6 +398,8 @@ class ModelLoader(ModelLoaderBase):
params = list(module.parameters(recurse=False))
if not params:
continue
+ if any(_is_quantized_param(p) for p in params):
+ continue
for param in params:
param.data = param.data.to(storage_dtype)
diff --git a/invokeai/frontend/web/src/features/modelManagerV2/subpanels/ModelPanel/MainModelDefaultSettings/MainModelDefaultSettings.tsx b/invokeai/frontend/web/src/features/modelManagerV2/subpanels/ModelPanel/MainModelDefaultSettings/MainModelDefaultSettings.tsx
index 91d255f5a4..b077ed2448 100644
--- a/invokeai/frontend/web/src/features/modelManagerV2/subpanels/ModelPanel/MainModelDefaultSettings/MainModelDefaultSettings.tsx
+++ b/invokeai/frontend/web/src/features/modelManagerV2/subpanels/ModelPanel/MainModelDefaultSettings/MainModelDefaultSettings.tsx
@@ -56,6 +56,12 @@ export const MainModelDefaultSettings = memo(({ modelConfig }: Props) => {
return ['flux', 'flux2'].includes(modelConfig.base);
}, [modelConfig]);
+ // Already-quantized weights cannot also be stored as FP8 — the backend refuses it (see
+ // `_should_use_fp8`), so offering the switch would be a control that silently does nothing.
+ const isQuantized = useMemo(() => {
+ return ['gguf_quantized', 'bnb_quantized_nf4b', 'bnb_quantized_int8b'].includes(modelConfig.format);
+ }, [modelConfig]);
+
const defaultSettingsDefaults = useMainModelDefaultSettings(modelConfig);
const optimalDimension = useMemo(() => {
const modelBase = modelConfig?.base;
@@ -144,7 +150,7 @@ export const MainModelDefaultSettings = memo(({ modelConfig }: Props) => {
{!isFluxFamily && <DefaultCfgRescaleMultiplier control={control} name="cfgRescaleMultiplier" />}
<DefaultWidth control={control} optimalDimension={optimalDimension} />
<DefaultHeight control={control} optimalDimension={optimalDimension} />
- <DefaultFp8Storage control={control} name="fp8Storage" />
+ {!isQuantized && <DefaultFp8Storage control={control} name="fp8Storage" />}
</SimpleGrid>
</>
);
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 b807820d87..7780cc2461 100644
--- a/tests/backend/model_manager/load/test_load_default_fp8.py
+++ b/tests/backend/model_manager/load/test_load_default_fp8.py
@@ -360,6 +360,56 @@ def test_anima_transformer_declares_t_embedder_skip():
assert model.blocks.weight.dtype == torch.float16
[email protected]("fmt", ["gguf_quantized", "bnb_quantized_nf4b", "bnb_quantized_int8b"])
+def test_should_use_fp8_excludes_quantized_formats(fmt: str):
+ """Already-quantized weights must never be re-encoded as FP8.
+
+ Every quantized-format loader reaches `_apply_fp8_layerwise_casting`, and casting there is not
+ a no-op: GGUF raises `Operation changed the dtype of GGMLTensor unexpectedly` at load time, and
+ bnb NF4 corrupts silently (`bnb.nn.LinearNF4` subclasses `nn.Linear`, so its packed uint8
+ payload is cast to float8 and inference then returns finite garbage).
+ """
+ loader = _make_loader(device="cuda")
+ config = _make_config(ModelType.Main, fp8=True)
+ config.format = fmt
+ assert loader._should_use_fp8(config) is False
+
+
+def test_apply_fp8_skips_quantized_params_regardless_of_format():
+ """Backstop behind the format check, for quantization the model's format does not reveal
+ (e.g. a `diffusers`-format checkpoint quantized by an external tool).
+
+ Both signals are covered: a non-floating-point payload (bnb's packed uint8) and a
+ `torch.Tensor` subclass (GGUF's `GGMLTensor`).
+ """
+
+ class _FakeQuantTensor(torch.Tensor):
+ """Stands in for GGMLTensor: a Tensor subclass carrying a quantized payload."""
+
+ class _Model(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.packed = torch.nn.Linear(4, 4, bias=False) # bnb-style uint8 payload
+ self.subclassed = torch.nn.Linear(4, 4, bias=False) # GGUF-style tensor subclass
+ # NB: not `normal` — that would be caught by the `norm` skip pattern.
+ self.attn = torch.nn.Linear(4, 4, bias=False)
+
+ model = _Model().to(torch.bfloat16)
+ model.packed.weight = torch.nn.Parameter(torch.zeros(8, 1, dtype=torch.uint8), requires_grad=False)
+ model.subclassed.weight = torch.nn.Parameter(
+ torch.zeros(4, 4, dtype=torch.bfloat16).as_subclass(_FakeQuantTensor), requires_grad=False
+ )
+
+ ModelLoader._apply_fp8_to_nn_module(model, torch.float8_e4m3fn, torch.bfloat16)
+
+ assert model.packed.weight.dtype == torch.uint8
+ assert not model.packed._forward_pre_hooks, "a quantized layer must not get cast hooks either"
+ assert model.subclassed.weight.dtype == torch.bfloat16
+ assert not model.subclassed._forward_pre_hooks
+ # Control: an ordinary layer in the same model is still cast.
+ assert model.attn.weight.dtype == torch.float8_e4m3fn
+
+
def test_should_use_fp8_allows_z_image():
"""Z-Image was excluded while we used diffusers' `enable_layerwise_casting()` with the global
torch dtype (fp16) as compute dtype, which clashed with the model's bf16 weights. The compute