Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(quantization): run ComfyUI scaled-fp8 checkpoints on the fp8 tensor cores

Alexander Eichhorn1bec90128a10
diff --git a/invokeai/app/services/config/config_default.py b/invokeai/app/services/config/config_default.py
index ae1e38e0cc..8d7446a30f 100644
--- a/invokeai/app/services/config/config_default.py
+++ b/invokeai/app/services/config/config_default.py
@@ -106,6 +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.
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.
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.
@@ -204,6 +205,7 @@ class InvokeAIAppConfig(BaseSettings):
device_working_mem_gb: float = Field(default=3, description="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: bool = Field(default=True, description="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: bool = Field(default=True, description="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: bool = Field(default=False, description="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.")
# Deprecated CACHE configs
ram: Optional[float] = Field(default=None, gt=0, description="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: Optional[float] = Field(default=None, ge=0, description="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_cache/torch_module_autocast/custom_modules/custom_linear.py b/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_linear.py
index 77227583cd..f8b80a9b4d 100644
--- a/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_linear.py
+++ b/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_linear.py
@@ -9,6 +9,13 @@ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custo
from invokeai.backend.patches.layers.base_layer_patch import BaseLayerPatch
from invokeai.backend.patches.layers.flux_control_lora_layer import FluxControlLoRALayer
from invokeai.backend.patches.layers.lora_layer import LoRALayer
+from invokeai.backend.quantization.fp8_scaled import (
+ FP8_DTYPE,
+ dequantize_weight,
+ device_supports_fp8_matmul,
+ is_fp8_matmul_enabled,
+ scaled_mm_linear,
+)
from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor
@@ -89,15 +96,57 @@ class CustomLinear(torch.nn.Linear, CustomModuleMixin):
return tensor
def _cast_weight_bias_for_input(self, input: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor | None]:
- weight = self._cast_tensor_for_input(self.weight, input)
+ weight = cast_to_device(self.weight, input.device)
+ assert weight is not None
+ if weight.dtype == FP8_DTYPE:
+ # A scaled fp8 weight must never be cast with a plain `.to(dtype)`: that drops the
+ # scale and yields a wrongly-scaled weight. `weight_scale` is None for fp8 weights that
+ # carry no scale (e.g. produced by fp8_storage layerwise casting), where a plain cast
+ # is correct.
+ weight = dequantize_weight(weight, self._fp8_weight_scale(input.device), input.dtype)
+ else:
+ weight = self._cast_tensor_for_input(weight, input)
bias = self._cast_tensor_for_input(self.bias, input)
assert weight is not None
return weight, bias
+ def _fp8_weight_scale(self, device: torch.device) -> torch.Tensor | None:
+ scale = getattr(self, "weight_scale", None)
+ return cast_to_device(scale, device) if scale is not None else None
+
+ def _can_use_fp8_matmul(self, input: torch.Tensor) -> bool:
+ """Whether this forward may run on the fp8 tensor cores.
+
+ Every condition is a hard requirement of `torch._scaled_mm` or an explicit instruction from
+ the checkpoint producer; failing any of them falls back to the dequantized path rather than
+ raising, because a mid-generation failure is far worse than losing the speedup.
+ """
+ if not is_fp8_matmul_enabled():
+ return False
+ if self.weight.dtype != FP8_DTYPE or not input.is_floating_point():
+ return False
+ if getattr(self, "_fp8_full_precision_matmul", False):
+ # The producer measured this layer as unsafe to multiply in fp8.
+ return False
+ if not device_supports_fp8_matmul(input.device):
+ return False
+ if self.in_features % 16 != 0 or self.out_features % 16 != 0:
+ return False
+ # Partial loading may leave the weight on the CPU; _scaled_mm needs both operands co-located.
+ return self.weight.device == input.device
+
def _autocast_forward_with_patches(self, input: torch.Tensor) -> torch.Tensor:
return autocast_linear_forward_sidecar_patches(self, input, self._patches_and_weights)
def _autocast_forward(self, input: torch.Tensor) -> torch.Tensor:
+ if self._can_use_fp8_matmul(input):
+ return scaled_mm_linear(
+ input,
+ self.weight,
+ self._fp8_weight_scale(input.device),
+ cast_to_device(self.bias, input.device),
+ input_scale=cast_to_device(getattr(self, "input_scale", None), input.device),
+ )
weight, bias = self._cast_weight_bias_for_input(input)
return torch.nn.functional.linear(input, weight, bias)
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.py
index 98cd4a2dec..47fb401e06 100644
--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py
+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py
@@ -24,6 +24,14 @@ from invokeai.backend.model_manager.taxonomy import (
ModelType,
SubModelType,
)
+from invokeai.backend.quantization.fp8_scaled import (
+ FP8_DTYPE,
+ attach_fp8_scales,
+ dequantize_fp8_scaled,
+ extract_fp8_scaled_layers,
+ is_fp8_matmul_enabled,
+ parse_quantization_metadata,
+)
from invokeai.backend.quantization.gguf.loaders import gguf_sd_loader
from invokeai.backend.util.devices import TorchDevice
@@ -112,6 +120,31 @@ def _dequantize_scaled_fp8(sd: dict[str, Any]) -> dict[str, Any]:
return out
+def _remap_native_layer_paths(layer_names: Any) -> dict[str, str]:
+ """Map native/ComfyUI layer paths to their diffusers equivalents.
+
+ ``_quantization_metadata`` names its layers in the checkpoint's own (native) scheme, but the
+ scales are extracted after the state dict has been renamed. Rather than restating the rename
+ rules - which would drift - each name is pushed through the real converter as a lone
+ ``<name>.weight`` entry and the resulting key is read back.
+ """
+ import torch
+
+ mapping: dict[str, str] = {}
+ for name in layer_names:
+ if not isinstance(name, str):
+ continue
+ try:
+ converted = _convert_krea2_native_to_diffusers({f"{name}.weight": torch.empty(0)})
+ except Exception:
+ continue
+ for key in converted:
+ if isinstance(key, str) and key.endswith(".weight"):
+ mapping[name] = key[: -len(".weight")]
+ break
+ return mapping
+
+
def _convert_krea2_native_to_diffusers(sd: dict[str, Any]) -> dict[str, Any]:
"""Convert a native/ComfyUI-format Krea-2 state dict (e.g. GGUF) to diffusers Krea2Transformer2DModel keys.
@@ -331,27 +364,58 @@ class Krea2CheckpointModel(ModelLoader):
raise TypeError(f"Expected Main_Checkpoint_Krea2_Config, got {type(config).__name__}.")
model_path = Path(config.path)
+ from safetensors import safe_open
+
sd = load_file(model_path)
+ with safe_open(model_path, framework="pt") as f:
+ metadata = f.metadata()
sd = _strip_comfyui_prefix(sd)
- # ComfyUI 'scaled fp8' checkpoints: fold the per-tensor weight_scale into the weights (→ float).
- sd = _dequantize_scaled_fp8(sd)
- # Native/ComfyUI key naming → diffusers Krea2Transformer2DModel keys.
+ # Native/ComfyUI key naming → diffusers Krea2Transformer2DModel keys. Done *before* the fp8
+ # scales are pulled out: the renames are substring-based on ".weight", so a sibling
+ # ".weight_scale" is carried to the same destination key automatically.
+ layer_hints = parse_quantization_metadata(metadata)
if _is_native_krea2_format(sd):
sd = _convert_krea2_native_to_diffusers(sd)
+ # The metadata still names layers natively; rename it the same way or its per-layer
+ # flags (notably full_precision_matrix_mult) match nothing.
+ path_map = _remap_native_layer_paths(layer_hints.keys())
+ layer_hints = {path_map.get(name, name): hints for name, hints in layer_hints.items()}
target_device = TorchDevice.choose_torch_device()
model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
+ # ComfyUI 'scaled fp8' checkpoints (fp8 weight + .weight_scale, optionally .input_scale).
+ fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)
+ if fp8_layers and not is_fp8_matmul_enabled():
+ # Legacy behavior: fold the scales into the weights. Keeping them quantized without the
+ # fp8 matmul would halve VRAM but run slower, so both are tied to the same setting.
+ dequantize_fp8_scaled(sd, fp8_layers, model_dtype)
+ fp8_layers = {}
+
with accelerate.init_empty_weights():
model = Krea2Transformer2DModel(**KREA2_TRANSFORMER_CONFIG)
- new_sd_size = sum(ten.nelement() * model_dtype.itemsize for ten in sd.values())
+ # fp8 weights keep their own (1-byte) footprint; everything else lands in model_dtype.
+ new_sd_size = sum(
+ ten.nelement() * (ten.element_size() if ten.dtype == FP8_DTYPE else model_dtype.itemsize)
+ for ten in sd.values()
+ )
self._ram_cache.make_room(new_sd_size)
for k in sd.keys():
- sd[k] = sd[k].to(model_dtype)
+ if sd[k].dtype is not FP8_DTYPE:
+ sd[k] = sd[k].to(model_dtype)
model.load_state_dict(sd, assign=True, strict=False)
_reject_incomplete_load(model, what="Krea-2 single-file checkpoint")
+
+ if fp8_layers:
+ attached = attach_fp8_scales(model, fp8_layers)
+ self._logger.info(f"Krea-2: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, fp8_compute enabled)")
+ # The layerwise-casting path exists to *produce* fp8 weights from full-precision ones. The
+ # checkpoint already is fp8, and its hooks would cast back to the compute dtype without
+ # applying weight_scale, so it must not run here.
+ return model
+
# Honor the fp8-storage setting (re-quantizes the dequantized weights to fp8-resident on CUDA).
model = self._apply_fp8_layerwise_casting(model, config, SubModelType.Transformer)
return model
diff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.py
new file mode 100644
index 0000000000..5d03a0134c
--- /dev/null
+++ b/invokeai/backend/quantization/fp8_scaled.py
@@ -0,0 +1,319 @@
+"""Shared handling for ComfyUI-style "scaled fp8" checkpoints.
+
+These checkpoints store each quantized Linear as:
+
+ <path>.weight float8_e4m3fn
+ <path>.weight_scale float32 (usually a scalar; per-output-channel also occurs)
+ <path>.input_scale float32 (optional; a calibrated *static* activation scale)
+
+so that ``w_real ≈ weight.to(float) * weight_scale``. Some producers use ``.scale_weight`` instead
+of ``.weight_scale``. A ``_quantization_metadata`` entry in the safetensors header may additionally
+mark individual layers with ``full_precision_matrix_mult``, meaning the producer determined that
+this layer must not be multiplied in fp8.
+
+Historically InvokeAI dequantized these to bf16 at load time (three near-identical implementations
+in the FLUX.2, Z-Image and Qwen-Image loaders). That throws away both the VRAM saving and the
+ability to run the matmul on the fp8 tensor cores. This module keeps the quantization intact so
+that :class:`CustomLinear` can decide per forward what to do with it.
+"""
+
+from dataclasses import dataclass
+from typing import Any, Iterable, Mapping
+
+import torch
+
+FP8_DTYPE = torch.float8_e4m3fn
+
+WEIGHT_SCALE_SUFFIXES = (".weight_scale", ".scale_weight")
+INPUT_SCALE_SUFFIX = ".input_scale"
+
+QUANT_METADATA_KEY = "_quantization_metadata"
+
+# Standalone marker keys some producers emit alongside the tensors. They carry no per-layer data.
+STRAY_METADATA_KEYS = ("scaled_fp8",)
+
+
+@dataclass
+class Fp8ScaledLayer:
+ """The quantization parameters recovered for a single Linear."""
+
+ weight_scale: torch.Tensor
+ """Scalar, or shape ``(out_features,)`` for per-output-channel quantization."""
+
+ input_scale: torch.Tensor | None = None
+ """Calibrated static activation scale, if the checkpoint ships one."""
+
+ full_precision_matmul: bool = False
+ """The producer marked this layer as unsafe for an fp8 matmul; only dequantized use is allowed."""
+
+ def is_per_tensor(self) -> bool:
+ return self.weight_scale.numel() == 1
+
+
+def parse_quantization_metadata(metadata: Mapping[str, Any] | None) -> dict[str, dict[str, Any]]:
+ """Parse the safetensors ``_quantization_metadata`` header entry into a per-layer mapping.
+
+ Returns an empty dict when the entry is absent or unparseable - the scales themselves are the
+ source of truth, the metadata only adds per-layer hints.
+ """
+ if not metadata:
+ return {}
+ raw = metadata.get(QUANT_METADATA_KEY)
+ if not raw:
+ return {}
+ if isinstance(raw, (bytes, bytearray)):
+ raw = raw.decode("utf-8", errors="replace")
+ if isinstance(raw, str):
+ import json
+
+ try:
+ raw = json.loads(raw)
+ except ValueError:
+ return {}
+ if not isinstance(raw, dict):
+ return {}
+ layers = raw.get("layers")
+ return layers if isinstance(layers, dict) else {}
+
+
+def _strip_scale_suffix(key: str) -> tuple[str, str] | None:
+ for suffix in WEIGHT_SCALE_SUFFIXES:
+ if key.endswith(suffix):
+ return key[: -len(suffix)], suffix
+ if key.endswith(INPUT_SCALE_SUFFIX):
+ return key[: -len(INPUT_SCALE_SUFFIX)], INPUT_SCALE_SUFFIX
+ return None
+
+
+def extract_fp8_scaled_layers(
+ sd: dict[str, Any],
+ metadata: Mapping[str, Any] | None = None,
+ layer_hints: Mapping[str, Mapping[str, Any]] | None = None,
+) -> dict[str, Fp8ScaledLayer]:
+ """Pop the quantization side-channel out of ``sd`` and return it keyed by module path.
+
+ ``sd`` is modified in place: scale and marker keys are removed so the remaining state dict
+ loads cleanly into a model that knows nothing about fp8. The ``.weight`` tensors are left as
+ float8 - the caller decides whether to keep or dequantize them.
+
+ Only layers whose ``.weight`` is actually float8 are reported; a stray scale without a matching
+ fp8 weight is dropped rather than silently mis-scaling a bf16 weight.
+
+ ``layer_hints`` overrides the parsed metadata. Loaders that rename checkpoint keys (native →
+ diffusers) must pass hints keyed by the *renamed* paths, otherwise the per-layer flags -
+ including ``full_precision_matrix_mult`` - silently match nothing.
+ """
+ layer_meta = dict(layer_hints) if layer_hints is not None else parse_quantization_metadata(metadata)
+
+ weight_scales: dict[str, torch.Tensor] = {}
+ input_scales: dict[str, torch.Tensor] = {}
+ for key in list(sd.keys()):
+ if not isinstance(key, str):
+ continue
+ parsed = _strip_scale_suffix(key)
+ if parsed is None:
+ continue
+ path, suffix = parsed
+ if suffix == INPUT_SCALE_SUFFIX:
+ input_scales[path] = sd.pop(key)
+ else:
+ weight_scales[path] = sd.pop(key)
+
+ for key in list(sd.keys()):
+ if isinstance(key, str) and (key in STRAY_METADATA_KEYS or "comfy_quant" in key):
+ del sd[key]
+
+ 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:
+ # 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(),
+ input_scale=input_scales.get(path).float().reshape(()) if path in input_scales else None,
+ full_precision_matmul=bool(hints.get("full_precision_matrix_mult", False)),
+ )
+ return layers
+
+
+def dequantize_fp8_scaled(
+ sd: dict[str, Any],
+ layers: Mapping[str, Fp8ScaledLayer],
+ dtype: torch.dtype = torch.bfloat16,
+) -> dict[str, Any]:
+ """Fold the scales back into the weights, producing a plain ``dtype`` state dict.
+
+ This is the legacy behavior, kept as the fallback for models/devices that cannot use the fp8
+ path. The multiply runs in float32 for precision but the result is stored as ``dtype``
+ immediately, so a cold load never holds the whole model in float32.
+ """
+ for path, layer in layers.items():
+ key = f"{path}.weight"
+ 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)
+ return sd
+
+
+def attach_fp8_scales(
+ model: torch.nn.Module,
+ layers: Mapping[str, Fp8ScaledLayer],
+ module_paths: Iterable[str] | None = None,
+) -> int:
+ """Register the recovered scales as buffers on the matching modules.
+
+ ``CustomLinear`` looks for ``weight_scale`` / ``input_scale`` buffers and a
+ ``_fp8_full_precision_matmul`` flag. The buffers are non-persistent: they must never end up in
+ ``state_dict()`` output, or a re-save would produce a checkpoint that gets scaled twice.
+
+ Returns the number of modules that were annotated.
+ """
+ wanted = set(module_paths) if module_paths is not None else None
+ count = 0
+ for path, layer in layers.items():
+ if wanted is not None and path not in wanted:
+ continue
+ try:
+ module = model.get_submodule(path) if path else model
+ except AttributeError:
+ continue
+ weight = getattr(module, "weight", None)
+ if weight is None or weight.dtype != FP8_DTYPE:
+ continue
+ module.register_buffer("weight_scale", layer.weight_scale.to(weight.device), persistent=False)
+ if layer.input_scale is not None:
+ module.register_buffer("input_scale", layer.input_scale.to(weight.device), persistent=False)
+ module._fp8_full_precision_matmul = layer.full_precision_matmul
+ count += 1
+ return count
+
+
+# ----------------------------------------------------------------------------------- runtime path
+
+FP8_MAX = torch.finfo(FP8_DTYPE).max
+
+# torch._scaled_mm requires every GEMM dimension to be a multiple of 16.
+_MM_ALIGNMENT = 16
+
+_fp8_mm_supported: dict[int, bool] = {}
+
+# fp8 compute quantizes the *activations* as well, so it changes numerics: an existing install would
+# start producing different images at the same seed. It is therefore opt-in (`fp8_compute` in
+# invokeai.yaml) for one release before becoming the default.
+#
+# The same flag also decides whether scaled fp8 checkpoints stay quantized at load. Keeping them
+# quantized without the fp8 matmul would halve VRAM but make generation *slower* (the dequantize
+# round trip costs more than it saves), so the two must be switched together.
+_fp8_matmul_override: bool | None = None
+
+
+def set_fp8_matmul_enabled(enabled: bool | None) -> None:
+ """Override the configured setting process-wide. Pass ``None`` to revert to the config value."""
+ global _fp8_matmul_override
+ _fp8_matmul_override = enabled
+
+
+def is_fp8_matmul_enabled() -> bool:
+ if _fp8_matmul_override is not None:
+ return _fp8_matmul_override
+ try:
+ from invokeai.app.services.config.config_default import get_config
+
+ return bool(get_config().fp8_compute)
+ except Exception:
+ # Backend code may run outside a configured app (scripts, tests). Default to the safe path.
+ return False
+
+
+def device_supports_fp8_matmul(device: torch.device) -> bool:
+ """Whether ``torch._scaled_mm`` can run on this device (Ada/SM 8.9 and newer)."""
+ if device.type != "cuda" or not torch.cuda.is_available():
+ 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:
+ cached = torch.cuda.get_device_capability(index) >= (8, 9)
+ _fp8_mm_supported[index] = cached
+ return cached
+
+
+def dequantize_weight(weight: torch.Tensor, weight_scale: torch.Tensor | None, dtype: torch.dtype) -> torch.Tensor:
+ """Cast an fp8 weight up to ``dtype``, applying its scale if it has one.
+
+ Used by the fallback path. Casting *without* the scale - which is what a plain ``.to(dtype)``
+ does - silently produces a wrongly-scaled weight, so every dequantization of a scaled fp8
+ weight must go through here.
+ """
+ out = weight.to(dtype)
+ 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
+
+
+def scaled_mm_linear(
+ input: torch.Tensor,
+ weight: torch.Tensor,
+ weight_scale: torch.Tensor | None,
+ bias: torch.Tensor | None = None,
+ input_scale: torch.Tensor | None = None,
+) -> torch.Tensor:
+ """``F.linear`` executed on the fp8 tensor cores via ``torch._scaled_mm``.
+
+ ``weight`` stays float8 and is never materialized in a wider dtype - that is where both the
+ VRAM and the speed come from.
+
+ Scaling notes:
+ - The activation scale is per-tensor. Ada rejects per-row activation scaling outright, and
+ a static ``input_scale`` from the checkpoint is used when available (calibrated, and it saves
+ the per-forward ``amax`` reduction).
+ - A per-output-channel weight scale cannot be handed to ``_scaled_mm`` on Ada either, but it is
+ separable: scaling row ``j`` of the weight scales output column ``j``, so it is applied to the
+ result instead. Per-tensor scales go straight into the kernel.
+ """
+ orig_shape = input.shape
+ x = input.reshape(-1, orig_shape[-1])
+
+ # The transpose must be produced here rather than cached: a stored transposed view stops being a
+ # view the moment the tensor is moved between devices (which partial loading does constantly),
+ # silently doubling the weight memory.
+ weight_t = weight.t()
+
+ pad = (-x.shape[0]) % _MM_ALIGNMENT
+ if pad:
+ x = torch.nn.functional.pad(x, (0, 0, 0, pad))
+
+ if input_scale is not None:
+ x_scale = input_scale.to(device=x.device, dtype=torch.float32).reshape(1, 1)
+ x_fp8 = (x / x_scale.to(x.dtype)).clamp(-FP8_MAX, FP8_MAX).to(FP8_DTYPE)
+ else:
+ amax = x.abs().amax().clamp(min=1e-12)
+ x_scale = (amax / FP8_MAX).float().reshape(1, 1)
+ x_fp8 = (x / x_scale.to(x.dtype)).to(FP8_DTYPE)
+
+ per_tensor = weight_scale is not None and weight_scale.numel() == 1
+ if per_tensor:
+ w_scale = weight_scale.to(device=x.device, dtype=torch.float32).reshape(1, 1)
+ else:
+ w_scale = torch.ones(1, 1, device=x.device, dtype=torch.float32)
+
+ out = torch._scaled_mm(x_fp8.contiguous(), weight_t, x_scale, w_scale, out_dtype=input.dtype)
+
+ if pad:
+ out = out[: x.shape[0] - pad]
+ if weight_scale is not None and not per_tensor:
+ out = out * weight_scale.to(device=out.device, dtype=out.dtype).reshape(1, -1)
+
+ out = out.reshape(*orig_shape[:-1], weight.shape[0])
+ if bias is not None:
+ out = out + bias.to(dtype=out.dtype)
+ return out
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index add72e7ac5..0a04f57f01 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -48051,6 +48051,12 @@
"description": "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.",
"default": true
},
+ "fp8_compute": {
+ "type": "boolean",
+ "title": "Fp8 Compute",
+ "description": "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.",
+ "default": false
+ },
"ram": {
"anyOf": [
{
@@ -48402,7 +48408,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 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`, `cuda: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 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 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."
+ "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 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`, `cuda: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 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 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."
},
"InvokeAIAppConfigWithSetFields": {
"properties": {
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index 001aa2233c..0e9d34e072 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -18525,6 +18525,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.
* 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.
* 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.
@@ -18821,6 +18822,12 @@ export type components = {
* @default true
*/
keep_ram_copy_of_weights?: boolean;
+ /**
+ * Fp8 Compute
+ * @description 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.
+ * @default false
+ */
+ fp8_compute?: boolean;
/**
* Ram
* @description 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.
diff --git a/tests/backend/quantization/test_fp8_scaled.py b/tests/backend/quantization/test_fp8_scaled.py
new file mode 100644
index 0000000000..d5abc22bb2
--- /dev/null
+++ b/tests/backend/quantization/test_fp8_scaled.py
@@ -0,0 +1,265 @@
+import pytest
+import torch
+
+from invokeai.backend.quantization.fp8_scaled import (
+ FP8_DTYPE,
+ Fp8ScaledLayer,
+ attach_fp8_scales,
+ dequantize_fp8_scaled,
+ dequantize_weight,
+ device_supports_fp8_matmul,
+ extract_fp8_scaled_layers,
+ parse_quantization_metadata,
+ scaled_mm_linear,
+ set_fp8_matmul_enabled,
+)
+
+cuda_fp8 = pytest.mark.skipif(
+ not (torch.cuda.is_available() and device_supports_fp8_matmul(torch.device("cuda"))),
+ reason="requires a CUDA device with fp8 tensor cores (SM 8.9+)",
+)
+
+
+def _fp8_weight(out_f: int, in_f: int, per_channel: bool = False):
+ w = torch.randn(out_f, in_f, dtype=torch.bfloat16) * 0.02
+ if per_channel:
+ scale = (w.abs().amax(dim=1) / torch.finfo(FP8_DTYPE).max).float().clamp(min=1e-12)
+ q = (w / scale.reshape(-1, 1)).to(FP8_DTYPE)
+ else:
+ scale = (w.abs().amax() / torch.finfo(FP8_DTYPE).max).float().clamp(min=1e-12)
+ q = (w / scale).to(FP8_DTYPE)
+ return q, scale
+
+
+class TestExtract:
+ def test_pops_scales_and_keys_layer_by_path(self):
+ q, scale = _fp8_weight(32, 16)
+ sd = {"blk.0.lin.weight": q, "blk.0.lin.weight_scale": scale, "blk.0.lin.bias": torch.zeros(32)}
+ layers = extract_fp8_scaled_layers(sd)
+ assert set(layers) == {"blk.0.lin"}
+ assert "blk.0.lin.weight_scale" not in sd, "scale keys must be removed so the sd loads cleanly"
+ assert sd["blk.0.lin.weight"].dtype == FP8_DTYPE, "weights must stay quantized"
+
+ def test_accepts_scale_weight_suffix(self):
+ q, scale = _fp8_weight(32, 16)
+ sd = {"lin.weight": q, "lin.scale_weight": scale}
+ assert set(extract_fp8_scaled_layers(sd)) == {"lin"}
+
+ def test_input_scale_is_captured(self):
+ q, scale = _fp8_weight(32, 16)
+ sd = {"lin.weight": q, "lin.weight_scale": scale, "lin.input_scale": torch.tensor(0.5)}
+ assert extract_fp8_scaled_layers(sd)["lin"].input_scale == pytest.approx(0.5)
+
+ def test_scale_without_fp8_weight_is_dropped(self):
+ """A scale applied to an already-dequantized weight would corrupt it."""
+ sd = {"lin.weight": torch.randn(32, 16, dtype=torch.bfloat16), "lin.weight_scale": torch.tensor(2.0)}
+ assert extract_fp8_scaled_layers(sd) == {}
+ assert "lin.weight_scale" not in sd
+
+ def test_strips_stray_marker_keys(self):
+ q, scale = _fp8_weight(32, 16)
+ sd = {
+ "lin.weight": q,
+ "lin.weight_scale": scale,
+ "scaled_fp8": torch.tensor(0.0),
+ "comfy_quant_x": torch.tensor(1),
+ }
+ extract_fp8_scaled_layers(sd)
+ assert set(sd) == {"lin.weight"}
+
+ def test_full_precision_hint_from_metadata(self):
+ q, scale = _fp8_weight(32, 16)
+ sd = {"a.weight": q, "a.weight_scale": scale, "b.weight": q.clone(), "b.weight_scale": scale.clone()}
+ meta = {"_quantization_metadata": '{"layers": {"a": {"full_precision_matrix_mult": true}, "b": {}}}'}
+ layers = extract_fp8_scaled_layers(sd, meta)
+ assert layers["a"].full_precision_matmul is True
+ assert layers["b"].full_precision_matmul is False
+
+ def test_malformed_metadata_is_ignored(self):
+ assert parse_quantization_metadata({"_quantization_metadata": "not json"}) == {}
+ assert parse_quantization_metadata(None) == {}
+
+ def test_layer_hints_override_metadata(self):
+ q, scale = _fp8_weight(32, 16)
+ sd = {"renamed.lin.weight": q, "renamed.lin.weight_scale": scale}
+ # Metadata uses the pre-rename path, so only the explicitly remapped hints can match.
+ meta = {"_quantization_metadata": '{"layers": {"native.lin": {"full_precision_matrix_mult": true}}}'}
+ layers = extract_fp8_scaled_layers(
+ dict(sd), metadata=meta, layer_hints={"renamed.lin": {"full_precision_matrix_mult": True}}
+ )
+ assert layers["renamed.lin"].full_precision_matmul is True
+
+ # Without the remap the flag silently matches nothing - the regression this guards against.
+ layers = extract_fp8_scaled_layers(dict(sd), metadata=meta)
+ assert layers["renamed.lin"].full_precision_matmul is False
+
+
+class TestKrea2MetadataRemap:
+ def test_native_layer_paths_are_remapped_like_the_state_dict(self):
+ """The quantization metadata names layers natively; the scales are keyed after renaming."""
+ from invokeai.backend.model_manager.load.model_loaders.krea2 import _remap_native_layer_paths
+
+ mapping = _remap_native_layer_paths(
+ ["blocks.0.attn.wq", "blocks.0.attn.wo", "blocks.3.mlp.down", "txtfusion.refiner_blocks.1.attn.wk"]
+ )
+ assert mapping["blocks.0.attn.wq"] == "transformer_blocks.0.attn.to_q"
+ assert mapping["blocks.0.attn.wo"] == "transformer_blocks.0.attn.to_out.0"
+ assert mapping["blocks.3.mlp.down"] == "transformer_blocks.3.ff.down"
+ assert mapping["txtfusion.refiner_blocks.1.attn.wk"] == "text_fusion.refiner_blocks.1.attn.to_k"
+
+
+class TestDequantize:
+ @pytest.mark.parametrize("per_channel", [False, True])
+ def test_roundtrip_close_to_original(self, per_channel: bool):
+ w = torch.randn(64, 32, dtype=torch.bfloat16) * 0.02
+ scale_src = w.abs().amax(dim=1) if per_channel else w.abs().amax()
+ scale = (scale_src / torch.finfo(FP8_DTYPE).max).float().clamp(min=1e-12)
+ q = (w / (scale.reshape(-1, 1) if per_channel else scale)).to(FP8_DTYPE)
+
+ out = dequantize_weight(q, scale, torch.bfloat16)
+ assert out.dtype == torch.bfloat16
+ assert ((out.float() - w.float()).norm() / w.float().norm()).item() < 0.05
+
+ def test_missing_scale_is_a_plain_cast(self):
+ """fp8_storage layerwise casting produces scale-free fp8 weights."""
+ q = torch.randn(8, 8, dtype=torch.bfloat16).to(FP8_DTYPE)
+ assert torch.equal(dequantize_weight(q, None, torch.bfloat16), q.to(torch.bfloat16))
+
+ def test_state_dict_dequantization_matches_helper(self):
+ q, scale = _fp8_weight(64, 32)
+ sd = {"lin.weight": q}
+ layers = {"lin": Fp8ScaledLayer(weight_scale=scale)}
+ dequantize_fp8_scaled(sd, layers)
+ assert torch.equal(sd["lin.weight"], dequantize_weight(q, scale, torch.bfloat16))
+
+
+class TestAttach:
+ def test_registers_non_persistent_buffers(self):
+ lin = torch.nn.Linear(16, 32, bias=False)
+ q, scale = _fp8_weight(32, 16)
+ lin.weight = torch.nn.Parameter(q, requires_grad=False)
+ model = torch.nn.Sequential(lin)
+
+ assert attach_fp8_scales(model, {"0": Fp8ScaledLayer(weight_scale=scale, full_precision_matmul=True)}) == 1
+ assert torch.equal(model[0].weight_scale, scale)
+ assert model[0]._fp8_full_precision_matmul is True
+ # Re-saving a model whose scales landed in state_dict() would double-scale on reload.
+ assert "0.weight_scale" not in model.state_dict()
+
+ def test_skips_non_fp8_modules(self):
+ model = torch.nn.Sequential(torch.nn.Linear(16, 32))
+ assert attach_fp8_scales(model, {"0": Fp8ScaledLayer(weight_scale=torch.tensor(1.0))}) == 0
+
+
+@cuda_fp8
+class TestScaledMm:
+ @pytest.mark.parametrize("per_channel", [False, True])
+ @pytest.mark.parametrize("tokens", [64, 100]) # 100 is deliberately not a multiple of 16
+ def test_matches_reference_linear(self, per_channel: bool, tokens: int):
+ dev = torch.device("cuda")
+ q, scale = _fp8_weight(256, 128, per_channel)
+ q, scale = q.to(dev), scale.to(dev)
+ w_ref = dequantize_weight(q, scale, torch.bfloat16)
+ x = torch.randn(tokens, 128, device=dev, dtype=torch.bfloat16)
+
+ got = scaled_mm_linear(x, q, scale)
+ expected = torch.nn.functional.linear(x, w_ref)
+
+ assert got.shape == expected.shape
+ rel = ((got.float() - expected.float()).norm() / expected.float().norm()).item()
+ assert rel < 0.08, f"relative error {rel:.4f} too high"
+
+ def test_preserves_leading_dims_and_bias(self):
+ dev = torch.device("cuda")
+ q, scale = _fp8_weight(64, 32)
+ q, scale = q.to(dev), scale.to(dev)
+ bias = torch.randn(64, device=dev, dtype=torch.bfloat16)
+ x = torch.randn(2, 48, 32, device=dev, dtype=torch.bfloat16)
+
+ got = scaled_mm_linear(x, q, scale, bias)
+ expected = torch.nn.functional.linear(x, dequantize_weight(q, scale, torch.bfloat16), bias)
+ assert got.shape == (2, 48, 64)
+ assert ((got.float() - expected.float()).norm() / expected.float().norm()).item() < 0.08
+
+ def test_static_input_scale_path(self):
+ dev = torch.device("cuda")
+ q, scale = _fp8_weight(64, 32)
+ q, scale = q.to(dev), scale.to(dev)
+ x = torch.randn(32, 32, device=dev, dtype=torch.bfloat16)
+ static = (x.abs().amax() / torch.finfo(FP8_DTYPE).max).float()
+
+ got = scaled_mm_linear(x, q, scale, input_scale=static)
+ expected = torch.nn.functional.linear(x, dequantize_weight(q, scale, torch.bfloat16))
+ assert ((got.float() - expected.float()).norm() / expected.float().norm()).item() < 0.08
+
+
+class TestCustomLinearIntegration:
+ """The fp8 matmul must be opt-in and must degrade to the dequantized path, never raise."""
+
+ def _module(self, device: torch.device, in_f=64, out_f=128):
+ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (
+ apply_custom_layers_to_model,
+ )
+
+ lin = torch.nn.Linear(in_f, out_f, bias=False)
+ q, scale = _fp8_weight(out_f, in_f)
+ lin.weight = torch.nn.Parameter(q.to(device), requires_grad=False)
+ lin.register_buffer("weight_scale", scale.to(device), persistent=False)
+ model = torch.nn.Sequential(lin).to(device)
+ apply_custom_layers_to_model(model)
+ return model
+
+ def test_disabled_by_default_uses_scaled_dequant(self):
+ """With the matmul off, the weight must still be dequantized *with* its scale."""
+ set_fp8_matmul_enabled(False)
+ dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+ model = self._module(dev)
+ x = torch.randn(32, 64, device=dev, dtype=torch.bfloat16)
+
+ got = model(x)
+ w_ref = dequantize_weight(model[0].weight, model[0].weight_scale, torch.bfloat16)
+ expected = torch.nn.functional.linear(x, w_ref)
+ assert torch.equal(got, expected)
+
+ @cuda_fp8
+ def test_full_precision_flag_forces_fallback(self):
+ set_fp8_matmul_enabled(True)
+ try:
+ dev = torch.device("cuda")
+ model = self._module(dev)
+ model[0]._fp8_full_precision_matmul = True
+ x = torch.randn(32, 64, device=dev, dtype=torch.bfloat16)
+
+ got = model(x)
+ w_ref = dequantize_weight(model[0].weight, model[0].weight_scale, torch.bfloat16)
+ assert torch.equal(got, torch.nn.functional.linear(x, w_ref))
+ finally:
+ set_fp8_matmul_enabled(False)
+
+ @cuda_fp8
+ def test_unaligned_features_fall_back(self):
+ set_fp8_matmul_enabled(True)
+ try:
+ dev = torch.device("cuda")
+ model = self._module(dev, in_f=60, out_f=120) # not multiples of 16
+ x = torch.randn(16, 60, device=dev, dtype=torch.bfloat16)
+ assert model(x).shape == (16, 120) # must not raise
+ finally:
+ set_fp8_matmul_enabled(False)
+
+ @cuda_fp8
+ def test_enabled_path_agrees_with_fallback(self):
+ dev = torch.device("cuda")
+ model = self._module(dev)
+ x = torch.randn(48, 64, device=dev, dtype=torch.bfloat16)
+
+ set_fp8_matmul_enabled(False)
+ baseline = model(x)
+ set_fp8_matmul_enabled(True)
+ try:
+ fp8 = model(x)
+ finally:
+ set_fp8_matmul_enabled(False)
+
+ rel = ((fp8.float() - baseline.float()).norm() / baseline.float().norm()).item()
+ assert rel < 0.1, f"fp8 matmul diverges from the dequantized path by {rel:.4f}"