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(ideogram4): let FP8 Storage keep a scaled checkpoint packed
Alexander Eichhorn326d00e82114
diff --git a/docs/src/content/docs/concepts/models.mdx b/docs/src/content/docs/concepts/models.mdxindex e698f6fff1..667bf5922d 100644--- a/docs/src/content/docs/concepts/models.mdx+++ b/docs/src/content/docs/concepts/models.mdx@@ -82,14 +82,16 @@ Two builds of the transformers are supported, and they behave differently in mem| | download, per branch | resident, per branch ||---|---|---|| **Ideogram 4 (single file, int8)** — `int8_convrot` | 8.9 GB | **8.9 GB**, on every device |-| **Ideogram 4 (single file, fp8)** — `fp8_scaled` | 8.6 GB | 8.7 GB with `fp8_compute`, ~17 GB without |+| **Ideogram 4 (single file, fp8)** — `fp8_scaled` | 8.6 GB | **8.7 GB** with `fp8_compute` *or* FP8 Storage; 17.3 GB with neither |Both branches are resident at once, so double those figures for the pair.:::note[Which to pick]**On an NVIDIA Ada card (RTX 40-series) or newer, with `fp8_compute` enabled**, take the fp8 build: the two are a wash on memory, and fp8 is the faster one because its weights stay quantized *and* run on the fp8 tensor cores. Measured at 1024px on a 4090, 12 steps: **35.6 s** for the fp8 pair against **45.7 s** for the int8 pair.-**Everywhere else, use int8.** Without `fp8_compute` the fp8 weights are expanded to bf16 on load — about 35 GB for the pair, which does not fit a 24 GB card — while int8 keeps its stored codes and dequantizes them per forward, on any device and with no setting to turn on. Those ~10 s are what the dequantization costs, and they buy the difference between the model fitting and not fitting.+**Without the fp8 matmul, the fp8 build still works — through FP8 Storage.** That setting keeps the file's own fp8 weights and per-tensor scales instead of expanding them, and installation switches it on for these files by itself. Measured on a 4090 with `fp8_compute` off, 1024px: **40.6 s**, 22.9 GB peak, 8.7 GB resident per branch — against **45.7 s** for the int8 pair. With *neither* the matmul nor Storage the weights are expanded to bf16 on load, 17.3 GB per branch, and a 24 GB card runs out of memory during the first step.++**Use int8 where FP8 Storage is not available.** It requires a CUDA device; on anything else the fp8 build falls back to the expanded path, while int8 keeps its stored codes and dequantizes them per forward on any device with no setting to turn on.On a 24 GB NVIDIA card without the fp8 matmul (RTX 30-series), the int8 pair plus the 8B encoder still adds up to more than the card holds, so the bundled [nf4 build](#installing-ideogram-4) remains the smaller option there.:::diff --git a/docs/src/content/docs/configuration/fp8-storage.mdx b/docs/src/content/docs/configuration/fp8-storage.mdxindex 0730acb38e..e124a387d4 100644--- a/docs/src/content/docs/configuration/fp8-storage.mdx+++ b/docs/src/content/docs/configuration/fp8-storage.mdx@@ -11,7 +11,7 @@ FP8 Storage cuts a model's VRAM footprint roughly in half by keeping weights onIt pairs well with [Low-VRAM mode](/configuration/low-vram-mode/): low-VRAM mode streams layers between RAM and VRAM, while FP8 Storage shrinks the layers themselves.:::caution[For full precision models only]-FP8 Storage is meant for **full precision** checkpoints (FP16 / BF16 / FP32). It is **silently a no-op** for **GGUF**, **NF4** and [**SDNQ**](/configuration/sdnq-quantization/) checkpoints, which carry their own storage precision. **int8** and **nvfp4** single-file checkpoints keep their quantized layers as they are — the loader returns a module type the FP8 layer cast does not touch — so there the toggle only reaches the layers the build ships in full precision. On **Qwen-Image** single-file checkpoints that ship scaled fp8 layers, the toggle keeps those layers in FP8 with their own scale instead of unpacking them, and casts the rest. If your model is already quantized, use its full-precision variant to get the full effect of FP8 Storage. Checkpoints that store FP8 weights are the exception: InvokeAI loads them at BF16 unless FP8 Storage is on, so they get it automatically when installed (see [When installing](#when-installing)).+FP8 Storage is meant for **full precision** checkpoints (FP16 / BF16 / FP32). It is **silently a no-op** for **GGUF**, **NF4** and [**SDNQ**](/configuration/sdnq-quantization/) checkpoints, which carry their own storage precision. **int8** and **nvfp4** single-file checkpoints keep their quantized layers as they are — the loader returns a module type the FP8 layer cast does not touch — so there the toggle reaches only the layers the build ships in full precision, and on an **Ideogram 4** int8 file nothing at all. On single-file checkpoints that ship *scaled* fp8 layers, the toggle keeps those layers in FP8 with their own scale instead of unpacking them; that is what FLUX.1, FLUX.2, Z-Image, Anima, Krea-2, Qwen-Image and Ideogram 4 all do. If your model is already quantized, use its full-precision variant to get the full effect of FP8 Storage. Checkpoints that store FP8 weights are the exception: InvokeAI loads them at BF16 unless FP8 Storage is on, so they get it automatically when installed (see [When installing](#when-installing)).:::## Requirements@@ -75,6 +75,7 @@ FP8 Storage is **only** applied to layers where the precision trade-off is accep| Main models (SD1, SD2, SDXL) | Yes || FLUX.1 / FLUX.2 Klein | Yes || Z-Image, Anima, Krea-2, Qwen-Image | Yes |+| Ideogram 4 (single file) | Yes — both transformer branches || ControlNet, T2I-Adapter | Yes || Wan | Not yet — the switch is shown but has no effect || VAE | No — visible decode-quality regression |@@ -128,7 +129,9 @@ It is for models that were **already saved in FP8** by whoever published them### 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.+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. Measured on a 4090 with `fp8_compute` off, the Ideogram 4 fp8 pair generates 1024px in 40.6 s against 35.6 s on the FP8 tensor cores, and holds 8.7 GB per branch instead of the 17.3 GB the unpacked weights need — which is the difference between fitting on a 24 GB card and running out of memory during the first step.++The loader reports what it kept, naming the setting that kept it — for example `Ideogram 4: kept 208 layer(s) in fp8 (scaled fp8 checkpoint, kept for FP8 Storage, dequantized per forward)`. Some loaders then hand the model to the layer cast anyway, which declines it and logs `FP8 storage skipped ... already fp8`; on FLUX.1, FLUX.2, Z-Image and Anima you therefore see both lines for the same model. Both are 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.diff --git a/invokeai/app/invocations/ideogram4/ideogram4_denoise.py b/invokeai/app/invocations/ideogram4/ideogram4_denoise.pyindex 5b843cae73..ce090072b6 100644--- a/invokeai/app/invocations/ideogram4/ideogram4_denoise.py+++ b/invokeai/app/invocations/ideogram4/ideogram4_denoise.py@@ -210,13 +210,16 @@ class Ideogram4DenoiseInvocation(BaseInvocation):Deliberately not clamped, and the consequence is worth stating. Ideogram 4 is the onlyarchitecture here that keeps *two* transformers resident, so on a 24 GB card with the fp8- pair (~17.5 GB) the headroom runs out somewhere above 1300px: past that the cache cannot+ pair (~17.4 GiB) the headroom runs out somewhere above 1300px: past that the cache cannotsatisfy the reservation, the second branch loses residency and streams. That is not theestimate being wrong -- the memory genuinely is not there -- and reserving less would onlyexchange a slow generation for an out-of-memory error, and the remedy is fewer resident- bytes rather than a smaller number here. The int8 build does not supply them: it is the same- ~8.9 GiB per branch as fp8 with `fp8_compute`. What it buys is that this holds on *every*- device, where the fp8 pair doubles to ~35 GiB without the fp8 matmul.+ bytes rather than a smaller number here. The int8 build does not supply them: 8.9 GiB per+ branch against fp8's 8.7, and fp8 reaches that with `fp8_compute` *or* with FP8 Storage,+ which installation switches on for such a file and which keeps the same weights without the+ matmul. What int8 buys is that this holds on *every* device: with neither of those two the+ fp8 pair expands to 17.3 GiB per branch, and a 24 GB card then runs out of memory during the+ first step."""image_tokens = (self.height // PIXELS_PER_IMAGE_TOKEN) * (self.width // PIXELS_PER_IMAGE_TOKEN)per_token_bytes = 3 * 1024**2 // 4 # 0.75 MiBdiff --git a/invokeai/backend/model_manager/load/model_loaders/ideogram4.py b/invokeai/backend/model_manager/load/model_loaders/ideogram4.pyindex 0011fa5d53..6dbe4dc2b3 100644--- a/invokeai/backend/model_manager/load/model_loaders/ideogram4.py+++ b/invokeai/backend/model_manager/load/model_loaders/ideogram4.py@@ -273,9 +273,10 @@ class Ideogram4CheckpointModel(ModelLoader):- plain bf16/fp16 -- loaded verbatim;- ComfyUI "scaled fp8" (fp8 weight + per-tensor ``.weight_scale``, plus ``.comfy_quant``- markers), kept quantized when the device can run the fp8 matmul and folded into the compute- dtype otherwise -- the same trade every other single-file loader here makes, and the reason an- 8.6 GiB file needs ~17 GiB resident without ``fp8_compute``;+ markers), kept quantized when either consumer wants it -- the fp8 matmul, or FP8 Storage asked+ of this model, which identification switches on for such a file by itself -- and folded into+ the compute dtype only when neither does. Kept, the 8.6 GiB file is 8.7 GiB resident; folded,+ it is 17.3 GiB. The same trade every other single-file loader here makes;- ComfyUI ``int8_tensorwise`` + ``convrot`` (int8 weight + per-output-channel ``.weight_scale``),kept in ``Int8ConvrotLinear`` and dequantized per forward, so the file's size is the residentsize with no setting to enable and no dependence on the device.@@ -328,10 +329,17 @@ class Ideogram4CheckpointModel(ModelLoader):}fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)- keep_fp8 = should_keep_fp8_weights(target_device)+ # Two consumers want these packed and either is enough: the fp8 matmul, which runs on+ # them directly, and FP8 Storage asked of this model. Asking only the matmul -- which is+ # what this did -- makes the storage path *lossy* on a scaled checkpoint: the fold below+ # widens the weights to the compute dtype and drops their scales, and the layerwise cast+ # at the end of this method then re-encodes that result as *unscaled* fp8, for the byte+ # 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:- # Fold the scales in. Staying quantized without the fp8 matmul would halve VRAM but- # dequantize on every forward, so both are tied to the same setting.+ # 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 = {}@@ -403,18 +411,21 @@ class Ideogram4CheckpointModel(ModelLoader):if kept and not fp8_layers:self._logger.info(- f"Ideogram 4: kept {kept} raw fp8 weight(s) quantized (no weight_scale in the checkpoint); "- "they will run on the fp8 tensor cores with unit scaling."+ f"Ideogram 4: kept {kept} raw fp8 weight(s) quantized (no weight_scale in the checkpoint), "+ f"kept for {self._fp8_kept_reason()}")if fp8_layers:attached = attach_fp8_scales(model, fp8_layers)self._logger.info(- f"Ideogram 4: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, fp8_compute enabled)"+ f"Ideogram 4: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, kept for {self._fp8_kept_reason()})")warn_on_unattached_scales(self._logger, "Ideogram 4", attached, fp8_layers)marked = sum(1 for layer in fp8_layers.values() if layer.full_precision_matmul)- if marked:+ # Only where the matmul is what runs. Kept for FP8 Storage alone, *every* layer+ # dequantizes per forward, so the hint decides nothing and the advice below would send a+ # user to override the checkpoint producer for a speedup that cannot happen.+ if marked and should_keep_fp8_weights(self._torch_device):if full_precision_hints_respected():self._logger.info(f"Ideogram 4: {marked} of {len(fp8_layers)} layer(s) are marked "diff --git a/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.py b/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.pyindex 6da6d051a8..8fee3b3677 100644--- a/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.py+++ b/tests/backend/model_manager/load/test_ideogram4_checkpoint_loader.py@@ -18,7 +18,9 @@ import pytestimport torchfrom invokeai.backend.ideogram4.modeling_ideogram4 import Ideogram4Config, Ideogram4Transformer+from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettingsfrom invokeai.backend.model_manager.configs.main import Main_Checkpoint_Ideogram4_Config+from invokeai.backend.model_manager.load import load_defaultfrom invokeai.backend.model_manager.load.model_loaders.ideogram4 import Ideogram4CheckpointModelfrom invokeai.backend.model_manager.taxonomy import SubModelTypefrom invokeai.backend.quantization.int8_convrot import (@@ -89,6 +91,7 @@ def _driver(state_dict: dict,*,keep_fp8: bool,+ fp8_storage: bool = False,trace: dict | None = None,geometry: Ideogram4Config = TINY_CONFIG,):@@ -109,7 +112,10 @@ def _driver(checkpoint = tmp_path / "ideogram4_fp8_scaled.safetensors"checkpoint.touch()config = Main_Checkpoint_Ideogram4_Config.model_construct(- path=str(checkpoint), name="ideogram4", branch="conditional"+ path=str(checkpoint),+ name="ideogram4",+ branch="conditional",+ default_settings=MainModelDefaultSettings(fp8_storage=fp8_storage),)def make_room(reserved: int) -> None:@@ -128,7 +134,11 @@ def _driver(loader._apply_fp8_layerwise_casting = apply_castingmonkeypatch.setattr(module, "load_file", lambda _path: state_dict)- monkeypatch.setattr(module, "should_keep_fp8_weights", lambda _device: keep_fp8)+ # The two inputs of the loader's decision, not the decision itself: `_keep_fp8_weights` asks the+ # fp8 matmul and this model's FP8 Storage setting, and either alone is enough. Stubbing the+ # answer would let a loader that consults only one of them stay green.+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _device: keep_fp8)+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda _device, _logger=None: True)monkeypatch.setattr(module, "read_safetensors_metadata", lambda _path, _logger: None)monkeypatch.setattr(module.TorchDevice, "choose_torch_device", staticmethod(lambda: torch.device("cpu")))monkeypatch.setattr(module.TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _device: torch.float32))@@ -142,14 +152,25 @@ def _load(state_dict,*,keep_fp8: bool,+ fp8_storage: bool = False,trace: dict | None = None,geometry: Ideogram4Config = TINY_CONFIG,) -> torch.nn.Module:- loader, model_config = _driver(monkeypatch, tmp_path, state_dict, keep_fp8=keep_fp8, trace=trace, geometry=geometry)+ loader, model_config = _driver(+ monkeypatch,+ tmp_path,+ state_dict,+ keep_fp8=keep_fp8,+ fp8_storage=fp8_storage,+ trace=trace,+ geometry=geometry,+ )return loader._load_model(model_config, SubModelType.Transformer)-def test_without_the_fp8_matmul_the_scales_are_folded_into_full_precision_weights(monkeypatch, tmp_path) -> None:+def test_with_neither_consumer_the_scales_are_folded_into_full_precision_weights(monkeypatch, tmp_path) -> None:+ """Neither the fp8 matmul nor FP8 Storage wants these packed, so folding is right: keeping them+ would dequantize on every forward to save memory nobody asked to save."""state_dict, originals = _checkpoint((KEPT, *SKIPPED))model = _load(monkeypatch, tmp_path, state_dict, keep_fp8=False)@@ -163,6 +184,44 @@ def test_without_the_fp8_matmul_the_scales_are_folded_into_full_precision_weightassert not any(hasattr(module, "weight_scale") for module in model.modules())+def test_fp8_storage_alone_keeps_the_checkpoint_in_its_own_scaled_form(monkeypatch, tmp_path) -> None:+ """FP8 Storage is the second consumer, and asking only the matmul made this path *lossy*.++ Folded, the weights reach the layerwise cast as full precision and it re-encodes them as+ *unscaled* fp8 -- for the byte count the file already had, and losing the layers whose scale was+ what kept them representable (~3% flushed to zero, measured on FLUX.2 Klein 4B). Kept, the+ checkpoint's own per-tensor scale stays exact and the cast is skipped as having nothing to do.+ """+ state_dict, _ = _checkpoint((KEPT,))+ before = {key: value.clone() for key, value in state_dict.items()}+ trace: dict = {}++ model = _load(monkeypatch, tmp_path, state_dict, keep_fp8=False, fp8_storage=True, trace=trace)++ kept = model.get_submodule(KEPT)+ assert kept.weight.dtype is FP8+ assert kept.weight_scale.shape == ()+ assert trace["casting_calls"] == 0+ # Byte for byte what the file holds -- that is the whole argument for keeping them. A fold+ # followed by the storage cast re-encodes without the scale, which on a checkpoint whose scales+ # are not powers of two silently flushes the smallest weights to zero.+ assert torch.equal(kept.weight.view(torch.uint8), before[f"{KEPT}.weight"].view(torch.uint8))+ assert kept.weight_scale == before[f"{KEPT}.weight_scale"]++ # And the reservation is sized for what is actually held. This is the number the fix moves --+ # measured on the released checkpoint, 17.28 GiB down to 8.68 -- and it is what a loader that+ # decided the prediction's flag separately from the fold's would get wrong while every+ # end-state assertion above still passed. The scale is popped out of the dict before this+ # point, so only the codes and the dense remainder are charged.+ kept_codes = before[f"{KEPT}.weight"].numel()+ dense = sum(+ tensor.numel() * torch.float32.itemsize+ for key, tensor in before.items()+ if key != f"{KEPT}.weight" and not key.endswith(".weight_scale")+ )+ assert trace["reserved"] == kept_codes + dense++def test_with_the_fp8_matmul_the_codes_stay_and_the_scales_are_attached(monkeypatch, tmp_path) -> None:state_dict, _ = _checkpoint((KEPT,))trace: dict = {}@@ -192,14 +251,19 @@ def test_room_is_reserved_before_the_scales_are_folded(monkeypatch, tmp_path) ->@pytest.mark.parametrize("path", SKIPPED)-def test_the_two_dtype_deriving_layers_never_stay_quantized(monkeypatch, tmp_path, path: str) -> None:+ ("keep_fp8", "fp8_storage"), [(True, False), (False, True)], ids=["fp8_compute", "fp8_storage"]+)+def test_the_two_dtype_deriving_layers_never_stay_quantized(+ monkeypatch, tmp_path, path: str, keep_fp8: bool, fp8_storage: bool+) -> None:# The regression this guards: both forwards read `<layer>.weight.dtype` (or its `compute_dtype`)# and cast x, t and the conditioning to it. With an fp8 weight there, the first matmul dies with# "addmm_cpu" not implemented for 'Float8_e4m3fn' -- and on a device where it does not die, it# computes in a dtype the model never intended.state_dict, originals = _checkpoint((KEPT, path))- model = _load(monkeypatch, tmp_path, state_dict, keep_fp8=True)+ model = _load(monkeypatch, tmp_path, state_dict, keep_fp8=keep_fp8, fp8_storage=fp8_storage)skipped = model.get_submodule(path)assert skipped.weight.dtype is torch.float32@@ -214,12 +278,14 @@ def test_a_plain_checkpoint_loads_verbatim_and_is_offered_to_the_storage_pass(moexpected = {key: value.clone() for key, value in state_dict.items()}trace: dict = {}- model = _load(monkeypatch, tmp_path, state_dict, keep_fp8=False, trace=trace)+ model = _load(monkeypatch, tmp_path, state_dict, keep_fp8=False, fp8_storage=True, trace=trace)for key, value in expected.items():assert torch.equal(model.get_parameter(key), value), key# Nothing here is fp8, so the model's own FP8 Storage setting is the only thing that could make- # it so -- this is the one path that must reach `_apply_fp8_layerwise_casting`.+ # it so -- this is the one path that must reach `_apply_fp8_layerwise_casting`. The setting is on+ # for realism rather than because the assertion needs it: the casting pass is stubbed out by a+ # counter here, so what is pinned is that the loader offers the model to it at all.assert trace["casting_calls"] == 1