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 remote-tracking branch 'origin/main' into feat/nvfp4-z-image-packed

Alexander Eichhorn94bbb7ddbdc9
diff --cc invokeai/app/invocations/minimax_h3/minimax_h3_denoise.py
index 1023577506,b120ff8442..2be13c40f5
--- a/invokeai/app/invocations/minimax_h3/minimax_h3_denoise.py
+++ b/invokeai/app/invocations/minimax_h3/minimax_h3_denoise.py
@@@ -474,8 -479,12 +476,12 @@@ class MiniMaxH3DenoiseInvocation(BaseIn
# Added to the activation estimate rather than compared against it: the transient is alive
# inside the same forward. Zero on a bf16 build. Read from the unlocked model, before the
# VRAM lock the reservation applies to.
- estimated_working_memory += peak_int8_dequant_transient_bytes(transformer_info.model, torch.bfloat16)
+ estimated_working_memory += peak_dequant_transient_bytes(transformer_info.model, torch.bfloat16)
+ # The hybrid AdaLN overlay (RAM cache, AdaLN tensors only) is materialized after the
+ # transformer's RAM load for the same reason as the LoRA patches below.
+ adaln_overlay = self._materialize_adaln_overlay(context, transformer_info.model)
+
# LoRA patches are materialized (RAM cache) before any VRAM locks. On the AdaLN-pruned
# transformer the AdaLN layers cannot be weight patches (their 2688-dim input space was
# collapsed into the curve table) and are split off for run-time re-injection, which
diff --cc invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py
index 1f2db772e5,b02bbfed16..b7013fbede
--- a/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py
+++ b/invokeai/app/invocations/text_encoder/qwen_image_text_encoder.py
@@@ -14,8 -19,8 +19,9 @@@ from invokeai.app.invocations.fields im
from invokeai.app.invocations.model import QwenVLEncoderField
from invokeai.app.invocations.primitives import QwenImageConditioningOutput
from invokeai.app.services.shared.invocation_context import InvocationContext
- from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LOAD_LOCK
+ from invokeai.backend.model_manager.load.model_cache.model_cache import MB, MODEL_LOAD_LOCK
+ from invokeai.backend.model_manager.load.model_util import calc_model_size_by_fs
+from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import (
ConditioningFieldData,
QwenImageConditioningInfo,
diff --cc invokeai/backend/model_manager/load/model_loaders/krea2.py
index 8df31b263a,051a41d9af..090b444a3c
--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py
+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py
@@@ -59,13 -58,8 +59,14 @@@ from invokeai.backend.quantization.int8
split_int8_convrot_layers,
swap_in_int8_linears,
)
+from invokeai.backend.quantization.nvfp4 import (
+ WEIGHT_SCALE_2_SUFFIX,
+ install_nvfp4_layers,
+ pop_nvfp4_layers,
+ predict_nvfp4_install_size,
+)
from invokeai.backend.util.devices import TorchDevice
+ from invokeai.backend.util.state_dict_loading import load_state_dict_ignoring_extras, reject_incomplete_load
# Kept as a module-level alias: this helper moved to model_manager.util.qwen3_vl so the MiniMax H3
# loader can share it without importing across family loaders.
@@@ -553,11 -528,9 +554,13 @@@ class Krea2CheckpointModel(ModelLoader)
skip_patterns=skip_patterns,
)
+ if nvfp4_payloads:
+ packed = install_nvfp4_layers(model, sd, nvfp4_payloads, model_dtype, skip_patterns)
+ self._logger.info(f"Krea-2: kept {packed} of {len(nvfp4_payloads)} nvfp4 layer(s) packed.")
+
- model.load_state_dict(sd, assign=True, strict=False)
+ load_state_dict_ignoring_extras(
+ model, sd, source="Krea-2 single-file checkpoint", assign=True, allow_missing=True
+ )
_reject_incomplete_load(model, what="Krea-2 single-file checkpoint")
# `assign=True` aliases every param to its `sd` tensor. Drop the dict's references before
# the FP8 cast, or each param's `model_dtype` original stays reachable while its fp8 copy is
diff --cc invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
index 44d759c3b3,31a8743a02..7096e54695
--- a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
+++ b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
@@@ -58,14 -56,9 +58,15 @@@ from invokeai.backend.quantization.fp8_
)
from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader
+from invokeai.backend.quantization.nvfp4 import (
+ NVFP4Payload,
+ install_nvfp4_layers,
+ pop_nvfp4_layers,
+ predict_nvfp4_install_size,
+)
from invokeai.backend.util.devices import TorchDevice
from invokeai.backend.util.logging import InvokeAILogger
+ from invokeai.backend.util.state_dict_loading import log_unexpected_keys
# Architecture constants for the 30-layer cow-mistral3-small distillation.
# Sourced from BFL's FLUX.2-dev ``text_encoder/config.json`` (text-model side of
@@@ -1046,16 -1003,11 +1047,15 @@@ class MistralEncoderCheckpointLoader(Mo
# 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)
+ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)
+ cast_state_dict(sd, model_dtype, keep_fp8=bool(fp8_layers), model=model, skip_patterns=skip_patterns)
+
+ if nvfp4_payloads:
+ packed = install_nvfp4_layers(model, sd, nvfp4_payloads, model_dtype, skip_patterns)
+ logger.info(f"Mistral encoder: kept {packed} of {len(nvfp4_payloads)} nvfp4 layer(s) packed.")
missing, unexpected = model.load_state_dict(sd, strict=False, assign=True)
- if unexpected:
- logger.debug(f"Mistral encoder: ignored {len(unexpected)} unexpected keys")
+ log_unexpected_keys("Mistral encoder checkpoint", unexpected)
if missing:
# Re-initialize any RMSNorm weights that may have been pruned during repackaging.
for name in missing:
diff --cc invokeai/backend/model_manager/load/model_loaders/qwen_image.py
index f59af7278e,f0b7026354..15582307d5
--- a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/qwen_image.py
@@@ -30,24 -30,10 +30,25 @@@ from invokeai.backend.model_manager.tax
QwenImageVariantType,
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,
+ parse_quantization_metadata,
+ predict_cast_state_dict_size,
+ read_safetensors_metadata,
+ should_keep_fp8_weights,
+ split_fp8_scaled_layers,
+ strip_layer_path_prefix,
+ 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.quantization.nvfp4 import install_nvfp4_layers, pop_nvfp4_layers, predict_nvfp4_install_size
from invokeai.backend.util.devices import TorchDevice
+ from invokeai.backend.util.state_dict_loading import load_state_dict_ignoring_extras, log_unexpected_keys
def _remap_qwen_vl_checkpoint_keys(sd: dict) -> dict:
@@@ -299,58 -275,22 +302,60 @@@ class QwenImageCheckpointModel(ModelLoa
is_edit = getattr(config, "variant", None) == QwenImageVariantType.Edit
model_config = _build_qwen_image_transformer_config(sd, is_edit=is_edit)
+ # Built before the reservation, which depends on its modules: they decide which nvfp4 and fp8 layers stay
+ # quantized.
with accelerate.init_empty_weights():
model = QwenImageTransformer2DModel(**model_config)
+ skip_patterns = _model_declared_skip_patterns(model)
- # Dequantized fp8 weights are already at model_dtype; this only casts any remaining
- # non-quantized float weights (e.g. a plain fp16/fp32 checkpoint) to the compute dtype
- # so the cache reservation below is sized from the actual post-cast tensors.
- for k in list(sd.keys()):
- if sd[k].is_floating_point():
- sd[k] = sd[k].to(model_dtype)
+ # One reservation, before the fold or the split widens a single weight: `make_room` makes that much room
+ # rather than adding to an earlier one.
+ self._ram_cache.make_room(
+ predict_cast_state_dict_size(
+ sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns, scaled_layers=fp8_layers
+ )
+ + predict_nvfp4_install_size(model, nvfp4_payloads, model_dtype, skip_patterns)
+ )
+
+ if fp8_layers and not keep_fp8:
+ dequantize_fp8_scaled(sd, fp8_layers, model_dtype)
+ logger.info(f"Qwen Image: folded {len(fp8_layers)} scaled fp8 layer(s) into {model_dtype}.")
+ fp8_layers = {}
+ # Layers the cast would widen anyway are folded here with their scale applied, so the cast never drops one.
+ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)
+ cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)
- new_sd_size = sum(t.nelement() * t.element_size() for t in sd.values())
- self._ram_cache.make_room(new_sd_size)
+ if nvfp4_payloads:
+ packed = install_nvfp4_layers(model, sd, nvfp4_payloads, model_dtype, skip_patterns)
+ logger.info(f"Qwen Image: kept {packed} of {len(nvfp4_payloads)} nvfp4 layer(s) packed.")
- model.load_state_dict(sd, strict=False, assign=True)
+ load_state_dict_ignoring_extras(
+ model, sd, source="Qwen-Image transformer checkpoint", assign=True, allow_missing=True
+ )
+ # `assign=True` aliases every param to its `sd` tensor: without this, the fp8 storage cast below would hold
+ # each dense weight at bf16 and fp8 at once, past the reservation.
+ sd.clear()
+
+ if fp8_layers:
+ attached = attach_fp8_scales(model, fp8_layers)
+ warn_on_unattached_scales(logger, "Qwen Image", attached, fp8_layers)
+ if not use_fp8_storage:
+ logger.info(f"Qwen Image: kept {attached} scaled fp8 layer(s) fp8 for fp8 compute.")
+ else:
+ # The rest of the dense weights go to fp8 storage too. The scaled layers are left alone: the cast
+ # hooks would upcast them without their scale. Marking the model cast keeps
+ # `_apply_fp8_layerwise_casting` from doing exactly that afterwards.
+ self._apply_fp8_to_nn_module(
+ model,
+ storage_dtype=torch.float8_e4m3fn,
+ compute_dtype=model_dtype,
+ extra_skip_patterns=skip_patterns,
+ skip=lambda _name, module: getattr(module, "weight_scale", None) is not None,
+ )
+ logger.info(
+ f"FP8 layerwise casting enabled for {config.name} (storage=float8_e4m3fn, compute={model_dtype}); "
+ f"kept {attached} scaled fp8 layer(s) with their own scale."
+ )
return model
diff --cc invokeai/backend/model_manager/load/model_loaders/z_image.py
index 9cda49bf8e,60e8b269d3..3ab7aefc8f
--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py
@@@ -677,19 -647,7 +678,19 @@@ class ZImageCheckpointModel(ModelLoader
skip_patterns=skip_patterns,
)
+ if nvfp4_payloads:
+ packed = install_nvfp4_layers(model, sd, nvfp4_payloads, model_dtype, skip_patterns)
+ decoded = len(nvfp4_payloads) - packed
+ self._logger.info(
+ f"Z-Image: kept {packed} nvfp4 layer(s) packed"
+ + (
+ f" and decoded {decoded} to {model_dtype} (precision-sensitive or not a Linear)."
+ if decoded
+ else "."
+ )
+ )
+
- model.load_state_dict(sd, assign=True)
+ load_state_dict_ignoring_extras(model, sd, source="Z-Image transformer checkpoint", assign=True)
# `assign=True` aliases every param to its `sd` tensor, so the dict keeps the whole model
# alive a second time. The FP8 cast below allocates the fp8 copy per param while the
# `model_dtype` original is still reachable through `sd`, pushing peak RAM to ~1.5x what