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): reserve cache room before the scale fold, not after it

Alexander Eichhorn3bd845220f66
diff --git a/invokeai/backend/model_manager/load/model_loaders/anima.py b/invokeai/backend/model_manager/load/model_loaders/anima.py
index e6f2cb0dd1..62bce3ad5a 100644
--- a/invokeai/backend/model_manager/load/model_loaders/anima.py
+++ b/invokeai/backend/model_manager/load/model_loaders/anima.py
@@ -188,24 +188,20 @@ class AnimaCheckpointModel(ModelLoader):
**strip_layer_path_prefix(header_hints),
}
fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)
- if fp8_layers and not keep_fp8:
- # 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 = {}
# Create an empty AnimaTransformer with Anima's default architecture parameters
with accelerate.init_empty_weights():
model = AnimaTransformer(**ANIMA_TRANSFORMER_CONFIG)
skip_patterns = _model_declared_skip_patterns(model)
- # 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.
- # 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. `scaled_layers` is what keeps that honest: the split also widens layers
- # whose scale layout `scaled_mm` cannot apply, and without the mapping the prediction would
- # charge those 1 byte/element and arrive at 2.
+ # Reserve before anything below widens a weight -- the fold and the split both do, and
+ # reserving afterwards lets either peak land on a cache that was only ever sized for the
+ # file. `scaled_layers` is what keeps the prediction honest where the weights are kept: the
+ # split also widens layers whose scale layout `scaled_mm` cannot apply, and without the
+ # mapping the prediction would charge those 1 byte/element and arrive at 2. Where they are
+ # not kept the prediction charges every float at `model_dtype`, folded yet or not, so the
+ # number is the same on either side of the fold -- what changes is when the room exists.
+ # Building the model first costs nothing: `init_empty_weights` leaves every param on meta.
self._ram_cache.make_room(
predict_cast_state_dict_size(
sd,
@@ -217,6 +213,14 @@ class AnimaCheckpointModel(ModelLoader):
)
)
+ if fp8_layers and not keep_fp8:
+ # 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 = {}
+
+ # Layers the cast would dequantize anyway are folded here too, 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)
kept = cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)
diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.py
index f67e0cb42f..4ca5f23ea5 100644
--- a/invokeai/backend/model_manager/load/model_loaders/flux.py
+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py
@@ -829,13 +829,6 @@ class FluxCheckpointModel(ModelLoader):
# The `match` above admits only the transformer, so that is the submodel the cast will be
# asked about too -- keep and cast therefore decide on the same input.
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
- # memory nobody wanted saved. Fold the scale into the weight instead — the legacy
- # result, except the scale is now actually applied rather than dropped.
- dequantize_fp8_scaled(sd, fp8_layers, torch.bfloat16)
- fp8_layers = {}
-
skip_patterns = _model_declared_skip_patterns(model)
if int8_markers:
@@ -861,13 +854,13 @@ class FluxCheckpointModel(ModelLoader):
f"FLUX: kept {len(quantized)} layer(s) in int8 (int8_tensorwise checkpoint, dequantized per forward)"
)
return model
- # 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.
- # 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. `scaled_layers` is what keeps that honest: the split also widens layers
- # whose scale layout `scaled_mm` cannot apply, and without the mapping the prediction would
- # charge those 1 byte/element and arrive at 2.
+ # Reserve before anything below widens a weight -- the fold and the split both do, and
+ # reserving afterwards lets either peak land on a cache that was only ever sized for the
+ # file. `scaled_layers` is what keeps the prediction honest where the weights are kept: the
+ # split also widens layers whose scale layout `scaled_mm` cannot apply, and without the
+ # mapping the prediction would charge those 1 byte/element and arrive at 2. Where they are
+ # not kept the prediction charges every float at the compute dtype, folded yet or not, so
+ # the number is the same on either side of the fold -- what changes is when the room exists.
self._ram_cache.make_room(
predict_cast_state_dict_size(
sd,
@@ -879,6 +872,15 @@ class FluxCheckpointModel(ModelLoader):
)
)
+ if fp8_layers and not keep_fp8:
+ # Neither consumer asked for them, and dequantizing per forward would cost speed for
+ # memory nobody wanted saved. Fold the scale into the weight instead — the legacy
+ # result, except the scale is now actually applied rather than dropped.
+ dequantize_fp8_scaled(sd, fp8_layers, torch.bfloat16)
+ fp8_layers = {}
+
+ # Scaled layers that the cast would dequantize anyway are folded here too, 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)
# 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)
@@ -1237,6 +1239,18 @@ class Flux2CheckpointModel(ModelLoader):
}
fp8_layers = extract_fp8_scaled_layers(converted_sd, layer_hints=layer_hints)
+
+ if not keep_fp8:
+ # Reserve before the two steps below widen weights: the scale fold, and
+ # `_dequantize_fp8_weights`'s raw-fp8 conversion. Unlike its peers this loader cannot
+ # leave that to the one reservation further down -- the architecture is read off these
+ # very keys, so no model exists yet to size a prediction against. It does not need one
+ # here: `predict_cast_state_dict_size` consults the model only to decide what *stays*
+ # quantized, and with `keep_fp8` false nothing does, so the model-less number is the
+ # same one. With `keep_fp8` true neither step widens anything, and the reservation
+ # below covers the split on its own.
+ self._ram_cache.make_room(predict_cast_state_dict_size(converted_sd, torch.bfloat16, keep_fp8=False))
+
if fp8_layers and not keep_fp8:
# 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
diff --git a/invokeai/backend/model_manager/load/model_loaders/ideogram4.py b/invokeai/backend/model_manager/load/model_loaders/ideogram4.py
index e13ef549dd..db69005978 100644
--- a/invokeai/backend/model_manager/load/model_loaders/ideogram4.py
+++ b/invokeai/backend/model_manager/load/model_loaders/ideogram4.py
@@ -393,11 +393,6 @@ class Ideogram4CheckpointModel(ModelLoader):
# count the file already had. Measured on FLUX.2 Klein 4B, ~3% of the weights flush to
# zero that way.
keep_fp8 = self._keep_fp8_weights(config, SubModelType.Transformer)
- if fp8_layers and not keep_fp8:
- # Neither consumer asked. Fold the scales in: staying quantized would halve VRAM but
- # dequantize on every forward, which is a cost nobody asked to pay.
- dequantize_fp8_scaled(sd, fp8_layers, model_dtype)
- fp8_layers = {}
with accelerate.init_empty_weights():
model: torch.nn.Module = Ideogram4Transformer(Ideogram4Config())
@@ -429,8 +424,12 @@ class Ideogram4CheckpointModel(ModelLoader):
)
kept = 0
else:
- # Reserve before the split: it dequantizes the layers it cannot keep through float32,
- # and a reservation made afterwards lets that transient peak land on an unreserved cache.
+ # Reserve before anything below widens a weight: the fold widens every scaled layer and
+ # the split dequantizes the ones it cannot keep through float32, so a reservation made
+ # afterwards lets either peak land on a cache that was only ever sized for the file.
+ # Where the weights are not kept the prediction charges every float at `model_dtype`,
+ # folded yet or not, so the number is the same on either side of the fold -- what changes
+ # is when the room exists.
self._ram_cache.make_room(
predict_cast_state_dict_size(
sd,
@@ -441,6 +440,11 @@ class Ideogram4CheckpointModel(ModelLoader):
scaled_layers=fp8_layers,
)
)
+ if fp8_layers and not keep_fp8:
+ # Neither consumer asked. Fold the scales in: staying quantized would halve VRAM but
+ # dequantize on every forward, which is a cost nobody asked to pay.
+ dequantize_fp8_scaled(sd, fp8_layers, model_dtype)
+ fp8_layers = {}
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)
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.py
index 436b2f687e..19ab227e34 100644
--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py
+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py
@@ -496,11 +496,6 @@ 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)
keep_fp8 = self._keep_fp8_weights(config, SubModelType.Transformer)
- if fp8_layers and not keep_fp8:
- # Neither consumer asked for them: keeping them quantized would halve VRAM but
- # dequantize on every forward, so fold the scales into the weights.
- dequantize_fp8_scaled(sd, fp8_layers, model_dtype)
- fp8_layers = {}
with accelerate.init_empty_weights():
model = Krea2Transformer2DModel(**KREA2_TRANSFORMER_CONFIG)
@@ -537,16 +532,14 @@ class Krea2CheckpointModel(ModelLoader):
fp8_layers = {}
kept = 0
else:
- # 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.
- # 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. `scaled_layers` is what keeps that honest: the split also widens layers
- # whose scale layout `scaled_mm` cannot apply, and without the mapping the prediction would
- # charge those 1 byte/element and arrive at 2.
+ # Reserve before anything below widens a weight -- the fold and the split both do, and
+ # reserving afterwards lets either peak land on a cache that was only ever sized for the
+ # file. `scaled_layers` is what keeps the prediction honest where the weights are kept:
+ # the split also widens layers whose scale layout `scaled_mm` cannot apply, and without
+ # the mapping the prediction would charge those 1 byte/element and arrive at 2. Where
+ # they are not kept the prediction charges every float at `model_dtype`, folded yet or
+ # not, so the number is the same on either side of the fold -- what changes is when the
+ # room exists.
self._ram_cache.make_room(
predict_cast_state_dict_size(
sd,
@@ -559,6 +552,17 @@ class Krea2CheckpointModel(ModelLoader):
+ nvfp4_bytes
)
+ if fp8_layers and not keep_fp8:
+ # Neither consumer asked for them: keeping them quantized would halve VRAM but
+ # dequantize on every forward, so fold the scales into the weights.
+ dequantize_fp8_scaled(sd, fp8_layers, model_dtype)
+ fp8_layers = {}
+
+ # Scaled layers the cast would dequantize anyway (skip patterns, non-Linear weights) are
+ # folded by the split, 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)
# 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
@@ -909,10 +913,6 @@ class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEnco
# *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 = {}
te_config = self._load_te_config(config)
with accelerate.init_empty_weights():
@@ -958,12 +958,20 @@ class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEnco
# 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.
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
- # prediction in step with the split's own scale-layout filter.
+ # Reserve before anything below widens a weight: the fold widens every scaled layer and
+ # the split dequantizes its unusable subset through fp32, so reserving afterwards lets
+ # either peak land on a cache that was only ever sized for the file. `scaled_layers`
+ # keeps the prediction in step with the split's own scale-layout filter; where the
+ # weights are not kept it charges every float at `model_dtype`, folded yet or not, so the
+ # number is the same on either side of the fold.
self._ram_cache.make_room(
predict_cast_state_dict_size(sd, model_dtype, keep_fp8=keep_fp8, model=model, scaled_layers=fp8_layers)
)
+ if fp8_layers and not keep_fp8:
+ # Neither consumer wants them packed: fold the scales into the weights. Both consumers
+ # were resolved above, next to the matmul probe, because this fold is irreversible.
+ dequantize_fp8_scaled(sd, fp8_layers, model_dtype)
+ fp8_layers = {}
fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model)
# No `skip_patterns` here on purpose: this model declares none, and the storage pass below
# applies `_FP8_DEFAULT_SKIP_PATTERNS` itself. Those two lists used to have to not intersect
diff --git a/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.py b/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.py
index a30ae8b94a..8b41250685 100644
--- a/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.py
+++ b/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.py
@@ -136,7 +136,7 @@ SEAM = Seam(
)
-def _driver(monkeypatch, tmp_path, state_dict: dict, header: dict | None = None):
+def _driver(monkeypatch, tmp_path, state_dict: dict, header: dict | None = None, observe: tuple[str, ...] = ()):
checkpoint = tmp_path / "flux-2-klein-9b-int8-convrot.safetensors"
checkpoint.touch()
config = Main_Checkpoint_Flux2_Config.model_construct(
@@ -149,7 +149,7 @@ def _driver(monkeypatch, tmp_path, state_dict: dict, header: dict | None = None)
# module symbol being gone.
patch.setattr(flux, "should_keep_fp8_weights", lambda _device: False, raising=False)
- run = prepare(SEAM, monkeypatch, state_dict=state_dict, metadata=header, geometry=geometry)
+ run = prepare(SEAM, monkeypatch, state_dict=state_dict, metadata=header, geometry=geometry, observe=observe)
# An instance attribute shadows the method, which is what keeps this working either way.
run.loader._keep_fp8_weights = lambda _config, _submodel=None: False
return run, config
@@ -499,3 +499,24 @@ def test_a_header_hint_reaches_every_projection_the_fused_qkv_became(monkeypatch
marked = model.get_submodule(f"transformer_blocks.0.attn.{projection}")
assert marked._fp8_full_precision_matmul is True, projection
assert model.get_submodule("transformer_blocks.0.attn.to_out.0")._fp8_full_precision_matmul is False
+
+
+def test_room_is_reserved_before_the_scales_are_folded(monkeypatch, tmp_path) -> None:
+ """This loader cannot reach its main reservation before it widens, so it needs an earlier one.
+
+ Its architecture is read off the converted keys, so no model exists at fold time to size a
+ prediction against -- unlike every peer in this series, which builds an empty model first and
+ reserves once. Left alone, the fold and `_dequantize_fp8_weights` both widen weights against a
+ cache that `_load_and_cache` sized for the file alone: roughly another file size, unreserved, on
+ the way to a 9B transformer.
+
+ The model-less prediction is exact here because it is only taken when nothing stays quantized,
+ and that is the only case in which either step widens anything.
+ """
+ state_dict, _ = _scaled_fp8_checkpoint()
+ run, config = _driver(monkeypatch, tmp_path, state_dict, observe=("dequantize_fp8_scaled",))
+
+ run.load(config)
+
+ assert [step for step, _ in run.order] == ["dequantize_fp8_scaled"], run.order
+ assert all(reserved for _step, reserved in run.order), run.order
diff --git a/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.py b/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.py
index 0fff557e58..4b25face3c 100644
--- a/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.py
+++ b/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.py
@@ -200,16 +200,21 @@ def test_with_the_fp8_matmul_the_codes_stay_and_the_scales_are_attached(monkeypa
assert run.casting_calls == 0
-def test_room_is_reserved_before_the_scales_are_folded(monkeypatch, tmp_path) -> None:
- # `split_fp8_scaled_layers` dequantizes what it cannot keep through float32, so a reservation
- # made afterwards lets that transient peak land on an unreserved cache. Reserving first is
- # invisible in the loaded model, so it is asserted where it happens.
[email protected]("keep_fp8", [True, False], ids=["fp8_compute", "folded"])
+def test_room_is_reserved_before_the_scales_are_folded(monkeypatch, tmp_path, keep_fp8: bool) -> None:
+ # Two steps widen weights and both must land on reserved room: `split_fp8_scaled_layers`
+ # dequantizes what it cannot keep through float32, and -- when neither consumer wants the codes
+ # -- the fold widens every scaled layer outright. Reserving first is invisible in the loaded
+ # model, so it is asserted where it happens.
+ #
+ # `keep_fp8=False` is the case that exercises the fold at all; with it true the fold never runs,
+ # so that parameter alone could not tell "reserved first" from "folded first".
state_dict, _ = _checkpoint((KEPT, *SKIPPED))
- _, run = _load(monkeypatch, tmp_path, state_dict, keep_fp8=True)
+ _, run = _load(monkeypatch, tmp_path, state_dict, keep_fp8=keep_fp8)
fp8_at_reservation = sum(1 for dtype in run.dtypes_at_make_room.values() if dtype is FP8)
- assert fp8_at_reservation == 3, "the fold ran before the cache was asked for room"
+ assert fp8_at_reservation == 3, "a weight was widened before the cache was asked for room"
@pytest.mark.parametrize("path", SKIPPED)
diff --git a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py
index b729e6d4dc..3a814d9121 100644
--- a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py
+++ b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py
@@ -718,7 +718,7 @@ class _TinyNativeKrea2(torch.nn.Module):
self.transformer_blocks = torch.nn.ModuleList([_TinyNativeKrea2Block(self.WIDTH)])
-def _native_fp8_driver(monkeypatch, tmp_path, state_dict):
+def _native_fp8_driver(monkeypatch, tmp_path, state_dict, observe: tuple[str, ...] = ()):
import diffusers
import safetensors.torch
@@ -737,6 +737,7 @@ def _native_fp8_driver(monkeypatch, tmp_path, state_dict):
state_dict=state_dict,
metadata=None,
geometry=lambda patch: patch.setattr(diffusers, "Krea2Transformer2DModel", _TinyNativeKrea2, raising=False),
+ observe=observe,
)
return run, config
@@ -823,3 +824,34 @@ def test_a_scale_on_a_reshaped_table_is_reported_rather_than_silently_absorbed(m
reports = [call.args[0] for call in run.loader._logger.info.call_args_list if "side-channel" in call.args[0]]
assert reports and "blocks.0.mod" in reports[0], f"the lost scale was not reported: {reports}"
+
+
+def test_room_is_reserved_before_the_scaled_weights_are_widened(monkeypatch, tmp_path) -> None:
+ """Both widening steps have to land on reserved room, and the fold is the earlier one.
+
+ `_load_and_cache` reserves the *file* size before this loader runs, so a fold that widens every
+ scaled layer 1 -> 2 bytes before `make_room` puts roughly another file size on a cache that was
+ never asked for it. The split has the same problem and its own fp32 transient besides.
+
+ Watched through `run.order` rather than `dtypes_at_make_room`: this path renames into a fresh
+ dict, so the served one never shows the widening at all.
+ """
+ from tests.fixtures.quantized_payloads import quantize_scaled_fp8
+
+ width = _TinyNativeKrea2.WIDTH
+ torch.manual_seed(0)
+ payload = quantize_scaled_fp8(torch.randn(width, width))
+ state_dict = {
+ **_native_block(width),
+ "blocks.0.attn.wq.weight": payload.codes,
+ "blocks.0.attn.wq.weight_scale": payload.scale,
+ }
+ widening = ("dequantize_fp8_scaled", "split_fp8_scaled_layers")
+ run, config = _native_fp8_driver(monkeypatch, tmp_path, state_dict, observe=widening)
+
+ model = run.load(config)
+
+ # The premise: neither consumer wanted the codes, so the fold really did run.
+ assert torch.allclose(model.transformer_blocks[0].attn.to_q.weight.float(), payload.dequantized, atol=1e-5)
+ assert [step for step, _ in run.order] == list(widening), run.order
+ assert all(reserved for _step, reserved in run.order), run.order