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.

18.7 KB
Raw Blame
"""SDNQ State Dict Loader - loads SDNQ quantized safetensors files."""

import gc
import json
import logging
from collections.abc import Iterable
from pathlib import Path
from typing import Any, Union

import torch
from safetensors.torch import load_file

from invokeai.backend.quantization.sdnq.sdnq_tensor import SDNQTensor
from invokeai.backend.quantization.sdnq.utils import SDNQQuantizationType
from invokeai.backend.util.state_dict_loading import log_unexpected_keys

logger = logging.getLogger(__name__)


def raise_on_incomplete_sdnq_load(
    model_name: str,
    missing_keys: Iterable[str],
    unexpected_keys: Iterable[str],
    allowed_missing: Iterable[str] = (),
) -> None:
    """Fail fast when ``load_state_dict(..., strict=False)`` left an SDNQ model incomplete.

    ``load_state_dict`` with ``strict=False`` silently ignores the missing/unexpected key lists.
    For SDNQ folder loads a missing key is dangerous: a partial export, missing shard key or
    architecture mismatch leaves required parameters on the meta device and returns a model that
    fails much later during device movement or inference, far from the real cause. This raises with
    the offending keys instead.

    Unexpected keys are *not* an error - they are exporter noise rather than a correctness signal,
    so they are logged at DEBUG and ignored (see ``log_unexpected_keys``).

    Args:
        model_name: Human-readable name for the error message (e.g. "SDNQ Z-Image transformer").
        missing_keys: The ``missing_keys`` returned by ``load_state_dict``.
        unexpected_keys: The ``unexpected_keys`` returned by ``load_state_dict``; logged, not fatal.
        allowed_missing: Keys that are expected to be absent (e.g. tied weights the caller re-shares
            after load), which must not trigger a failure.
    """
    allowed = set(allowed_missing)
    real_missing = [k for k in missing_keys if k not in allowed]
    log_unexpected_keys(model_name, unexpected_keys)
    if real_missing:
        raise ValueError(f"Missing keys loading {model_name} (required parameters left on meta): {real_missing}")


def cast_unpacked_floats(state_dict: dict[str, Union[SDNQTensor, torch.Tensor]], dtype: torch.dtype) -> None:
    """Cast the floating-point tensors that are not packed (norms, biases, unquantized layers) to ``dtype``, in place.

    ``sdnq_sd_loader`` keeps them in the dtype on disk, while the packed weights dequantize to its ``compute_dtype``.
    A module that does not cast its input, such as a group norm, then meets an input of the compute dtype and a
    parameter of another one. ``from_pretrained(torch_dtype=...)`` makes the same cast for an ordinary model, but only
    where the model declares no ``_keep_in_fp32_modules``: such a model (T5, several transformers) needs those modules
    left wider, so this suits the VAEs, not every SDNQ load.
    """
    for key, value in state_dict.items():
        if not isinstance(value, SDNQTensor) and value.is_floating_point() and value.dtype != dtype:
            state_dict[key] = value.to(dtype)


def _parse_quantization_config(config_path: Path) -> dict[str, Any]:
    """Parse quantization_config.json for SDNQ parameters."""
    if not config_path.exists():
        return {}

    with open(config_path, "r", encoding="utf-8") as f:
        return json.load(f)


_DTYPE_NAME_TO_QUANT_TYPE = {
    "uint4": SDNQQuantizationType.UINT4_ASYM,
    "int4": SDNQQuantizationType.UINT4_ASYM,  # signed naming, same packed storage
    "uint5": SDNQQuantizationType.INT5_ASYM,
    "int5": SDNQQuantizationType.INT5_ASYM,  # SDNQ dynamic-mixed uses this label
    "int8": SDNQQuantizationType.INT8_SYM,
    "uint8": SDNQQuantizationType.UINT8_SYM,
}


def _infer_quantization_type(
    weight_dtype: torch.dtype,
    has_zero_point: bool,
    config: dict[str, Any],
    weight: torch.Tensor | None = None,
    scale: torch.Tensor | None = None,
    tensor_name: str | None = None,
    per_tensor_dtype: str | None = None,
) -> SDNQQuantizationType:
    """Infer quantization type from weight dtype and config.

    Dynamic-mixed-precision SDNQ models use ``modules_dtype_dict`` to record per-tensor dtypes
    (e.g. some layers uint4, others int5). ``per_tensor_dtype`` is the resolved label for this
    tensor; when provided it takes precedence over the global ``weights_dtype``.
    """
    # Per-tensor override (dynamic mixed precision)
    if per_tensor_dtype:
        mapped = _DTYPE_NAME_TO_QUANT_TYPE.get(per_tensor_dtype)
        if mapped is not None:
            # Asymmetric vs symmetric: int8/uint8 follow has_zero_point; everything else is asym.
            if mapped == SDNQQuantizationType.INT8_SYM and has_zero_point:
                return SDNQQuantizationType.INT8_ASYM
            if mapped == SDNQQuantizationType.UINT8_SYM and has_zero_point:
                return SDNQQuantizationType.UINT8_ASYM
            return mapped

    # Check config for weights_dtype (SDNQ style; static-quantization fallback)
    weights_dtype = config.get("weights_dtype", "")
    if weights_dtype == "uint4":
        return SDNQQuantizationType.UINT4_ASYM
    if weights_dtype == "uint5" or weights_dtype == "int5":
        return SDNQQuantizationType.INT5_ASYM

    # Check config for quant_type
    if "quant_type" in config:
        return SDNQQuantizationType(config["quant_type"])

    # Try to detect uint4 from shapes:
    # uint4 is packed as 2 values per uint8, so if scale suggests a shape that's
    # 2x the weight's last dimension, it's likely uint4
    if weight is not None and scale is not None and weight_dtype == torch.uint8:
        if len(weight.shape) == 2 and len(scale.shape) >= 2:
            # For per-group quantization: scale shape [out, num_groups, 1] or [out, num_groups]
            # weight shape [out, in/2] for uint4
            # Check if scale's out_features matches weight's out_features
            # and if num_groups * group_size would be 2x weight's in_features
            out_features = weight.shape[0]
            packed_in = weight.shape[1]
            scale_out = scale.shape[0]
            num_groups = scale.shape[1]

            if scale_out == out_features and num_groups > 0:
                # If we can infer that unpacked shape would be 2x packed, it's uint4
                # For typical group sizes (32, 64, 128), num_groups * group_size = in_features
                # If packed_in * 2 can be divided by num_groups, it's likely uint4
                unpacked_in = packed_in * 2
                if unpacked_in % num_groups == 0:
                    inferred_group_size = unpacked_in // num_groups
                    if inferred_group_size in (32, 64, 128, 256):
                        return SDNQQuantizationType.UINT4_ASYM

    # Infer from dtype
    if weight_dtype == torch.int8:
        return SDNQQuantizationType.INT8_ASYM if has_zero_point else SDNQQuantizationType.INT8_SYM
    elif weight_dtype == torch.uint8:
        return SDNQQuantizationType.UINT8_ASYM if has_zero_point else SDNQQuantizationType.UINT8_SYM
    elif weight_dtype in (torch.float8_e4m3fn, torch.float8_e4m3fnuz):
        return SDNQQuantizationType.FP8_E4M3
    elif weight_dtype in (torch.float8_e5m2, torch.float8_e5m2fnuz):
        return SDNQQuantizationType.FP8_E5M2

    # Default to symmetric int8
    return SDNQQuantizationType.INT8_SYM


def _get_original_shape(
    weight: torch.Tensor,
    config: dict[str, Any],
    tensor_name: str,
    quant_type: SDNQQuantizationType,
    scale: torch.Tensor | None = None,
    group_size: int = 128,
) -> torch.Size:
    """Determine the original tensor shape before quantization."""
    # Check if shape is stored in config
    if "shapes" in config and tensor_name in config["shapes"]:
        return torch.Size(config["shapes"][tensor_name])

    # For uint4 packed weights with per-group quantization. The packed size is the
    # authoritative source for in_features: scale's num_groups × the passed-in group_size can
    # be wrong if group_size was not actually known (e.g. Klein 4B uses group_size=64 for some
    # to_out layers while others use 128).
    if quant_type == SDNQQuantizationType.UINT4_ASYM:
        if scale is not None and scale.shape and scale.shape[0] > 0:
            out_features = scale.shape[0]
            # uint4 packs 2 values per byte; total unpacked = numel * 2 regardless of 1D/2D layout.
            total_elements = weight.numel() * 2
            if total_elements % out_features == 0:
                in_features = total_elements // out_features
                return torch.Size([out_features, in_features])

        # Fallback for 2D packed weights without usable scale info.
        if len(weight.shape) == 2:
            return torch.Size([weight.shape[0], weight.shape[1] * 2])

        # Final fallback for 1D.
        if len(weight.shape) == 1:
            return torch.Size([weight.numel() * 2])

    # For uint5 packed weights with per-group quantization. SDNQ stores uint5 as 2D with last
    # dim = 5 (8 unpacked values per 5 bytes). Same authoritative-packed-size logic.
    if quant_type == SDNQQuantizationType.INT5_ASYM:
        total_elements = weight.numel() * 8 // 5
        if scale is not None and scale.shape and scale.shape[0] > 0:
            out_features = scale.shape[0]
            if total_elements % out_features == 0:
                return torch.Size([out_features, total_elements // out_features])
        # Fallback when there's no scale: trust the 2D packed layout.
        if len(weight.shape) == 2 and weight.shape[-1] == 5:
            return torch.Size([total_elements])

    # Quantized tensors usually keep the same shape
    return weight.shape


def sdnq_sd_loader(
    model_path: Path,
    compute_dtype: torch.dtype = torch.bfloat16,
) -> dict[str, Union[SDNQTensor, torch.Tensor]]:
    """Load SDNQ quantized safetensors files.

    SDNQ stores quantized weights with associated scale, zero_point (optional),
    and SVD correction matrices (optional). This loader creates SDNQTensor
    wrappers that provide on-the-fly dequantization.

    Args:
        model_path: Path to safetensors file or directory containing model files.
        compute_dtype: Dtype for dequantized computation (default: bfloat16).

    Returns:
        State dict with SDNQTensor wrappers for quantized weights and
        regular tensors for non-quantized weights.
    """
    # Determine which safetensors file(s) hold the weights. For larger models (FLUX.2 Klein 9B,
    # FLUX.2 dev, ...) the transformer is sharded across multiple ``*-NNNNN-of-MMMMM.safetensors``
    # files; we merge all of them into one state_dict before grouping.
    if model_path.is_dir():
        safetensors_files = sorted(model_path.glob("*.safetensors"))
        if not safetensors_files:
            raise ValueError(f"No safetensors files found in {model_path}")
        config_path = model_path / "quantization_config.json"
    else:
        safetensors_files = [model_path]
        config_path = model_path.parent / "quantization_config.json"

    # Load quantization config if available
    quant_config = _parse_quantization_config(config_path)

    # Get group_size from config (default: 128 for SDNQ)
    # Note: group_size=0 in config means per-tensor quantization or it needs to be inferred
    config_group_size = quant_config.get("group_size", 128)

    # Build a reverse map for dynamic-mixed-precision models. SDNQ stores
    # ``modules_dtype_dict`` as ``{dtype_name: [list of layer keys]}``; we flip it to
    # ``{layer_key: dtype_name}`` for O(1) lookup during the per-tensor type inference.
    per_tensor_dtype_map: dict[str, str] = {}
    modules_dtype_dict = quant_config.get("modules_dtype_dict") or {}
    if isinstance(modules_dtype_dict, dict):
        for dtype_name, layer_keys in modules_dtype_dict.items():
            if isinstance(layer_keys, list):
                for layer_key in layer_keys:
                    per_tensor_dtype_map[layer_key] = dtype_name

    # Load and merge all safetensors shards.
    raw_sd: dict[str, torch.Tensor] = {}
    for shard in safetensors_files:
        shard_sd = load_file(shard)
        # Detect accidental key collisions between shards — would indicate a corrupted bundle.
        overlap = set(shard_sd).intersection(raw_sd)
        if overlap:
            raise ValueError(f"Duplicate keys across SDNQ shards (model={model_path}): {sorted(overlap)[:3]}")
        raw_sd.update(shard_sd)

    # Group related tensors (weight, scale, zero_point, svd_up, svd_down)
    sd: dict[str, Union[SDNQTensor, torch.Tensor]] = {}
    processed_keys: set[str] = set()

    for key in raw_sd.keys():
        if key in processed_keys:
            continue

        # Check if this is a base weight tensor
        if key.endswith(".weight"):
            base_key = key[:-7]  # Remove ".weight"

            weight = raw_sd[key]
            scale_key = f"{base_key}.scale"
            zero_point_key = f"{base_key}.zero_point"
            svd_up_key = f"{base_key}.svd_up"
            svd_down_key = f"{base_key}.svd_down"

            # Check if this is a quantized tensor (has scale)
            if scale_key in raw_sd:
                scale = raw_sd[scale_key]
                zero_point = raw_sd.get(zero_point_key)
                svd_up = raw_sd.get(svd_up_key)
                svd_down = raw_sd.get(svd_down_key)

                # Determine quantization type. For dynamic-mixed-precision models, look up the
                # per-tensor dtype in the reverse map we built from ``modules_dtype_dict``.
                quant_type = _infer_quantization_type(
                    weight.dtype,
                    zero_point is not None,
                    quant_config,
                    weight=weight,
                    scale=scale,
                    tensor_name=key,
                    per_tensor_dtype=per_tensor_dtype_map.get(key),
                )

                # Determine original shape (need quant_type and scale to handle uint4 packing).
                # For the per-group uint4/int5 types this derives in_features from the packed byte
                # count, so it does not depend on group_size.
                original_shape = _get_original_shape(
                    weight, quant_config, key, quant_type, scale=scale, group_size=config_group_size or 128
                )

                # Determine group_size for this tensor.
                #
                # The scale tensor's group dimension is authoritative and takes precedence over the
                # nominal ``group_size`` from quantization_config.json. SDNQ dynamic-mixed-precision
                # models (e.g. FLUX.2 Klein 4B) quantize some layers with a group size that differs
                # from the global config value, so trusting ``config_group_size`` whenever it is > 0
                # can yield a group size that disagrees with scale.shape[1]. That mismatch makes
                # ``num_groups = in_features // group_size`` wrong and breaks the reshape/broadcast
                # in dequantize_uint4_per_group / dequantize_int5_per_group. We therefore derive the
                # per-tensor group size from ``in_features / num_groups`` whenever the scale exposes a
                # usable group dimension, and only fall back to the config value (then the SDNQ
                # default of 128) when it doesn't.
                tensor_group_size: int | None = None
                if len(original_shape) == 2 and len(scale.shape) >= 2 and scale.shape[1] > 0:
                    _, in_features = original_shape
                    num_groups = scale.shape[1]
                    if in_features % num_groups == 0:
                        tensor_group_size = in_features // num_groups
                if tensor_group_size is None:
                    tensor_group_size = config_group_size if config_group_size > 0 else 128

                # Log quantization info for debugging
                logger.debug(
                    f"SDNQ: {key} - type={quant_type.value}, weight_shape={weight.shape}, "
                    f"weight_dtype={weight.dtype}, scale_shape={scale.shape}, "
                    f"original_shape={original_shape}, group_size={tensor_group_size}"
                )

                # Create SDNQTensor
                sd[key] = SDNQTensor(
                    data=weight,
                    quantization_type=quant_type,
                    tensor_shape=original_shape,
                    compute_dtype=compute_dtype,
                    scale=scale,
                    zero_point=zero_point,
                    svd_up=svd_up,
                    svd_down=svd_down,
                    group_size=tensor_group_size
                    if quant_type in (SDNQQuantizationType.UINT4_ASYM, SDNQQuantizationType.INT5_ASYM)
                    else None,
                )

                # Mark related keys as processed
                processed_keys.add(key)
                processed_keys.add(scale_key)
                if zero_point is not None:
                    processed_keys.add(zero_point_key)
                if svd_up is not None:
                    processed_keys.add(svd_up_key)
                if svd_down is not None:
                    processed_keys.add(svd_down_key)
            else:
                # Regular tensor, not quantized
                sd[key] = weight
                processed_keys.add(key)

        elif key.endswith((".scale", ".zero_point", ".svd_up", ".svd_down")):
            # Skip - these are handled with their parent weight tensor
            continue

        else:
            # Other tensors (biases, norms, etc.) - copy as-is
            sd[key] = raw_sd[key]
            processed_keys.add(key)

    # Log summary
    sdnq_count = sum(1 for v in sd.values() if isinstance(v, SDNQTensor))
    regular_count = len(sd) - sdnq_count
    source_desc = (
        str(safetensors_files[0]) if len(safetensors_files) == 1 else f"{len(safetensors_files)} shards in {model_path}"
    )
    # Logged, not printed: stdout bypasses the app's log level, format and handlers, and this line
    # already went to the logger on the next call anyway.
    logger.info(f"SDNQ loader: {sdnq_count} quantized tensors, {regular_count} regular tensors from {source_desc}")

    gc.collect()
    return sd


def has_sdnq_tensors(state_dict: dict[str, Any]) -> bool:
    """Check if state dict contains SDNQTensor instances."""
    return any(isinstance(v, SDNQTensor) for v in state_dict.values())


def has_sdnq_keys(state_dict: dict[str, Any]) -> bool:
    """Check if state dict has SDNQ-style keys (weight + scale pairs).

    SDNQ quantized models store weights with associated scale tensors.
    This function detects this pattern to identify SDNQ models.

    Args:
        state_dict: State dict to check.

    Returns:
        True if state dict has SDNQ-style key patterns.
    """
    keys = {k for k in state_dict.keys() if isinstance(k, str)}
    for key in keys:
        if key.endswith(".weight"):
            base = key[:-7]
            if f"{base}.scale" in keys:
                return True
    return False