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
feat(fp8): run raw fp8 checkpoints on the tensor cores
Alexander Eichhorne93854e6ae4e
diff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.pyindex e84a084a3a..0facefb1c7 100644--- a/invokeai/backend/model_manager/load/load_default.py+++ b/invokeai/backend/model_manager/load/load_default.py@@ -27,6 +27,7 @@ from invokeai.backend.model_manager.taxonomy import (AnyModel,SubModelType,)+from invokeai.backend.quantization.fp8_scaled import count_fp8_weights, should_keep_fp8_weightsfrom invokeai.backend.util.devices import TorchDevice# Layer classes that benefit from FP8 storage. Mirrors diffusers'@@ -288,6 +289,22 @@ class ModelLoader(ModelLoaderBase):if not self._should_use_fp8(config, submodel_type):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):+ 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."+ )+ return model+storage_dtype = torch.float8_e4m3fncompute_dtype = self._torch_dtypediff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.pyindex bea68c56fd..16aeaa6379 100644--- a/invokeai/backend/model_manager/load/model_loaders/flux.py+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py@@ -74,6 +74,7 @@ from invokeai.backend.model_manager.taxonomy import (from invokeai.backend.model_manager.util.model_util import (convert_bundle_to_flux_transformer_checkpoint,)+from invokeai.backend.quantization.fp8_scaled import FP8_DTYPE, cast_state_dict, should_keep_fp8_weightsfrom invokeai.backend.quantization.gguf.loaders import gguf_sd_loaderfrom invokeai.backend.quantization.gguf.utils import TORCH_COMPATIBLE_QTYPESfrom invokeai.backend.util.silence_warnings import SilenceWarnings@@ -650,11 +651,19 @@ class FluxCheckpointModel(ModelLoader):sd = load_file(model_path)if "model.diffusion_model.double_blocks.0.img_attn.norm.key_norm.scale" in sd:sd = convert_bundle_to_flux_transformer_checkpoint(sd)- new_sd_size = sum([ten.nelement() * torch.bfloat16.itemsize for ten in sd.values()])+ # A checkpoint that ships raw fp8 weights (fp8 tensors, no weight_scale) keeps them when the+ # fp8 matmul is available; casting them to bf16 here would throw away both the VRAM saving+ # and the tensor cores before the model is ever built.+ keep_fp8 = should_keep_fp8_weights(self._torch_device)+ new_sd_size = sum(+ ten.nelement() * (ten.element_size() if keep_fp8 and ten.dtype is FP8_DTYPE else torch.bfloat16.itemsize)+ for ten in sd.values()+ )self._ram_cache.make_room(new_sd_size)- for k in sd.keys():- # We need to cast to bfloat16 due to it being the only currently supported dtype for inference- sd[k] = sd[k].to(torch.bfloat16)+ # 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)+ if kept:+ self._logger.info(f"FLUX: kept {kept} raw fp8 weight(s) quantized for the fp8 tensor cores.")model.load_state_dict(sd, assign=True)return model@@ -998,9 +1007,19 @@ class Flux2CheckpointModel(ModelLoader):out_features2, in_features2, dtype=torch.bfloat16)- # Convert to bfloat16 and load- for k in converted_sd.keys():- converted_sd[k] = converted_sd[k].to(torch.bfloat16)+ # Convert to bfloat16 and load, leaving raw fp8 weights quantized when the tensor cores can+ # take them (the scaled-fp8 path above has already folded any weight_scale it found). The+ # model's own precision-sensitive list is honored — see the Z-Image loader for why that is+ # a correctness requirement and not just a quality nicety.+ kept = cast_state_dict(+ converted_sd,+ torch.bfloat16,+ keep_fp8=should_keep_fp8_weights(self._torch_device),+ model=model,+ skip_patterns=getattr(model, "_skip_layerwise_casting_patterns", None) or (),+ )+ if kept:+ self._logger.info(f"FLUX.2: kept {kept} raw fp8 weight(s) quantized for the fp8 tensor cores.")# Load the state dict - guidance weights were already initialized above if missingmodel.load_state_dict(converted_sd, assign=True)diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.pyindex 082e918a0c..22a3b5cf6c 100644--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py@@ -27,6 +27,7 @@ from invokeai.backend.model_manager.taxonomy import (from invokeai.backend.quantization.fp8_scaled import (FP8_DTYPE,attach_fp8_scales,+ cast_state_dict,dequantize_fp8_scaled,device_supports_fp8_matmul,extract_comfy_quant_hints,@@ -34,6 +35,7 @@ from invokeai.backend.quantization.fp8_scaled import (full_precision_hints_respected,is_fp8_matmul_enabled,parse_quantization_metadata,+ should_keep_fp8_weights,)from invokeai.backend.quantization.gguf.loaders import gguf_sd_loaderfrom invokeai.backend.util.devices import TorchDevice@@ -425,13 +427,28 @@ class Krea2CheckpointModel(ModelLoader):for ten in sd.values())self._ram_cache.make_room(new_sd_size)- for k in sd.keys():- if sd[k].dtype is not FP8_DTYPE:- sd[k] = sd[k].to(model_dtype)+ # `keep_fp8` covers the scaled path decided above; 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 they are kept whenever the matmul is available.+ kept = cast_state_dict(+ sd,+ model_dtype,+ keep_fp8=bool(fp8_layers) or should_keep_fp8_weights(target_device),+ model=model,+ skip_patterns=getattr(model, "_skip_layerwise_casting_patterns", None) or (),+ )model.load_state_dict(sd, assign=True, strict=False)_reject_incomplete_load(model, what="Krea-2 single-file checkpoint")+ if kept and not fp8_layers:+ # Raw fp8: no scales to attach, but say so — otherwise the tensor-core path is invisible,+ # and the only other fp8 log line (the scaled one below) never fires for this checkpoint.+ self._logger.info(+ f"Krea-2: kept {kept} raw fp8 weight(s) quantized (no weight_scale in the checkpoint); "+ "they will run on the fp8 tensor cores with unit scaling."+ )+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)")diff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.pyindex 406d243c37..aec0373c59 100644--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py@@ -27,6 +27,7 @@ from invokeai.backend.model_manager.taxonomy import (ModelType,SubModelType,)+from invokeai.backend.quantization.fp8_scaled import FP8_DTYPE, cast_state_dict, should_keep_fp8_weightsfrom invokeai.backend.quantization.gguf.loaders import gguf_sd_loaderfrom invokeai.backend.qwen3.qwen3_tokenizer import load_bundled_qwen3_tokenizerfrom invokeai.backend.util.devices import TorchDevice@@ -280,13 +281,29 @@ class ZImageCheckpointModel(ModelLoader):for k in keys_to_remove:del sd[k]- # Handle memory management and dtype conversion- new_sd_size = sum([ten.nelement() * model_dtype.itemsize for ten in sd.values()])+ # Handle memory management and dtype conversion. A checkpoint that ships raw fp8 weights+ # (fp8 tensors, no weight_scale) keeps them when the fp8 matmul is available — casting them+ # here would discard both the VRAM saving and the tensor cores before the model is built.+ keep_fp8 = should_keep_fp8_weights(self._torch_device)+ new_sd_size = sum(+ ten.nelement() * (ten.element_size() if keep_fp8 and ten.dtype is FP8_DTYPE else model_dtype.itemsize)+ for ten in sd.values()+ )self._ram_cache.make_room(new_sd_size)- # Convert to target dtype- for k in sd.keys():- sd[k] = sd[k].to(model_dtype)+ # Honor the model's own precision-sensitive list. Z-Image declares+ # ["t_embedder", "cap_embedder"], and `TimestepEmbedder.forward` casts its activations to+ # `self.mlp[0].weight.dtype` — an fp8 weight there turns the activations fp8 and the forward+ # dies in `x.abs()`. Those layers must be dequantized even though the rest stays quantized.+ kept = cast_state_dict(+ sd,+ model_dtype,+ keep_fp8=keep_fp8,+ model=model,+ skip_patterns=getattr(model, "_skip_layerwise_casting_patterns", None) or (),+ )+ if kept:+ self._logger.info(f"Z-Image: kept {kept} raw fp8 weight(s) quantized for the fp8 tensor cores.")model.load_state_dict(sd, assign=True)return modeldiff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.pyindex 3c8a823f28..36ae6f7f6f 100644--- a/invokeai/backend/quantization/fp8_scaled.py+++ b/invokeai/backend/quantization/fp8_scaled.py@@ -345,6 +345,91 @@ def device_supports_fp8_matmul(device: torch.device) -> bool:return cached+def should_keep_fp8_weights(device: torch.device) -> bool:+ """Whether fp8 weights in a checkpoint should survive the load instead of being dequantized.++ Only true when the fp8 matmul is both enabled and usable, because keeping weights quantized+ without it is the worst of both worlds: the same VRAM as fp8 but a dequantize round trip on+ every forward (measured slower than plain bf16).+ """+ return is_fp8_matmul_enabled() and device_supports_fp8_matmul(device)+++def _is_fp8_matmul_weight(key: str, tensor: Any, model: torch.nn.Module | None) -> bool:+ """Whether this state-dict entry is a weight `scaled_mm_linear` can actually consume.++ Only the ``.weight`` of an ``nn.Linear`` qualifies. This matters because checkpoints exist that+ quantize *everything* — biases, norm weights, even learned pad tokens. Keeping those in fp8 does+ not save anything worth having and actively breaks inference: an fp8 norm or pad token flows+ into the activations, and the next Linear then receives an fp8 *input*, which dies in+ ``x.abs()`` with ``"abs_cuda" not implemented for 'Float8_e4m3fn'``. Observed on a Z-Image+ checkpoint where 243 of 453 fp8 tensors were 1-D.+ """+ if not key.endswith(".weight") or getattr(tensor, "dim", None) is None or tensor.dim() < 2:+ return False+ if model is None:+ # No model to resolve against: the 2-D + `.weight` shape test above is the safe subset.+ return True+ try:+ module = model.get_submodule(key[: -len(".weight")])+ except AttributeError:+ return False+ return isinstance(module, torch.nn.Linear)+++def cast_state_dict(+ sd: dict[str, Any],+ dtype: torch.dtype,+ *,+ keep_fp8: bool,+ model: torch.nn.Module | None = None,+ skip_patterns: Iterable[str] = (),+) -> int:+ """Cast every tensor in ``sd`` to ``dtype`` in place, optionally leaving fp8 weights quantized.++ Loaders historically cast the whole state dict unconditionally, which silently dequantizes a+ checkpoint that ships raw fp8 weights (fp8 tensors with no ``weight_scale`` alongside them) —+ the VRAM saving and the tensor cores are both thrown away before the model is ever built.++ Only ``float8_e4m3fn`` is preserved. ``float8_e5m2`` is left to be cast because+ :func:`scaled_mm_linear` cannot use it as the weight operand on Ada, so keeping it quantized+ would buy VRAM at the cost of a per-forward dequantize.++ ``skip_patterns`` are substrings of the state-dict key whose weights must be dequantized even+ when the rest stays fp8. Pass the model's ``_skip_layerwise_casting_patterns``: diffusers uses+ it to mark precision-sensitive modules, and some of them *read their own weight's dtype and cast+ their activations to it*. Z-Image's ``TimestepEmbedder.forward`` does exactly that+ (``t_freq.to(self.mlp[0].weight.dtype)``), so leaving its weight in fp8 hands the next Linear an+ fp8 activation and the forward dies in ``x.abs()`` with+ ``"abs_cuda" not implemented for 'Float8_e4m3fn'``.++ Returns the number of tensors left in fp8.+ """+ patterns = tuple(skip_patterns)+ kept = 0+ for key in sd:+ tensor = sd[key]+ if (+ keep_fp8+ and getattr(tensor, "dtype", None) is FP8_DTYPE+ and _is_fp8_matmul_weight(key, tensor, model)+ and not any(pattern in key for pattern in patterns)+ ):+ kept += 1+ continue+ sd[key] = tensor.to(dtype)+ return kept+++def count_fp8_weights(model: torch.nn.Module) -> int:+ """Number of parameters already stored as ``float8_e4m3fn``.++ Used to tell a checkpoint that arrived quantized apart from one this loader is about to+ quantize itself — the two must not both happen (see `ModelLoader._apply_fp8_layerwise_casting`).+ """+ return sum(1 for p in model.parameters() if p.dtype is FP8_DTYPE)++def dequantize_weight(weight: torch.Tensor, weight_scale: torch.Tensor | None, dtype: torch.dtype) -> torch.Tensor:"""Cast an fp8 weight up to ``dtype``, applying its scale if it has one.diff --git a/tests/backend/quantization/test_fp8_scaled.py b/tests/backend/quantization/test_fp8_scaled.pyindex 4e8028c6bb..e10e71e92f 100644--- a/tests/backend/quantization/test_fp8_scaled.py+++ b/tests/backend/quantization/test_fp8_scaled.py@@ -5,6 +5,8 @@ from invokeai.backend.quantization.fp8_scaled import (FP8_DTYPE,Fp8ScaledLayer,attach_fp8_scales,+ cast_state_dict,+ count_fp8_weights,dequantize_fp8_scaled,dequantize_weight,device_supports_fp8_matmul,@@ -102,6 +104,106 @@ def _comfy_quant_blob(full_precision: bool):return torch.tensor(list(payload.encode("utf-8")), dtype=torch.uint8)+class TestRawFp8:+ """Checkpoints that ship fp8 weights with no weight_scale at all."""++ def test_cast_state_dict_preserves_fp8_when_asked(self):+ q, _ = _fp8_weight(32, 16)+ sd = {"lin.weight": q, "lin.bias": torch.zeros(32), "norm.weight": torch.ones(16)}+ kept = cast_state_dict(sd, torch.bfloat16, keep_fp8=True)+ assert kept == 1+ assert sd["lin.weight"].dtype is FP8_DTYPE, "raw fp8 must survive the load"+ assert sd["lin.bias"].dtype is torch.bfloat16+ assert sd["norm.weight"].dtype is torch.bfloat16++ def test_cast_state_dict_dequantizes_when_matmul_unavailable(self):+ """Without the matmul, staying quantized costs a dequantize per forward for no gain."""+ q, _ = _fp8_weight(32, 16)+ sd = {"lin.weight": q}+ assert cast_state_dict(sd, torch.bfloat16, keep_fp8=False) == 0+ assert sd["lin.weight"].dtype is torch.bfloat16++ def test_e5m2_is_never_preserved(self):+ """scaled_mm cannot take e5m2 as the weight operand on Ada, so keeping it buys nothing."""+ sd = {"lin.weight": torch.zeros(32, 16).to(torch.float8_e5m2)}+ assert cast_state_dict(sd, torch.bfloat16, keep_fp8=True) == 0+ assert sd["lin.weight"].dtype is torch.bfloat16++ def test_only_linear_weights_stay_quantized(self):+ """The regression an end-to-end run caught: checkpoints exist that quantize *everything*.++ A Z-Image checkpoint had 243 of its 453 fp8 tensors 1-D — biases, norm weights, a learned+ pad token. Keeping those quantized saves nothing usable and breaks inference: the fp8 value+ flows into the activations and the next Linear receives an fp8 *input*, which dies in+ `x.abs()` with `"abs_cuda" not implemented for 'Float8_e4m3fn'`.+ """+ model = torch.nn.Sequential()+ model.add_module("lin", torch.nn.Linear(16, 32))+ model.add_module("norm", torch.nn.LayerNorm(32))+ q, _ = _fp8_weight(32, 16)+ sd = {+ "lin.weight": q, # keep: a Linear weight the matmul can use+ "lin.bias": torch.zeros(32).to(FP8_DTYPE), # dequantize: bias+ "norm.weight": torch.ones(32).to(FP8_DTYPE), # dequantize: 1-D norm+ "pad_token": torch.zeros(1, 32).to(FP8_DTYPE), # dequantize: not a module weight+ }+ assert cast_state_dict(sd, torch.bfloat16, keep_fp8=True, model=model) == 1+ assert sd["lin.weight"].dtype is FP8_DTYPE+ for key in ("lin.bias", "norm.weight", "pad_token"):+ assert sd[key].dtype is torch.bfloat16, f"{key} must not stay fp8"++ def test_skip_patterns_dequantize_named_modules(self):+ """Modules a model marks precision-sensitive must be dequantized even if they are Linears.++ Z-Image declares `_skip_layerwise_casting_patterns = ["t_embedder", "cap_embedder"]`, and+ `TimestepEmbedder.forward` casts its activations to `self.mlp[0].weight.dtype` — an fp8+ weight there makes the activations fp8.+ """+ model = torch.nn.Sequential()+ model.add_module("t_embedder", torch.nn.Linear(16, 32))+ model.add_module("blocks", torch.nn.Linear(16, 32))+ q, _ = _fp8_weight(32, 16)+ sd = {"t_embedder.weight": q, "blocks.weight": q.clone()}+ assert cast_state_dict(sd, torch.bfloat16, keep_fp8=True, model=model, skip_patterns=["t_embedder"]) == 1+ assert sd["t_embedder.weight"].dtype is torch.bfloat16+ assert sd["blocks.weight"].dtype is FP8_DTYPE++ def test_count_fp8_weights(self):+ model = torch.nn.Sequential(torch.nn.Linear(16, 32, bias=False), torch.nn.Linear(32, 16, bias=False))+ assert count_fp8_weights(model) == 0+ model[0].weight = torch.nn.Parameter(_fp8_weight(32, 16)[0], requires_grad=False)+ assert count_fp8_weights(model) == 1++ @cuda_fp8+ def test_fp8_weight_without_scale_uses_the_tensor_cores(self):+ """The runtime already supports scale-less fp8 — `weight_scale` is optional in+ `scaled_mm_linear`, and `_can_use_fp8_matmul` only requires the fp8 dtype. This pins that+ down so a future change cannot quietly make a scale mandatory."""+ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (+ apply_custom_layers_to_model,+ )++ torch.manual_seed(0)+ net = torch.nn.Sequential(torch.nn.Linear(64, 64, bias=False)).cuda()+ net[0].weight.data = (net[0].weight.data * 0.02).to(FP8_DTYPE)+ apply_custom_layers_to_model(net)+ lin = net[0]+ x = torch.randn(1, 32, 64, device="cuda", dtype=torch.bfloat16)++ set_fp8_matmul_enabled(True)+ try:+ assert getattr(lin, "weight_scale", None) is None+ assert lin._can_use_fp8_matmul(x) is True+ out = net(x)+ finally:+ set_fp8_matmul_enabled(None)++ reference = torch.nn.functional.linear(x, dequantize_weight(lin.weight, None, x.dtype))+ rel = ((out.float() - reference.float()).norm() / reference.float().norm()).item()+ assert torch.isfinite(out).all()+ assert rel < 0.1, f"unit-scaled fp8 matmul drifted too far from bf16: {rel:.4f}"++class TestInputScale:def test_calibrated_scale_is_kept(self):q, scale = _fp8_weight(32, 16)