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.

fix(fp8): recover the weight scales the loaders were silently dropping

Alexander Eichhorn21b39ab0af97
diff --git a/invokeai/app/services/config/config_default.py b/invokeai/app/services/config/config_default.py
index 99e6a7b375..a0f32e1560 100644
--- a/invokeai/app/services/config/config_default.py
+++ b/invokeai/app/services/config/config_default.py
@@ -106,7 +106,7 @@ class InvokeAIAppConfig(BaseSettings):
device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.
enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.
keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.
- fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU; falls back automatically otherwise). Roughly halves the transformer's VRAM and speeds up denoising, but quantizes activations as well, so images will differ from previous versions at the same seed.
+ fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU; falls back automatically otherwise). Roughly halves the transformer's VRAM and speeds up denoising, but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).
fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.
ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.
vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.
diff --git a/invokeai/backend/model_manager/load/model_loaders/anima.py b/invokeai/backend/model_manager/load/model_loaders/anima.py
index fb149c03b2..c5cf39ce5e 100644
--- a/invokeai/backend/model_manager/load/model_loaders/anima.py
+++ b/invokeai/backend/model_manager/load/model_loaders/anima.py
@@ -2,7 +2,7 @@
"""Class for Anima model loading in InvokeAI."""
from pathlib import Path
-from typing import Any, Optional
+from typing import Optional
import accelerate
@@ -31,6 +31,7 @@ from invokeai.backend.quantization.fp8_scaled import (
read_safetensors_metadata,
should_keep_fp8_weights,
split_fp8_scaled_layers,
+ strip_layer_path_prefix,
warn_on_unattached_scales,
)
from invokeai.backend.util.devices import TorchDevice
@@ -81,19 +82,6 @@ _NON_MODEL_KEY_SUFFIXES = (
_NON_MODEL_KEY_PREFIXES = ("model_sampling.",)
-def _strip_anima_prefix_from_layer_paths(layer_names: Any) -> dict[str, str]:
- """Map checkpoint-scheme layer names to the paths the module tree actually uses.
-
- `_quantization_metadata` names its layers in the checkpoint's own scheme -- `net.`-prefixed on
- every Anima redistribution measured -- while the scales are read after `_strip_anima_bundle_prefix`
- has run. Without this the per-layer flags, `full_precision_matrix_mult` above all, match nothing
- and are silently ignored. Rather than restating the prefix list, the names are pushed through
- the real strip function and read back.
- """
- stripped = _strip_anima_bundle_prefix({f"{name}.weight": None for name in layer_names})
- return {name: key[: -len(".weight")] for name, key in zip(layer_names, stripped.keys(), strict=True)}
-
-
def _filter_non_model_keys(sd: dict) -> dict:
"""Drop checkpoint keys that don't belong to the transformer module's state dict."""
return {
@@ -196,10 +184,13 @@ class AnimaCheckpointModel(ModelLoader):
# so a sibling scale travels with its weight and nothing has to be split.
keep_fp8 = should_keep_fp8_weights(target_device)
header_hints = parse_quantization_metadata(read_safetensors_metadata(model_path, logger))
- path_map = _strip_anima_prefix_from_layer_paths(list(header_hints))
+ # The header names layers in the checkpoint's own scheme -- `net.`-prefixed on every Anima
+ # redistribution measured -- while the scales are read after `_strip_anima_bundle_prefix`
+ # has run. Without this the per-layer flags, `full_precision_matrix_mult` above all, match
+ # nothing and are silently ignored.
layer_hints = {
**extract_comfy_quant_hints(sd),
- **{path_map.get(name, name): hints for name, hints in header_hints.items()},
+ **strip_layer_path_prefix(header_hints),
}
fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)
if fp8_layers and not keep_fp8:
diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.py
index 9bcc99adc6..7374729570 100644
--- a/invokeai/backend/model_manager/load/model_loaders/flux.py
+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py
@@ -96,6 +96,7 @@ from invokeai.backend.quantization.fp8_scaled import (
read_safetensors_metadata,
should_keep_fp8_weights,
split_fp8_scaled_layers,
+ strip_layer_path_prefix,
warn_on_unattached_scales,
)
from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader
@@ -747,7 +748,12 @@ class FluxCheckpointModel(ModelLoader):
# Hints ship either in the safetensors header or as per-layer `.comfy_quant` markers; the
# header wins on the rare checkpoint carrying both.
metadata = read_safetensors_metadata(model_path, self._logger)
- layer_hints = {**extract_comfy_quant_hints(sd), **parse_quantization_metadata(metadata)}
+ # Header names still carry the checkpoint prefix that was stripped off `sd`; strip it from
+ # them too, or every per-layer flag matches nothing.
+ layer_hints = {
+ **extract_comfy_quant_hints(sd),
+ **strip_layer_path_prefix(parse_quantization_metadata(metadata)),
+ }
fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)
# A checkpoint that ships raw fp8 weights (fp8 tensors, no weight_scale) keeps them when the
@@ -1060,7 +1066,9 @@ class Flux2CheckpointModel(ModelLoader):
# Hints ship in the safetensors header or as per-layer `.comfy_quant` markers, and both name
# layers in the checkpoint's BFL scheme. The scales are read after the rename, so the hints
# have to be renamed too -- a fused `qkv` becomes three diffusers layers.
- header_hints = parse_quantization_metadata(read_safetensors_metadata(model_path, self._logger))
+ header_hints = strip_layer_path_prefix(
+ parse_quantization_metadata(read_safetensors_metadata(model_path, self._logger))
+ )
layer_hints = {**extract_comfy_quant_hints(sd), **header_hints}
path_map = remap_flux2_layer_paths(layer_hints.keys())
layer_hints = {
diff --git a/invokeai/backend/model_manager/load/model_loaders/flux2_state_dict_utils.py b/invokeai/backend/model_manager/load/model_loaders/flux2_state_dict_utils.py
index c705d9f024..43db644ebd 100644
--- a/invokeai/backend/model_manager/load/model_loaders/flux2_state_dict_utils.py
+++ b/invokeai/backend/model_manager/load/model_loaders/flux2_state_dict_utils.py
@@ -364,6 +364,28 @@ def _flux2_sidechannel_destinations(base: str) -> list[str]:
return [k[: -len(".weight")] for k in _convert_flux2_weight_keys(probe) if k.endswith(".weight")]
+# Converter transforms that reorder weight *rows*. A per-output-channel weight scale has one entry
+# per row, so it has to be reordered identically or every row ends up scaled by another row's
+# factor. The fused-QKV split is handled separately (`split_qkv_sidechannel`); this is the only
+# other row-reordering transform the converter applies.
+_ROW_PERMUTED_BY_CONVERSION = {"final_layer.adaLN_modulation.1"}
+
+
+def _mirror_row_permutation(base: str, suffix: str, value: Any) -> Any:
+ """Apply the converter's row reordering to a per-output-channel weight scale.
+
+ Only weight scales carry per-row structure: the activation scale is per-tensor and the
+ `comfy_quant` marker is a byte blob, both of which describe the whole layer and must be copied
+ verbatim. A per-tensor weight scale is likewise unaffected.
+ """
+ if base not in _ROW_PERMUTED_BY_CONVERSION or suffix not in ("weight_scale", "scale_weight"):
+ return value
+ tensor = torch.as_tensor(value) if hasattr(value, "shape") else value
+ if not hasattr(tensor, "shape") or tensor.dim() < 1 or tensor.numel() <= 1 or tensor.shape[0] % 2 != 0:
+ return value
+ return _flux2_swap_scale_shift(tensor)
+
+
def convert_flux2_bfl_to_diffusers(sd: dict) -> dict:
"""Convert a FLUX.2 transformer BFL-format state dict to diffusers format.
@@ -386,7 +408,7 @@ def convert_flux2_bfl_to_diffusers(sd: dict) -> dict:
# no matching fp8 weight, which is the safe outcome -- better than guessing a target.
converted[key] = value
elif len(destinations) == 1:
- converted[f"{destinations[0]}.{suffix}"] = value
+ converted[f"{destinations[0]}.{suffix}"] = _mirror_row_permutation(base, suffix, value)
else:
for destination, part in zip(destinations, split_qkv_sidechannel(key, value), strict=True):
converted[f"{destination}.{suffix}"] = part
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.py
index f47cfdbc77..7feb9951a6 100644
--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py
+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py
@@ -2,7 +2,7 @@
"""Class for Krea-2 model loading in InvokeAI."""
from pathlib import Path
-from typing import TYPE_CHECKING, Any, Optional
+from typing import Any, Optional
import accelerate
from transformers import AutoConfig, AutoTokenizer
@@ -26,28 +26,25 @@ from invokeai.backend.model_manager.taxonomy import (
)
from invokeai.backend.quantization.fp8_scaled import (
FP8_DTYPE,
- WEIGHT_SCALE_SUFFIXES,
attach_fp8_scales,
cast_state_dict,
dequantize_fp8_scaled,
+ detach_layer_sidechannel,
extract_comfy_quant_hints,
extract_fp8_scaled_layers,
full_precision_hints_respected,
- iter_weight_scale_pairs,
parse_quantization_metadata,
predict_cast_state_dict_size,
read_safetensors_metadata,
+ reattach_layer_sidechannel,
should_keep_fp8_weights,
split_fp8_scaled_layers,
+ strip_layer_path_prefix,
warn_on_unattached_scales,
)
from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader
from invokeai.backend.util.devices import TorchDevice
-if TYPE_CHECKING:
- # torch is imported lazily inside the helpers below; this is annotations-only.
- import torch
-
def _normalize_qwen3vl_rope_config(config: Any) -> Any:
"""Mirror Qwen3-VL rope_parameters into rope_scaling for Transformers compatibility."""
@@ -110,42 +107,6 @@ def _is_native_krea2_format(sd: dict[str, Any]) -> bool:
)
-def _dequantize_scaled_fp8(sd: dict[str, Any], dtype: "torch.dtype") -> dict[str, Any]:
- """Dequantize ComfyUI 'scaled fp8' weights: ``dequant = weight.float() * weight_scale``.
-
- Each quantized layer stores an fp8 ``<name>.weight`` plus a (usually scalar) ``<name>.weight_scale``.
- Returns a new dict with the weights dequantized and the ``.weight_scale`` keys removed. No-op if
- there are no scale keys.
-
- The multiply runs in float32 for precision, but each result is stored as ``dtype`` immediately so
- the *whole model* is never materialized in float32. Krea-2's ~12 GB fp8 checkpoint would otherwise
- peak at ~50 GB of RAM (4 bytes/param) before the caller's later bf16 cast brings it down to ~25 GB,
- which puts a 32 GB machine into swap during a cold load. This mirrors the same fix already applied
- to the FLUX.2 loader.
-
- ``dtype`` is required on purpose. It used to default to bfloat16, which is wrong on a device where
- ``choose_bfloat16_safe_dtype`` picks float16: the weights would land in bf16 and then take a second
- rounding step on the caller's later float16 cast. Callers already know the compute dtype, so there
- is no reason to guess one here.
- """
- import torch
-
- scale_keys = [k for k in sd if isinstance(k, str) and k.endswith(WEIGHT_SCALE_SUFFIXES)]
- if not scale_keys:
- return sd
- out = dict(sd)
- for weight_key, scale_key in iter_weight_scale_pairs(sd):
- weight = torch.as_tensor(_to_plain_tensor(out[weight_key])).float()
- scale = torch.as_tensor(_to_plain_tensor(out[scale_key])).float()
- out[weight_key] = (weight * scale).to(dtype)
- del weight
- # Every scale key goes, including one whose `.weight` is missing: there is nothing to fold it
- # into, and leaving the orphan behind trips `load_state_dict(..., strict=True)`.
- for scale_key in scale_keys:
- out.pop(scale_key, None)
- return out
-
-
def _remap_native_layer_paths(layer_names: Any) -> dict[str, str]:
"""Map native/ComfyUI layer paths to their diffusers equivalents.
@@ -396,21 +357,33 @@ class Krea2CheckpointModel(ModelLoader):
sd = load_file(model_path)
metadata = read_safetensors_metadata(model_path, self._logger)
sd = _strip_comfyui_prefix(sd)
- # 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)}
+ # the key conversion). 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. Header names carry the prefix that was just stripped off the
+ # state dict, so strip it from them too or they match nothing.
+ layer_hints = {
+ **extract_comfy_quant_hints(sd),
+ **strip_layer_path_prefix(parse_quantization_metadata(metadata)),
+ }
if _is_native_krea2_format(sd):
+ # Take the quantization side channel out before renaming. The converter renames
+ # ".weight"-suffixed keys by substring and five more by whole-key equality, so a sibling
+ # ".scale_weight", ".input_scale", or any scale on one of the equality-renamed keys
+ # (e.g. `last.linear.weight_scale`) would be left behind at its old path while the
+ # weight moves — and then silently dropped, leaving the weight unscaled.
+ detached = detach_layer_sidechannel(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())
+ # The metadata and the detached scales still name layers natively; rename both the same
+ # way or the per-layer flags (notably full_precision_matrix_mult) match nothing.
+ path_map = _remap_native_layer_paths({*detached, *layer_hints})
+ orphaned = reattach_layer_sidechannel(sd, detached, path_map)
+ if orphaned:
+ self._logger.debug(
+ f"Krea-2: dropped quantization side-channel for {len(orphaned)} module(s) with no "
+ f"diffusers counterpart (e.g. {orphaned[0]})."
+ )
layer_hints = {path_map.get(name, name): hints for name, hints in layer_hints.items()}
# ComfyUI 'scaled fp8' checkpoints (fp8 weight + .weight_scale, optionally .input_scale).
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 9d3fa59f24..0c30c2932f 100644
--- a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
+++ b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py
@@ -49,6 +49,7 @@ from invokeai.backend.quantization.fp8_scaled import (
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
@@ -948,12 +949,21 @@ class MistralEncoderCheckpointLoader(ModelLoader):
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))
+ header_hints = strip_layer_path_prefix(
+ 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)
+ 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)
logger.info(
diff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.py
index 5d973b6f2c..47a6f010d1 100644
--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py
@@ -50,6 +50,7 @@ from invokeai.backend.quantization.fp8_scaled import (
should_keep_fp8_weights,
split_fp8_scaled_layers,
split_qkv_sidechannel,
+ strip_layer_path_prefix,
warn_on_unattached_scales,
)
from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader
@@ -466,7 +467,10 @@ class ZImageCheckpointModel(ModelLoader):
# Per-layer `full_precision_matrix_mult` hints, from the safetensors header and/or the
# per-tensor `.comfy_quant` markers. The header names layers in the checkpoint's own scheme,
# so it is remapped below; the markers ride along through the key conversion instead.
- header_hints = parse_quantization_metadata(read_safetensors_metadata(model_path, self._logger))
+ # The names in the header still carry the checkpoint prefix stripped off `sd` above.
+ header_hints = strip_layer_path_prefix(
+ parse_quantization_metadata(read_safetensors_metadata(model_path, self._logger))
+ )
# Check if the state dict is in original format (not diffusers format)
# Original format has keys like "x_embedder.weight" instead of "all_x_embedder.2-1.weight"
diff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.py
index e2f77b0d87..91b89efafb 100644
--- a/invokeai/backend/quantization/fp8_scaled.py
+++ b/invokeai/backend/quantization/fp8_scaled.py
@@ -26,6 +26,12 @@ import torch
FP8_DTYPE = torch.float8_e4m3fn
+# Every float8 dtype a checkpoint may store weights in. Scale *recovery* must cover all of them:
+# only `float8_e4m3fn` can stay quantized (see `can_stay_quantized`), but an `e5m2` weight still
+# needs its `weight_scale` folded in on the way to bf16. Gating extraction on e4m3fn alone dropped
+# the scale key and then cast the weight unscaled — off by `1/weight_scale`, silently.
+FP8_WEIGHT_DTYPES = (torch.float8_e4m3fn, torch.float8_e5m2)
+
WEIGHT_SCALE_SUFFIXES = (".weight_scale", ".scale_weight")
# Both spellings occur, exactly as for the weight scale. ComfyUI normalizes `.scale_input` to
# `.input_scale` on load (comfy/utils.py, convert_old_quants); reading only one of them means a
@@ -141,6 +147,92 @@ def extract_comfy_quant_hints(sd: dict[str, Any]) -> dict[str, dict[str, Any]]:
return hints
+# Key prefixes redistributors wrap a transformer in. Loaders strip these off the state dict before
+# anything else, so `_quantization_metadata` — which is read from the file and still carries them —
+# has to be stripped the same way.
+TRANSFORMER_KEY_PREFIXES = ("model.diffusion_model.", "diffusion_model.", "net.")
+
+
+def strip_layer_path_prefix(
+ layer_hints: Mapping[str, Any],
+ prefixes: Iterable[str] = TRANSFORMER_KEY_PREFIXES,
+) -> dict[str, Any]:
+ """Re-key ``layer_hints`` as if the checkpoint prefix had been stripped from their names.
+
+ ``_quantization_metadata`` lives in the safetensors header, so its layer names are in the
+ file's own scheme — ``model.diffusion_model.blocks.0.attn.wq`` — while the state dict has had
+ that prefix removed before the scales are extracted. A hint whose name still carries the prefix
+ matches no layer, so ``full_precision_matrix_mult`` is silently ignored and the producer's
+ "do not multiply this one in fp8" instruction is disregarded: exactly the failure the hint
+ plumbing exists to prevent.
+
+ Names that carry none of ``prefixes`` are passed through unchanged. Dropping them instead — as
+ running the names through a strip function that filters by prefix would — turns a
+ partially-prefixed header into a silently truncated one, and can abort the load.
+ """
+ out: dict[str, Any] = {}
+ for name, hints in layer_hints.items():
+ if isinstance(name, str):
+ for prefix in prefixes:
+ if name.startswith(prefix):
+ name = name[len(prefix) :]
+ break
+ out[name] = hints
+ return out
+
+
+# Every per-layer side-channel suffix that belongs to a module rather than being a tensor of its
+# own. Used by the detach/reattach pair below.
+LAYER_SIDECHANNEL_SUFFIXES = WEIGHT_SCALE_SUFFIXES + INPUT_SCALE_SUFFIXES + (COMFY_QUANT_SUFFIX,)
+
+
+def detach_layer_sidechannel(sd: dict[str, Any]) -> dict[str, list[tuple[str, Any]]]:
+ """Pop every per-layer quantization side-channel entry, keyed by the module path it belongs to.
+
+ For loaders that rename checkpoint keys. Key converters are written against ``.weight`` — they
+ match it as a substring, or test whole keys for equality — so a sibling ``.scale_weight`` or
+ ``.input_scale`` is *not* carried along, and neither is any scale on a key the converter renames
+ by equality. The scale is then orphaned under its old path while its weight moves, and
+ :func:`extract_fp8_scaled_layers` drops it because no fp8 weight sits at the old path any more.
+ The weight stays quantized with no scale attached and is off by ``1/weight_scale``, in silence:
+ the layer never enters ``fp8_layers``, so :func:`warn_on_unattached_scales` cannot see it either.
+
+ Take the side channel out of the way, convert, then :func:`reattach_layer_sidechannel`.
+ """
+ detached: dict[str, list[tuple[str, Any]]] = {}
+ for key in list(sd.keys()):
+ if not isinstance(key, str):
+ continue
+ for suffix in LAYER_SIDECHANNEL_SUFFIXES:
+ if key.endswith(suffix):
+ detached.setdefault(key[: -len(suffix)], []).append((suffix, sd.pop(key)))
+ break
+ return detached
+
+
+def reattach_layer_sidechannel(
+ sd: dict[str, Any],
+ detached: Mapping[str, list[tuple[str, Any]]],
+ path_map: Mapping[str, str],
+) -> list[str]:
+ """Put detached side-channel entries back under their renamed module paths.
+
+ Returns the module paths that could not be placed. A path with no entry in ``path_map`` had no
+ destination in the converted state dict — usually because the converter drops that module
+ outright — so its scale is dropped with it. Returning them rather than swallowing them lets the
+ caller say so: a *silently* dropped scale is exactly the failure this pair exists to prevent.
+ """
+ orphaned: list[str] = []
+ for path, entries in detached.items():
+ destination = path_map.get(path, path)
+ if f"{destination}.weight" not in sd:
+ orphaned.append(path)
+ continue
+ for suffix, value in entries:
+ sd[f"{destination}{suffix}"] = value
+ return orphaned
+
+
def iter_weight_scale_pairs(sd: Mapping[str, Any]) -> Iterable[tuple[str, str]]:
"""Yield ``(weight_key, scale_key)`` for every weight scale in ``sd``, in either spelling.
@@ -240,6 +332,63 @@ def _usable_input_scale(scale: torch.Tensor | None) -> torch.Tensor | None:
return scale
+def _normalize_weight_scale(scale: torch.Tensor) -> torch.Tensor:
+ """Canonical float32 form of a weight scale, preserving its layout.
+
+ Per-tensor scales become 0-d and per-output-channel scales 1-D, so downstream code can branch on
+ ``numel()``. A scale with more than one dimension is *block-wise* — one entry per block of
+ weight elements — and is returned with its shape intact: flattening it destroys the block
+ geometry that :func:`expand_weight_scale` needs to line it back up with the weight.
+ """
+ scale = scale.float()
+ if scale.numel() == 1:
+ return scale.reshape(())
+ if scale.dim() > 1:
+ return scale
+ return scale.flatten()
+
+
+def expand_weight_scale(weight: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
+ """Broadcast ``scale`` to line up with ``weight`` for an elementwise multiply.
+
+ Handles the three layouts producers emit:
+
+ - per-tensor (0-d / single element) — returned unchanged, broadcasting handles it;
+ - per-output-channel (one entry per row) — reshaped to ``(rows, 1, ...)``;
+ - block-wise (one entry per block along one or more dims) — each axis is
+ ``repeat_interleave``d by that axis' block size.
+
+ Without the block-wise case a 2-D scale reaches the multiply as-is and raises a shape error, so
+ a checkpoint using that layout fails to load outright. That is the layout ComfyUI's own
+ dequantizer expands, and the FLUX.2 loader used to expand before this module centralized the
+ logic.
+ """
+ if scale.numel() == 1:
+ return scale
+ if scale.dim() <= 1:
+ return scale.reshape(-1, *([1] * (weight.dim() - 1)))
+ for dim in range(weight.dim()):
+ if dim < scale.dim() and scale.shape[dim] != weight.shape[dim]:
+ block = weight.shape[dim] // scale.shape[dim]
+ if block > 1:
+ scale = scale.repeat_interleave(block, dim=dim)
+ return scale
+
+
+def is_matmul_usable_scale(weight: Any, scale: torch.Tensor) -> bool:
+ """Whether ``scaled_mm_linear`` can apply ``scale`` without materializing the weight.
+
+ It handles exactly two layouts: a per-tensor scalar, which goes into the ``_scaled_mm`` call,
+ and a per-output-channel vector, which is applied to the *result* (scaling weight row ``j``
+ scales output column ``j``). A block-wise scale is separable in neither sense, so such a layer
+ has to be dequantized up front instead of failing mid-generation inside the kernel.
+ """
+ if scale.numel() == 1:
+ return True
+ rows = getattr(weight, "shape", (None,))[0]
+ return scale.dim() == 1 and scale.numel() == rows
+
+
def extract_fp8_scaled_layers(
sd: dict[str, Any],
metadata: Mapping[str, Any] | None = None,
@@ -281,13 +430,13 @@ def extract_fp8_scaled_layers(
layers: dict[str, Fp8ScaledLayer] = {}
for path, scale in weight_scales.items():
weight = sd.get(f"{path}.weight")
- if weight is None or getattr(weight, "dtype", None) != FP8_DTYPE:
+ if weight is None or getattr(weight, "dtype", None) not in FP8_WEIGHT_DTYPES:
# A scale without an fp8 weight means the weight was already dequantized (or the key
# naming does not line up). Applying the scale later would corrupt it, so drop it.
continue
hints = layer_meta.get(path, {})
layers[path] = Fp8ScaledLayer(
- weight_scale=scale.float().reshape(()) if scale.numel() == 1 else scale.float().flatten(),
+ weight_scale=_normalize_weight_scale(scale),
input_scale=_usable_input_scale(input_scales.get(path)),
full_precision_matmul=bool(hints.get("full_precision_matrix_mult", False)),
)
@@ -310,10 +459,8 @@ def dequantize_fp8_scaled(
weight = sd.get(key)
if weight is None:
continue
- scale = layer.weight_scale
- if scale.numel() > 1:
- scale = scale.reshape(-1, *([1] * (weight.dim() - 1)))
- sd[key] = (weight.float() * scale).to(dtype)
+ weight = weight.float()
+ sd[key] = (weight * expand_weight_scale(weight, layer.weight_scale)).to(dtype)
return sd
@@ -441,7 +588,7 @@ def full_precision_hints_respected() -> bool:
return True
-def _probe_fp8_matmul(index: int) -> bool:
+def _probe_fp8_matmul(index: int) -> bool | None:
"""Run one minimal ``_scaled_mm`` on device ``index`` and report whether it worked.
Asking the device is the only reliable test. ``get_device_capability`` reports the *gfx arch*
@@ -450,6 +597,12 @@ def _probe_fp8_matmul(index: int) -> bool:
devices with compute capability >= 9.0 or 8.9, or ROCm MI300+``. The whole point of the
capability gate is to *fall back* rather than raise mid-generation, so it must not itself be a
guess. The probe is one 16x16 matmul, run once per device and cached.
+
+ Returns ``None`` when the probe could not be *carried out* — an allocation failure rather than
+ an unsupported operation. The probe runs during a model load, i.e. under real VRAM pressure, and
+ caching a momentary OOM as "this GPU cannot do fp8" would disable the fp8 matmul for the rest of
+ the process. Same reasoning as `_device_supports_fp8_storage`, which also refuses to cache a
+ transient failure.
"""
try:
device = torch.device("cuda", index)
@@ -458,6 +611,13 @@ def _probe_fp8_matmul(index: int) -> bool:
rhs = torch.zeros((_MM_ALIGNMENT, _MM_ALIGNMENT), device=device, dtype=FP8_DTYPE).t()
scale = torch.ones((1, 1), device=device, dtype=torch.float32)
torch._scaled_mm(lhs, rhs, scale, scale, out_dtype=torch.bfloat16)
+ except torch.OutOfMemoryError:
+ return None
+ except RuntimeError as e:
+ # cuBLAS reports a failed workspace allocation as a plain RuntimeError, not an OOM.
+ if "out of memory" in str(e).lower() or "ALLOC_FAILED" in str(e):
+ return None
+ return False
except Exception:
return False
return True
@@ -469,13 +629,20 @@ def device_supports_fp8_matmul(device: torch.device) -> bool:
return False
index = device.index if device.index is not None else torch.cuda.current_device()
cached = _fp8_mm_supported.get(index)
- if cached is None:
- # The capability check is only a cheap pre-filter that spares older CUDA cards the probe;
- # it is deliberately not trusted on its own (see `_probe_fp8_matmul`).
- supported = torch.version.hip is not None or torch.cuda.get_device_capability(index) >= (8, 9)
- cached = supported and _probe_fp8_matmul(index)
- _fp8_mm_supported[index] = cached
- return cached
+ if cached is not None:
+ return cached
+ # The capability check is only a cheap pre-filter that spares older CUDA cards the probe;
+ # it is deliberately not trusted on its own (see `_probe_fp8_matmul`).
+ if not (torch.version.hip is not None or torch.cuda.get_device_capability(index) >= (8, 9)):
+ _fp8_mm_supported[index] = False
+ return False
+ probed = _probe_fp8_matmul(index)
+ if probed is None:
+ # Inconclusive: answer this call conservatively but leave the cache empty so the next load
+ # re-probes instead of the process being stuck without fp8 after one transient OOM.
+ return False
+ _fp8_mm_supported[index] = probed
+ return probed
def reset_fp8_matmul_support_cache() -> None:
@@ -546,6 +713,17 @@ def can_stay_quantized(
)
+def _is_castable_float(tensor: Any) -> bool:
+ """Whether ``tensor`` is a floating-point payload that may be cast to the compute dtype."""
+ is_floating_point = getattr(tensor, "is_floating_point", None)
+ if not callable(is_floating_point):
+ return False
+ try:
+ return bool(is_floating_point())
+ except Exception:
+ return False
+
+
def cast_state_dict(
sd: dict[str, Any],
dtype: torch.dtype,
@@ -574,6 +752,11 @@ def cast_state_dict(
if keep_fp8 and can_stay_quantized(key, tensor, model, patterns):
kept += 1
continue
+ if not _is_castable_float(tensor):
+ # Integer payloads (embedding indices, packed buffers) are not weights and must keep
+ # their dtype. Loaders used to guard this themselves; centralizing it here means a
+ # loader that switches to `cast_state_dict` does not silently lose the guard.
+ continue
sd[key] = tensor.to(dtype)
return kept
@@ -597,7 +780,7 @@ def predict_cast_state_dict_size(
patterns = tuple(skip_patterns)
total = 0
for key, tensor in sd.items():
- if keep_fp8 and can_stay_quantized(key, tensor, model, patterns):
+ if (keep_fp8 and can_stay_quantized(key, tensor, model, patterns)) or not _is_castable_float(tensor):
total += tensor.nelement() * tensor.element_size()
else:
total += tensor.nelement() * dtype.itemsize
@@ -625,6 +808,15 @@ def split_fp8_scaled_layers(
So the filters are applied here instead, *before* the cast, and the affected layers go through
:func:`dequantize_fp8_scaled`, which applies the scale properly. They are then dropped from the
returned mapping — they are no longer fp8, so there is nothing left to attach.
+
+ A scale layout :func:`scaled_mm_linear` cannot apply — block-wise, or a vector that does not
+ match the weight's row count — is dequantized here too. Left quantized it would fail inside the
+ kernel mid-generation instead. Doing it here rather than in :func:`can_stay_quantized` keeps the
+ RAM accounting honest: every caller runs this before
+ :func:`predict_cast_state_dict_size`, so the prediction sees the already-widened tensor.
+
+ ``float8_e5m2`` layers land here by way of :func:`can_stay_quantized`, which admits only
+ ``float8_e4m3fn`` — they are dequantized *with* their scale applied rather than losing it.
"""
patterns = tuple(skip_patterns)
usable: dict[str, Fp8ScaledLayer] = {}
@@ -632,7 +824,11 @@ def split_fp8_scaled_layers(
for path, layer in layers.items():
key = f"{path}.weight"
tensor = sd.get(key)
- if tensor is not None and can_stay_quantized(key, tensor, model, patterns):
+ if (
+ tensor is not None
+ and can_stay_quantized(key, tensor, model, patterns)
+ and is_matmul_usable_scale(tensor, layer.weight_scale)
+ ):
usable[path] = layer
else:
unusable[path] = layer
@@ -661,9 +857,7 @@ def dequantize_weight(weight: torch.Tensor, weight_scale: torch.Tensor | None, d
if weight_scale is None:
return out
scale = weight_scale.to(device=out.device, dtype=dtype)
- if scale.numel() > 1:
- scale = scale.reshape(-1, *([1] * (out.dim() - 1)))
- return out * scale
+ return out * expand_weight_scale(out, scale)
def scaled_mm_linear(
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index 71070d6494..aeb8154d0f 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -49896,7 +49896,7 @@
"additionalProperties": false,
"type": "object",
"title": "InvokeAIAppConfig",
- "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU; falls back automatically otherwise). Roughly halves the transformer's VRAM and speeds up denoising, but quantizes activations as well, so images will differ from previous versions at the same seed.\n fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `xpu`, `cuda:N`, `xpu:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.\n pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.\n attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`\n attention_slice_size: Slice size, valid when attention_type==\"sliced\".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty).\n pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n allow_private_download_urls: Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.\n download_proxy: Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set.\n http_compression_level: Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses."
+ "description": "Invoke's global app configuration.\n\nTypically, you won't need to interact with this class directly. Instead, use the `get_config` function from `invokeai.app.services.config` to get a singleton config object.\n\nAttributes:\n host: IP address to bind to. Use `0.0.0.0` to serve to your local network.\n port: Port to bind to.\n allow_origins: Allowed CORS origins.\n allow_credentials: Allow CORS credentials.\n allow_methods: Methods allowed for CORS.\n allow_headers: Headers allowed for CORS.\n ssl_certfile: SSL certificate file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n ssl_keyfile: SSL key file for HTTPS. See https://www.uvicorn.dev/settings/#https.\n log_tokenization: Enable logging of parsed prompt tokens.\n patchmatch: Enable patchmatch inpaint code.\n models_dir: Path to the models directory.\n convert_cache_dir: Path to the converted models cache directory (DEPRECATED, but do not delete because it is needed for migration from previous versions).\n download_cache_dir: Path to the directory that contains dynamically downloaded models.\n legacy_conf_dir: Path to directory of legacy checkpoint config files.\n db_dir: Path to InvokeAI databases directory.\n outputs_dir: Path to directory for outputs.\n image_subfolder_strategy: Strategy for organizing images into subfolders. 'flat' stores all images in a single folder. 'date' organizes by YYYY/MM/DD. 'type' organizes by image category. 'hash' uses first 2 characters of UUID for filesystem performance.<br>Valid values: `flat`, `date`, `type`, `hash`\n custom_nodes_dir: Path to directory for custom nodes.\n style_presets_dir: Path to directory for style presets.\n workflow_thumbnails_dir: Path to directory for workflow thumbnails.\n log_handlers: Log handler. Valid options are \"console\", \"file=<path>\", \"syslog=path|address:host:port\", \"http=<url>\".\n log_format: Log format. Use \"plain\" for text-only, \"color\" for colorized output, \"legacy\" for 2.3-style logging and \"syslog\" for syslog-style.<br>Valid values: `plain`, `color`, `syslog`, `legacy`\n log_level: Emit logging messages at this level or higher.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n log_sql: Log SQL queries. `log_level` must be `debug` for this to do anything. Extremely verbose.\n log_level_network: Log level for network-related messages. 'info' and 'debug' are very verbose.<br>Valid values: `debug`, `info`, `warning`, `error`, `critical`\n use_memory_db: Use in-memory database. Useful for development.\n dev_reload: Automatically reload when Python sources are changed. Does not reload node definitions.\n profile_graphs: Enable graph profiling using `cProfile`.\n profile_prefix: An optional prefix for profile output files.\n profiles_dir: Path to profiles output directory.\n max_cache_ram_gb: The maximum amount of CPU RAM to use for model caching in GB. If unset, the limit will be configured based on the available RAM. In most cases, it is recommended to leave this unset.\n max_cache_vram_gb: The amount of VRAM to use for model caching in GB. If unset, the limit will be configured based on the available VRAM and the device_working_mem_gb. In most cases, it is recommended to leave this unset.\n log_memory_usage: If True, a memory snapshot will be captured before and after every model cache operation, and the result will be logged (at debug level). There is a time cost to capturing the memory snapshots, so it is recommended to only enable this feature if you are actively inspecting the model cache's behaviour.\n model_cache_keep_alive_min: How long to keep models in cache after last use, in minutes. A value of 0 (the default) means models are kept in cache indefinitely. If no model generations occur within the timeout period, the model cache is cleared using the same logic as the 'Clear Model Cache' button.\n device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.\n enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.\n keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.\n fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU; falls back automatically otherwise). Roughly halves the transformer's VRAM and speeds up denoising, but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).\n fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.\n ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.\n lazy_offload: DEPRECATED: This setting is no longer used. Lazy-offloading is enabled by default. This config setting will be removed once the new model cache behavior is stable.\n pytorch_cuda_alloc_conf: Configure the Torch CUDA memory allocator. This will impact peak reserved VRAM usage and performance. Setting to \"backend:cudaMallocAsync\" works well on many systems. The optimal configuration is highly dependent on the system configuration (device type, VRAM, CUDA driver version, etc.), so must be tuned experimentally.\n device: Preferred execution device. `auto` will choose the device depending on the hardware platform and the installed torch capabilities.<br>Valid values: `auto`, `cpu`, `cuda`, `mps`, `xpu`, `cuda:N`, `xpu:N` (where N is a device number)\n precision: Floating point precision. `float16` will consume half the memory of `float32` but produce slightly lower-quality images. The `auto` setting will guess the proper precision based on your video card and operating system.<br>Valid values: `auto`, `float16`, `bfloat16`, `float32`\n sequential_guidance: Whether to calculate guidance in serial instead of in parallel, lowering memory requirements.\n wan_memory_optimization: Enable experimental Wan memory optimizations at the cost of slower generation.\n pid_memory_optimization: Enable experimental PiD decode memory optimizations. Roughly halves the peak activation memory of a PiD decode; in exchange the decoded image changes slightly, because neither the chunked pixel pathway nor the float32 sampler intermediates are bit-exact with the default path.\n attention_type: Attention type.<br>Valid values: `auto`, `normal`, `xformers`, `sliced`, `torch-sdp`\n attention_slice_size: Slice size, valid when attention_type==\"sliced\".<br>Valid values: `auto`, `balanced`, `max`, `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`\n force_tiled_decode: Whether to enable tiled VAE decode (reduces memory consumption with some performance penalty).\n pil_compress_level: The compress_level setting of PIL.Image.save(), used for PNG encoding. All settings are lossless. 0 = no compression, 1 = fastest with slightly larger filesize, 9 = slowest with smallest filesize. 1 is typically the best setting.\n max_queue_size: Maximum number of items in the session queue.\n session_queue_mode: Session queue mode. Use 'FIFO' for traditional first-in-first-out, or 'round_robin' to serve each user's jobs in turn. In single-user mode, FIFO is always used regardless of this setting.<br>Valid values: `FIFO`, `round_robin`\n clear_queue_on_startup: Empties session queue on startup. If true, disables `max_queue_history`.\n max_queue_history: Keep the last N completed, failed, and canceled queue items. Older items are deleted on startup. Set to 0 to prune all terminal items. Ignored if `clear_queue_on_startup` is true.\n allow_nodes: List of nodes to allow. Omit to allow all.\n deny_nodes: List of nodes to deny. Omit to deny none.\n node_cache_size: How many cached nodes to keep in memory.\n hashing_algorithm: Model hashing algorthim for model installs. 'blake3_multi' is best for SSDs. 'blake3_single' is best for spinning disk HDDs. 'random' disables hashing, instead assigning a UUID to models. Useful when using a memory db to reduce model installation time, or if you don't care about storing stable hashes for models. Alternatively, any other hashlib algorithm is accepted, though these are not nearly as performant as blake3.<br>Valid values: `blake3_multi`, `blake3_single`, `random`, `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`, `blake2b`, `blake2s`, `sha3_224`, `sha3_256`, `sha3_384`, `sha3_512`, `shake_128`, `shake_256`\n remote_api_tokens: List of regular expression and token pairs used when downloading models from URLs. The download URL is tested against the regex, and if it matches, the token is provided in as a Bearer token.\n scan_models_on_startup: Scan the models directory on startup, registering orphaned models. This is typically only used in conjunction with `use_memory_db` for testing purposes.\n allow_private_download_urls: Allow the download queue to fetch from loopback, link-local and private-network addresses. Disabled by default so that a download URL cannot be used to reach services that are only reachable from the server. Enable this only if you install models from a mirror on your own network.\n download_proxy: Optional HTTP proxy for model downloads. The proxy must enforce the public-address policy because proxy-side DNS cannot be checked by InvokeAI.\n unsafe_disable_picklescan: UNSAFE. Disable the picklescan security check during model installation. Recommended only for development and testing purposes. This will allow arbitrary code execution during model installation, so should never be used in production.\n allow_unknown_models: Allow installation of models that we are unable to identify. If enabled, models will be marked as `unknown` in the database, and will not have any metadata associated with them. If disabled, unknown models will be rejected during installation.\n multiuser: Enable multiuser support. When disabled, the application runs in single-user mode using a default system account with administrator privileges. When enabled, requires user authentication and authorization.\n strict_password_checking: Enforce strict password requirements. When True, passwords must contain uppercase, lowercase, and numbers. When False (default), any password is accepted but its strength (weak/moderate/strong) is reported to the user.\n external_alibabacloud_api_key: API key for Alibaba Cloud DashScope image generation.\n external_alibabacloud_base_url: Base URL override for Alibaba Cloud DashScope image generation.\n external_gemini_api_key: API key for Gemini image generation.\n external_openai_api_key: API key for OpenAI image generation.\n external_gemini_base_url: Base URL override for Gemini image generation.\n external_openai_base_url: Base URL override for OpenAI image generation.\n external_seedream_api_key: API key for Seedream image generation.\n external_seedream_base_url: Base URL override for Seedream image generation.\n base_url: Public base path when running behind a reverse proxy under a sub-path, e.g. `/invoke`. Set only when the proxy PRESERVES the sub-path (the backend receives `/invoke/api/...`). Leave unset when the proxy strips the sub-path or when serving at the domain root.\n forwarded_allow_ips: Comma-separated list of IPs (or `*`) allowed to set X-Forwarded-* headers. Set to the reverse proxy's IP. Only used when `base_url` is set.\n http_compression_level: Compression level for gzipped HTTP API responses. 0 disables response compression entirely, 1 is fastest, 9 (the default) is smallest. Compression runs on the event loop and blocks the whole server while it works, and level 9 costs about 5.5x the time of level 1 for 0.4 percentage points of extra compression, so lowering this makes the app noticeably more responsive on large libraries. Set to 0 when a reverse proxy already compresses responses."
},
"InvokeAIAppConfigWithSetFields": {
"properties": {
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index 739aa075e0..47a0297e7e 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -19058,7 +19058,7 @@ export type components = {
* device_working_mem_gb: The amount of working memory to keep available on the compute device (in GB). Has no effect if running on CPU. If you are experiencing OOM errors, try increasing this value.
* enable_partial_loading: Enable partial loading of models. This enables models to run with reduced VRAM requirements (at the cost of slower speed) by streaming the model from RAM to VRAM as its used. In some edge cases, partial loading can cause models to run more slowly if they were previously being fully loaded into VRAM.
* keep_ram_copy_of_weights: Whether to keep a full RAM copy of a model's weights when the model is loaded in VRAM. Keeping a RAM copy increases average RAM usage, but speeds up model switching and LoRA patching (assuming there is sufficient RAM). Set this to False if RAM pressure is consistently high.
- * fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU; falls back automatically otherwise). Roughly halves the transformer's VRAM and speeds up denoising, but quantizes activations as well, so images will differ from previous versions at the same seed.
+ * fp8_compute: Keep ComfyUI 'scaled fp8' checkpoints quantized instead of dequantizing them at load, and run their matmuls on the fp8 tensor cores (requires an Ada/SM 8.9 or newer NVIDIA GPU; falls back automatically otherwise). Roughly halves the transformer's VRAM and speeds up denoising, but quantizes activations as well, so images will differ from previous versions at the same seed. Reproducibility also requires the model to be FULLY resident in VRAM: a layer whose weights are still in RAM falls back to the dequantized path, and since which layers are resident shifts from run to run, the same seed then yields visibly different images. For repeatable output, ensure the model loads at 100% (e.g. enable_partial_loading=false with enough free VRAM).
* fp8_compute_full_precision_hints: Honor the per-layer 'full_precision_matrix_mult' flags that some scaled-fp8 checkpoints ship. Those layers then dequantize on every forward instead of using the fp8 tensor cores, which can cost a large part of the fp8_compute speedup - on checkpoints that mark many layers, most of it. Set to false to run every quantized layer on the fp8 tensor cores, ignoring the producer's instruction; faster, but the marked layers were flagged as numerically sensitive, so quality may suffer. Only has an effect when fp8_compute is enabled.
* ram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_ram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.
* vram: DEPRECATED: This setting is no longer used. It has been replaced by `max_cache_vram_gb`, but most users will not need to use this config since automatic cache size limits should work well in most cases. This config setting will be removed once the new model cache behavior is stable.
diff --git a/tests/backend/model_manager/load/test_anima_scaled_fp8_keys.py b/tests/backend/model_manager/load/test_anima_scaled_fp8_keys.py
index d15b12fd64..05f7c597e8 100644
--- a/tests/backend/model_manager/load/test_anima_scaled_fp8_keys.py
+++ b/tests/backend/model_manager/load/test_anima_scaled_fp8_keys.py
@@ -18,13 +18,13 @@ import torch
from invokeai.backend.model_manager.load.model_loaders.anima import (
_filter_non_model_keys,
_strip_anima_bundle_prefix,
- _strip_anima_prefix_from_layer_paths,
)
from invokeai.backend.quantization.fp8_scaled import (
FP8_DTYPE,
extract_comfy_quant_hints,
extract_fp8_scaled_layers,
is_scale_metadata_key,
+ strip_layer_path_prefix,
)
from tests.backend.model_manager.load.state_dicts.anima_transformer_scaled_fp8_keys import (
layer_hints as header_hints,
@@ -89,10 +89,9 @@ def test_header_hints_are_renamed_to_the_stripped_paths() -> None:
"""
assert all(name.startswith("net.") for name in header_hints), "fixture header is not prefixed"
- mapping = _strip_anima_prefix_from_layer_paths(list(header_hints))
+ remapped = strip_layer_path_prefix(header_hints)
- assert all(not renamed.startswith("net.") for renamed in mapping.values())
- remapped = {mapping[name]: hints for name, hints in header_hints.items()}
+ assert all(not renamed.startswith("net.") for renamed in remapped)
layers = extract_fp8_scaled_layers(_build_state_dict(), layer_hints=remapped)
@@ -109,9 +108,8 @@ def test_the_single_full_precision_flag_survives_both_transports() -> None:
marked = [name for name, hints in header_hints.items() if hints.get("full_precision_matrix_mult")]
assert len(marked) == 1, f"fixture should carry exactly one marked layer, has {len(marked)}"
- mapping = _strip_anima_prefix_from_layer_paths(list(header_hints))
for hints in (
- {mapping[n]: h for n, h in header_hints.items()}, # header transport
+ strip_layer_path_prefix(header_hints), # header transport
extract_comfy_quant_hints(_build_state_dict()), # per-layer marker transport
):
layers = extract_fp8_scaled_layers(_build_state_dict(), layer_hints=hints)
@@ -124,8 +122,7 @@ def test_only_the_full_precision_layer_lacks_an_input_scale() -> None:
That is coherent on the producer's side: a layer excluded from the fp8 matmul has no activation
scale to calibrate. It also means "all layers have an input scale" is the wrong invariant.
"""
- mapping = _strip_anima_prefix_from_layer_paths(list(header_hints))
- marked = {mapping[n] for n, h in header_hints.items() if h.get("full_precision_matrix_mult")}
+ marked = {n for n, h in strip_layer_path_prefix(header_hints).items() if h.get("full_precision_matrix_mult")}
layers = extract_fp8_scaled_layers(_build_state_dict())
diff --git a/tests/backend/model_manager/load/test_flux2_state_dict_utils.py b/tests/backend/model_manager/load/test_flux2_state_dict_utils.py
index dc817cd672..a5c3c5972d 100644
--- a/tests/backend/model_manager/load/test_flux2_state_dict_utils.py
+++ b/tests/backend/model_manager/load/test_flux2_state_dict_utils.py
@@ -142,3 +142,66 @@ class TestFlux2RawFp8Gate:
assert out["double_blocks.0.img_attn.qkv.weight"].dtype is torch.bfloat16
assert torch.allclose(out["double_blocks.0.img_attn.qkv.weight"], torch.full((48, 16), 4.0).bfloat16())
assert "double_blocks.0.img_attn.qkv.weight_scale" not in out
+
+
+class TestAdaLnSwapIsMirroredOntoTheScale:
+ """`final_layer.adaLN_modulation.1.weight` has its two halves swapped (BFL vs diffusers order).
+
+ A per-output-channel `weight_scale` has one entry per row, so it has to be swapped identically.
+ Copying it verbatim leaves rows 0..n/2 holding the original second half while still carrying the
+ first half's scale factors - every row scaled by another row's factor. It is the one converter
+ transform that reorders rows and is not the fused-qkv split.
+ """
+
+ def test_a_per_channel_scale_is_swapped_with_its_weight(self) -> None:
+ weight = torch.arange(24, dtype=torch.float32).reshape(6, 4)
+ sd = {
+ "final_layer.adaLN_modulation.1.weight": weight,
+ "final_layer.adaLN_modulation.1.weight_scale": torch.arange(1, 7, dtype=torch.float32),
+ }
+
+ converted = convert_flux2_bfl_to_diffusers(sd)
+
+ assert converted["norm_out.linear.weight"][:, 0].tolist() == [12, 16, 20, 0, 4, 8]
+ assert converted["norm_out.linear.weight_scale"].tolist() == [4, 5, 6, 1, 2, 3]
+
+ def test_the_scale_weight_spelling_is_swapped_too(self) -> None:
+ sd = {
+ "final_layer.adaLN_modulation.1.weight": torch.arange(24, dtype=torch.float32).reshape(6, 4),
+ "final_layer.adaLN_modulation.1.scale_weight": torch.arange(1, 7, dtype=torch.float32),
+ }
+
+ converted = convert_flux2_bfl_to_diffusers(sd)
+
+ assert converted["norm_out.linear.scale_weight"].tolist() == [4, 5, 6, 1, 2, 3]
+
+ def test_per_tensor_scales_and_markers_are_left_alone(self) -> None:
+ """They describe the whole layer, so reordering them would be wrong.
+
+ The `input_scale` is per-tensor by construction (Ada rejects per-row activation scaling) and
+ `comfy_quant` is a JSON byte blob, not a vector.
+ """
+ sd = {
+ "final_layer.adaLN_modulation.1.weight": torch.arange(24, dtype=torch.float32).reshape(6, 4),
+ "final_layer.adaLN_modulation.1.weight_scale": torch.tensor(0.5),
+ "final_layer.adaLN_modulation.1.input_scale": torch.tensor(0.25),
+ "final_layer.adaLN_modulation.1.comfy_quant": torch.tensor(list(b'{"a":1}'), dtype=torch.uint8),
+ }
+
+ converted = convert_flux2_bfl_to_diffusers(sd)
+
+ assert converted["norm_out.linear.weight_scale"].item() == 0.5
+ assert converted["norm_out.linear.input_scale"].item() == 0.25
+ assert bytes(converted["norm_out.linear.comfy_quant"].tolist()) == b'{"a":1}'
+
+ def test_other_layers_are_not_reordered(self) -> None:
+ """Only this one key is row-permuted; a scale elsewhere must be copied verbatim."""
+ sd = {
+ "final_layer.linear.weight": torch.arange(24, dtype=torch.float32).reshape(6, 4),
+ "final_layer.linear.weight_scale": torch.arange(1, 7, dtype=torch.float32),
+ }
+
+ converted = convert_flux2_bfl_to_diffusers(sd)
+
+ scale = next(v for k, v in converted.items() if k.endswith(".weight_scale"))
+ assert scale.tolist() == [1, 2, 3, 4, 5, 6]
diff --git a/tests/backend/model_manager/load/test_krea2_state_dict_utils.py b/tests/backend/model_manager/load/test_krea2_state_dict_utils.py
index 5a91084d6f..d9058268bb 100644
--- a/tests/backend/model_manager/load/test_krea2_state_dict_utils.py
+++ b/tests/backend/model_manager/load/test_krea2_state_dict_utils.py
@@ -17,13 +17,19 @@ import torch
from invokeai.backend.model_manager.load.model_loaders.krea2 import (
KREA2_TRANSFORMER_CONFIG,
_convert_krea2_native_to_diffusers,
- _dequantize_scaled_fp8,
_is_native_krea2_format,
_normalize_qwen3vl_rope_config,
_reject_incomplete_load,
+ _remap_native_layer_paths,
_remap_qwen3vl_singlefile_keys,
_strip_comfyui_prefix,
)
+from invokeai.backend.quantization.fp8_scaled import (
+ FP8_DTYPE,
+ detach_layer_sidechannel,
+ extract_fp8_scaled_layers,
+ reattach_layer_sidechannel,
+)
class TestNormalizeQwen3vlRopeConfig:
@@ -84,66 +90,6 @@ class TestIsNativeKrea2Format:
assert _is_native_krea2_format({key: torch.zeros(1)}) is False
-class TestDequantizeScaledFp8:
- def test_folds_scale_into_weight_and_drops_scale_key(self) -> None:
- sd = {
- "layer.weight": torch.tensor([2.0, 4.0]),
- "layer.weight_scale": torch.tensor(0.5),
- }
- out = _dequantize_scaled_fp8(sd, torch.bfloat16)
- assert "layer.weight_scale" not in out
- assert torch.allclose(out["layer.weight"].float(), torch.tensor([1.0, 2.0]))
-
- def test_result_is_stored_in_the_compute_dtype_not_float32(self) -> None:
- """The whole model must never be materialized in float32.
-
- The multiply runs in float32 for precision, but holding every dequantized weight there
- costs 4 bytes per parameter: Krea-2's ~12 GB fp8 checkpoint peaked at ~50 GB of RAM before
- the caller's later bf16 cast, which swaps a 32 GB machine during a cold load.
- """
- sd = {
- "layer.weight": torch.tensor([2.0, 4.0]),
- "layer.weight_scale": torch.tensor(0.5),
- }
- assert _dequantize_scaled_fp8(dict(sd), torch.bfloat16)["layer.weight"].dtype is torch.bfloat16
- assert _dequantize_scaled_fp8(dict(sd), torch.float16)["layer.weight"].dtype is torch.float16
-
- def test_dtype_is_required(self) -> None:
- """No implicit bfloat16 fallback: on a float16-only device that would cost an extra rounding step."""
- with pytest.raises(TypeError):
- _dequantize_scaled_fp8({"layer.weight": torch.tensor([2.0])}) # type: ignore[call-arg]
-
- def test_noop_without_scale_keys(self) -> None:
- sd = {"layer.weight": torch.tensor([2.0, 4.0])}
- out = _dequantize_scaled_fp8(sd, torch.bfloat16)
- assert out is sd
-
- def test_orphan_scale_key_is_dropped(self) -> None:
- # A scale key with no matching weight is simply removed (nothing to multiply).
- sd = {"other.weight": torch.tensor([1.0]), "layer.weight_scale": torch.tensor(0.5)}
- out = _dequantize_scaled_fp8(sd, torch.bfloat16)
- assert "layer.weight_scale" not in out
- assert "other.weight" in out
-
- def test_the_scale_weight_spelling_is_folded_too(self) -> None:
- # Producers use both spellings. Reading only `.weight_scale` left the weight unscaled and
- # dropped the key anyway, so the error was silent - off by exactly 1/weight_scale.
- sd = {"layer.weight": torch.tensor([2.0, 4.0]), "layer.scale_weight": torch.tensor(0.5)}
-
- out = _dequantize_scaled_fp8(sd, torch.bfloat16)
-
- assert torch.equal(out["layer.weight"], torch.tensor([1.0, 2.0], dtype=torch.bfloat16))
- assert "layer.scale_weight" not in out
-
- def test_an_orphan_scale_weight_is_dropped_too(self) -> None:
- sd = {"other.weight": torch.tensor([1.0]), "layer.scale_weight": torch.tensor(0.5)}
-
- out = _dequantize_scaled_fp8(sd, torch.bfloat16)
-
- assert "layer.scale_weight" not in out
- assert "other.weight" in out
-
-
class TestConvertKrea2NativeToDiffusers:
def test_top_level_module_renames(self) -> None:
sd = {
@@ -394,3 +340,83 @@ class TestConvertedShapesMatchRealKrea2Transformer:
for name in table_keys:
if name.startswith(("transformer_blocks.", "text_fusion.")):
assert expected[name][0] == 6, f"{name} expected 6 modulation rows, got {expected[name]}"
+
+
+class TestNativeConversionCarriesTheQuantizationSideChannel:
+ """Regression guard for scales orphaned by the native -> diffusers rename.
+
+ `_convert_krea2_native_to_diffusers` renames `.weight` keys by substring *and* renames five
+ more by whole-key equality. Neither carries a sibling scale: `.scale_weight` and `.input_scale`
+ do not contain `.weight`, and `last.linear.weight_scale` is not equal to `last.linear.weight`.
+ An orphaned scale is then dropped by `extract_fp8_scaled_layers` (no fp8 weight sits at the old
+ path any more) and the weight is left quantized but unscaled - off by exactly 1/weight_scale,
+ with nothing logged, because the layer never enters `fp8_layers` for
+ `warn_on_unattached_scales` to see.
+ """
+
+ @staticmethod
+ def _convert(sd: dict) -> dict:
+ detached = detach_layer_sidechannel(sd)
+ converted = _convert_krea2_native_to_diffusers(sd)
+ orphaned = reattach_layer_sidechannel(converted, detached, _remap_native_layer_paths(set(detached)))
+ return converted, orphaned
+
+ def test_every_spelling_and_rename_style_survives(self) -> None:
+ fp8 = torch.ones(4, 4).to(FP8_DTYPE)
+ sd = {
+ # substring rename, `.weight_scale` spelling
+ "blocks.0.attn.wq.weight": fp8.clone(),
+ "blocks.0.attn.wq.weight_scale": torch.tensor(0.5),
+ "blocks.0.attn.wq.input_scale": torch.tensor(0.25),
+ # substring rename, `.scale_weight` spelling
+ "blocks.0.attn.wk.weight": fp8.clone(),
+ "blocks.0.attn.wk.scale_weight": torch.tensor(0.5),
+ # whole-key-equality rename
+ "last.linear.weight": fp8.clone(),
+ "last.linear.weight_scale": torch.tensor(0.5),
+ }
+
+ converted, orphaned = self._convert(sd)
+ layers = extract_fp8_scaled_layers(converted)
+
+ assert set(layers) == {
+ "transformer_blocks.0.attn.to_q",
+ "transformer_blocks.0.attn.to_k",
+ "final_layer.linear",
+ }
+ assert orphaned == []
+ # The calibrated activation scale must come across too, or every forward pays an amax pass.
+ assert layers["transformer_blocks.0.attn.to_q"].input_scale is not None
+
+ def test_no_fp8_weight_is_left_without_its_scale(self) -> None:
+ """The property that actually matters, stated directly."""
+ fp8 = torch.ones(4, 4).to(FP8_DTYPE)
+ sd = {
+ "blocks.0.attn.wk.weight": fp8.clone(),
+ "blocks.0.attn.wk.scale_weight": torch.tensor(0.5),
+ "last.linear.weight": fp8.clone(),
+ "last.linear.weight_scale": torch.tensor(0.5),
+ }
+
+ converted, _ = self._convert(sd)
+ layers = extract_fp8_scaled_layers(converted)
+
+ unscaled = [
+ key
+ for key, value in converted.items()
+ if key.endswith(".weight")
+ and getattr(value, "dtype", None) is FP8_DTYPE
+ and key[: -len(".weight")] not in layers
+ ]
+ assert unscaled == []
+
+ def test_a_scale_on_a_dropped_module_is_reported(self) -> None:
+ """`last.down`/`last.up` have no diffusers counterpart, so their scales go too - loudly."""
+ sd = {
+ "last.down.weight": torch.ones(4, 4).to(FP8_DTYPE),
+ "last.down.weight_scale": torch.tensor(0.5),
+ }
+
+ _, orphaned = self._convert(sd)
+
+ assert orphaned == ["last.down"]
diff --git a/tests/backend/quantization/test_fp8_scaled.py b/tests/backend/quantization/test_fp8_scaled.py
index af6c68565b..cd666ac8aa 100644
--- a/tests/backend/quantization/test_fp8_scaled.py
+++ b/tests/backend/quantization/test_fp8_scaled.py
@@ -12,6 +12,7 @@ from invokeai.backend.quantization.fp8_scaled import (
count_fp8_weights,
dequantize_fp8_scaled,
dequantize_weight,
+ detach_layer_sidechannel,
device_supports_fp8_matmul,
extract_comfy_quant_hints,
extract_fp8_scaled_layers,
@@ -19,11 +20,13 @@ from invokeai.backend.quantization.fp8_scaled import (
iter_weight_scale_pairs,
parse_quantization_metadata,
predict_cast_state_dict_size,
+ reattach_layer_sidechannel,
reset_fp8_matmul_support_cache,
scaled_mm_linear,
set_fp8_matmul_enabled,
set_full_precision_hints_respected,
split_fp8_scaled_layers,
+ strip_layer_path_prefix,
warn_on_unattached_scales,
)
@@ -770,3 +773,192 @@ class TestScaleSpellingHelpers:
# `norm.scale` is a real learned parameter in several architectures - stripping it would
# delete weights, and it is why this cannot just match "scale" anywhere in the key.
assert not is_scale_metadata_key(key)
+
+
+def _fp8(rows: int = 4, cols: int = 4, value: float = 1.0) -> torch.Tensor:
+ return (torch.ones(rows, cols) * value).to(FP8_DTYPE)
+
+
+class _Linear(torch.nn.Module):
+ def __init__(self, out_features: int = 4, in_features: int = 4) -> None:
+ super().__init__()
+ self.lin = torch.nn.Linear(in_features, out_features, bias=False)
+
+
+class TestE5m2ScaleRecovery:
+ """`float8_e5m2` may not stay quantized, but it must not lose its scale on the way to bf16."""
+
+ def test_the_scale_is_recovered_and_folded(self) -> None:
+ # Gating extraction on e4m3fn alone popped the scale key and then dropped it, so
+ # `cast_state_dict` did a plain `.to(bf16)` and the weight came out off by 1/weight_scale.
+ sd = {"lin.weight": (torch.ones(4, 4) * 2).to(torch.float8_e5m2), "lin.weight_scale": torch.tensor(0.25)}
+
+ layers = extract_fp8_scaled_layers(sd)
+ assert "lin" in layers
+
+ dequantize_fp8_scaled(sd, layers, torch.bfloat16)
+ assert torch.allclose(sd["lin.weight"].float(), torch.full((4, 4), 0.5))
+
+ def test_it_is_never_left_quantized(self) -> None:
+ """`scaled_mm_linear` cannot take e5m2 as the weight operand, so it must be widened."""
+ sd = {"lin.weight": (torch.ones(4, 4) * 2).to(torch.float8_e5m2), "lin.weight_scale": torch.tensor(0.25)}
+
+ kept = split_fp8_scaled_layers(sd, extract_fp8_scaled_layers(sd), torch.bfloat16, model=_Linear())
+
+ assert kept == {}
+ assert sd["lin.weight"].dtype is torch.bfloat16
+ assert torch.allclose(sd["lin.weight"].float(), torch.full((4, 4), 0.5))
+
+
+class TestBlockWiseScale:
+ """A 2-D ``weight_scale`` has one entry per *block* of weight elements, not per row."""
+
+ def test_the_layout_survives_extraction(self) -> None:
+ # Flattening it destroys the block geometry, and the multiply then fails on shape.
+ sd = {"b.weight": _fp8(64, 128), "b.weight_scale": torch.full((64, 2), 0.5)}
+
+ layers = extract_fp8_scaled_layers(sd)
+
+ assert tuple(layers["b"].weight_scale.shape) == (64, 2)
+
+ def test_it_is_expanded_rather_than_raising(self) -> None:
+ # Before: `RuntimeError: The size of tensor a (64) must match the size of tensor b (128)`,
+ # i.e. with fp8_compute off - the default - the model failed to load at all.
+ sd = {"b.weight": _fp8(64, 128), "b.weight_scale": torch.full((64, 2), 0.5)}
+
+ dequantize_fp8_scaled(sd, extract_fp8_scaled_layers(sd), torch.bfloat16)
+
+ assert sd["b.weight"].shape == (64, 128)
+ assert torch.allclose(sd["b.weight"].float(), torch.full((64, 128), 0.5))
+
+ def test_it_is_never_left_quantized(self) -> None:
+ """`scaled_mm_linear` can apply a per-tensor or per-row scale and nothing else.
+
+ Left quantized, the mismatch surfaces mid-generation inside the kernel instead.
+ Dequantizing here - before `predict_cast_state_dict_size` runs - also keeps the RAM
+ reservation honest.
+ """
+ sd = {"lin.weight": _fp8(4, 4), "lin.weight_scale": torch.full((4, 2), 0.5)}
+
+ kept = split_fp8_scaled_layers(sd, extract_fp8_scaled_layers(sd), torch.bfloat16, model=_Linear())
+
+ assert kept == {}
+ assert sd["lin.weight"].dtype is torch.bfloat16
+
+ def test_a_per_row_scale_still_stays_quantized(self) -> None:
+ sd = {"lin.weight": _fp8(4, 4), "lin.weight_scale": torch.full((4,), 0.5)}
+
+ kept = split_fp8_scaled_layers(sd, extract_fp8_scaled_layers(sd), torch.bfloat16, model=_Linear())
+
+ assert set(kept) == {"lin"}
+ assert sd["lin.weight"].dtype is FP8_DTYPE
+
+
+class TestSidechannelDetachReattach:
+ """Key converters rename ``.weight``; the side channel has to be carried across separately."""
+
+ def test_entries_follow_their_module_to_the_new_path(self) -> None:
+ sd = {
+ "old.linear.weight": _fp8(),
+ "old.linear.weight_scale": torch.tensor(0.5),
+ "old.linear.input_scale": torch.tensor(0.25),
+ }
+
+ detached = detach_layer_sidechannel(sd)
+ assert list(sd) == ["old.linear.weight"], "scales must be out of the converter's way"
+
+ converted = {"new.linear.weight": sd["old.linear.weight"]}
+ orphaned = reattach_layer_sidechannel(converted, detached, {"old.linear": "new.linear"})
+
+ assert orphaned == []
+ layers = extract_fp8_scaled_layers(converted)
+ assert set(layers) == {"new.linear"}
+ assert layers["new.linear"].input_scale is not None
+
+ def test_a_module_the_converter_drops_is_reported_not_swallowed(self) -> None:
+ """A silently dropped scale is exactly the failure this pair exists to prevent."""
+ sd = {"gone.weight": _fp8(), "gone.weight_scale": torch.tensor(0.5)}
+
+ detached = detach_layer_sidechannel(sd)
+ orphaned = reattach_layer_sidechannel({}, detached, {})
+
+ assert orphaned == ["gone"]
+
+ def test_both_scale_spellings_are_detached(self) -> None:
+ sd = {
+ "a.weight": _fp8(),
+ "a.scale_weight": torch.tensor(0.5),
+ "b.weight": _fp8(),
+ "b.weight_scale": torch.tensor(0.5),
+ }
+
+ detached = detach_layer_sidechannel(sd)
+
+ assert set(detached) == {"a", "b"}
+
+
+class TestStripLayerPathPrefix:
+ """`_quantization_metadata` is read from the file header, so its names keep the prefix."""
+
+ def test_the_checkpoint_prefix_is_removed(self) -> None:
+ hints = {"model.diffusion_model.blocks.0.attn.wq": {"full_precision_matrix_mult": True}}
+
+ assert strip_layer_path_prefix(hints) == {"blocks.0.attn.wq": {"full_precision_matrix_mult": True}}
+
+ def test_unprefixed_names_are_passed_through_not_dropped(self) -> None:
+ """Running the names through a prefix *filter* truncated a partially-prefixed header, and
+ the strict-zip that read the result back aborted the whole load with a ValueError."""
+ hints = {"net.blocks.0.attn.q_proj": {}, "final_layer.linear": {}}
+
+ assert set(strip_layer_path_prefix(hints)) == {"blocks.0.attn.q_proj", "final_layer.linear"}
+
+
+class TestNonFloatTensorsAreNotCast:
+ """Integer payloads are not weights; casting them to the compute dtype corrupts them."""
+
+ def test_cast_state_dict_leaves_them_alone(self) -> None:
+ sd = {"w.weight": torch.ones(2, 2), "ids": torch.arange(4, dtype=torch.int64)}
+
+ cast_state_dict(sd, torch.bfloat16, keep_fp8=False)
+
+ assert sd["w.weight"].dtype is torch.bfloat16
+ assert sd["ids"].dtype is torch.int64
+
+ def test_the_size_prediction_agrees(self) -> None:
+ sd = {"ids": torch.arange(4, dtype=torch.int64)}
+
+ assert predict_cast_state_dict_size(sd, torch.bfloat16, keep_fp8=False) == 4 * 8
+
+
+class TestProbeFailureCaching:
+ """The probe runs during a model load, i.e. under real VRAM pressure."""
+
+ def test_an_allocation_failure_is_not_cached(self) -> None:
+ reset_fp8_matmul_support_cache()
+ device = torch.device("cuda", 0)
+ with (
+ mock.patch("torch.cuda.is_available", return_value=True),
+ mock.patch("torch.cuda.get_device_capability", return_value=(8, 9)),
+ mock.patch("torch.cuda.current_device", return_value=0),
+ ):
+ with mock.patch("torch._scaled_mm", side_effect=torch.OutOfMemoryError("transient")):
+ assert device_supports_fp8_matmul(device) is False
+ # A momentary OOM must not disable fp8 for the rest of the process.
+ with mock.patch("torch._scaled_mm", return_value=torch.zeros(1)):
+ assert device_supports_fp8_matmul(device) is True
+ reset_fp8_matmul_support_cache()
+
+ def test_a_genuine_unsupported_op_is_cached(self) -> None:
+ reset_fp8_matmul_support_cache()
+ device = torch.device("cuda", 0)
+ with (
+ mock.patch("torch.cuda.is_available", return_value=True),
+ mock.patch("torch.cuda.get_device_capability", return_value=(8, 9)),
+ mock.patch("torch.cuda.current_device", return_value=0),
+ ):
+ with mock.patch("torch._scaled_mm", side_effect=RuntimeError("not supported on this device")):
+ assert device_supports_fp8_matmul(device) is False
+ # No second probe: the answer cannot change at runtime.
+ with mock.patch("torch._scaled_mm", side_effect=AssertionError("must not be probed again")):
+ assert device_supports_fp8_matmul(device) is False
+ reset_fp8_matmul_support_cache()