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.

Merge branch 'main' into feat/fp8_compute_raw

Alexander Eichhorn781cc9f01967
diff --cc invokeai/backend/model_manager/load/load_default.py
index 0facefb1c7,ca8ba6d5ab..2cfe084c99
--- a/invokeai/backend/model_manager/load/load_default.py
+++ b/invokeai/backend/model_manager/load/load_default.py
@@@ -27,8 -27,8 +27,9 @@@ from invokeai.backend.model_manager.tax
AnyModel,
SubModelType,
)
+from invokeai.backend.quantization.fp8_scaled import count_fp8_weights, should_keep_fp8_weights
from invokeai.backend.util.devices import TorchDevice
+ from invokeai.backend.util.fp8 import FP8_COMPUTE_DTYPE_ATTR, set_fp8_compute_dtype
# Layer classes that benefit from FP8 storage. Mirrors diffusers'
# `_GO_LC_SUPPORTED_PYTORCH_LAYERS` so the plain-nn.Module fallback path makes the same
@@@ -289,22 -289,12 +290,28 @@@ class ModelLoader(ModelLoaderBase)
if not self._should_use_fp8(config, submodel_type):
return model
+ # The cast is not idempotent: on a second pass the first parameter is already fp8, so the
+ # compute dtype below would be derived as float8. The marker is set by
+ # `_apply_fp8_to_nn_module`, so its presence means this model has already been cast.
+ if isinstance(model, torch.nn.Module) and getattr(model, FP8_COMPUTE_DTYPE_ATTR, None) is not None:
+ 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_e4m3fn
compute_dtype = self._torch_dtype
@@@ -354,12 -339,13 +361,19 @@@
Without the skip list, precision-sensitive tiny learned scalars (e.g. FLUX RMSNorm.scale)
get crushed to FP8 and quality degrades noticeably.
+ `skip` excludes further modules by (dotted name, module). Its one caller uses it to leave
+ scaled-fp8 layers alone: those already hold fp8 weights plus a `weight_scale`, and the cast
+ hooks installed here would upcast them *without* applying that scale — a silently wrong
+ weight. Casting only the remainder lets a partly-quantized checkpoint (fp8 language model,
+ bf16 visual tower) end up fully fp8-resident.
++
+ Records the compute dtype on the model. After the cast, `model.dtype` reports the float8
+ storage dtype, which must never be used to create or cast tensors — torch has no arithmetic
+ kernels for it (see `get_model_compute_dtype`). The marker is set here rather than at the
+ call sites so a new caller cannot forget it.
"""
+ set_fp8_compute_dtype(model, compute_dtype)
+
for module_name, module in model.named_modules():
if not isinstance(module, _FP8_SUPPORTED_PYTORCH_LAYERS):
continue
diff --cc invokeai/backend/model_manager/load/model_loaders/krea2.py
index 22a3b5cf6c,00bb79648d..c18743aafd
--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py
+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py
@@@ -387,37 -347,19 +403,38 @@@ class Krea2CheckpointModel(ModelLoader)
raise TypeError(f"Expected Main_Checkpoint_Krea2_Config, got {type(config).__name__}.")
model_path = Path(config.path)
+ target_device = TorchDevice.choose_torch_device()
+ model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
+
sd = load_file(model_path)
+ metadata = _read_safetensors_metadata(model_path, self._logger)
sd = _strip_comfyui_prefix(sd)
- # ComfyUI 'scaled fp8' checkpoints: fold the per-tensor weight_scale into the weights. The
- # compute dtype is resolved first so the dequantized weights land there directly instead of
- # transiently materializing the whole model in float32.
- sd = _dequantize_scaled_fp8(sd, model_dtype)
- # Native/ComfyUI key naming → diffusers Krea2Transformer2DModel keys.
+ # Native/ComfyUI key naming → diffusers Krea2Transformer2DModel keys. Done *before* the fp8
+ # scales are pulled out: the renames are substring-based on ".weight", so a sibling
+ # ".weight_scale" is carried to the same destination key automatically.
+ #
+ # Per-layer `.comfy_quant` markers are read first (they are popped out of `sd` here, before
+ # the key conversion, which only knows how to rename ".weight"-suffixed keys). Checkpoints
+ # ship the flags in either the header or these markers; without both, a checkpoint using
+ # only the per-tensor form has its full_precision_matrix_mult layers silently multiplied in
+ # fp8. The header wins on the rare checkpoint carrying both.
+ layer_hints = {**extract_comfy_quant_hints(sd), **parse_quantization_metadata(metadata)}
if _is_native_krea2_format(sd):
sd = _convert_krea2_native_to_diffusers(sd)
+ # The metadata still names layers natively; rename it the same way or its per-layer
+ # flags (notably full_precision_matrix_mult) match nothing.
+ path_map = _remap_native_layer_paths(layer_hints.keys())
+ layer_hints = {path_map.get(name, name): hints for name, hints in layer_hints.items()}
+
- target_device = TorchDevice.choose_torch_device()
- model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
-
+ # ComfyUI 'scaled fp8' checkpoints (fp8 weight + .weight_scale, optionally .input_scale).
+ fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)
+ if fp8_layers and not is_fp8_matmul_enabled():
+ # Legacy behavior: fold the scales into the weights. Keeping them quantized without the
+ # fp8 matmul would halve VRAM but run slower, so both are tied to the same setting.
+ dequantize_fp8_scaled(sd, fp8_layers, model_dtype)
+ fp8_layers = {}
+
+
with accelerate.init_empty_weights():
model = Krea2Transformer2DModel(**KREA2_TRANSFORMER_CONFIG)