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 scaled fp8 FLUX.1 checkpoints on the tensor cores
Alexander Eichhornb2854a1373d0
diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.pyindex e3b95de590..727549af1b 100644--- a/invokeai/backend/model_manager/load/model_loaders/flux.py+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py@@ -81,12 +81,21 @@ from invokeai.backend.model_manager.util.model_util import (convert_bundle_to_flux_transformer_checkpoint,)from invokeai.backend.quantization.fp8_scaled import (+ attach_fp8_scales,can_stay_quantized,cast_state_dict,+ dequantize_fp8_scaled,+ extract_comfy_quant_hints,+ extract_fp8_scaled_layers,+ full_precision_hints_respected,is_scale_metadata_key,iter_weight_scale_pairs,+ 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.quantization.gguf.loaders import gguf_sd_loaderfrom invokeai.backend.quantization.gguf.utils import TORCH_COMPATIBLE_QTYPES@@ -723,16 +732,62 @@ 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)++ # ComfyUI 'scaled fp8' (fp8 weight + .weight_scale/.scale_weight, optionally an input+ # scale). Read *after* the bundle conversion: the scale keys carry the same+ # `model.diffusion_model.` prefix as the weights and only line up with the module tree once+ # it has been stripped. Until now the loader had no idea these keys existed and+ # `load_state_dict` rejected the checkpoint outright as unexpected keys.+ #+ # Unlike FLUX.2 there is no key conversion here: the checkpoint is already in the BFL+ # layout this model implements, and `qkv` stays one fused Linear, so a per-tensor scale+ # attaches to exactly the module it was computed for.+ #+ # Hints ship either in the safetensors header or as per-layer `.comfy_quant` markers; the+ # header wins on the rare checkpoint carrying both.+ metadata = read_safetensors_metadata(model_path, self._logger)+ layer_hints = {**extract_comfy_quant_hints(sd), **parse_quantization_metadata(metadata)}+ fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)+# 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)- self._ram_cache.make_room(predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=keep_fp8, model=model))+ 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 — 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 = tuple(getattr(model, "_skip_layerwise_casting_patterns", None) or ())+ # 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.+ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, torch.bfloat16, model=model, skip_patterns=skip_patterns)++ self._ram_cache.make_room(+ predict_cast_state_dict_size(+ sd, torch.bfloat16, keep_fp8=keep_fp8, 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)- if kept:- self._logger.info(f"FLUX: kept {kept} raw fp8 weight(s) quantized for the fp8 tensor cores.")+ kept = cast_state_dict(sd, torch.bfloat16, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)model.load_state_dict(sd, assign=True)++ if fp8_layers:+ attached = attach_fp8_scales(model, fp8_layers)+ self._logger.info(f"FLUX: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, fp8_compute enabled)")+ warn_on_unattached_scales(self._logger, "FLUX", attached, fp8_layers)+ marked = sum(1 for layer in fp8_layers.values() if layer.full_precision_matmul)+ if marked and full_precision_hints_respected():+ self._logger.info(+ f"FLUX: {marked} of {len(fp8_layers)} layer(s) are marked full_precision_matrix_mult "+ "and will dequantize per forward. Set fp8_compute_full_precision_hints=false to run "+ "them on the fp8 tensor cores instead."+ )+ elif kept:+ self._logger.info(f"FLUX: kept {kept} raw fp8 weight(s) quantized for the fp8 tensor cores.")+return modeldiff --git a/invokeai/backend/model_manager/util/model_util.py b/invokeai/backend/model_manager/util/model_util.pyindex c153129353..f85c1be490 100644--- a/invokeai/backend/model_manager/util/model_util.py+++ b/invokeai/backend/model_manager/util/model_util.py@@ -10,6 +10,7 @@ import torchfrom invokeai.app.services.config.config_default import get_configfrom invokeai.backend.model_manager.taxonomy import ClipVariantType+from invokeai.backend.quantization.fp8_scaled import is_scale_metadata_keyfrom invokeai.backend.quantization.gguf.loaders import gguf_sd_loaderfrom invokeai.backend.util.logging import InvokeAILogger@@ -172,9 +173,14 @@ def convert_bundle_to_flux_transformer_checkpoint(if not k.startswith("model.diffusion_model"):keys_to_remove.append(k) # This can be removed in the future if we only want to delete transformer keyscontinue- if k.endswith("scale"):+ if k.endswith("scale") and not is_scale_metadata_key(k):# Scale math must be done at bfloat16 due to our current flux model- # support limitations at inference time+ # support limitations at inference time.+ #+ # fp8 quantization scales are excluded. `.weight_scale` also ends in "scale", so the+ # unguarded test folded a scaled-fp8 checkpoint's f32 scales down to bf16 before the+ # loader ever saw them — 8 mantissa bits for a value every quantized weight is+ # multiplied by. Only the model's own RMSNorm `.scale` parameters belong here.v = v.to(dtype=torch.bfloat16)new_key = k.replace("model.diffusion_model.", "")original_state_dict[new_key] = vdiff --git a/tests/backend/model_manager/load/state_dicts/flux1_transformer_scaled_fp8_keys.py b/tests/backend/model_manager/load/state_dicts/flux1_transformer_scaled_fp8_keys.pynew file mode 100644index 0000000000..99cef0f12d--- /dev/null+++ b/tests/backend/model_manager/load/state_dicts/flux1_transformer_scaled_fp8_keys.py@@ -0,0 +1,122 @@+"""Representative key layout of a *scaled* fp8 FLUX.1 dev transformer checkpoint.++Captured from `comfyanonymous/flux_dev_scaled_fp8_test`, the reference ComfyUI scaled-fp8 export+for FLUX.1. Every key in that file carries the `model.diffusion_model.` bundle prefix; this fixture+records them as they look *after* `convert_bundle_to_flux_transformer_checkpoint` has stripped it,+which is where the loader reads them.++Worth capturing for three reasons. It spells the scales `.scale_weight`/`.scale_input` rather than+`.weight_scale`/`.input_scale`, so it exercises the second spelling end to end. Every one of its+314 quantized Linears carries a *calibrated* `scale_input` -- not the uncalibrated 1.0 placeholder+that `_usable_input_scale` rejects -- which no other captured fixture provides. And its `qkv` stays+one fused `[9216, 3072]` Linear with a single scalar scale, matching the BFL layout InvokeAI's own+`Flux` implements, so no scale has to be split or copied.++Before scaled-fp8 support reached this loader the file did not load at all: 629 scale and marker+keys reached `load_state_dict` as unexpected keys.++Subsetting rule as for the sibling fixtures: block 0 of each stack plus every non-block key.+Values are `(shape, dtype)`.+"""++state_dict_keys: dict[str, tuple[list[int], str]] = {+ "double_blocks.0.img_attn.norm.key_norm.scale": ([128], "BF16"),+ "double_blocks.0.img_attn.norm.query_norm.scale": ([128], "BF16"),+ "double_blocks.0.img_attn.proj.bias": ([3072], "F8_E4M3"),+ "double_blocks.0.img_attn.proj.scale_input": ([], "F32"),+ "double_blocks.0.img_attn.proj.scale_weight": ([], "F32"),+ "double_blocks.0.img_attn.proj.weight": ([3072, 3072], "F8_E4M3"),+ "double_blocks.0.img_attn.qkv.bias": ([9216], "F8_E4M3"),+ "double_blocks.0.img_attn.qkv.scale_input": ([], "F32"),+ "double_blocks.0.img_attn.qkv.scale_weight": ([], "F32"),+ "double_blocks.0.img_attn.qkv.weight": ([9216, 3072], "F8_E4M3"),+ "double_blocks.0.img_mlp.0.bias": ([12288], "F8_E4M3"),+ "double_blocks.0.img_mlp.0.scale_input": ([], "F32"),+ "double_blocks.0.img_mlp.0.scale_weight": ([], "F32"),+ "double_blocks.0.img_mlp.0.weight": ([12288, 3072], "F8_E4M3"),+ "double_blocks.0.img_mlp.2.bias": ([3072], "F8_E4M3"),+ "double_blocks.0.img_mlp.2.scale_input": ([], "F32"),+ "double_blocks.0.img_mlp.2.scale_weight": ([], "F32"),+ "double_blocks.0.img_mlp.2.weight": ([3072, 12288], "F8_E4M3"),+ "double_blocks.0.img_mod.lin.bias": ([18432], "F8_E4M3"),+ "double_blocks.0.img_mod.lin.scale_input": ([], "F32"),+ "double_blocks.0.img_mod.lin.scale_weight": ([], "F32"),+ "double_blocks.0.img_mod.lin.weight": ([18432, 3072], "F8_E4M3"),+ "double_blocks.0.txt_attn.norm.key_norm.scale": ([128], "BF16"),+ "double_blocks.0.txt_attn.norm.query_norm.scale": ([128], "BF16"),+ "double_blocks.0.txt_attn.proj.bias": ([3072], "F8_E4M3"),+ "double_blocks.0.txt_attn.proj.scale_input": ([], "F32"),+ "double_blocks.0.txt_attn.proj.scale_weight": ([], "F32"),+ "double_blocks.0.txt_attn.proj.weight": ([3072, 3072], "F8_E4M3"),+ "double_blocks.0.txt_attn.qkv.bias": ([9216], "F8_E4M3"),+ "double_blocks.0.txt_attn.qkv.scale_input": ([], "F32"),+ "double_blocks.0.txt_attn.qkv.scale_weight": ([], "F32"),+ "double_blocks.0.txt_attn.qkv.weight": ([9216, 3072], "F8_E4M3"),+ "double_blocks.0.txt_mlp.0.bias": ([12288], "F8_E4M3"),+ "double_blocks.0.txt_mlp.0.scale_input": ([], "F32"),+ "double_blocks.0.txt_mlp.0.scale_weight": ([], "F32"),+ "double_blocks.0.txt_mlp.0.weight": ([12288, 3072], "F8_E4M3"),+ "double_blocks.0.txt_mlp.2.bias": ([3072], "F8_E4M3"),+ "double_blocks.0.txt_mlp.2.scale_input": ([], "F32"),+ "double_blocks.0.txt_mlp.2.scale_weight": ([], "F32"),+ "double_blocks.0.txt_mlp.2.weight": ([3072, 12288], "F8_E4M3"),+ "double_blocks.0.txt_mod.lin.bias": ([18432], "F8_E4M3"),+ "double_blocks.0.txt_mod.lin.scale_input": ([], "F32"),+ "double_blocks.0.txt_mod.lin.scale_weight": ([], "F32"),+ "double_blocks.0.txt_mod.lin.weight": ([18432, 3072], "F8_E4M3"),+ "final_layer.adaLN_modulation.1.bias": ([6144], "F8_E4M3"),+ "final_layer.adaLN_modulation.1.scale_input": ([], "F32"),+ "final_layer.adaLN_modulation.1.scale_weight": ([], "F32"),+ "final_layer.adaLN_modulation.1.weight": ([6144, 3072], "F8_E4M3"),+ "final_layer.linear.bias": ([64], "F8_E4M3"),+ "final_layer.linear.scale_input": ([], "F32"),+ "final_layer.linear.scale_weight": ([], "F32"),+ "final_layer.linear.weight": ([64, 3072], "F8_E4M3"),+ "guidance_in.in_layer.bias": ([3072], "F8_E4M3"),+ "guidance_in.in_layer.scale_input": ([], "F32"),+ "guidance_in.in_layer.scale_weight": ([], "F32"),+ "guidance_in.in_layer.weight": ([3072, 256], "F8_E4M3"),+ "guidance_in.out_layer.bias": ([3072], "F8_E4M3"),+ "guidance_in.out_layer.scale_input": ([], "F32"),+ "guidance_in.out_layer.scale_weight": ([], "F32"),+ "guidance_in.out_layer.weight": ([3072, 3072], "F8_E4M3"),+ "img_in.bias": ([3072], "F8_E4M3"),+ "img_in.scale_input": ([], "F32"),+ "img_in.scale_weight": ([], "F32"),+ "img_in.weight": ([3072, 64], "F8_E4M3"),+ "scaled_fp8": ([0], "F8_E4M3"),+ "single_blocks.0.linear1.bias": ([21504], "F8_E4M3"),+ "single_blocks.0.linear1.scale_input": ([], "F32"),+ "single_blocks.0.linear1.scale_weight": ([], "F32"),+ "single_blocks.0.linear1.weight": ([21504, 3072], "F8_E4M3"),+ "single_blocks.0.linear2.bias": ([3072], "F8_E4M3"),+ "single_blocks.0.linear2.scale_input": ([], "F32"),+ "single_blocks.0.linear2.scale_weight": ([], "F32"),+ "single_blocks.0.linear2.weight": ([3072, 15360], "F8_E4M3"),+ "single_blocks.0.modulation.lin.bias": ([9216], "F8_E4M3"),+ "single_blocks.0.modulation.lin.scale_input": ([], "F32"),+ "single_blocks.0.modulation.lin.scale_weight": ([], "F32"),+ "single_blocks.0.modulation.lin.weight": ([9216, 3072], "F8_E4M3"),+ "single_blocks.0.norm.key_norm.scale": ([128], "BF16"),+ "single_blocks.0.norm.query_norm.scale": ([128], "BF16"),+ "time_in.in_layer.bias": ([3072], "F8_E4M3"),+ "time_in.in_layer.scale_input": ([], "F32"),+ "time_in.in_layer.scale_weight": ([], "F32"),+ "time_in.in_layer.weight": ([3072, 256], "F8_E4M3"),+ "time_in.out_layer.bias": ([3072], "F8_E4M3"),+ "time_in.out_layer.scale_input": ([], "F32"),+ "time_in.out_layer.scale_weight": ([], "F32"),+ "time_in.out_layer.weight": ([3072, 3072], "F8_E4M3"),+ "txt_in.bias": ([3072], "F8_E4M3"),+ "txt_in.scale_input": ([], "F32"),+ "txt_in.scale_weight": ([], "F32"),+ "txt_in.weight": ([3072, 4096], "F8_E4M3"),+ "vector_in.in_layer.bias": ([3072], "F8_E4M3"),+ "vector_in.in_layer.scale_input": ([], "F32"),+ "vector_in.in_layer.scale_weight": ([], "F32"),+ "vector_in.in_layer.weight": ([3072, 768], "F8_E4M3"),+ "vector_in.out_layer.bias": ([3072], "F8_E4M3"),+ "vector_in.out_layer.scale_input": ([], "F32"),+ "vector_in.out_layer.scale_weight": ([], "F32"),+ "vector_in.out_layer.weight": ([3072, 3072], "F8_E4M3"),+}diff --git a/tests/backend/model_manager/load/test_flux1_scaled_fp8_keys.py b/tests/backend/model_manager/load/test_flux1_scaled_fp8_keys.pynew file mode 100644index 0000000000..5dba27a672--- /dev/null+++ b/tests/backend/model_manager/load/test_flux1_scaled_fp8_keys.py@@ -0,0 +1,143 @@+"""The scaled-fp8 FLUX.1 key layout must be recognized, scales and all.++Before scaled-fp8 support reached `FluxCheckpointModel`, this checkpoint did not load at all: the+loader knew nothing about `.scale_weight`/`.scale_input`, so all 629 scale and marker keys reached+`load_state_dict` as unexpected keys and it raised.++The fixture is a real key layout; the tensors are synthetic because only shapes and dtypes matter+to the code under test.+"""++import torch++from invokeai.backend.model_manager.util.model_util import convert_bundle_to_flux_transformer_checkpoint+from invokeai.backend.quantization.fp8_scaled import (+ FP8_DTYPE,+ can_stay_quantized,+ extract_comfy_quant_hints,+ extract_fp8_scaled_layers,+ is_scale_metadata_key,+)+from tests.backend.model_manager.load.state_dicts.flux1_transformer_scaled_fp8_keys import (+ state_dict_keys as scaled_keys,+)++_DTYPES = {"F8_E4M3": FP8_DTYPE, "F32": torch.float32, "BF16": torch.bfloat16}+++def _build_state_dict() -> dict[str, torch.Tensor]:+ sd: dict[str, torch.Tensor] = {}+ for key, (shape, dtype) in scaled_keys.items():+ torch_dtype = _DTYPES[dtype]+ if torch_dtype is FP8_DTYPE:+ sd[key] = torch.zeros(shape, dtype=torch.float32).to(FP8_DTYPE)+ elif key.endswith((".scale_weight", ".scale_input")):+ # Real checkpoints carry calibrated scales; 1.0 is the placeholder value that+ # `_usable_input_scale` deliberately 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 sd+++def test_every_quantized_linear_is_recognized() -> None:+ """Each fp8 `.weight` in the fixture must come back as a scaled layer, not be left behind."""+ 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, "fixture carries no 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_the_fp8_biases_must_not_stay_quantized() -> None:+ """This checkpoint quantizes the biases too -- 314 of them, alongside the 314 weights.++ An fp8 bias saves nothing usable and breaks inference: the value reaches the activations and+ the next Linear receives an fp8 *input*, which dies in `x.abs()` with+ `"abs_cuda" not implemented for 'Float8_e4m3fn'`. Only 2-D `nn.Linear.weight` may stay+ quantized, which is what `can_stay_quantized` decides -- a bias is 1-D and fails it.+ """+ fp8_biases = [k for k, (_, dtype) in scaled_keys.items() if dtype == "F8_E4M3" and k.endswith(".bias")]+ assert fp8_biases, "fixture is expected to carry fp8 biases -- the real checkpoint does"++ sd = _build_state_dict()+ for key in fp8_biases:+ assert not can_stay_quantized(key, sd[key], None)+++def test_the_second_spelling_is_read() -> None:+ """This checkpoint spells the scales `.scale_weight`/`.scale_input`.++ Reading only `.weight_scale`/`.input_scale` would drop every scale here, leaving each weight+ off by `1/scale` with nothing logged.+ """+ assert any(k.endswith(".scale_weight") for k in scaled_keys)+ assert not any(k.endswith(".weight_scale") for k in scaled_keys)++ layers = extract_fp8_scaled_layers(_build_state_dict())++ assert layers+ assert all(layer.weight_scale is not None for layer in layers.values())+++def test_the_calibrated_input_scales_survive() -> None:+ """Every quantized Linear here ships a calibrated `scale_input`; none may be discarded.++ `_usable_input_scale` drops uncalibrated placeholders (exactly 1.0, non-finite, <= 0). A+ calibrated value must pass, otherwise every forward pays an amax reduction it does not need.+ """+ layers = extract_fp8_scaled_layers(_build_state_dict())++ assert all(layer.input_scale is not None for layer in layers.values())+++def test_extraction_strips_every_scale_and_marker_key() -> None:+ """What is left must load into a model that knows nothing about fp8."""+ sd = _build_state_dict()+ assert "scaled_fp8" in sd, "fixture is missing the producer's marker key"++ extract_fp8_scaled_layers(sd)++ assert not [k for k in sd if is_scale_metadata_key(k)]+ assert "scaled_fp8" not in sd+++def test_qkv_stays_fused_with_one_scalar_scale() -> None:+ """FLUX.1 needs no qkv split, unlike FLUX.2.++ InvokeAI's `Flux` implements the BFL layout, where `qkv` is a single Linear. The checkpoint+ matches it, so the per-tensor scale attaches to exactly the module it was computed for. If this+ ever changes, the scale would have to be *copied* to each split part rather than moved.+ """+ qkv = [k for k in scaled_keys if k.endswith(".qkv.weight")]+ assert qkv, "fixture carries no fused qkv weight"++ for key in qkv:+ shape, dtype = scaled_keys[key]+ assert dtype == "F8_E4M3"+ assert shape[0] == 3 * shape[1], f"{key} is not a fused qkv: {shape}"+ assert scaled_keys[key.replace(".weight", ".scale_weight")][0] == []+++def test_bundle_conversion_keeps_the_scales_at_full_precision() -> None:+ """The bundle converter casts RMSNorm `.scale` to bf16; fp8 quantization scales must not follow.++ `.weight_scale` also ends in "scale". Folding an f32 quantization scale to bf16 leaves 8+ mantissa bits on a value every quantized weight is multiplied by.+ """+ sd = {+ "model.diffusion_model.double_blocks.0.img_attn.norm.key_norm.scale": torch.ones(128, dtype=torch.float32),+ "model.diffusion_model.double_blocks.0.img_attn.qkv.weight_scale": torch.full((), 2.5, dtype=torch.float32),+ "model.diffusion_model.double_blocks.0.img_attn.qkv.scale_weight": torch.full((), 2.5, dtype=torch.float32),+ "model.diffusion_model.double_blocks.0.img_attn.qkv.weight": torch.zeros(9216, 3072, dtype=torch.float32).to(+ FP8_DTYPE+ ),+ }++ converted = convert_bundle_to_flux_transformer_checkpoint(sd)++ assert converted["double_blocks.0.img_attn.norm.key_norm.scale"].dtype is torch.bfloat16+ assert converted["double_blocks.0.img_attn.qkv.weight_scale"].dtype is torch.float32+ assert converted["double_blocks.0.img_attn.qkv.scale_weight"].dtype is torch.float32