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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(fp8): put the stored weights back instead of re-quantizing them
Alexander Eichhorn4c343a646def
diff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.pyindex ec380403d1..a5c887c8b5 100644--- a/invokeai/backend/model_manager/load/load_default.py+++ b/invokeai/backend/model_manager/load/load_default.py@@ -146,6 +146,17 @@ _FP8_SUPPORTED_PYTORCH_LAYERS: tuple[type[torch.nn.Module], ...] = (torch.nn.Embedding,)+# Where a hooked module parks the params as stored while its forward runs on widened copies. Lives+# in the module's `__dict__`, which `wrap_custom_layer` shares with the `Custom*` instance it swaps+# in, so the pair survives `apply_custom_layers_to_model`. Not a buffer: `state_dict()` must not see it.+#+# It is only ever live inside a single `__call__`, and that is what keeps it safe: everything that+# copies or rebinds a module's params — `_build_meta_shell`, `apply_custom_layers_to_model`,+# partial load/unload, eviction — runs outside any forward on the same model. Worth preserving if+# that ordering is ever changed: a *live* stash reaching `_build_meta_shell` would be deep-copied+# as a real tensor, materializing the weight inside a shell whose whole point is to hold no data.+_FP8_STORED_WEIGHTS_ATTR = "_invokeai_fp8_stored_weights"+# Module-path regexes (matched against `named_modules()` dotted paths) for precision-sensitive# layers that should never be cast to FP8. Mirrors diffusers' `DEFAULT_SKIP_MODULES_PATTERN`# — without these, FLUX RMSNorm.scale and similar tiny learned scalars get crushed to FP8 and@@ -652,7 +663,7 @@ class ModelLoader(ModelLoaderBase):for param in params:param.data = param.data.to(storage_dtype)- ModelLoader._wrap_forward_with_fp8_cast(module, storage_dtype, compute_dtype)+ ModelLoader._wrap_forward_with_fp8_cast(module, compute_dtype)@staticmethoddef _restore_compute_dtype(module: torch.nn.Module, compute_dtype: torch.dtype) -> None:@@ -670,11 +681,26 @@ class ModelLoader(ModelLoaderBase):param.data = param.data.to(compute_dtype)@staticmethod- def _wrap_forward_with_fp8_cast(- module: torch.nn.Module, storage_dtype: torch.dtype, compute_dtype: torch.dtype- ) -> None:- """Register pre/post forward hooks that cast params to compute dtype on entry and back- to storage dtype on exit.+ def _wrap_forward_with_fp8_cast(module: torch.nn.Module, compute_dtype: torch.dtype) -> None:+ """Register pre/post forward hooks that widen params to compute dtype on entry and put the+ stored ones back on exit.++ The exit puts back the *same tensors*, rather than re-quantizing to the storage dtype. Both+ end with a param of the storage dtype, and the difference is the whole point:++ - `.to(storage_dtype)` allocates new storage. `CachedModelWithPartialLoad` keeps+ `_cpu_state_dict = model.state_dict()` (the `keep_ram_copy_of_weights` default), so after+ the first forward the param pointed at a private copy while that RAM copy pinned the+ original — both live, 2 bytes per element for every param still CPU-resident, against a+ budget snapshotted at `put()` that still said 1. It healed only when the model moved to+ VRAM or was evicted, so it lasted a whole generation, and multi-GPU multiplied it: the+ `SharedCpuWeightsStore` canonical tensor stayed pinned while each device detached its own.+ - Putting the stored tensor back also skips the fp8 round trip entirely. Only the widening+ cast remains, one per forward instead of two, and the exit allocates nothing at all.++ The cost is that the stored tensor stays alive for the duration of the forward, so the module+ in flight holds storage + compute dtype at once rather than just compute. That is one module+ at a time and bounded by the largest layer.We use hooks (rather than overriding `module.forward`) for two reasons:@@ -696,12 +722,33 @@ class ModelLoader(ModelLoaderBase):"""def pre_hook(mod: torch.nn.Module, _args: object) -> None:- for p in mod.parameters(recurse=False):- p.data = p.data.to(compute_dtype)+ state = getattr(mod, _FP8_STORED_WEIGHTS_ATTR, None)+ if state is not None:+ # Already inside a forward on this module. The outermost call owns the restore;+ # widening again would stash the *widened* tensor as if it were the stored one.+ state["depth"] += 1+ return+ stored = [(p, p.data) for p in mod.parameters(recurse=False)]+ # Installed *before* the widening, not after. The widening asks for twice the param's+ # storage on a device the cache deliberately drives to its ceiling, so it is the most+ # likely allocation here to raise; `always_call=True` then runs the post-hook, and if+ # the record were not in place yet it would find nothing to put back and leave the+ # already-widened params in compute dtype — permanently, because the next forward would+ # record *those* as the stored ones.+ setattr(mod, _FP8_STORED_WEIGHTS_ATTR, {"depth": 1, "stored": stored})+ for p, data in stored:+ p.data = data.to(compute_dtype)def post_hook(mod: torch.nn.Module, _args: object, _output: object) -> None:- for p in mod.parameters(recurse=False):- p.data = p.data.to(storage_dtype)+ state = getattr(mod, _FP8_STORED_WEIGHTS_ATTR, None)+ if state is None:+ return+ state["depth"] -= 1+ if state["depth"] > 0:+ return+ setattr(mod, _FP8_STORED_WEIGHTS_ATTR, None)+ for p, data in state["stored"]:+ p.data = datamodule.register_forward_pre_hook(pre_hook)module.register_forward_hook(post_hook, always_call=True)diff --git a/tests/backend/model_manager/load/test_load_default_fp8.py b/tests/backend/model_manager/load/test_load_default_fp8.pyindex 51dbe2efce..4547e77538 100644--- a/tests/backend/model_manager/load/test_load_default_fp8.py+++ b/tests/backend/model_manager/load/test_load_default_fp8.py@@ -183,7 +183,7 @@ def test_wrap_forward_restores_storage_dtype_on_exception():for p in module.parameters(recurse=False):p.data = p.data.to(storage_dtype)- ModelLoader._wrap_forward_with_fp8_cast(module, storage_dtype, compute_dtype)+ ModelLoader._wrap_forward_with_fp8_cast(module, compute_dtype)# Sanity: params start in storage dtype.assert module.weight.dtype == storage_dtype@@ -218,7 +218,7 @@ def test_wrap_forward_casts_to_compute_then_back_on_success():for p in module.parameters(recurse=False):p.data = p.data.to(storage_dtype)- ModelLoader._wrap_forward_with_fp8_cast(module, storage_dtype, compute_dtype)+ ModelLoader._wrap_forward_with_fp8_cast(module, compute_dtype)module(torch.zeros(4, dtype=compute_dtype))@@ -226,6 +226,83 @@ def test_wrap_forward_casts_to_compute_then_back_on_success():assert module.weight.dtype == storage_dtype[email protected](not _fp8_supported(), reason="torch.float8_e4m3fn not available")+def test_the_forward_puts_the_stored_weights_back_rather_than_re_quantizing():+ """The exit must restore the same tensors, or the cache's RAM copy is orphaned.++ `CachedModelWithPartialLoad` snapshots `model.state_dict()` at `put()` and charges the RAM+ budget from it. A post-hook that re-derived the storage dtype with `.to()` allocated new+ storage, so from the first forward on, every CPU-resident param pointed at a private copy+ while that snapshot pinned the original: both live, 2 bytes per element against a budget that+ still said 1, for as long as the weights stayed in RAM.+ """+ model = torch.nn.Sequential(*[torch.nn.Linear(64, 64, bias=False) for _ in range(4)]).to(torch.bfloat16)+ ModelLoader._apply_fp8_to_nn_module(model, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16)+ cached = model.state_dict()++ model(torch.randn(1, 64, dtype=torch.bfloat16))++ for name, snapshot in cached.items():+ param = model.get_parameter(name)+ assert param.dtype is torch.float8_e4m3fn, name+ assert param.data_ptr() == snapshot.data_ptr(), f"{name}: the RAM snapshot now pins a second copy"++[email protected](not _fp8_supported(), reason="torch.float8_e4m3fn not available")+def test_a_doubly_wrapped_module_still_ends_with_the_weights_stored():+ """Only the outermost hook pair may restore, which is what the depth counter is for.++ `_apply_fp8_to_nn_module` carries no idempotency guard of its own — the marker check lives in+ its caller — so a second pass over the same tree registers a second hook pair. Without the+ counter the inner pre-hook records the *widened* weight as the stored one and the module stays+ in compute dtype for good: fp8 storage silently off, and the cache under-counting it by half.+ """+ model = torch.nn.Sequential(torch.nn.Linear(8, 8, bias=False)).to(torch.bfloat16)+ ModelLoader._apply_fp8_to_nn_module(model, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16)+ cached = model.state_dict()+ ModelLoader._apply_fp8_to_nn_module(model, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16)+ assert len(model[0]._forward_pre_hooks) == 2, "the premise is a module wrapped twice"++ model(torch.randn(1, 8, dtype=torch.bfloat16))++ assert model[0].weight.dtype is torch.float8_e4m3fn+ assert model[0].weight.data_ptr() == cached["0.weight"].data_ptr()++[email protected](not _fp8_supported(), reason="torch.float8_e4m3fn not available")+def test_a_widening_that_runs_out_of_memory_leaves_the_weights_stored():+ """The widening is the likeliest allocation here to fail, and it must not strand the module.++ It asks for twice the param's storage on a device the cache deliberately drives to its ceiling.+ `always_call=True` runs the post-hook when it raises, so the record of what the params held has+ to be in place before the first cast — otherwise the already-widened ones stay widened, and the+ next forward records *those* as the stored ones, which makes it permanent.+ """+ module = torch.nn.Linear(8, 8).to(torch.bfloat16)+ for p in module.parameters(recurse=False):+ p.data = p.data.to(torch.float8_e4m3fn)+ cached = {name: p.data for name, p in module.named_parameters()}+ ModelLoader._wrap_forward_with_fp8_cast(module, torch.bfloat16)++ real_to = torch.Tensor.to+ calls = {"n": 0}++ def failing_to(self, *args, **kwargs):+ # Fail on the second widening, so one param is already widened when it raises.+ if args and args[0] is torch.bfloat16:+ calls["n"] += 1+ if calls["n"] == 2:+ raise torch.OutOfMemoryError("probe")+ return real_to(self, *args, **kwargs)++ with patch.object(torch.Tensor, "to", failing_to), pytest.raises(torch.OutOfMemoryError):+ module(torch.randn(1, 8, dtype=torch.bfloat16))++ for name, param in module.named_parameters():+ assert param.dtype is torch.float8_e4m3fn, name+ assert param.data_ptr() == cached[name].data_ptr(), f"{name}: restored a copy, not the stored tensor"++def test_apply_fp8_to_nn_module_uses_wrapper():"""`_apply_fp8_to_nn_module` should delegate per-module wrapping to`_wrap_forward_with_fp8_cast`, which encapsulates the hook registration.@@ -233,7 +310,7 @@ def test_apply_fp8_to_nn_module_uses_wrapper():module = torch.nn.Linear(4, 4)with patch.object(ModelLoader, "_wrap_forward_with_fp8_cast") as mock_wrap:ModelLoader._apply_fp8_to_nn_module(module, torch.float16, torch.float32)- mock_wrap.assert_called_once_with(module, torch.float16, torch.float32)+ mock_wrap.assert_called_once_with(module, torch.float32)def test_apply_fp8_to_nn_module_skips_norm_modules():@@ -508,7 +585,7 @@ def test_wrap_forward_reaches_custom_linear_after_apply_custom_layers():parent = Parent()original_linear = parent.child- ModelLoader._wrap_forward_with_fp8_cast(original_linear, torch.float16, torch.float32)+ ModelLoader._wrap_forward_with_fp8_cast(original_linear, torch.float32)apply_custom_layers_to_model(parent)new_child = parent.child