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(quantization): keep Comfy fp4_mixed Mistral encoders packed

Alexander Eichhorna69d3ca5d6f8
diff --git a/invokeai/app/invocations/text_encoder/flux2_dev_text_encoder.py b/invokeai/app/invocations/text_encoder/flux2_dev_text_encoder.py
index d1b0bd08e4..da8cd02189 100644
--- a/invokeai/app/invocations/text_encoder/flux2_dev_text_encoder.py
+++ b/invokeai/app/invocations/text_encoder/flux2_dev_text_encoder.py
@@ -42,6 +42,7 @@ from invokeai.backend.model_manager.load.model_cache.utils import get_effective_
from invokeai.backend.patches.layer_patcher import LayerPatcher
from invokeai.backend.patches.lora_conversions.flux_lora_constants import FLUX_LORA_T5_PREFIX
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
+from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes, requires_sidecar_patching
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData, FLUXConditioningInfo
from invokeai.backend.util.devices import TorchDevice
@@ -129,7 +130,15 @@ class Flux2DevTextEncoderInvocation(BaseInvocation):
def _encode_prompt(self, context: InvocationContext, exit_stack: ExitStack) -> torch.Tensor:
text_encoder_info = context.models.load(self.mistral_encoder.text_encoder)
- (cached_weights, text_encoder) = exit_stack.enter_context(text_encoder_info.model_on_device())
+ text_encoder_format = context.models.get_config(self.mistral_encoder.text_encoder).format
+ # An nvfp4 build dequantizes each packed Linear per forward, a transient its resident size does not
+ # cover. Read from the unlocked model, before the lock the reservation applies to; zero for other builds.
+ dequant_bytes = peak_dequant_transient_bytes(
+ text_encoder_info.model, TorchDevice.choose_bfloat16_safe_dtype(text_encoder_info.compute_device)
+ )
+ (cached_weights, text_encoder) = exit_stack.enter_context(
+ text_encoder_info.model_on_device(working_mem_bytes=dequant_bytes)
+ )
processor_info = context.models.load(self.mistral_encoder.tokenizer)
(_, processor) = exit_stack.enter_context(processor_info.model_on_device())
@@ -150,6 +159,9 @@ class Flux2DevTextEncoderInvocation(BaseInvocation):
prefix=FLUX_LORA_T5_PREFIX,
dtype=lora_dtype,
cached_weights=cached_weights,
+ # Quantized weights (packed nvfp4 Linears, GGUF, SDNQ) cannot take a direct patch, so
+ # their LoRAs ride as sidecars.
+ force_sidecar_patching=requires_sidecar_patching(text_encoder, text_encoder_format),
)
)
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 0f0cd1e915..44d759c3b3 100644
--- a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
+++ b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
@@ -14,6 +14,7 @@ tokenizer from ``black-forest-labs/FLUX.2-dev`` via HuggingFace.
"""
import re
+from collections.abc import Mapping
from pathlib import Path
from typing import Any, Optional
@@ -27,7 +28,7 @@ from invokeai.backend.model_manager.configs.mistral_encoder import (
MistralEncoder_Diffusers_Config,
MistralEncoder_GGUF_Config,
)
-from invokeai.backend.model_manager.load.load_default import ModelLoader
+from invokeai.backend.model_manager.load.load_default import ModelLoader, _model_declared_skip_patterns
from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistry
from invokeai.backend.model_manager.taxonomy import (
AnyModel,
@@ -48,6 +49,7 @@ from invokeai.backend.quantization.fp8_scaled import (
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,
@@ -56,7 +58,12 @@ from invokeai.backend.quantization.fp8_scaled import (
)
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 dequantize_nvfp4_layers
+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
@@ -83,11 +90,15 @@ _COW_RMS_NORM_EPS = 1e-5
_TOKENIZER_FALLBACK_SOURCE: tuple[str, str] = ("black-forest-labs/FLUX.2-dev", "tokenizer")
+_Q_PROJ_PATH = re.compile(r"model\.layers\.(\d+)\.self_attn\.q_proj")
+
+
def _build_mistral_config(
state_dict: dict[str, Any],
torch_dtype: torch.dtype,
rope_theta: float | None = None,
max_position_embeddings: int | None = None,
+ packed_layers: Mapping[str, NVFP4Payload] | None = None,
) -> MistralConfig:
"""Build a transformers ``MistralConfig`` from a cow-mistral3-small state dict.
@@ -95,7 +106,21 @@ def _build_mistral_config(
intermediate, layer count). ``rope_theta`` and ``max_position_embeddings`` can
be passed explicitly when an out-of-band source is available (e.g. GGUF
metadata); otherwise we fall back to cow defaults.
+
+ ``packed_layers`` are the nvfp4 layers a loader took out of the state dict to keep them packed. They count
+ as their weights would: read from the state dict alone, a packed encoder silently gets the cow layer count
+ and head counts.
"""
+ packed_layers = packed_layers or {}
+
+ def output_rows(path: str) -> int | None:
+ if path in packed_layers:
+ return packed_layers[path].out_features
+ weight = state_dict.get(f"{path}.weight")
+ if weight is None:
+ return None
+ return int((weight.tensor_shape if isinstance(weight, GGMLTensor) else weight.shape)[0])
+
# Vocab and hidden_size come from embed_tokens.
embed_key = "model.embed_tokens.weight" if "model.embed_tokens.weight" in state_dict else None
if embed_key is None:
@@ -104,30 +129,20 @@ def _build_mistral_config(
embed_shape = embed.tensor_shape if isinstance(embed, GGMLTensor) else embed.shape
vocab_size, hidden_size = int(embed_shape[0]), int(embed_shape[1])
- # Count layers by scanning self_attn.q_proj keys.
- layer_indices: set[int] = set()
- for key in state_dict.keys():
- if not isinstance(key, str):
- continue
- if key.startswith("model.layers.") and ".self_attn.q_proj.weight" in key:
- try:
- layer_indices.add(int(key.split(".")[2]))
- except (ValueError, IndexError):
- pass
+ # Count layers by their attention query projections.
+ layer_paths = [*(key.removesuffix(".weight") for key in state_dict if isinstance(key, str)), *packed_layers]
+ layer_indices = {int(match.group(1)) for path in layer_paths if (match := _Q_PROJ_PATH.fullmatch(path))}
num_hidden_layers = (max(layer_indices) + 1) if layer_indices else _COW_NUM_HIDDEN_LAYERS
# Derive head counts from the first layer's attention projections.
- q_proj = state_dict.get("model.layers.0.self_attn.q_proj.weight")
- k_proj = state_dict.get("model.layers.0.self_attn.k_proj.weight")
- gate_proj = state_dict.get("model.layers.0.mlp.gate_proj.weight")
+ q_rows = output_rows("model.layers.0.self_attn.q_proj")
+ k_rows = output_rows("model.layers.0.self_attn.k_proj")
+ gate_rows = output_rows("model.layers.0.mlp.gate_proj")
head_dim = _COW_HEAD_DIM
- if q_proj is not None and k_proj is not None and gate_proj is not None:
- q_shape = q_proj.tensor_shape if isinstance(q_proj, GGMLTensor) else q_proj.shape
- k_shape = k_proj.tensor_shape if isinstance(k_proj, GGMLTensor) else k_proj.shape
- gate_shape = gate_proj.tensor_shape if isinstance(gate_proj, GGMLTensor) else gate_proj.shape
- num_attention_heads = int(q_shape[0]) // head_dim
- num_key_value_heads = int(k_shape[0]) // head_dim
- intermediate_size = int(gate_shape[0])
+ if q_rows is not None and k_rows is not None and gate_rows is not None:
+ num_attention_heads = q_rows // head_dim
+ num_key_value_heads = k_rows // head_dim
+ intermediate_size = gate_rows
else:
num_attention_heads = _COW_NUM_ATTENTION_HEADS
num_key_value_heads = _COW_NUM_KV_HEADS
@@ -235,6 +250,11 @@ def _strip_known_prefixes(sd: dict[str, Any]) -> dict[str, Any]:
return out
+def _bare_mistral_path(path: str) -> str:
+ """A CausalLM layer path as bare ``MistralModel`` names it (see ``_convert_for_bare_mistral_model``)."""
+ return path.removeprefix("model.")
+
+
def _convert_for_bare_mistral_model(sd: dict[str, Any]) -> dict[str, Any]:
"""Rewrite a `model.*` causal-LM state dict for direct loading into ``MistralModel``.
@@ -248,13 +268,8 @@ def _convert_for_bare_mistral_model(sd: dict[str, Any]) -> dict[str, Any]:
for key, value in sd.items():
if not isinstance(key, str):
out[key] = value
- continue
- if key.startswith("lm_head."):
- continue
- if key.startswith("model."):
- out[key[len("model.") :]] = value
- else:
- out[key] = value
+ elif not key.startswith("lm_head."):
+ out[_bare_mistral_path(key)] = value
return out
@@ -372,8 +387,9 @@ def _warn_if_40_layer_mistral(variant: MistralVariantType, logger: Any) -> None:
def _drop_quantization_metadata(sd: dict[str, Any], logger, target_dtype: torch.dtype | None = None) -> dict[str, Any]:
"""Dequantize Comfy-Org-style scaled FP8 weights and drop their metadata keys.
- nvfp4 layers must be decoded before this runs (see ``_load_text_encoder``): their block scales pair
- with a ``.weight`` just like an fp8 scale, and the fold below would stretch them over the packed weight.
+ nvfp4 layers must be taken out with ``pop_nvfp4_layers`` before this runs (see ``_load_text_encoder``): their
+ block scales pair with a ``.weight`` just like an fp8 scale, and the fold below would stretch them over the
+ packed weight.
Comfy-Org's Mistral FLUX.2 redistributions store quantized weights alongside
``*.weight_scale`` (and occasionally ``*.input_scale``) tensors. We apply the
@@ -957,18 +973,11 @@ class MistralEncoderCheckpointLoader(ModelLoader):
prefixes=(*MISTRAL_KEY_PREFIXES, *TRANSFORMER_KEY_PREFIXES),
)
- # Comfy's fp4_mixed build keeps most projections in nvfp4 beside scaled fp8. Decode those first:
- # the keep-fp8 branch below pops every `weight_scale` and discards the ones whose weight is not
- # float8, nvfp4's block scales included, and the dequantizing branch would stretch them over the
- # packed weight.
- nvfp4_layers = dequantize_nvfp4_layers(
- sd, model_dtype, reserve=self._ram_cache.make_room, header_layers=header_hints
- )
- if nvfp4_layers:
- logger.info(
- f"Mistral encoder: decoded {nvfp4_layers} nvfp4 layer(s) to {model_dtype}. They are not kept packed, "
- "so the encoder needs as much memory as its bf16 build."
- )
+ # Comfy's fp4_mixed build keeps most projections in nvfp4 beside scaled fp8. Take those out before
+ # anything below reads the side channel: the keep-fp8 branch pops every `weight_scale` and discards the
+ # ones whose weight is not float8, nvfp4's block scales included, and the dequantizing branch and the cast
+ # would widen the packed codes. `install_nvfp4_layers` puts them back, packed.
+ nvfp4_payloads = pop_nvfp4_layers(sd, header_layers=header_hints)
# 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
@@ -983,45 +992,66 @@ class MistralEncoderCheckpointLoader(ModelLoader):
if keep_fp8:
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)
- else:
- # `extract_fp8_scaled_layers` removes the keys it interprets, but this producer also
- # emits `.scale` and `scaled_fp8*`, which it does not recognize. On the dequantizing
- # path `_drop_quantization_metadata` takes those; here nothing did, so they reached
- # `load_state_dict` and padded the "ignored N unexpected keys" line.
- for k in [k for k in sd if isinstance(k, str) and (k.endswith(".scale") or k.startswith("scaled_fp8"))]:
- del sd[k]
- mistral_config = _build_mistral_config(sd, torch_dtype=model_dtype)
+ mistral_config = _build_mistral_config(sd, torch_dtype=model_dtype, packed_layers=nvfp4_payloads)
logger.info(
f"Mistral encoder config (checkpoint): layers={mistral_config.num_hidden_layers}, "
f"hidden={mistral_config.hidden_size}, heads={mistral_config.num_attention_heads}, "
f"kv_heads={mistral_config.num_key_value_heads}, intermediate={mistral_config.intermediate_size}"
)
- # Drop the LM head before casting: it's the single largest tensor (vocab × hidden),
- # bare MistralModel doesn't use it, and `_convert_for_bare_mistral_model` drops it
- # anyway — casting it first would just waste memory and time.
- for k in [k for k in sd.keys() if isinstance(k, str) and k.startswith("lm_head.")]:
- del sd[k]
-
- # 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.
+ # Built before the reservation, which depends on its modules: they decide which fp8 weights and which
+ # nvfp4 layers stay quantized.
+ with accelerate.init_empty_weights():
+ model = MistralModel(mistral_config)
+ skip_patterns = _model_declared_skip_patterns(model)
+
+ # Adapt CausalLM-prefixed keys for bare MistralModel -- a rename, nothing is widened -- which also drops the
+ # LM head, the single largest tensor (vocab × hidden). The recovered scales and the packed layers are keyed
+ # on the same CausalLM paths and need the same strip, or nothing resolves: every fp8 weight stays quantized
+ # but unscaled, and every packed layer names no module. Only the text tower has modules in the bare model,
+ # so packed layers outside it -- the LM head, a vision tower a multimodal export bundles -- are dropped,
+ # as their dense weights are dropped by the non-strict load.
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()
+ nvfp4_payloads = {
+ _bare_mistral_path(path): payload for path, payload in nvfp4_payloads.items() if path.startswith("model.")
}
+ fp8_layers = {_bare_mistral_path(path): layer for path, layer in fp8_layers.items()}
+
+ # One reservation, before the dequantizing branch or the split widens a single weight -- `make_room` makes
+ # that much room rather than adding to an earlier one. The state dict is sized by the predicate the split and
+ # the cast below decide with, the nvfp4 layers as they will be held.
+ self._ram_cache.make_room(
+ predict_cast_state_dict_size(
+ sd,
+ model_dtype,
+ keep_fp8=bool(fp8_layers),
+ model=model,
+ skip_patterns=skip_patterns,
+ scaled_layers=fp8_layers,
+ )
+ + predict_nvfp4_install_size(model, nvfp4_payloads, model_dtype, skip_patterns)
+ )
- with accelerate.init_empty_weights():
- model = MistralModel(mistral_config)
+ 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)
+ else:
+ # `extract_fp8_scaled_layers` removes the keys it interprets, but this producer also
+ # emits `.scale` and `scaled_fp8*`, which it does not recognize. On the dequantizing
+ # path `_drop_quantization_metadata` takes those; here nothing did, so they reached
+ # `load_state_dict` and padded the "ignored N unexpected keys" line.
+ for k in [k for k in sd if isinstance(k, str) and (k.endswith(".scale") or k.startswith("scaled_fp8"))]:
+ del sd[k]
# 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:
diff --git a/invokeai/backend/model_manager/starter_models/common.py b/invokeai/backend/model_manager/starter_models/common.py
index edb0c15daa..5910c722ae 100644
--- a/invokeai/backend/model_manager/starter_models/common.py
+++ b/invokeai/backend/model_manager/starter_models/common.py
@@ -263,7 +263,7 @@ flux2_dev_comfy_mistral_fp4 = StarterModel(
name="FLUX.2 [dev] Mistral Encoder (Comfy FP4 mixed)",
base=BaseModelType.Any,
source="https://huggingface.co/Comfy-Org/flux2-dev/resolve/main/split_files/text_encoders/mistral_3_small_flux2_fp4_mixed.safetensors",
- description="Comfy-Org FP4-mixed of BFL's 30-layer cow-mistral3-small; embeds Tekken tokenizer. Smallest download, but loads at BF16 size. ~12.3GB",
+ description="Comfy-Org FP4-mixed of BFL's 30-layer cow-mistral3-small; embeds Tekken tokenizer. Its nvfp4 layers stay packed, up to about 14.7GB once loaded. ~12.3GB download",
type=ModelType.MistralEncoder,
)
diff --git a/invokeai/backend/quantization/nvfp4.py b/invokeai/backend/quantization/nvfp4.py
index 12327233bd..76aec234be 100644
--- a/invokeai/backend/quantization/nvfp4.py
+++ b/invokeai/backend/quantization/nvfp4.py
@@ -1,4 +1,4 @@
-"""Comfy "nvfp4" quantized linears: packed storage decoded per forward, or a decode at load.
+"""Comfy "nvfp4" quantized linears: packed storage decoded per forward.
``nvfp4`` is a ComfyUI-wide scheme, not one architecture's format: Comfy-Org ships it for Z-Image,
Krea-2, Qwen-Image, the FLUX.2 Mistral encoder and more, often beside scaled fp8 and plain bf16 in the
@@ -24,20 +24,16 @@ its conditioning slightly worse -- which is why tests pin the layout against the
and a slice of a real checkpoint. Nothing guarantees that another producer writing the same key names
shares these conventions, so a layer is only read when a Comfy marker or header entry names it nvfp4.
-Loaders take one of two routes:
+Loaders keep the layers packed: :func:`pop_nvfp4_layers` takes them out of the state dict before any fp8
+handling, and :func:`install_nvfp4_layers` swaps :class:`NVFP4Linear` modules in before the load. A layer
+then occupies about 0.56 bytes per weight element against bf16's 2 and dequantizes per forward.
-- Keep the layers packed: :func:`pop_nvfp4_layers` takes them out of the state dict before any fp8
- handling, and :func:`install_nvfp4_layers` swaps :class:`NVFP4Linear` modules in before the load. A
- layer then occupies about 0.56 bytes per weight element against bf16's 2 and dequantizes per forward.
-- Decode at load with :func:`dequantize_nvfp4_layers`. The model then needs as much memory as its bf16
- build.
-
-AWQ builds (``pre_quant_scale``) are refused either way: their input channels were rescaled before
-quantization, so a plain decode would produce wrong weights.
+AWQ builds (``pre_quant_scale``) are refused: their input channels were rescaled before quantization, so a
+plain decode would produce wrong weights.
"""
import functools
-from collections.abc import Callable, Iterable, Mapping
+from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from typing import Any
@@ -299,36 +295,6 @@ def _find_nvfp4_layers(sd: Mapping[str, Any], header_layers: Mapping[str, Any] |
return layers
-def dequantize_nvfp4_layers(
- sd: dict[str, Any],
- dtype: torch.dtype,
- reserve: Callable[[int], object] | None = None,
- header_layers: Mapping[str, Any] | None = None,
-) -> int:
- """Decode every nvfp4 layer in ``sd`` to ``dtype`` in place, drop its side channel, return the count.
-
- For loaders that do not keep the layers packed. Call it before any fp8 handling, for the reasons given
- at :func:`pop_nvfp4_layers`; the scaled-fp8 weights, scales and markers of a mixed file are left for
- that path.
-
- Nothing is widened until every layer has been checked. Then ``reserve`` -- a loader's ``make_room`` --
- is called once with the size ``sd`` will have after decoding. The model cache reserves only the file
- size before a load and decoding more than triples it, so reserving afterwards would let the peak land
- on memory other cached models still hold.
- """
- layers = _find_nvfp4_layers(sd, header_layers)
- if not layers:
- return 0
- if reserve is not None:
- reserve(_decoded_size(sd, layers, dtype))
- for path in layers:
- weight, scale = sd[f"{path}.weight"], sd[f"{path}.weight_scale"]
- sd[f"{path}.weight"] = dequantize_nvfp4_weight(weight, scale, sd[f"{path}{WEIGHT_SCALE_2_SUFFIX}"], dtype)
- for suffix in _SIDE_CHANNEL_SUFFIXES:
- sd.pop(f"{path}{suffix}", None)
- return len(layers)
-
-
def pop_nvfp4_layers(sd: dict[str, Any], header_layers: Mapping[str, Any] | None = None) -> dict[str, NVFP4Payload]:
"""Take every nvfp4 layer's packed tensors out of ``sd`` and drop the rest of its side channel.
@@ -452,11 +418,3 @@ def _stays_packed(model: torch.nn.Module, path: str, payload: NVFP4Payload, skip
f"Linear there is {module.out_features}x{module.in_features}. The checkpoint is misidentified."
)
return True
-
-
-def _decoded_size(sd: dict[str, Any], layers: list[str], dtype: torch.dtype) -> int:
- """Bytes ``sd`` occupies once ``layers`` are decoded to ``dtype`` and their side channels dropped."""
- replaced = {f"{path}{suffix}" for path in layers for suffix in (".weight", *_SIDE_CHANNEL_SUFFIXES)}
- kept = sum(tensor.nelement() * tensor.element_size() for key, tensor in sd.items() if key not in replaced)
- decoded = sum(sd[f"{path}.weight"].shape[0] * sd[f"{path}.weight"].shape[1] * 2 for path in layers)
- return kept + decoded * dtype.itemsize
diff --git a/tests/app/invocations/test_qwen3_text_encoders_with_packed_layers.py b/tests/app/invocations/test_text_encoders_with_packed_layers.py
similarity index 65%
rename from tests/app/invocations/test_qwen3_text_encoders_with_packed_layers.py
rename to tests/app/invocations/test_text_encoders_with_packed_layers.py
index 4e16809897..c43579842f 100644
--- a/tests/app/invocations/test_qwen3_text_encoders_with_packed_layers.py
+++ b/tests/app/invocations/test_text_encoders_with_packed_layers.py
@@ -1,8 +1,9 @@
-"""The Qwen3 text-encoder nodes have to treat a quantized encoder the way the denoise nodes treat a quantized
-transformer: reserve working memory for the per-forward dequantization of packed nvfp4 Linears, and apply LoRA as
-a sidecar wherever a direct patch cannot write the weights -- packed nvfp4 Linears, and GGUF or SDNQ encoders,
-which the denoise nodes already patch this way. All three nodes load through the same Qwen3 loader, so each of
-them receives a packed encoder as soon as someone installs Comfy's fp4_mixed file.
+"""The text-encoder nodes have to treat a quantized encoder the way the denoise nodes treat a quantized transformer:
+reserve working memory for the per-forward dequantization of packed nvfp4 Linears, and apply LoRA as a sidecar
+wherever a direct patch cannot write the weights -- packed nvfp4 Linears, and GGUF or SDNQ encoders, which the denoise
+nodes already patch this way. The three Qwen3 nodes load through the Qwen3 loader and the FLUX.2 [dev] node through
+the Mistral loader, and both keep Comfy's fp4_mixed files packed, so each node receives a packed encoder as soon as
+someone installs one.
"""
from contextlib import ExitStack, contextmanager
@@ -13,6 +14,7 @@ import pytest
import torch
from invokeai.app.invocations.text_encoder.anima_text_encoder import AnimaTextEncoderInvocation
+from invokeai.app.invocations.text_encoder.flux2_dev_text_encoder import Flux2DevTextEncoderInvocation
from invokeai.app.invocations.text_encoder.flux2_klein_text_encoder import Flux2KleinTextEncoderInvocation
from invokeai.app.invocations.text_encoder.z_image_text_encoder import ZImageTextEncoderInvocation
from invokeai.backend.model_manager.taxonomy import ModelFormat
@@ -49,10 +51,24 @@ def _encoder(packed: bool) -> torch.nn.Module:
return encoder
+# (node class, the field naming its encoder, how the node's encode step is called)
NODES = {
- "z_image": (ZImageTextEncoderInvocation, lambda node, context: node._encode_prompt(context, max_seq_len=512)),
- "flux2_klein": (Flux2KleinTextEncoderInvocation, lambda node, context: node._encode_prompt(context, ExitStack())),
- "anima": (AnimaTextEncoderInvocation, lambda node, context: node._encode_prompt(context)),
+ "z_image": (
+ ZImageTextEncoderInvocation,
+ "qwen3_encoder",
+ lambda node, context: node._encode_prompt(context, max_seq_len=512),
+ ),
+ "flux2_klein": (
+ Flux2KleinTextEncoderInvocation,
+ "qwen3_encoder",
+ lambda node, context: node._encode_prompt(context, ExitStack()),
+ ),
+ "anima": (AnimaTextEncoderInvocation, "qwen3_encoder", lambda node, context: node._encode_prompt(context)),
+ "flux2_dev": (
+ Flux2DevTextEncoderInvocation,
+ "mistral_encoder",
+ lambda node, context: node._encode_prompt(context, ExitStack()),
+ ),
}
@@ -74,7 +90,7 @@ def test_the_node_reserves_the_dequant_transient_and_patches_quantized_encoders_
sidecar: bool,
working_memory: bool,
) -> None:
- invocation_class, encode = NODES[node_name]
+ invocation_class, encoder_field, encode = NODES[node_name]
encoder = _LoadedModel(_encoder(packed))
context = MagicMock()
context.models.load.side_effect = [encoder, _LoadedModel(object())]
@@ -88,7 +104,7 @@ def test_the_node_reserves_the_dequant_transient_and_patches_quantized_encoders_
monkeypatch.setattr(LayerPatcher, "apply_smart_model_patches", stop)
node = invocation_class.model_construct(
prompt="a prompt",
- qwen3_encoder=SimpleNamespace(text_encoder=SimpleNamespace(), tokenizer=SimpleNamespace(), loras=[]),
+ **{encoder_field: SimpleNamespace(text_encoder=SimpleNamespace(), tokenizer=SimpleNamespace(), loras=[])},
mask=None,
max_seq_len=512,
)
diff --git a/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.py b/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.py
index 2d98d94e23..ef21086ea1 100644
--- a/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.py
+++ b/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.py
@@ -1,10 +1,9 @@
"""Loader-level tests for the Mistral encoder's single-file path.
-These drive `_load_text_encoder` on a real, tiny safetensors file, because what they pin is order
-inside the loader: nvfp4 layers have to be decoded before either scaled-fp8 branch reads the side
-channel, with room reserved for the result first. Without the decode both branches hand a packed
-weight to `load_state_dict`. With it only in the dequantizing branch, the branch that keeps fp8 pops the
-block scales first and loads the packed weight anyway -- which is why both branches are exercised.
+These drive `_load_text_encoder` on a real, tiny safetensors file, because what they pin is order inside the loader:
+the nvfp4 layers have to leave the state dict before either scaled-fp8 branch reads the side channel, the config has
+to count them although they left it, and the one reservation has to come before anything widens a weight. Both fp8
+branches are exercised: the one that keeps fp8 pops every block scale, the one that dequantizes folds them.
"""
import json
@@ -20,46 +19,64 @@ from invokeai.backend.model_manager.configs.mistral_encoder import MistralEncode
from invokeai.backend.model_manager.load.model_loaders import mistral_encoder
from invokeai.backend.model_manager.load.model_loaders.mistral_encoder import MistralEncoderCheckpointLoader
from invokeai.backend.model_manager.taxonomy import MistralVariantType
-
-# The loader derives the head count as `q_proj` rows // 128, so this is a one-head model.
-HIDDEN = 128
-INTERMEDIATE = 256
-VOCAB = 32
+from invokeai.backend.quantization.nvfp4 import NVFP4Linear, NVFP4Payload
+
+# The loader derives head counts as projection rows // 128: two query heads over one key/value head, so a config
+# that mixes up the two lookups, or falls back to the cow model's, cannot build this model. Dimensions are multiples
+# of 128 rows and 64 columns, as nvfp4's tile layout needs. VOCAB too, because the LM head is packed.
+HIDDEN = 256
+KV_ROWS = 128
+INTERMEDIATE = 512
+VOCAB = 128
+LAYERS = 2
+# The file carries 32-bit floats, the compute dtype is bf16 as in production.
+COMPUTE_DTYPE = torch.bfloat16
NVFP4_PROJECTIONS = {
"self_attn.q_proj": (HIDDEN, HIDDEN),
- "self_attn.k_proj": (HIDDEN, HIDDEN),
+ "self_attn.k_proj": (KV_ROWS, HIDDEN),
"self_attn.o_proj": (HIDDEN, HIDDEN),
"mlp.gate_proj": (INTERMEDIATE, HIDDEN),
"mlp.up_proj": (INTERMEDIATE, HIDDEN),
"mlp.down_proj": (HIDDEN, INTERMEDIATE),
}
+FP8_PROJECTION = "self_attn.v_proj"
def _marker_blob(marker: dict) -> torch.Tensor:
return torch.frombuffer(bytearray(json.dumps(marker).encode("utf-8")), dtype=torch.uint8)
-def _write_checkpoint(tmp_path: Path, evidence: str) -> tuple[Path, dict[str, torch.Tensor], torch.Tensor]:
- """A Comfy-style fp4_mixed Mistral: nvfp4 projections, one scaled-fp8 projection, bf16 for the rest.
+def _packed_bytes(rows: int, columns: int) -> int:
+ """A layer as stored: two codes per byte, one e4m3 scale per 16 elements, a float32 global scale."""
+ return rows * columns // 2 + rows * (columns // 16) + 4
+
+
+def _write_checkpoint(tmp_path: Path, evidence: str) -> tuple[Path, dict[str, torch.Tensor], dict[int, torch.Tensor]]:
+ """A Comfy-style fp4_mixed Mistral: nvfp4 projections and LM head, one scaled-fp8 projection per layer, full
+ precision for the rest.
The nvfp4 layers are named by per-tensor markers, as in Comfy-Org's build, or -- with `evidence="header"` --
only in the `_quantization_metadata` header, with every key under the `language_model.` wrapper prefix some
redistributions add. The loader strips that prefix from the keys and has to strip it from the header's
- names as well, or it refuses the layers as unnamed.
+ names as well, or it refuses the layers as unnamed. With `evidence="none"` the projections are plain weights.
- Returns the file, the weights the nvfp4 projections must load as, and the fp8 projection's
- dequantized weight. Codes 2 and 10 decode to +1.0 and -1.0, so no E2M1 table is needed here.
+ Returns the file, the weights the projections must compute with, and each layer's dequantized fp8
+ projection. Codes 2 and 10 decode to +1.0 and -1.0, so no E2M1 table is needed here.
"""
torch.manual_seed(0)
prefix = "language_model." if evidence == "header" else ""
tensors: dict[str, torch.Tensor] = {}
expected: dict[str, torch.Tensor] = {}
+ fp8_dequantized: dict[int, torch.Tensor] = {}
header: dict[str, dict[str, str]] = {}
- for name, shape in NVFP4_PROJECTIONS.items():
+
+ def add_projection(path: str, shape: tuple[int, int]) -> torch.Tensor:
positive = torch.randint(0, 2, shape, dtype=torch.bool)
+ if evidence == "none":
+ tensors[f"{path}.weight"] = torch.where(positive, 0.5, -0.5)
+ return tensors[f"{path}.weight"]
codes = torch.where(positive, 2, 10).to(torch.uint8)
- path = f"{prefix}model.layers.0.{name}"
tensors[f"{path}.weight"] = (codes[:, 0::2] << 4) | codes[:, 1::2]
tensors[f"{path}.weight_scale"] = torch.full((shape[0], shape[1] // 16), 2.0).to(torch.float8_e4m3fn)
tensors[f"{path}.weight_scale_2"] = torch.tensor(0.25)
@@ -67,31 +84,56 @@ def _write_checkpoint(tmp_path: Path, evidence: str) -> tuple[Path, dict[str, to
header[path] = {"format": "nvfp4"}
else:
tensors[f"{path}.comfy_quant"] = _marker_blob({"format": "nvfp4"})
- expected[f"layers.0.{name}.weight"] = torch.where(positive, 0.5, -0.5)
+ return torch.where(positive, 0.5, -0.5)
+
+ for layer in range(LAYERS):
+ for name, shape in NVFP4_PROJECTIONS.items():
+ expected[f"layers.{layer}.{name}"] = add_projection(f"{prefix}model.layers.{layer}.{name}", shape)
+
+ fp8_values = torch.randint(-8, 9, (KV_ROWS, HIDDEN)).float()
+ v_proj = f"{prefix}model.layers.{layer}.{FP8_PROJECTION}"
+ tensors[f"{v_proj}.weight"] = fp8_values.to(torch.float8_e4m3fn)
+ tensors[f"{v_proj}.weight_scale"] = torch.tensor(0.5)
+ tensors[f"{v_proj}.comfy_quant"] = _marker_blob({"format": "float8_e4m3fn"})
+ fp8_dequantized[layer] = fp8_values * 0.5
- fp8_values = torch.randint(-8, 9, (HIDDEN, HIDDEN)).float()
- tensors[f"{prefix}model.layers.0.self_attn.v_proj.weight"] = fp8_values.to(torch.float8_e4m3fn)
- tensors[f"{prefix}model.layers.0.self_attn.v_proj.weight_scale"] = torch.tensor(0.5)
- tensors[f"{prefix}model.layers.0.self_attn.v_proj.comfy_quant"] = _marker_blob({"format": "float8_e4m3fn"})
+ for norm in ("input_layernorm", "post_attention_layernorm"):
+ tensors[f"{prefix}model.layers.{layer}.{norm}.weight"] = torch.ones(HIDDEN)
+ # Bare MistralModel has no LM head; a packed one must be dropped, not refused as naming no module.
+ add_projection(f"{prefix}lm_head", (VOCAB, HIDDEN))
tensors[f"{prefix}model.embed_tokens.weight"] = torch.randn(VOCAB, HIDDEN)
- for norm in ("model.layers.0.input_layernorm", "model.layers.0.post_attention_layernorm", "model.norm"):
- tensors[f"{prefix}{norm}.weight"] = torch.ones(HIDDEN)
+ tensors[f"{prefix}model.norm.weight"] = torch.ones(HIDDEN)
tensors["tekken_model"] = torch.randint(0, 256, (64,), dtype=torch.uint8)
checkpoint = tmp_path / "mistral_3_small_flux2_fp4_mixed.safetensors"
metadata = {"_quantization_metadata": json.dumps({"layers": header})} if header else None
save_file(tensors, checkpoint, metadata=metadata)
- return checkpoint, expected, fp8_values * 0.5
+ return checkpoint, expected, fp8_dequantized
-def _loader(monkeypatch: pytest.MonkeyPatch, keep_fp8: bool) -> MistralEncoderCheckpointLoader:
+def _loader(monkeypatch: pytest.MonkeyPatch, keep_fp8: bool) -> tuple[MistralEncoderCheckpointLoader, list[str]]:
+ """The loader, and a log of the steps that widen weights, each recorded with whether room was made first."""
monkeypatch.setattr(mistral_encoder.TorchDevice, "choose_torch_device", lambda: torch.device("cpu"))
- monkeypatch.setattr(mistral_encoder.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: torch.float32)
+ monkeypatch.setattr(mistral_encoder.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: COMPUTE_DTYPE)
monkeypatch.setattr(mistral_encoder, "should_keep_fp8_weights", lambda _device: keep_fp8)
loader = object.__new__(MistralEncoderCheckpointLoader)
loader._ram_cache = SimpleNamespace(make_room=MagicMock())
- return loader
+
+ widening: list[str] = []
+ for name in ("_drop_quantization_metadata", "split_fp8_scaled_layers"):
+ original = getattr(mistral_encoder, name)
+
+ def recording(*args, _name=name, _original=original, **kwargs):
+ widening.append(f"{_name}, reserved={loader._ram_cache.make_room.called}")
+ return _original(*args, **kwargs)
+
+ monkeypatch.setattr(mistral_encoder, name, recording)
+ return loader, widening
+
+
+def _config(checkpoint: Path) -> MistralEncoder_Checkpoint_Config:
+ return MistralEncoder_Checkpoint_Config.model_construct(path=str(checkpoint), variant=MistralVariantType.Cow)
@pytest.mark.parametrize(
@@ -99,24 +141,86 @@ def _loader(monkeypatch: pytest.MonkeyPatch, keep_fp8: bool) -> MistralEncoderCh
[(False, "marker"), (True, "marker"), (False, "header")],
ids=["fp8_dequantized", "fp8_kept", "named_in_prefixed_header"],
)
-def test_an_nvfp4_mixed_checkpoint_loads_under_either_fp8_branch(
+def test_an_nvfp4_mixed_checkpoint_keeps_its_nvfp4_layers_packed_under_either_fp8_branch(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, keep_fp8: bool, evidence: str
) -> None:
checkpoint, expected, fp8_dequantized = _write_checkpoint(tmp_path, evidence)
- loader = _loader(monkeypatch, keep_fp8)
- config = MistralEncoder_Checkpoint_Config.model_construct(path=str(checkpoint), variant=MistralVariantType.Cow)
-
- model = loader._load_text_encoder(config)
-
- for name, weight in expected.items():
- assert torch.equal(model.get_parameter(name), weight), name
- v_proj = model.layers[0].self_attn.v_proj
- if keep_fp8:
- assert v_proj.weight.dtype is torch.float8_e4m3fn
- assert torch.equal(v_proj.weight.float() * v_proj.weight_scale, fp8_dequantized)
- else:
- assert torch.equal(v_proj.weight, fp8_dequantized)
- # The base loader reserved only the file size; the decode has to ask for its float32 result.
+ loader, widening = _loader(monkeypatch, keep_fp8)
+
+ model = loader._load_text_encoder(_config(checkpoint))
+
+ assert len(model.layers) == LAYERS
+ assert (model.config.num_attention_heads, model.config.num_key_value_heads) == (2, 1)
+ for path, weight in expected.items():
+ module = model.get_submodule(path)
+ assert isinstance(module, NVFP4Linear), path
+ assert module.weight.dtype is torch.uint8, path
+ # Installed after the cast, which would otherwise round the global scale to the compute dtype.
+ assert module.weight_scale_2.dtype is torch.float32, path
+ x = torch.randn(3, module.in_features, dtype=COMPUTE_DTYPE)
+ torch.testing.assert_close(module(x), x @ weight.to(COMPUTE_DTYPE).T)
+ for layer, weight in fp8_dequantized.items():
+ v_proj = model.layers[layer].self_attn.v_proj
+ if keep_fp8:
+ assert v_proj.weight.dtype is torch.float8_e4m3fn
+ assert torch.equal(v_proj.weight.float() * v_proj.weight_scale, weight)
+ else:
+ assert torch.equal(v_proj.weight, weight.to(COMPUTE_DTYPE))
+ assert all(step.endswith("reserved=True") for step in widening), widening
+
+ # One reservation for what the state dict ends up holding: the nvfp4 layers packed (the LM head not at all), the
+ # fp8 weights at one byte where the keep branch holds them and at the compute dtype where they are dequantized,
+ # full precision at the compute dtype. Scale scalars and markers aside, which is what the tolerance is for.
+ packed = LAYERS * sum(_packed_bytes(*shape) for shape in NVFP4_PROJECTIONS.values())
+ fp8_elements = LAYERS * KV_ROWS * HIDDEN
+ full_precision_elements = VOCAB * HIDDEN + (2 * LAYERS + 1) * HIDDEN
+ expected_bytes = (
+ packed
+ + fp8_elements * (1 if keep_fp8 else COMPUTE_DTYPE.itemsize)
+ + full_precision_elements * COMPUTE_DTYPE.itemsize
+ + 64 # tekken_model
+ )
(reserved,), _ = loader._ram_cache.make_room.call_args
assert loader._ram_cache.make_room.call_count == 1
- assert reserved >= sum(rows * columns * 4 for rows, columns in NVFP4_PROJECTIONS.values())
+ assert abs(reserved - expected_bytes) < 1024, (reserved, expected_bytes)
+
+
+def test_a_checkpoint_without_nvfp4_layers_loads_as_before(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ checkpoint, expected, _ = _write_checkpoint(tmp_path, evidence="none")
+ loader, widening = _loader(monkeypatch, keep_fp8=False)
+
+ model = loader._load_text_encoder(_config(checkpoint))
+
+ for path, weight in expected.items():
+ module = model.get_submodule(path)
+ assert type(module) is torch.nn.Linear, path
+ assert torch.equal(module.weight, weight.to(COMPUTE_DTYPE)), path
+ assert loader._ram_cache.make_room.call_count == 1
+ assert all(step.endswith("reserved=True") for step in widening), widening
+
+
+def test_the_config_reads_layer_and_head_counts_through_packed_projections() -> None:
+ """A 40-layer encoder whose query and MLP projections left the state dict packed, with widths that differ from
+ the cow model's defaults: every count has to come from the payloads or from the dense key projections."""
+
+ def meta(*shape: int, dtype: torch.dtype = torch.float32) -> torch.Tensor:
+ return torch.empty(shape, dtype=dtype, device="meta")
+
+ def payload(rows: int, columns: int) -> NVFP4Payload:
+ return NVFP4Payload(
+ weight=meta(rows, columns // 2, dtype=torch.uint8),
+ weight_scale=meta(rows, columns // 16, dtype=torch.float8_e4m3fn),
+ weight_scale_2=meta(),
+ )
+
+ state_dict: dict[str, torch.Tensor] = {"model.embed_tokens.weight": meta(1024, 5120)}
+ packed: dict[str, NVFP4Payload] = {}
+ for layer in range(40):
+ packed[f"model.layers.{layer}.self_attn.q_proj"] = payload(5120, 5120)
+ packed[f"model.layers.{layer}.mlp.gate_proj"] = payload(16384, 5120)
+ state_dict[f"model.layers.{layer}.self_attn.k_proj.weight"] = meta(2048, 5120, dtype=torch.float8_e4m3fn)
+
+ config = mistral_encoder._build_mistral_config(state_dict, torch.bfloat16, packed_layers=packed)
+
+ assert (config.num_hidden_layers, config.num_attention_heads, config.num_key_value_heads) == (40, 40, 16)
+ assert config.intermediate_size == 16384
diff --git a/tests/backend/quantization/test_nvfp4.py b/tests/backend/quantization/test_nvfp4.py
index 766e8bfdae..e181b6a162 100644
--- a/tests/backend/quantization/test_nvfp4.py
+++ b/tests/backend/quantization/test_nvfp4.py
@@ -25,7 +25,6 @@ from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
from invokeai.backend.quantization.dequantizing_linear import peak_dequant_transient_bytes, requires_sidecar_patching
from invokeai.backend.quantization.nvfp4 import (
NVFP4Linear,
- dequantize_nvfp4_layers,
dequantize_nvfp4_weight,
install_nvfp4_layers,
pop_nvfp4_layers,
@@ -36,8 +35,6 @@ from invokeai.backend.quantization.nvfp4 import (
FIXTURE = Path(__file__).parent / "data" / "z_image_turbo_nvfp4_slices.safetensors"
-E2M1 = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0])
-
def _marker_blob(marker: dict) -> torch.Tensor:
return torch.frombuffer(bytearray(json.dumps(marker).encode("utf-8")), dtype=torch.uint8)
@@ -140,47 +137,20 @@ def test_a_real_checkpoint_slice_decodes_to_its_bf16_build(layer: str) -> None:
assert torch.equal(module(x), torch.nn.functional.linear(x, decoded.view(128, 128)))
[email protected]("dtype", [torch.float32, torch.bfloat16])
-def test_only_nvfp4_layers_are_decoded_and_the_rest_is_left_for_the_fp8_path(dtype: torch.dtype) -> None:
- torch.manual_seed(0)
- codes = torch.randint(0, 16, (128, 64), dtype=torch.uint8)
+def test_popped_layers_keep_their_tensors_as_stored_and_leave_the_rest_for_the_fp8_path() -> None:
fp8_weight = torch.randn(32, 32).to(torch.float8_e4m3fn)
fp8_scale = torch.tensor(0.5)
fp8_marker = _marker_blob({"format": "float8_e4m3fn"})
- dense = torch.randn(8)
tekken = torch.randint(0, 256, (64,), dtype=torch.uint8)
sd = {
- **_nvfp4_tensors("blocks.0.mlp", codes, block_scale=2.0, global_scale=0.25),
+ **_zero_layer("blocks.0.mlp"),
"blocks.0.mlp.input_scale": torch.tensor(1.0),
+ "blocks.0.mlp.bias": torch.zeros(128),
"blocks.0.attn.weight": fp8_weight,
"blocks.0.attn.weight_scale": fp8_scale,
"blocks.0.attn.comfy_quant": fp8_marker,
- "blocks.0.norm.weight": dense,
"tekken_model": tekken,
}
-
- assert dequantize_nvfp4_layers(sd, dtype) == 1
-
- assert sd["blocks.0.mlp.weight"].dtype is dtype
- assert torch.equal(sd["blocks.0.mlp.weight"], (E2M1[codes.long()] * 0.5).to(dtype))
- assert [k for k in sd if k.startswith("blocks.0.mlp.")] == ["blocks.0.mlp.weight"]
- # The scaled-fp8 layer, its scale and its marker belong to the fp8 path.
- assert sd["blocks.0.attn.weight"] is fp8_weight
- assert sd["blocks.0.attn.weight_scale"] is fp8_scale
- assert sd["blocks.0.attn.comfy_quant"] is fp8_marker
- assert sd["blocks.0.norm.weight"] is dense
- assert sd["tekken_model"] is tekken
-
-
-def test_popped_layers_keep_their_tensors_as_stored_and_leave_the_rest_in_place() -> None:
- fp8_weight = torch.randn(32, 32).to(torch.float8_e4m3fn)
- sd = {
- **_zero_layer("blocks.0.mlp"),
- "blocks.0.mlp.input_scale": torch.tensor(1.0),
- "blocks.0.mlp.bias": torch.zeros(128),
- "blocks.0.attn.weight": fp8_weight,
- "blocks.0.attn.weight_scale": torch.tensor(0.5),
- }
weight, scale = sd["blocks.0.mlp.weight"], sd["blocks.0.mlp.weight_scale"]
payloads = pop_nvfp4_layers(sd)
@@ -189,7 +159,18 @@ def test_popped_layers_keep_their_tensors_as_stored_and_leave_the_rest_in_place(
assert payloads["blocks.0.mlp"].weight is weight
assert payloads["blocks.0.mlp"].weight_scale is scale
# The bias is an ordinary tensor the loader casts; everything else of the layer is gone.
- assert sorted(sd) == ["blocks.0.attn.weight", "blocks.0.attn.weight_scale", "blocks.0.mlp.bias"]
+ assert sorted(sd) == [
+ "blocks.0.attn.comfy_quant",
+ "blocks.0.attn.weight",
+ "blocks.0.attn.weight_scale",
+ "blocks.0.mlp.bias",
+ "tekken_model",
+ ]
+ # The scaled-fp8 layer, its scale and its marker belong to the fp8 path.
+ assert sd["blocks.0.attn.weight"] is fp8_weight
+ assert sd["blocks.0.attn.weight_scale"] is fp8_scale
+ assert sd["blocks.0.attn.comfy_quant"] is fp8_marker
+ assert sd["tekken_model"] is tekken
def test_a_layer_only_the_safetensors_header_names_is_read() -> None:
@@ -197,7 +178,7 @@ def test_a_layer_only_the_safetensors_header_names_is_read() -> None:
sd = _zero_layer("layer")
del sd["layer.comfy_quant"]
- assert dequantize_nvfp4_layers(sd, torch.float32, header_layers={"layer": {"format": "nvfp4"}}) == 1
+ assert list(pop_nvfp4_layers(sd, header_layers={"layer": {"format": "nvfp4"}})) == ["layer"]
def test_a_layer_nothing_names_as_nvfp4_is_refused_rather_than_read_by_comfy_conventions() -> None:
@@ -211,32 +192,12 @@ def test_a_layer_nothing_names_as_nvfp4_is_refused_rather_than_read_by_comfy_con
assert "layer.weight" in sd
-def test_room_for_the_decoded_state_dict_is_reserved_before_any_layer_is_widened() -> None:
- sd = {**_zero_layer("layer", rows=256), "layer.input_scale": torch.tensor(1.0), "norm.weight": torch.zeros(10)}
- reservations: list[tuple[int, torch.dtype]] = []
-
- dequantize_nvfp4_layers(
- sd, torch.bfloat16, reserve=lambda size: reservations.append((size, sd["layer.weight"].dtype))
- )
-
- # The decoded [256, 64] weight at two bytes per element plus the untouched float32 norm; the packed
- # payload and the side channel are gone by then. Still uint8 when asked: nothing was widened yet.
- assert reservations == [(256 * 64 * 2 + 10 * 4, torch.uint8)]
-
-
-def test_nothing_is_reserved_for_a_checkpoint_without_nvfp4_layers() -> None:
- reservations: list[int] = []
-
- assert dequantize_nvfp4_layers({"norm.weight": torch.zeros(10)}, torch.bfloat16, reserve=reservations.append) == 0
- assert reservations == []
-
-
-def test_an_awq_checkpoint_is_refused_before_anything_is_decoded() -> None:
+def test_an_awq_checkpoint_is_refused_before_anything_is_taken_out() -> None:
sd = {**_zero_layer("layer"), "layer.pre_quant_scale": torch.ones(64)}
with pytest.raises(ValueError, match="AWQ"):
- dequantize_nvfp4_layers(sd, torch.float32)
- assert sd["layer.weight"].dtype is torch.uint8
+ pop_nvfp4_layers(sd)
+ assert "layer.weight" in sd
def test_a_packed_weight_without_its_global_scale_is_refused() -> None:
@@ -244,7 +205,7 @@ def test_a_packed_weight_without_its_global_scale_is_refused() -> None:
del sd["layer.weight_scale_2"], sd["layer.comfy_quant"]
with pytest.raises(ValueError, match="with a weight_scale but no weight_scale_2"):
- dequantize_nvfp4_layers(sd, torch.float32)
+ pop_nvfp4_layers(sd)
@pytest.mark.parametrize("missing", ["weight", "weight_scale"])
@@ -253,7 +214,7 @@ def test_a_global_scale_without_its_layer_is_refused_naming_it(missing: str) ->
del sd[f"layer.{missing}"]
with pytest.raises(ValueError, match=f"nvfp4 layer 'layer': has a weight_scale_2 but no {missing}$"):
- dequantize_nvfp4_layers(sd, torch.float32)
+ pop_nvfp4_layers(sd)
def test_a_global_scale_on_a_dense_weight_is_refused() -> None:
@@ -261,18 +222,16 @@ def test_a_global_scale_on_a_dense_weight_is_refused() -> None:
sd["layer.weight"] = torch.zeros(128, 64)
with pytest.raises(ValueError, match="nvfp4 layer 'layer': expected a packed uint8"):
- dequantize_nvfp4_layers(sd, torch.float32)
+ pop_nvfp4_layers(sd)
-def test_a_malformed_layer_is_refused_before_any_layer_is_decoded_or_reserved() -> None:
+def test_a_malformed_layer_is_refused_before_any_layer_is_taken_out() -> None:
sd = {**_zero_layer("a"), **_zero_layer("b")}
sd["b.weight_scale"] = torch.ones(128, 8).to(torch.float8_e4m3fn)
- reservations: list[int] = []
with pytest.raises(ValueError, match="nvfp4 layer 'b': .* does not describe"):
- dequantize_nvfp4_layers(sd, torch.float32, reserve=reservations.append)
- assert sd["a.weight"].dtype is torch.uint8
- assert reservations == []
+ pop_nvfp4_layers(sd)
+ assert "a.weight" in sd
@pytest.mark.parametrize(
@@ -287,7 +246,7 @@ def test_a_marker_that_contradicts_its_tensors_is_refused(tensors: str, marker:
sd["layer.comfy_quant"] = _marker_blob(marker)
with pytest.raises(ValueError, match=message):
- dequantize_nvfp4_layers(sd, torch.float32)
+ pop_nvfp4_layers(sd)
@pytest.mark.parametrize(