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 Mistral encoders on the tensor cores

Alexander Eichhorn27a138f2498e
diff --git a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
index 0707ae19bf..9d3fa59f24 100644
--- a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
+++ b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
@@ -37,7 +37,20 @@ from invokeai.backend.model_manager.taxonomy import (
ModelType,
SubModelType,
)
-from invokeai.backend.quantization.fp8_scaled import is_scale_metadata_key, iter_weight_scale_pairs
+from invokeai.backend.quantization.fp8_scaled import (
+ attach_fp8_scales,
+ cast_state_dict,
+ extract_comfy_quant_hints,
+ extract_fp8_scaled_layers,
+ full_precision_hints_respected,
+ is_scale_metadata_key,
+ iter_weight_scale_pairs,
+ parse_quantization_metadata,
+ read_safetensors_metadata,
+ should_keep_fp8_weights,
+ split_fp8_scaled_layers,
+ warn_on_unattached_scales,
+)
from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader
from invokeai.backend.util.devices import TorchDevice
@@ -920,10 +933,27 @@ class MistralEncoderCheckpointLoader(ModelLoader):
target_device = TorchDevice.choose_torch_device()
model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
- sd = load_file(Path(config.path))
+ model_path = Path(config.path)
+ sd = load_file(model_path)
sd = _strip_known_prefixes(sd)
- # Dequantize straight to the compute dtype (per-tensor peak, not whole-dict fp32).
- sd = _drop_quantization_metadata(sd, logger, target_dtype=model_dtype)
+
+ # These redistributions are ComfyUI 'scaled fp8': an fp8 weight plus a `weight_scale`.
+ # Folding the scale doubles the encoder -- 16.8 GiB on disk becomes 32.3 GiB in bf16, which
+ # does not fit on a 24 GB card even on its own. Keeping the weights quantized is therefore
+ # not just a speed question here, it decides whether the model loads at all.
+ #
+ # Both key rewrites in this loader (`_strip_known_prefixes` above and
+ # `_convert_for_bare_mistral_model` below) are plain prefix operations, so a sibling
+ # `.weight_scale` travels with its weight automatically -- no fused projections to split.
+ keep_fp8 = should_keep_fp8_weights(target_device)
+ fp8_layers: dict[str, Any] = {}
+ if keep_fp8:
+ header_hints = parse_quantization_metadata(read_safetensors_metadata(model_path, logger))
+ layer_hints = {**extract_comfy_quant_hints(sd), **header_hints}
+ fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)
+ if not fp8_layers:
+ # Dequantize straight to the compute dtype (per-tensor peak, not whole-dict fp32).
+ sd = _drop_quantization_metadata(sd, logger, target_dtype=model_dtype)
mistral_config = _build_mistral_config(sd, torch_dtype=model_dtype)
logger.info(
@@ -938,18 +968,22 @@ class MistralEncoderCheckpointLoader(ModelLoader):
for k in [k for k in sd.keys() if isinstance(k, str) and k.startswith("lm_head.")]:
del sd[k]
- # Cast remaining tensors to compute dtype before loading. Dequantized weights are
- # already at model_dtype; this covers the un-quantized ones (norms, embeddings).
- for k in list(sd.keys()):
- if sd[k].dtype != model_dtype:
- sd[k] = sd[k].to(model_dtype)
-
- # Adapt CausalLM-prefixed keys for bare MistralModel.
+ # Adapt CausalLM-prefixed keys for bare MistralModel. The recovered scales are keyed on the
+ # checkpoint's paths, so they need the same `model.` strip or `attach_fp8_scales` resolves
+ # nothing and every weight stays quantized but unscaled.
sd = _convert_for_bare_mistral_model(sd)
+ fp8_layers = {
+ (path[len("model.") :] if path.startswith("model.") else path): layer for path, layer in fp8_layers.items()
+ }
with accelerate.init_empty_weights():
model = MistralModel(mistral_config)
+ # 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)
+ cast_state_dict(sd, model_dtype, keep_fp8=bool(fp8_layers), model=model)
+
missing, unexpected = model.load_state_dict(sd, strict=False, assign=True)
if unexpected:
logger.debug(f"Mistral encoder: ignored {len(unexpected)} unexpected keys")
@@ -977,6 +1011,19 @@ class MistralEncoderCheckpointLoader(ModelLoader):
_strip_final_norm_for_cow(model, config.variant, logger)
_warn_if_40_layer_mistral(config.variant, logger)
+ if fp8_layers:
+ attached = attach_fp8_scales(model, fp8_layers)
+ logger.info(
+ f"Mistral encoder: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, fp8_compute enabled)"
+ )
+ warn_on_unattached_scales(logger, "Mistral encoder", 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"Mistral encoder: {marked} of {len(fp8_layers)} layer(s) are marked "
+ "full_precision_matrix_mult and will dequantize per forward."
+ )
+
return model