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(models): never cast a model that already holds fp8 weights

Alexander Eichhorn40e8973770fe
diff --git a/docs/src/content/docs/configuration/fp8-storage.mdx b/docs/src/content/docs/configuration/fp8-storage.mdx
index 89d4db6399..bb2df6e558 100644
--- a/docs/src/content/docs/configuration/fp8-storage.mdx
+++ b/docs/src/content/docs/configuration/fp8-storage.mdx
@@ -31,7 +31,7 @@ The toggle works as advertised: the UNet / transformer drops by roughly 50% on t
### RTX 40-series, RTX 50-series, and Hopper — VRAM win, plus a compute win via a separate setting
-These GPUs have native FP8 tensor cores. FP8 *Storage* on its own still only buys the ~50% VRAM reduction, because the forward pass runs in BF16 — the hook casts weights back up to compute precision before each layer. To actually use the tensor cores you need the separate [FP8 Compute](#fp8-compute) setting, which applies to checkpoints that ship pre-quantized ("scaled fp8") rather than to full-precision ones.
+These GPUs have native FP8 tensor cores. FP8 *Storage* on its own still only buys the ~50% VRAM reduction, because the forward pass runs in BF16 — the hook casts weights back up to compute precision before each layer. To actually use the tensor cores you need the separate [FP8 Compute](#fp8-compute) setting. Note that on a checkpoint which already ships FP8 weights, FP8 Storage does something different from what this section describes — see [Checkpoints that are already FP8](#checkpoints-that-are-already-fp8).
### Older CUDA cards — still a VRAM win
@@ -95,6 +95,7 @@ FP8 Storage is **near-lossless** for most workloads because:
- Norms and embeddings (the precision-sensitive layers) are skipped.
- The actual matmul still happens in FP16/BF16 — FP8 is only the on-GPU storage format.
+- On a checkpoint that is already FP8, the weights are not re-encoded at all: they stay exactly as published and are unpacked with their own scale before each layer, so there is no added rounding, and no re-quantization to undo.
That said, some artifacts have been reported on:
@@ -115,7 +116,11 @@ If you see unexpected quality regressions, disable FP8 Storage on the affected m
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 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.
+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. Without either setting 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; with FP8 Storage on they also stay as they are, but are unpacked layer by layer during the forward pass instead.
+
+### Checkpoints that are already FP8
+
+For these, FP8 Storage does not re-encode anything — it simply stops InvokeAI from unpacking them. That matters because the file stores a per-tensor scale alongside each weight, and re-encoding the unpacked result would throw that scale away: on FLUX.2 Klein 4B roughly 3% of the weights would round to zero, for a file that was already one byte per weight. What it costs instead is a little speed, since each layer is unpacked on use. The log says `FP8 storage skipped ... already fp8` for such a model, which is the intended outcome, not a failure.
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.
@@ -147,7 +152,7 @@ The cache eviction is immediate for idle models, but **deferred until the next u
If VRAM still hasn't dropped:
-- Check the InvokeAI log for `FP8 layerwise casting enabled for <model name>`. If the line isn't there, the model is on the exclusion list, or its loader does not apply FP8 yet (VAE, text encoder, LoRA, Wan — see table above).
+- Check the InvokeAI log for `FP8 layerwise casting enabled for <model name>`. If the line isn't there, the model is on the exclusion list, or its loader does not apply FP8 yet (VAE, text encoder, LoRA, Wan — see table above). For a checkpoint that is already FP8 the expected line is `FP8 storage skipped ... already fp8` instead: nothing needed re-encoding.
- Confirm you are on CUDA. FP8 Storage is silently disabled on CPU and MPS.
### Quality regression on a specific model
diff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.py
index d2e83df6b7..22dc1ad240 100644
--- a/invokeai/backend/model_manager/load/load_default.py
+++ b/invokeai/backend/model_manager/load/load_default.py
@@ -496,12 +496,27 @@ class ModelLoader(ModelLoaderBase):
fp8 -- measured on FLUX.2 Klein 4B, that loses ~3% of the weights to underflow for the
same one byte per weight.
- With neither, folding is right: staying packed would dequantize on every forward, spending
- speed to save memory nobody asked to save. `_should_use_fp8` already requires the device to
- support fp8 storage, so an unsupported device keeps the folding path.
+ Kept weights are dequantized with their scale on each forward (`CustomLinear`), so the
+ storage branch trades a little speed for half the VRAM -- the cost is not measured here, but
+ it replaces the upcast the storage cast used to perform per forward anyway. With neither
+ consumer asking, folding is right: packed weights would pay that per-forward work to save
+ memory nobody asked to save. `_should_use_fp8` already requires the device to support fp8
+ storage, so an unsupported device keeps the folding path.
"""
return should_keep_fp8_weights(self._torch_device) or self._should_use_fp8(config, submodel_type)
+ def _fp8_kept_reason(self) -> str:
+ """Which consumer kept a checkpoint's fp8 weights packed, for the line that reports it.
+
+ Worth naming rather than assuming: the log used to say "fp8_compute enabled" for both, and
+ that is now false exactly when FP8 Storage is the reason -- the matmul is off there, which
+ is the case a reader would most want to tell apart. The storage path also dequantizes on
+ each forward instead of running on the tensor cores, so the line says so.
+ """
+ if should_keep_fp8_weights(self._torch_device):
+ return "fp8_compute, on the fp8 tensor cores"
+ return "FP8 Storage, dequantized per forward"
+
def _apply_fp8_layerwise_casting(
self, model: AnyModel, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None
) -> AnyModel:
@@ -515,19 +530,23 @@ class ModelLoader(ModelLoaderBase):
if isinstance(model, torch.nn.Module) and getattr(model, FP8_COMPUTE_DTYPE_ATTR, None) is not None:
return model
- # A checkpoint that already ships fp8 weights is running (or is about to run) on the fp8
- # tensor cores. Layerwise casting would install hooks that restore the compute dtype before
- # every forward, so `CustomLinear._can_use_fp8_matmul` would no longer see an fp8 weight and
- # would silently fall back to the dequantized path — the VRAM toggle would make the model
- # *slower* with no indication why. Storage has nothing to add here anyway: the weights are
- # already 1 byte per parameter.
- if isinstance(model, torch.nn.Module) and should_keep_fp8_weights(self._torch_device):
+ # A checkpoint that already ships fp8 weights has nothing to gain from this cast -- they are
+ # already one byte per parameter -- and everything to lose. The cast installs hooks that
+ # restore the compute dtype before every forward, so:
+ # - with the fp8 matmul, `CustomLinear._can_use_fp8_matmul` no longer sees an fp8 weight
+ # and silently falls back to the dequantized path, making the VRAM toggle *slower*;
+ # - without it, a scaled-fp8 weight is upcast with its `weight_scale` never applied, i.e.
+ # off by 1/weight_scale on every kept layer, and a model whose first parameter is fp8
+ # derives an fp8 `compute_dtype`, which `set_fp8_compute_dtype` refuses outright.
+ # It therefore keys on the weights the model actually holds, not on which consumer kept
+ # them: FP8 Storage keeps scaled weights packed too, so the matmul is no longer the only
+ # way to arrive here.
+ if isinstance(model, torch.nn.Module):
already_fp8 = count_fp8_weights(model)
if already_fp8:
self._logger.info(
- f"FP8 storage skipped for {config.name}: {already_fp8} weight(s) are already fp8 and "
- "are being run on the fp8 tensor cores (fp8_compute). Layerwise casting would "
- "disable that matmul without saving any further VRAM."
+ f"FP8 storage skipped for {config.name}: {already_fp8} weight(s) are already fp8, so there is "
+ "no further VRAM to save and casting them would drop the scales they are stored with."
)
return model
diff --git a/invokeai/backend/model_manager/load/model_loaders/anima.py b/invokeai/backend/model_manager/load/model_loaders/anima.py
index 71e91e7efd..da2575eeb6 100644
--- a/invokeai/backend/model_manager/load/model_loaders/anima.py
+++ b/invokeai/backend/model_manager/load/model_loaders/anima.py
@@ -193,8 +193,8 @@ class AnimaCheckpointModel(ModelLoader):
}
fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)
if fp8_layers and not keep_fp8:
- # Without the matmul, keeping them quantized would halve VRAM but dequantize on every
- # forward. Fold the scale into the weight instead.
+ # Neither the matmul nor FP8 Storage asked for them, so keeping them quantized would
+ # dequantize on every forward to save memory nobody wanted saved. Fold the scale in.
dequantize_fp8_scaled(sd, fp8_layers, model_dtype)
fp8_layers = {}
@@ -237,13 +237,17 @@ class AnimaCheckpointModel(ModelLoader):
f"(expected for inv_freq buffers). First 5: {load_result.missing_keys[:5]}"
)
- # Without this the `fp8_storage` toggle is shown for Anima models but does nothing. The
- # state dict was cast to a single `model_dtype` above, so the layerwise cast has one
- # unambiguous compute dtype to restore to. AnimaTransformer is a plain nn.Module, so this
- # takes the hook-based path in `_apply_fp8_to_nn_module`.
+ # Without this the `fp8_storage` toggle is shown for Anima models but does nothing. When
+ # nothing stayed packed, the state dict was cast to a single `model_dtype` above, so the
+ # layerwise cast has one unambiguous compute dtype to restore to; when something did stay
+ # packed, the cast bails out on its own rather than upcast a scaled weight without applying
+ # its scale. AnimaTransformer is a plain nn.Module, so this takes the hook-based path in
+ # `_apply_fp8_to_nn_module`.
if fp8_layers:
attached = attach_fp8_scales(model, fp8_layers)
- logger.info(f"Anima: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, fp8_compute enabled)")
+ logger.info(
+ f"Anima: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, kept for {self._fp8_kept_reason()})"
+ )
warn_on_unattached_scales(logger, "Anima", attached, fp8_layers)
marked = sum(1 for layer in fp8_layers.values() if layer.full_precision_matmul)
if marked and full_precision_hints_respected():
@@ -252,7 +256,7 @@ class AnimaCheckpointModel(ModelLoader):
"and will dequantize per forward."
)
elif kept:
- logger.info(f"Anima: kept {kept} raw fp8 weight(s) quantized for the fp8 tensor cores.")
+ logger.info(f"Anima: kept {kept} raw fp8 weight(s) quantized ({self._fp8_kept_reason()}).")
model = self._apply_fp8_layerwise_casting(model, config, SubModelType.Transformer)
return model
diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.py
index 2708b0228e..33607dd7d6 100644
--- a/invokeai/backend/model_manager/load/model_loaders/flux.py
+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py
@@ -795,7 +795,9 @@ class FluxCheckpointModel(ModelLoader):
if fp8_layers:
attached = attach_fp8_scales(model, fp8_layers)
- self._logger.info(f"FLUX: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, fp8_compute enabled)")
+ self._logger.info(
+ f"FLUX: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, kept for {self._fp8_kept_reason()})"
+ )
warn_on_unattached_scales(self._logger, "FLUX", attached, fp8_layers)
marked = sum(1 for layer in fp8_layers.values() if layer.full_precision_matmul)
if marked and full_precision_hints_respected():
@@ -805,7 +807,7 @@ class FluxCheckpointModel(ModelLoader):
"them on the fp8 tensor cores instead."
)
elif kept:
- self._logger.info(f"FLUX: kept {kept} raw fp8 weight(s) quantized for the fp8 tensor cores.")
+ self._logger.info(f"FLUX: kept {kept} raw fp8 weight(s) quantized ({self._fp8_kept_reason()}).")
return model
@@ -1095,9 +1097,9 @@ class Flux2CheckpointModel(ModelLoader):
fp8_layers = extract_fp8_scaled_layers(converted_sd, layer_hints=layer_hints)
if fp8_layers and not keep_fp8:
- # Without the matmul, keeping them quantized would halve VRAM but dequantize on every
- # forward. Fold the scale into the weight instead -- the legacy result, except reached
- # through the shared helper.
+ # Neither the matmul nor FP8 Storage asked for them, so keeping them quantized would
+ # dequantize on every forward to save memory nobody wanted saved. Fold the scale in --
+ # the legacy result, except reached through the shared helper.
dequantize_fp8_scaled(converted_sd, fp8_layers, torch.bfloat16)
fp8_layers = {}
@@ -1204,7 +1206,9 @@ class Flux2CheckpointModel(ModelLoader):
if fp8_layers:
attached = attach_fp8_scales(model, fp8_layers)
- self._logger.info(f"FLUX.2: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, fp8_compute enabled)")
+ self._logger.info(
+ f"FLUX.2: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, kept for {self._fp8_kept_reason()})"
+ )
warn_on_unattached_scales(self._logger, "FLUX.2", attached, fp8_layers)
marked = sum(1 for layer in fp8_layers.values() if layer.full_precision_matmul)
if marked and full_precision_hints_respected():
@@ -1214,7 +1218,7 @@ class Flux2CheckpointModel(ModelLoader):
"them on the fp8 tensor cores instead."
)
elif kept:
- self._logger.info(f"FLUX.2: kept {kept} raw fp8 weight(s) quantized for the fp8 tensor cores.")
+ self._logger.info(f"FLUX.2: kept {kept} raw fp8 weight(s) quantized ({self._fp8_kept_reason()}).")
return model
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.py
index e252d00b70..0d1dce0b05 100644
--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py
+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py
@@ -544,7 +544,9 @@ 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)")
+ self._logger.info(
+ f"Krea-2: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, kept for {self._fp8_kept_reason()})"
+ )
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.
@@ -563,14 +565,14 @@ class Krea2CheckpointModel(ModelLoader):
f"Krea-2: ignoring the full_precision_matrix_mult marker on {marked} layer(s) "
"(fp8_compute_full_precision_hints=false)."
)
- # fp8_storage exists to *create* fp8 weights from full-precision ones; here they already
- # are fp8, so it is bypassed entirely. Say so, otherwise a user who enabled it is left
- # wondering whether it took effect.
+ # `fp8_storage` exists to *create* fp8 weights from full-precision ones. Here they are
+ # already fp8 -- kept either by the matmul or by that setting itself -- so the cast has
+ # nothing to add. Say so, otherwise a user who enabled it cannot tell whether it took.
default_settings = getattr(config, "default_settings", None)
if default_settings is not None and getattr(default_settings, "fp8_storage", None):
self._logger.info(
- "Krea-2: the model's fp8_storage setting is redundant here and was skipped - the "
- "checkpoint already ships fp8 weights."
+ "Krea-2: fp8_storage is satisfied by the checkpoint itself - its weights are already "
+ "fp8 and are kept that way, so the layerwise cast is skipped."
)
# The layerwise-casting path exists to *produce* fp8 weights from full-precision ones. The
# checkpoint already is fp8, and its hooks would cast back to the compute dtype without
@@ -848,9 +850,14 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):
# would leave the scales already folded while the raw Linears stay quantized, i.e. the
# encoder silently on the storage path with the matmul log line never printed.
keep_matmul_fp8 = should_keep_fp8_weights(target_device)
- if fp8_layers and not keep_matmul_fp8:
- # 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.
+ # Resolved here, next to the matmul probe and for the same reason: the fold below is
+ # irreversible, so both consumers have to be known before it runs. Asking only about the
+ # matmul folded the scales away and then let the storage cast re-quantize the result to
+ # *unscaled* fp8 -- on a scaled checkpoint that is ~3% of the weights lost to underflow,
+ # for the byte count the file already had.
+ use_fp8_storage = source_is_fp8 and _device_supports_fp8_storage(self._torch_device, self._logger)
+ if fp8_layers and not keep_matmul_fp8 and not use_fp8_storage:
+ # Neither consumer wants them packed: fold the scales into the weights.
dequantize_fp8_scaled(sd, fp8_layers, model_dtype)
fp8_layers = {}
@@ -893,7 +900,6 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):
# `model_dtype` here would double both this reservation and the host-RAM peak (~4.4 -> ~8.9
# GiB on the 4B encoder) for a round trip that ends where it started -- e4m3fn is a subset
# of bf16, so it is value-exact. Keep them for either consumer.
- use_fp8_storage = source_is_fp8 and _device_supports_fp8_storage(self._torch_device, self._logger)
keep_fp8 = keep_matmul_fp8 or use_fp8_storage
# Reserve before the split: it dequantizes its unusable subset through fp32, so reserving
# afterwards lets that transient peak land on an unreserved cache. `scaled_layers` keeps the
@@ -938,8 +944,8 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):
or isinstance(module, torch.nn.Embedding),
)
self._logger.info(
- f"FP8 compute enabled for Qwen3-VL encoder '{config.name}': kept {attached} layer(s) "
- f"quantized (storage=float8_e4m3fn, matmul=torch._scaled_mm, compute={model_dtype}); "
+ f"Qwen3-VL encoder '{config.name}': kept {attached} scaled layer(s) quantized "
+ f"({self._fp8_kept_reason()}, storage=float8_e4m3fn, compute={model_dtype}); "
"remaining layers cast to fp8 storage."
)
# The layerwise-casting path below exists to *produce* fp8 weights from full-precision
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 7ffd212935..9cb9fc3fad 100644
--- a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
+++ b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
@@ -954,8 +954,11 @@ class MistralEncoderCheckpointLoader(ModelLoader):
# `.weight_scale` travels with its weight automatically -- no fused projections to split.
# Storage keeps them too, gated on the device alone: `_should_use_fp8` excludes text encoders
# by design (fp8 rounding costs text quality), so there is no per-model setting to read here.
- # This mirrors the Qwen3-VL encoder in the Krea-2 loader. Folding stays the fallback only
- # where fp8 cannot be held at all.
+ # Folding is the fallback only where fp8 cannot be held at all, and folding is what hurts
+ # here: 16.8 GiB on disk becomes 32.3 GiB resident. Note what that makes this -- on CUDA the
+ # device check is always true, so the choice is unconditional and has no user setting behind
+ # it. This loader never calls the layerwise cast (text encoders are excluded there), so the
+ # kept weights reach `CustomLinear` with their scales intact.
keep_fp8 = should_keep_fp8_weights(target_device) or _device_supports_fp8_storage(target_device, logger)
fp8_layers: dict[str, Any] = {}
if keep_fp8:
@@ -1039,7 +1042,7 @@ class MistralEncoderCheckpointLoader(ModelLoader):
if fp8_layers:
attached = attach_fp8_scales(model, fp8_layers)
logger.info(
- f"Mistral encoder: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, fp8_compute enabled)"
+ f"Mistral encoder: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, kept for {self._fp8_kept_reason()})"
)
warn_on_unattached_scales(logger, "Mistral encoder", attached, fp8_layers)
marked = sum(1 for layer in fp8_layers.values() if layer.full_precision_matmul)
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 c45df80b3f..44fb8feb21 100644
--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py
@@ -603,7 +603,8 @@ class ZImageCheckpointModel(ModelLoader):
fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)
# Handle memory management and dtype conversion. Casting fp8 weights here would discard
- # both the VRAM saving and the tensor cores before the model is even built.
+ # the VRAM saving before the model is even built -- and the tensor cores too, where the
+ # fp8 matmul is what kept them.
keep_fp8 = self._keep_fp8_weights(config, SubModelType.Transformer)
if fp8_layers and not keep_fp8:
# Neither consumer asked for them, and dequantizing per forward would cost speed for
@@ -654,7 +655,9 @@ class ZImageCheckpointModel(ModelLoader):
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)")
+ self._logger.info(
+ f"Z-Image: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, kept for {self._fp8_kept_reason()})"
+ )
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():
@@ -672,8 +675,9 @@ class ZImageCheckpointModel(ModelLoader):
# FP8 *storage* on top. When nothing was kept quantized above, every param is uniform
# `model_dtype` here, so the layerwise cast has one unambiguous compute dtype to restore to.
# When weights *were* kept fp8, `_apply_fp8_layerwise_casting` bails out on its own (and
- # says so in the log): its hooks would restore the compute dtype before every forward and
- # silently disable the fp8 matmul, for no VRAM saving.
+ # says so in the log): its hooks would restore the compute dtype before every forward, which
+ # disables the fp8 matmul where there is one and drops the `weight_scale` where there is
+ # not -- and saves no VRAM either way.
model = self._apply_fp8_layerwise_casting(model, config, SubModelType.Transformer)
return model
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 9ed38273bf..68ec4d923e 100644
--- a/tests/backend/model_manager/load/test_load_default_fp8.py
+++ b/tests/backend/model_manager/load/test_load_default_fp8.py
@@ -798,10 +798,8 @@ class TestAlreadyFp8StorageGuard:
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.)
+ The mirror case -- an already-fp8 model with the matmul off -- is covered below. It used to
+ be unreachable, and is not any more: FP8 Storage keeps scaled weights packed too.
"""
loader = _make_loader("cuda")
model = torch.nn.Sequential(torch.nn.Linear(16, 32))
@@ -811,6 +809,33 @@ class TestAlreadyFp8StorageGuard:
assert model[0].weight.dtype is torch.float8_e4m3fn
+ def test_already_fp8_weights_are_left_alone_when_the_matmul_is_off(self) -> None:
+ """The case FP8 Storage created: weights kept packed without the fp8 matmul.
+
+ The guard used to ask whether the matmul was available, which is a different question from
+ the one that matters -- whether the model already holds fp8 weights. With FP8 Storage on and
+ `fp8_compute` off the cast would run over packed weights and upcast them with their
+ `weight_scale` never applied, i.e. off by 1/weight_scale on every layer, or derive an fp8
+ compute dtype and refuse the load outright.
+ """
+ loader = _make_loader("cuda")
+ model = torch.nn.Sequential(torch.nn.Linear(16, 32))
+ scale = torch.tensor(0.0056)
+ model[0].weight = torch.nn.Parameter(
+ torch.full((32, 16), 0.5 / scale.item()).to(torch.float8_e4m3fn), requires_grad=False
+ )
+ model[0].register_buffer("weight_scale", scale)
+
+ with patch("invokeai.backend.model_manager.load.load_default.should_keep_fp8_weights", return_value=False):
+ returned = loader._apply_fp8_layerwise_casting(model, _make_config(ModelType.Main, fp8=True))
+
+ assert returned is model
+ assert model[0].weight.dtype is torch.float8_e4m3fn
+ assert torch.equal(model[0].weight_scale, scale)
+ # No hooks: an upcast before every forward is what would drop the scale.
+ assert not model[0]._forward_pre_hooks
+ assert getattr(model, FP8_COMPUTE_DTYPE_ATTR, None) is None
+
class TestApplyFp8SkipCallback:
"""The `skip=` callback keeps scaled-fp8 layers out of the storage cast.
diff --git a/tests/backend/model_manager/load/test_z_image_loader_boundaries.py b/tests/backend/model_manager/load/test_z_image_loader_boundaries.py
index 4270597076..6952a3f88b 100644
--- a/tests/backend/model_manager/load/test_z_image_loader_boundaries.py
+++ b/tests/backend/model_manager/load/test_z_image_loader_boundaries.py
@@ -13,7 +13,9 @@ from unittest.mock import MagicMock
import pytest
import torch
+from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettings
from invokeai.backend.model_manager.configs.main import Main_Checkpoint_ZImage_Config
+from invokeai.backend.model_manager.load import load_default
from invokeai.backend.model_manager.load.model_loaders.z_image import ZImageCheckpointModel
from invokeai.backend.quantization.int8_convrot import CONVROT_GROUP_SIZE, Int8ConvrotLinear, build_regular_hadamard
@@ -183,3 +185,36 @@ def test_a_precision_sensitive_layer_is_not_left_int8(monkeypatch, tmp_path) ->
# And the reservation covers the widened layer at its post-split width, not at one byte.
(reserved,), _ = loader._ram_cache.make_room.call_args
assert reserved >= sensitive.nelement() * 4 + ordinary_q.nelement()
+
+
+def test_a_scaled_fp8_checkpoint_stays_packed_when_storage_is_on(monkeypatch, tmp_path) -> None:
+ """The keep decision has to reach the loader, not only the helper it was extracted into.
+
+ With FP8 Storage on, the checkpoint's own scaled fp8 weights are kept rather than folded into
+ bf16 and re-quantized by the layerwise cast, which has no scale to apply. A loader that goes
+ back to asking only about the fp8 matmul folds them again -- silently, and precisely on the
+ hardware most users have, since `fp8_compute` is off by default.
+ """
+ torch.manual_seed(3)
+ original = torch.randn(4, CONVROT_GROUP_SIZE)
+ scale = (original.abs().max() / 448.0).to(torch.float32)
+ packed = (original / scale).to(torch.float8_e4m3fn)
+ state_dict = {"layers.0.proj.weight": packed, "layers.0.proj.weight_scale": scale}
+
+ loader, driver_config = _driver(monkeypatch, tmp_path, state_dict)
+ config = Main_Checkpoint_ZImage_Config.model_construct(
+ path=driver_config.path,
+ name="z-image",
+ default_settings=MainModelDefaultSettings(fp8_storage=True),
+ )
+ # The configuration this path exists for: no fp8 matmul, but a device that can hold fp8.
+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _device: False)
+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda _device, _logger=None: True)
+
+ model = loader._load_from_singlefile(config)
+
+ proj = model.layers[0].proj
+ assert proj.weight.dtype is torch.float8_e4m3fn, "folded back to a float dtype"
+ assert getattr(proj, "weight_scale", None) is not None, "kept packed but without its scale"
+ dequantized = (proj.weight.float() * proj.weight_scale).flatten()
+ assert torch.corrcoef(torch.stack([dequantized, original.flatten()]))[0, 1] > 0.999