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.

feat(fp8): run scaled fp8 Anima checkpoints on the tensor cores

Alexander Eichhorn9f25f1e94b8d
diff --git a/invokeai/backend/model_manager/load/model_loaders/anima.py b/invokeai/backend/model_manager/load/model_loaders/anima.py
index a2c334ee6d..b2dd04a035 100644
--- a/invokeai/backend/model_manager/load/model_loaders/anima.py
+++ b/invokeai/backend/model_manager/load/model_loaders/anima.py
@@ -2,7 +2,7 @@
"""Class for Anima model loading in InvokeAI."""
from pathlib import Path
-from typing import Optional
+from typing import Any, Optional
import accelerate
@@ -19,6 +19,20 @@ from invokeai.backend.model_manager.taxonomy import (
ModelType,
SubModelType,
)
+from invokeai.backend.quantization.fp8_scaled import (
+ attach_fp8_scales,
+ cast_state_dict,
+ dequantize_fp8_scaled,
+ extract_comfy_quant_hints,
+ extract_fp8_scaled_layers,
+ full_precision_hints_respected,
+ parse_quantization_metadata,
+ predict_cast_state_dict_size,
+ read_safetensors_metadata,
+ should_keep_fp8_weights,
+ split_fp8_scaled_layers,
+ warn_on_unattached_scales,
+)
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.logging import InvokeAILogger
@@ -67,6 +81,19 @@ _NON_MODEL_KEY_SUFFIXES = (
_NON_MODEL_KEY_PREFIXES = ("model_sampling.",)
+def _strip_anima_prefix_from_layer_paths(layer_names: Any) -> dict[str, str]:
+ """Map checkpoint-scheme layer names to the paths the module tree actually uses.
+
+ `_quantization_metadata` names its layers in the checkpoint's own scheme -- `net.`-prefixed on
+ every Anima redistribution measured -- while the scales are read after `_strip_anima_bundle_prefix`
+ has run. Without this the per-layer flags, `full_precision_matrix_mult` above all, match nothing
+ and are silently ignored. Rather than restating the prefix list, the names are pushed through
+ the real strip function and read back.
+ """
+ stripped = _strip_anima_bundle_prefix({f"{name}.weight": None for name in layer_names})
+ return {name: key[: -len(".weight")] for name, key in zip(layer_names, stripped.keys(), strict=True)}
+
+
def _filter_non_model_keys(sd: dict) -> dict:
"""Drop checkpoint keys that don't belong to the transformer module's state dict."""
return {
@@ -125,6 +152,30 @@ class AnimaCheckpointModel(ModelLoader):
# Drop runtime-derived buffers and exporter metadata that aren't model weights.
sd = _filter_non_model_keys(sd)
+ target_device = TorchDevice.choose_torch_device()
+ model_dtype = TorchDevice.choose_anima_inference_dtype(target_device)
+
+ # ComfyUI 'scaled fp8': an fp8 weight plus a `weight_scale`. `_filter_non_model_keys` above
+ # keeps those keys, and `load_state_dict` below rejects the checkpoint outright over them --
+ # 500 unexpected keys on a plain scaled export, 749 on one that also ships `comfy_quant`
+ # markers. Such a checkpoint therefore does not load at all today.
+ #
+ # Anima keeps `q_proj`/`k_proj`/`v_proj` separate and the only key rewrite is a prefix strip,
+ # so a sibling scale travels with its weight and nothing has to be split.
+ keep_fp8 = should_keep_fp8_weights(target_device)
+ header_hints = parse_quantization_metadata(read_safetensors_metadata(model_path, logger))
+ path_map = _strip_anima_prefix_from_layer_paths(list(header_hints))
+ layer_hints = {
+ **extract_comfy_quant_hints(sd),
+ **{path_map.get(name, name): hints for name, hints in header_hints.items()},
+ }
+ 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.
+ 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(
@@ -156,18 +207,15 @@ class AnimaCheckpointModel(ModelLoader):
image_model="anima",
)
- # Determine safe dtype
- target_device = TorchDevice.choose_torch_device()
- model_dtype = TorchDevice.choose_anima_inference_dtype(target_device)
+ skip_patterns = tuple(getattr(model, "_skip_layerwise_casting_patterns", None) or ())
+ # 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.
+ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)
- # Handle memory management
- new_sd_size = sum(ten.nelement() * model_dtype.itemsize for ten in sd.values())
- self._ram_cache.make_room(new_sd_size)
-
- # Convert to target dtype (skip non-float tensors like embedding indices)
- for k in sd.keys():
- if sd[k].is_floating_point():
- sd[k] = sd[k].to(model_dtype)
+ self._ram_cache.make_room(
+ predict_cast_state_dict_size(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)
+ )
+ kept = cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)
load_result = model.load_state_dict(sd, assign=True, strict=False)
if load_result.unexpected_keys:
@@ -186,6 +234,19 @@ class AnimaCheckpointModel(ModelLoader):
# 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`.
+ 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)")
+ 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():
+ logger.info(
+ f"Anima: {marked} of {len(fp8_layers)} layer(s) are marked full_precision_matrix_mult "
+ "and will dequantize per forward."
+ )
+ elif kept:
+ logger.info(f"Anima: kept {kept} raw fp8 weight(s) quantized for the fp8 tensor cores.")
+
model = self._apply_fp8_layerwise_casting(model, config, SubModelType.Transformer)
return model
diff --git a/tests/backend/model_manager/load/state_dicts/anima_transformer_scaled_fp8_keys.py b/tests/backend/model_manager/load/state_dicts/anima_transformer_scaled_fp8_keys.py
new file mode 100644
index 0000000000..115e8287b0
--- /dev/null
+++ b/tests/backend/model_manager/load/state_dicts/anima_transformer_scaled_fp8_keys.py
@@ -0,0 +1,92 @@
+"""Representative key layout of a scaled-fp8 Anima checkpoint.
+
+Captured from `pachiiahri/anima-fp8-comfyui` (`anima-preview_tcfp8_mixed`). It is the only
+checkpoint in this series that ships **both** hint transports at once: a safetensors-header
+`_quantization_metadata` block *and* per-layer `.comfy_quant` marker tensors. It also carries
+exactly one `full_precision_matrix_mult` layer -- every other captured checkpoint marks either
+none or a large fraction, so the single-marked case was previously untested.
+
+The header names its layers `net.`-prefixed, i.e. in the checkpoint's own scheme, while the scales
+are read after `_strip_anima_bundle_prefix` has run. Reading the header without renaming matches
+nothing and drops every flag silently.
+
+Subsetting rule: block 24 (the one carrying the marked layer) plus every non-block key. Values are
+`(shape, dtype)`; `layer_hints` is the header block, subset the same way.
+"""
+
+state_dict_keys: dict[str, tuple[list[int], str]] = {
+ "net.blocks.24.adaln_modulation_cross_attn.1.weight": ([256, 2048], "BF16"),
+ "net.blocks.24.adaln_modulation_cross_attn.2.weight": ([6144, 256], "BF16"),
+ "net.blocks.24.adaln_modulation_mlp.1.weight": ([256, 2048], "BF16"),
+ "net.blocks.24.adaln_modulation_mlp.2.weight": ([6144, 256], "BF16"),
+ "net.blocks.24.adaln_modulation_self_attn.1.weight": ([256, 2048], "BF16"),
+ "net.blocks.24.adaln_modulation_self_attn.2.weight": ([6144, 256], "BF16"),
+ "net.blocks.24.cross_attn.k_norm.weight": ([128], "BF16"),
+ "net.blocks.24.cross_attn.k_proj.comfy_quant": ([64], "U8"),
+ "net.blocks.24.cross_attn.k_proj.input_scale": ([], "F32"),
+ "net.blocks.24.cross_attn.k_proj.weight": ([2048, 1024], "F8_E4M3"),
+ "net.blocks.24.cross_attn.k_proj.weight_scale": ([], "F32"),
+ "net.blocks.24.cross_attn.output_proj.comfy_quant": ([64], "U8"),
+ "net.blocks.24.cross_attn.output_proj.input_scale": ([], "F32"),
+ "net.blocks.24.cross_attn.output_proj.weight": ([2048, 2048], "F8_E4M3"),
+ "net.blocks.24.cross_attn.output_proj.weight_scale": ([], "F32"),
+ "net.blocks.24.cross_attn.q_norm.weight": ([128], "BF16"),
+ "net.blocks.24.cross_attn.q_proj.comfy_quant": ([63], "U8"),
+ "net.blocks.24.cross_attn.q_proj.weight": ([2048, 2048], "F8_E4M3"),
+ "net.blocks.24.cross_attn.q_proj.weight_scale": ([], "F32"),
+ "net.blocks.24.cross_attn.v_proj.comfy_quant": ([64], "U8"),
+ "net.blocks.24.cross_attn.v_proj.input_scale": ([], "F32"),
+ "net.blocks.24.cross_attn.v_proj.weight": ([2048, 1024], "F8_E4M3"),
+ "net.blocks.24.cross_attn.v_proj.weight_scale": ([], "F32"),
+ "net.blocks.24.mlp.layer1.comfy_quant": ([64], "U8"),
+ "net.blocks.24.mlp.layer1.input_scale": ([], "F32"),
+ "net.blocks.24.mlp.layer1.weight": ([8192, 2048], "F8_E4M3"),
+ "net.blocks.24.mlp.layer1.weight_scale": ([], "F32"),
+ "net.blocks.24.mlp.layer2.comfy_quant": ([64], "U8"),
+ "net.blocks.24.mlp.layer2.input_scale": ([], "F32"),
+ "net.blocks.24.mlp.layer2.weight": ([2048, 8192], "F8_E4M3"),
+ "net.blocks.24.mlp.layer2.weight_scale": ([], "F32"),
+ "net.blocks.24.self_attn.k_norm.weight": ([128], "BF16"),
+ "net.blocks.24.self_attn.k_proj.comfy_quant": ([64], "U8"),
+ "net.blocks.24.self_attn.k_proj.input_scale": ([], "F32"),
+ "net.blocks.24.self_attn.k_proj.weight": ([2048, 2048], "F8_E4M3"),
+ "net.blocks.24.self_attn.k_proj.weight_scale": ([], "F32"),
+ "net.blocks.24.self_attn.output_proj.comfy_quant": ([64], "U8"),
+ "net.blocks.24.self_attn.output_proj.input_scale": ([], "F32"),
+ "net.blocks.24.self_attn.output_proj.weight": ([2048, 2048], "F8_E4M3"),
+ "net.blocks.24.self_attn.output_proj.weight_scale": ([], "F32"),
+ "net.blocks.24.self_attn.q_norm.weight": ([128], "BF16"),
+ "net.blocks.24.self_attn.q_proj.comfy_quant": ([64], "U8"),
+ "net.blocks.24.self_attn.q_proj.input_scale": ([], "F32"),
+ "net.blocks.24.self_attn.q_proj.weight": ([2048, 2048], "F8_E4M3"),
+ "net.blocks.24.self_attn.q_proj.weight_scale": ([], "F32"),
+ "net.blocks.24.self_attn.v_proj.comfy_quant": ([64], "U8"),
+ "net.blocks.24.self_attn.v_proj.input_scale": ([], "F32"),
+ "net.blocks.24.self_attn.v_proj.weight": ([2048, 2048], "F8_E4M3"),
+ "net.blocks.24.self_attn.v_proj.weight_scale": ([], "F32"),
+ "net.final_layer.adaln_modulation.1.weight": ([256, 2048], "BF16"),
+ "net.final_layer.adaln_modulation.2.weight": ([4096, 256], "BF16"),
+ "net.final_layer.linear.weight": ([64, 2048], "BF16"),
+ "net.llm_adapter.embed.weight": ([32128, 1024], "BF16"),
+ "net.llm_adapter.norm.weight": ([1024], "BF16"),
+ "net.llm_adapter.out_proj.bias": ([1024], "BF16"),
+ "net.llm_adapter.out_proj.weight": ([1024, 1024], "BF16"),
+ "net.t_embedder.1.linear_1.weight": ([2048, 2048], "BF16"),
+ "net.t_embedder.1.linear_2.weight": ([6144, 2048], "BF16"),
+ "net.t_embedding_norm.weight": ([2048], "BF16"),
+ "net.x_embedder.proj.1.weight": ([2048, 68], "BF16"),
+}
+
+# The `_quantization_metadata` header block, layer names exactly as the producer wrote them.
+layer_hints: dict[str, dict[str, object]] = {
+ "net.blocks.24.cross_attn.k_proj": {"format": "float8_e4m3fn", "full_precision_matrix_mult": False},
+ "net.blocks.24.cross_attn.output_proj": {"format": "float8_e4m3fn", "full_precision_matrix_mult": False},
+ "net.blocks.24.cross_attn.q_proj": {"format": "float8_e4m3fn", "full_precision_matrix_mult": True},
+ "net.blocks.24.cross_attn.v_proj": {"format": "float8_e4m3fn", "full_precision_matrix_mult": False},
+ "net.blocks.24.mlp.layer1": {"format": "float8_e4m3fn", "full_precision_matrix_mult": False},
+ "net.blocks.24.mlp.layer2": {"format": "float8_e4m3fn", "full_precision_matrix_mult": False},
+ "net.blocks.24.self_attn.k_proj": {"format": "float8_e4m3fn", "full_precision_matrix_mult": False},
+ "net.blocks.24.self_attn.output_proj": {"format": "float8_e4m3fn", "full_precision_matrix_mult": False},
+ "net.blocks.24.self_attn.q_proj": {"format": "float8_e4m3fn", "full_precision_matrix_mult": False},
+ "net.blocks.24.self_attn.v_proj": {"format": "float8_e4m3fn", "full_precision_matrix_mult": False},
+}
diff --git a/tests/backend/model_manager/load/test_anima_scaled_fp8_keys.py b/tests/backend/model_manager/load/test_anima_scaled_fp8_keys.py
new file mode 100644
index 0000000000..d15b12fd64
--- /dev/null
+++ b/tests/backend/model_manager/load/test_anima_scaled_fp8_keys.py
@@ -0,0 +1,134 @@
+"""A scaled-fp8 Anima checkpoint must load, and its layer flags must survive the prefix strip.
+
+Two separate failures are covered here. Before scaled-fp8 support reached `AnimaCheckpointModel`,
+`_filter_non_model_keys` let the scale and marker keys through and the loader raised on them --
+500 unexpected keys on a plain scaled export, 749 on one that also ships `comfy_quant` markers, so
+such a checkpoint did not load at all.
+
+The second is quieter: `_quantization_metadata` names its layers `net.`-prefixed, in the
+checkpoint's own scheme, while the scales are read after the prefix has been stripped. Reading the
+header without renaming matches nothing, and every `full_precision_matrix_mult` flag is dropped
+without a word.
+"""
+
+import json
+
+import torch
+
+from invokeai.backend.model_manager.load.model_loaders.anima import (
+ _filter_non_model_keys,
+ _strip_anima_bundle_prefix,
+ _strip_anima_prefix_from_layer_paths,
+)
+from invokeai.backend.quantization.fp8_scaled import (
+ FP8_DTYPE,
+ extract_comfy_quant_hints,
+ extract_fp8_scaled_layers,
+ is_scale_metadata_key,
+)
+from tests.backend.model_manager.load.state_dicts.anima_transformer_scaled_fp8_keys import (
+ layer_hints as header_hints,
+)
+from tests.backend.model_manager.load.state_dicts.anima_transformer_scaled_fp8_keys import (
+ state_dict_keys as anima_keys,
+)
+
+_DTYPES = {"F8_E4M3": FP8_DTYPE, "F32": torch.float32, "BF16": torch.bfloat16, "U8": torch.uint8}
+
+
+def _build_state_dict() -> dict[str, torch.Tensor]:
+ """Rebuild the checkpoint. `comfy_quant` markers are real JSON blobs, not placeholders.
+
+ The marker is the only transport some checkpoints have, so a test that fakes it would not
+ exercise the path that reads it.
+ """
+ sd: dict[str, torch.Tensor] = {}
+ for key, (shape, dtype) in anima_keys.items():
+ torch_dtype = _DTYPES[dtype]
+ if key.endswith(".comfy_quant"):
+ path = key[: -len(".comfy_quant")]
+ blob = header_hints.get(path, {"format": "float8_e4m3fn"})
+ # Real JSON: the producer writes `true`/`false`, and `extract_comfy_quant_hints`
+ # parses the blob. Python's `False` would not parse and the flag would vanish.
+ sd[key] = torch.frombuffer(bytearray(json.dumps(blob).encode()), dtype=torch.uint8).clone()
+ elif torch_dtype is FP8_DTYPE:
+ sd[key] = torch.zeros(shape, dtype=torch.float32).to(FP8_DTYPE)
+ elif key.endswith((".weight_scale", ".input_scale")):
+ # 1.0 is the placeholder `_usable_input_scale` rejects, so it must not be used here.
+ sd[key] = torch.full(shape, 2.5, dtype=torch_dtype)
+ else:
+ sd[key] = torch.zeros(shape, dtype=torch_dtype)
+ return _filter_non_model_keys(_strip_anima_bundle_prefix(sd))
+
+
+def test_nothing_the_loader_would_reject_is_left_behind() -> None:
+ """`load_state_dict` must see only model tensors; the loader raises on anything else."""
+ sd = _build_state_dict()
+ assert [k for k in sd if is_scale_metadata_key(k)], "fixture carries no side-channel keys"
+
+ extract_fp8_scaled_layers(sd)
+
+ assert [k for k in sd if is_scale_metadata_key(k)] == []
+
+
+def test_every_quantized_linear_is_recognized() -> None:
+ sd = _build_state_dict()
+ fp8_weights = {k for k, v in sd.items() if v.dtype is FP8_DTYPE and k.endswith(".weight")}
+ assert fp8_weights
+
+ layers = extract_fp8_scaled_layers(sd, layer_hints=extract_comfy_quant_hints(sd))
+
+ assert {f"{path}.weight" for path in layers} == fp8_weights
+
+
+def test_header_hints_are_renamed_to_the_stripped_paths() -> None:
+ """The header names layers `net.`-prefixed; the scales are keyed on the stripped paths.
+
+ Without the rename the flags match nothing. This is the mistake that already cost a debugging
+ round on Krea-2, where the metadata was read against the wrong naming.
+ """
+ assert all(name.startswith("net.") for name in header_hints), "fixture header is not prefixed"
+
+ mapping = _strip_anima_prefix_from_layer_paths(list(header_hints))
+
+ assert all(not renamed.startswith("net.") for renamed in mapping.values())
+ remapped = {mapping[name]: hints for name, hints in header_hints.items()}
+
+ layers = extract_fp8_scaled_layers(_build_state_dict(), layer_hints=remapped)
+
+ assert layers
+ assert set(remapped) >= set(layers), "a renamed hint no longer lines up with its layer"
+
+
+def test_the_single_full_precision_flag_survives_both_transports() -> None:
+ """Exactly one layer is marked. It must come through whichever transport is read.
+
+ Every other captured checkpoint marks either no layers or a large fraction, so a bug that
+ dropped a lone flag would go unnoticed there.
+ """
+ marked = [name for name, hints in header_hints.items() if hints.get("full_precision_matrix_mult")]
+ assert len(marked) == 1, f"fixture should carry exactly one marked layer, has {len(marked)}"
+
+ mapping = _strip_anima_prefix_from_layer_paths(list(header_hints))
+ for hints in (
+ {mapping[n]: h for n, h in header_hints.items()}, # header transport
+ extract_comfy_quant_hints(_build_state_dict()), # per-layer marker transport
+ ):
+ layers = extract_fp8_scaled_layers(_build_state_dict(), layer_hints=hints)
+ assert sum(1 for layer in layers.values() if layer.full_precision_matmul) == 1
+
+
+def test_only_the_full_precision_layer_lacks_an_input_scale() -> None:
+ """Every quantized Linear ships a calibrated `scale_input` -- except the marked one.
+
+ That is coherent on the producer's side: a layer excluded from the fp8 matmul has no activation
+ scale to calibrate. It also means "all layers have an input scale" is the wrong invariant.
+ """
+ mapping = _strip_anima_prefix_from_layer_paths(list(header_hints))
+ marked = {mapping[n] for n, h in header_hints.items() if h.get("full_precision_matrix_mult")}
+
+ layers = extract_fp8_scaled_layers(_build_state_dict())
+
+ assert layers
+ without = {path for path, layer in layers.items() if layer.input_scale is None}
+ assert without == marked