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): keep the Qwen3-VL encoder's unquantized layers fp8-resident

Alexander Eichhorna3784ebfc99e
diff --git a/invokeai/app/services/config/config_default.py b/invokeai/app/services/config/config_default.py
index 8d7446a30f..f4857bb173 100644
--- a/invokeai/app/services/config/config_default.py
+++ b/invokeai/app/services/config/config_default.py
@@ -206,6 +206,7 @@ class InvokeAIAppConfig(BaseSettings):
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.")
+ fp8_compute_full_precision_hints: bool = Field(default=True, description="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.")
# 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/load_default.py b/invokeai/backend/model_manager/load/load_default.py
index ba617b2b55..e84a084a3a 100644
--- a/invokeai/backend/model_manager/load/load_default.py
+++ b/invokeai/backend/model_manager/load/load_default.py
@@ -6,7 +6,7 @@ import itertools
import re
from logging import Logger
from pathlib import Path
-from typing import Optional
+from typing import Callable, Optional
import torch
@@ -323,7 +323,12 @@ class ModelLoader(ModelLoaderBase):
return model
@staticmethod
- def _apply_fp8_to_nn_module(model: torch.nn.Module, storage_dtype: torch.dtype, compute_dtype: torch.dtype) -> None:
+ def _apply_fp8_to_nn_module(
+ model: torch.nn.Module,
+ storage_dtype: torch.dtype,
+ compute_dtype: torch.dtype,
+ skip: Optional[Callable[[str, torch.nn.Module], bool]] = None,
+ ) -> None:
"""Apply FP8 layerwise casting to a plain nn.Module.
Mirrors diffusers' `apply_layerwise_casting` semantics: only the layer classes in
@@ -331,12 +336,20 @@ class ModelLoader(ModelLoaderBase):
`_FP8_DEFAULT_SKIP_PATTERNS` (norm, pos_embed, patch_embed, proj_in/out) are skipped.
Without the skip list, precision-sensitive tiny learned scalars (e.g. FLUX RMSNorm.scale)
get crushed to FP8 and quality degrades noticeably.
+
+ `skip` excludes further modules by (dotted name, module). Its one caller uses it to leave
+ scaled-fp8 layers alone: those already hold fp8 weights plus a `weight_scale`, and the cast
+ hooks installed here would upcast them *without* applying that scale — a silently wrong
+ weight. Casting only the remainder lets a partly-quantized checkpoint (fp8 language model,
+ bf16 visual tower) end up fully fp8-resident.
"""
for module_name, module in model.named_modules():
if not isinstance(module, _FP8_SUPPORTED_PYTORCH_LAYERS):
continue
if any(re.search(pattern, module_name) for pattern in _FP8_DEFAULT_SKIP_PATTERNS):
continue
+ if skip is not None and skip(module_name, module):
+ continue
params = list(module.parameters(recurse=False))
if not params:
continue
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.py
index 593e18b0c1..6eeb4eecd5 100644
--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py
+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py
@@ -28,7 +28,10 @@ from invokeai.backend.quantization.fp8_scaled import (
FP8_DTYPE,
attach_fp8_scales,
dequantize_fp8_scaled,
+ device_supports_fp8_matmul,
+ extract_comfy_quant_hints,
extract_fp8_scaled_layers,
+ full_precision_hints_respected,
is_fp8_matmul_enabled,
parse_quantization_metadata,
)
@@ -388,7 +391,13 @@ class Krea2CheckpointModel(ModelLoader):
# 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)
+ #
+ # 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)}
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
@@ -426,6 +435,23 @@ class Krea2CheckpointModel(ModelLoader):
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)")
+ # Marked layers dequantize on every forward instead of using the tensor cores, which is
+ # the single biggest lever on how much fp8_compute actually buys for a given checkpoint.
+ # Surface it: otherwise "fp8_compute is on but barely faster" has no visible cause.
+ marked = sum(1 for layer in fp8_layers.values() if layer.full_precision_matmul)
+ if marked:
+ if full_precision_hints_respected():
+ self._logger.info(
+ f"Krea-2: {marked} of {len(fp8_layers)} layer(s) are marked "
+ "full_precision_matrix_mult and will dequantize per forward. Set "
+ "fp8_compute_full_precision_hints=false to run them on the fp8 tensor cores "
+ "instead (faster, but overrides the checkpoint producer's instruction)."
+ )
+ else:
+ self._logger.info(
+ f"Krea-2: ignoring the full_precision_matrix_mult marker on {marked} layer(s) "
+ "(fp8_compute_full_precision_hints=false)."
+ )
# fp8_storage exists to *create* fp8 weights from full-precision ones; here they already
# are fp8, so it is bypassed entirely. Say so, otherwise a user who enabled it is left
# wondering whether it took effect.
@@ -545,12 +571,26 @@ class Qwen3VLEncoderLoader(ModelLoader):
)
-def _remap_qwen3vl_singlefile_keys(sd: dict[str, Any]) -> dict[str, Any]:
- """Remap ComfyUI single-file Qwen3-VL keys to the transformers ``Qwen3VLModel`` layout.
+def _qwen3vl_target_key(key: str) -> str:
+ """Map one ComfyUI single-file Qwen3-VL key (or module path) to the transformers layout.
ComfyUI/native layout uses a single ``model.`` prefix for both towers; transformers splits them:
``model.visual.*`` -> ``visual.*`` and ``model.<rest>`` (layers/embed_tokens/norm) -> ``language_model.<rest>``.
+
+ Shared by the state-dict remap and the fp8 layer-hint remap so the two cannot drift apart: a hint
+ keyed by a path the model does not have matches nothing and is silently ignored.
"""
+ # Strip a leading "model." (some checkpoints prefix everything with it), then route by tower.
+ key = key[len("model.") :] if key.startswith("model.") else key
+ if key.startswith("visual.") or key.startswith("language_model."):
+ # Already the transformers layout (e.g. "model.language_model.*" / "model.visual.*").
+ return key
+ # Bare language-model keys (layers.* / embed_tokens / norm) belong under language_model.
+ return "language_model." + key
+
+
+def _remap_qwen3vl_singlefile_keys(sd: dict[str, Any]) -> dict[str, Any]:
+ """Remap ComfyUI single-file Qwen3-VL keys to the transformers ``Qwen3VLModel`` layout."""
out: dict[str, Any] = {}
source_of: dict[Any, Any] = {}
what = "Qwen3-VL encoder checkpoint"
@@ -558,14 +598,7 @@ def _remap_qwen3vl_singlefile_keys(sd: dict[str, Any]) -> dict[str, Any]:
if not isinstance(k, str):
_put_unique_key(out, k, v, source=k, source_of=source_of, what=what)
continue
- # Strip a leading "model." (some checkpoints prefix everything with it), then route by tower.
- key = k[len("model.") :] if k.startswith("model.") else k
- if key.startswith("visual.") or key.startswith("language_model."):
- # Already the transformers layout (e.g. "model.language_model.*" / "model.visual.*").
- _put_unique_key(out, key, v, source=k, source_of=source_of, what=what)
- else:
- # Bare language-model keys (layers.* / embed_tokens / norm) belong under language_model.
- _put_unique_key(out, "language_model." + key, v, source=k, source_of=source_of, what=what)
+ _put_unique_key(out, _qwen3vl_target_key(k), v, source=k, source_of=source_of, what=what)
return out
@@ -649,31 +682,85 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):
model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
sd = load_file(str(model_path))
- # Detect an fp8 source (ComfyUI 'scaled fp8' weight_scale keys, or raw float8 weights) BEFORE
- # dequantizing. An fp8-on-disk encoder is kept fp8-resident with layerwise upcasting below, so
- # it occupies ~half the VRAM of the dequantized bf16 model (the whole point of shipping fp8).
- source_is_fp8 = any(isinstance(k, str) and k.endswith(".weight_scale") for k in sd) or any(
- getattr(t, "dtype", None) in (torch.float8_e4m3fn, torch.float8_e5m2) for t in sd.values()
- )
- # ComfyUI 'scaled fp8': fold weight_scale into the weights, then drop quantization metadata.
- sd = _dequantize_scaled_fp8(sd)
+ metadata = _read_safetensors_metadata(model_path, self._logger)
+ # Per-layer markers must be read before extract_fp8_scaled_layers() drops them, and before
+ # the key remap, which would not carry a ".comfy_quant" suffix to a sensible destination.
+ layer_hints = {**extract_comfy_quant_hints(sd), **parse_quantization_metadata(metadata)}
+ # A legacy activation-scale marker this loader has never consumed.
for k in list(sd.keys()):
- if isinstance(k, str) and (k.endswith(".comfy_quant") or "scale_input" in k):
+ if isinstance(k, str) and "scale_input" in k:
del sd[k]
+
+ # Remap BEFORE pulling the scales out. The remap rewrites whole keys, so each
+ # ".weight_scale" travels with its ".weight" and the recovered layer paths already match the
+ # model's module paths — which is what attach_fp8_scales() resolves them against.
sd = _remap_qwen3vl_singlefile_keys(sd)
+ layer_hints = {_qwen3vl_target_key(path): hints for path, hints in layer_hints.items()}
+
+ # ComfyUI 'scaled fp8' (fp8 weight + .weight_scale). Only the language-model linears are
+ # quantized in the checkpoints seen so far; the visual tower stays bf16 either way.
+ fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)
+ source_is_fp8 = bool(fp8_layers) or any(
+ getattr(t, "dtype", None) in (torch.float8_e4m3fn, torch.float8_e5m2) for t in sd.values()
+ )
+ keep_fp8 = bool(fp8_layers) and is_fp8_matmul_enabled() and device_supports_fp8_matmul(target_device)
+ if fp8_layers and not keep_fp8:
+ # Legacy behavior: fold the scales into the weights. Without the fp8 matmul, staying
+ # quantized would save VRAM but cost speed, so the two are tied to the same setting.
+ dequantize_fp8_scaled(sd, fp8_layers, model_dtype)
+ fp8_layers = {}
te_config = self._load_hf_config()
with accelerate.init_empty_weights():
model = Qwen3VLModel._from_config(te_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="Qwen3-VL encoder checkpoint")
+ if fp8_layers:
+ # Keep the weights quantized and let CustomLinear run their matmuls on the fp8 tensor
+ # cores. Same resident VRAM as the layerwise-casting path below, but without paying a
+ # fp8->bf16 round trip on every forward.
+ attached = attach_fp8_scales(model, fp8_layers)
+ # The checkpoint quantizes only the language-model linears; the visual tower ships bf16
+ # and would make the encoder ~0.4GB larger resident than the plain fp8_storage path. On a
+ # GPU already holding a ~12GB transformer that is enough to push the transformer into
+ # partial loading, so cast the rest to fp8 storage. Two exclusions:
+ #
+ # - anything carrying a `weight_scale`: those keep their scale and go through
+ # _scaled_mm; the cast hooks would upcast them without it, i.e. a wrong weight.
+ # - `nn.Embedding`: the token embedding table is this model's *input* representation
+ # and it is large (389M params). Measured on qwen3vl_4b_fp8_scaled, quantizing it
+ # doubles the encoder's error against bf16 (relative L2 0.0079 -> 0.0163) to save
+ # 371MiB. That is a bad trade for a model whose entire job is text fidelity. (The
+ # old fp8_storage path did cast it — this is strictly more accurate than before.)
+ self._apply_fp8_to_nn_module(
+ model,
+ storage_dtype=torch.float8_e4m3fn,
+ compute_dtype=model_dtype,
+ skip=lambda _name, module: getattr(module, "weight_scale", None) is not None
+ or isinstance(module, torch.nn.Embedding),
+ )
+ self._logger.info(
+ f"FP8 compute enabled for Qwen3-VL encoder '{config.name}': kept {attached} layer(s) "
+ f"quantized (storage=float8_e4m3fn, matmul=torch._scaled_mm, compute={model_dtype}); "
+ "remaining layers cast to fp8 storage."
+ )
+ # The layerwise-casting path below exists to *produce* fp8 weights from full-precision
+ # ones. These already are fp8, and its hooks would cast them to the compute dtype without
+ # applying weight_scale — a silently wrong weight. It must not run here.
+ return model
+
# Keep an fp8 encoder running in fp8 (storage=float8_e4m3fn, per-layer upcast to the compute
# dtype during forward) on CUDA. `_should_use_fp8` deliberately excludes text encoders (and the
# config has no fp8_storage toggle), so apply the hook-based casting directly here. This roughly
diff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.py
index 5d03a0134c..54067dcc4e 100644
--- a/invokeai/backend/quantization/fp8_scaled.py
+++ b/invokeai/backend/quantization/fp8_scaled.py
@@ -29,6 +29,9 @@ INPUT_SCALE_SUFFIX = ".input_scale"
QUANT_METADATA_KEY = "_quantization_metadata"
+# Per-layer marker tensor written by ComfyUI exports that do not use the header entry above.
+COMFY_QUANT_SUFFIX = ".comfy_quant"
+
# Standalone marker keys some producers emit alongside the tensors. They carry no per-layer data.
STRAY_METADATA_KEYS = ("scaled_fp8",)
@@ -76,6 +79,45 @@ def parse_quantization_metadata(metadata: Mapping[str, Any] | None) -> dict[str,
return layers if isinstance(layers, dict) else {}
+def extract_comfy_quant_hints(sd: dict[str, Any]) -> dict[str, dict[str, Any]]:
+ """Decode per-layer ``<path>.comfy_quant`` markers into the same mapping
+ :func:`parse_quantization_metadata` produces, popping them out of ``sd``.
+
+ ComfyUI writes the per-layer quantization flags in one of two places. Newer exports use the
+ safetensors *header* (``_quantization_metadata``); others store one uint8 JSON blob per
+ quantized layer as an ordinary tensor, e.g.::
+
+ model.layers.0.mlp.down_proj.comfy_quant
+ -> {"format": "float8_e4m3fn", "full_precision_matrix_mult": false}
+
+ Both forms carry ``full_precision_matrix_mult`` - the producer's instruction that a layer must
+ not be multiplied in fp8. A loader that reads only the header therefore *silently ignores that
+ instruction* on a checkpoint using the per-tensor form, and runs an fp8 matmul the producer
+ measured as unsafe. Checkpoints using the per-tensor form and marking layers this way exist in
+ the wild, so both forms must be read.
+
+ Malformed blobs are skipped rather than raised on: the marker is an optimization hint, and the
+ scales themselves remain the source of truth.
+ """
+ import json
+
+ hints: dict[str, dict[str, Any]] = {}
+ for key in list(sd.keys()):
+ if not isinstance(key, str) or not key.endswith(COMFY_QUANT_SUFFIX):
+ continue
+ raw = sd.pop(key)
+ path = key[: -len(COMFY_QUANT_SUFFIX)]
+ try:
+ # A uint8 tensor holding UTF-8 JSON, sometimes NUL-padded to a fixed width.
+ blob = bytes(raw.flatten().tolist()).decode("utf-8", errors="replace").rstrip("\x00")
+ parsed = json.loads(blob)
+ except Exception:
+ continue
+ if isinstance(parsed, dict):
+ hints[path] = parsed
+ return hints
+
+
def _strip_scale_suffix(key: str) -> tuple[str, str] | None:
for suffix in WEIGHT_SCALE_SUFFIXES:
if key.endswith(suffix):
@@ -173,9 +215,14 @@ def attach_fp8_scales(
``_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.
+ The producer's ``full_precision_matrix_mult`` markers are applied here rather than dropped at
+ parse time, so the recovered metadata stays inspectable, and are suppressed when the user has
+ turned the hints off (see :func:`full_precision_hints_respected`).
+
Returns the number of modules that were annotated.
"""
wanted = set(module_paths) if module_paths is not None else None
+ respect_hints = full_precision_hints_respected()
count = 0
for path, layer in layers.items():
if wanted is not None and path not in wanted:
@@ -190,7 +237,7 @@ def attach_fp8_scales(
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
+ module._fp8_full_precision_matmul = layer.full_precision_matmul and respect_hints
count += 1
return count
@@ -232,6 +279,36 @@ def is_fp8_matmul_enabled() -> bool:
return False
+_full_precision_hints_override: bool | None = None
+
+
+def set_full_precision_hints_respected(respected: bool | None) -> None:
+ """Override the configured setting process-wide. Pass ``None`` to revert to the config value."""
+ global _full_precision_hints_override
+ _full_precision_hints_override = respected
+
+
+def full_precision_hints_respected() -> bool:
+ """Whether ``full_precision_matrix_mult`` markers are obeyed.
+
+ Honoring a marker means that layer dequantizes on every forward instead of using the fp8 tensor
+ cores, and that is not cheap: on a checkpoint that marks the attention output, gate and FFN-down
+ projections (a common choice) the marked layers can be ~40% of the quantized weights, and
+ measurably erase most of the fp8_compute speedup. Whether that trade is worth it depends on how
+ much the producer's flags actually buy in a given checkpoint, so it is a user-facing setting
+ rather than a hard-coded policy.
+ """
+ if _full_precision_hints_override is not None:
+ return _full_precision_hints_override
+ try:
+ from invokeai.app.services.config.config_default import get_config
+
+ return bool(get_config().fp8_compute_full_precision_hints)
+ except Exception:
+ # Backend code may run outside a configured app (scripts, tests). Default to obeying them.
+ return True
+
+
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():
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index 25414cff36..7479edb4e2 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -48057,6 +48057,12 @@
"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_full_precision_hints": {
+ "type": "boolean",
+ "title": "Fp8 Compute Full Precision Hints",
+ "description": "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.",
+ "default": true
+ },
"ram": {
"anyOf": [
{
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index 56b735b966..b6ca2cbf4d 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -18828,6 +18828,12 @@ export type components = {
* @default false
*/
fp8_compute?: boolean;
+ /**
+ * Fp8 Compute Full Precision Hints
+ * @description 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.
+ * @default true
+ */
+ fp8_compute_full_precision_hints?: 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
index 15e2ef1492..03a6729888 100644
--- a/tests/backend/quantization/test_fp8_scaled.py
+++ b/tests/backend/quantization/test_fp8_scaled.py
@@ -8,10 +8,12 @@ from invokeai.backend.quantization.fp8_scaled import (
dequantize_fp8_scaled,
dequantize_weight,
device_supports_fp8_matmul,
+ extract_comfy_quant_hints,
extract_fp8_scaled_layers,
parse_quantization_metadata,
scaled_mm_linear,
set_fp8_matmul_enabled,
+ set_full_precision_hints_respected,
)
cuda_fp8 = pytest.mark.skipif(
@@ -94,6 +96,101 @@ class TestExtract:
assert layers["renamed.lin"].full_precision_matmul is False
+def _comfy_quant_blob(full_precision: bool):
+ """The per-layer marker some ComfyUI exports write instead of the header entry."""
+ payload = f'{{"format": "float8_e4m3fn", "full_precision_matrix_mult": {"true" if full_precision else "false"}}}'
+ return torch.tensor(list(payload.encode("utf-8")), dtype=torch.uint8)
+
+
+class TestComfyQuantHints:
+ def test_reads_per_layer_markers_and_pops_them(self):
+ sd = {
+ "blk.0.lin.weight": _fp8_weight(32, 16)[0],
+ "blk.0.lin.comfy_quant": _comfy_quant_blob(True),
+ "blk.1.lin.comfy_quant": _comfy_quant_blob(False),
+ }
+ hints = extract_comfy_quant_hints(sd)
+ assert hints["blk.0.lin"]["full_precision_matrix_mult"] is True
+ assert hints["blk.1.lin"]["full_precision_matrix_mult"] is False
+ assert not [k for k in sd if "comfy_quant" in k], "markers must not reach load_state_dict"
+
+ def test_full_precision_flag_reaches_the_layer(self):
+ """The regression this guards: a checkpoint carrying the flags *only* in per-layer markers
+ had them silently ignored, so layers the producer marked unsafe were multiplied in fp8."""
+ q, scale = _fp8_weight(32, 16)
+ sd = {"blk.0.lin.weight": q, "blk.0.lin.weight_scale": scale, "blk.0.lin.comfy_quant": _comfy_quant_blob(True)}
+ hints = extract_comfy_quant_hints(sd)
+ layers = extract_fp8_scaled_layers(sd, layer_hints=hints)
+ assert layers["blk.0.lin"].full_precision_matmul is True
+
+ # Reading only the header (no hints) is what used to happen - the flag matches nothing.
+ sd2 = {"blk.0.lin.weight": q, "blk.0.lin.weight_scale": scale, "blk.0.lin.comfy_quant": _comfy_quant_blob(True)}
+ assert extract_fp8_scaled_layers(sd2).get("blk.0.lin").full_precision_matmul is False
+
+ def test_nul_padded_and_malformed_blobs(self):
+ padded = torch.cat([_comfy_quant_blob(True), torch.zeros(8, dtype=torch.uint8)])
+ sd = {
+ "a.comfy_quant": padded,
+ "b.comfy_quant": torch.tensor(list(b"not json"), dtype=torch.uint8),
+ }
+ hints = extract_comfy_quant_hints(sd)
+ assert hints["a"]["full_precision_matrix_mult"] is True
+ # A malformed marker is a lost hint, never a failed load.
+ assert "b" not in hints
+ assert not sd
+
+
+class TestQwen3VLKeyRemap:
+ def test_scale_keys_and_hint_paths_land_on_the_same_module(self):
+ """attach_fp8_scales resolves hint paths against the *model*, so the state-dict remap and the
+ hint remap must agree - otherwise every recovered scale silently matches nothing."""
+ from invokeai.backend.model_manager.load.model_loaders.krea2 import (
+ _qwen3vl_target_key,
+ _remap_qwen3vl_singlefile_keys,
+ )
+
+ q, scale = _fp8_weight(32, 16)
+ sd = _remap_qwen3vl_singlefile_keys(
+ {
+ "model.layers.0.mlp.down_proj.weight": q,
+ "model.layers.0.mlp.down_proj.weight_scale": scale,
+ "model.visual.blocks.0.attn.qkv.weight": torch.zeros(16, 16),
+ }
+ )
+ assert "language_model.layers.0.mlp.down_proj.weight_scale" in sd
+ assert "visual.blocks.0.attn.qkv.weight" in sd
+
+ hints = {_qwen3vl_target_key("model.layers.0.mlp.down_proj"): {"full_precision_matrix_mult": True}}
+ layers = extract_fp8_scaled_layers(sd, layer_hints=hints)
+ assert set(layers) == {"language_model.layers.0.mlp.down_proj"}
+ assert layers["language_model.layers.0.mlp.down_proj"].full_precision_matmul is True
+
+
+class TestFullPrecisionHintToggle:
+ def test_marker_is_applied_by_default(self):
+ q, scale = _fp8_weight(32, 16)
+ module = torch.nn.Linear(16, 32, bias=False)
+ module.weight = torch.nn.Parameter(q, requires_grad=False)
+ model = torch.nn.Sequential()
+ model.add_module("lin", module)
+ attach_fp8_scales(model, {"lin": Fp8ScaledLayer(weight_scale=scale, full_precision_matmul=True)})
+ assert module._fp8_full_precision_matmul is True
+
+ def test_marker_suppressed_when_hints_are_off(self):
+ """Turning the hints off must reach the module flag CustomLinear reads, not just the parse."""
+ q, scale = _fp8_weight(32, 16)
+ module = torch.nn.Linear(16, 32, bias=False)
+ module.weight = torch.nn.Parameter(q, requires_grad=False)
+ model = torch.nn.Sequential()
+ model.add_module("lin", module)
+ set_full_precision_hints_respected(False)
+ try:
+ attach_fp8_scales(model, {"lin": Fp8ScaledLayer(weight_scale=scale, full_precision_matmul=True)})
+ finally:
+ set_full_precision_hints_respected(None)
+ assert module._fp8_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."""