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 matmul probe off the forward path, probe CUDA for storage

Alexander Eichhorn43a154659af1
diff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.py
index a5c887c8b5..c1d696d0e1 100644
--- a/invokeai/backend/model_manager/load/load_default.py
+++ b/invokeai/backend/model_manager/load/load_default.py
@@ -83,8 +83,13 @@ def _device_supports_fp8_storage(device: torch.device, logger: Optional[Logger]
"""Whether FP8 layerwise casting (float8 weight storage + upcast) is usable on this device.
The feature needs only float8 *storage* and casting to the compute dtype -- not native FP8
- matmul -- so it holds on CUDA and, for current torch builds, on Intel XPU. XPU float8 support is
- build/driver dependent ("emerging" on Xe2), so probe it rather than assume.
+ matmul -- so it is within reach of CUDA and, for current torch builds, of Intel XPU. Neither is
+ assumed: float8 support is build- and driver-dependent on both ("emerging" on Xe2), and ROCm
+ reports ``device.type == "cuda"`` while its float8 coverage varies by architecture -- gfx90a
+ prefers ``e4m3fnuz``, and older gfx has no ``e4m3fn`` conversion at all. Exempting the CUDA
+ branch let such a build pass the gate, have its weights cast on the CPU (which always works) and
+ moved to VRAM, and then raise "not implemented for 'Float8_e4m3fn'" on the first forward --
+ after the VRAM was committed, rather than here where the fallback lives.
The probe allocates on the *given* device rather than an index-less ``"xpu"``, which would
resolve through the thread's current XPU device -- not necessarily the device the caller is
@@ -100,9 +105,7 @@ def _device_supports_fp8_storage(device: torch.device, logger: Optional[Logger]
may be transiently out of memory, and a cached failure would silently disable FP8 for the
lifetime of the process with no remedy short of a restart.
"""
- if device.type == "cuda":
- return True
- if device.type != "xpu":
+ if device.type not in ("cuda", "xpu"):
return False
device = TorchDevice.normalize(device)
diff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.py
index 964d00744c..46e0d8d46e 100644
--- a/invokeai/backend/quantization/fp8_scaled.py
+++ b/invokeai/backend/quantization/fp8_scaled.py
@@ -722,6 +722,15 @@ _MM_ALIGNMENT = 16
_fp8_mm_supported: dict[int, bool] = {}
+# Devices whose probe could not be *carried out* (see `_probe_fp8_matmul`). Deliberately apart from
+# the result cache above, because the two are read by callers with opposite needs. A load can afford
+# to re-probe and must, or one transient OOM would disable fp8 for the rest of the process; a
+# forward cannot, because `CustomLinear._can_use_fp8_matmul` asks once per quantized Linear per step
+# and an unrecorded inconclusive answer means probing all of them, every step, forever. So the
+# answer is recorded for the forward path and `should_keep_fp8_weights` drops it, which keeps the
+# retry on the load where it belongs.
+_fp8_mm_inconclusive: set[int] = set()
+
# 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.
@@ -844,6 +853,10 @@ def device_supports_fp8_matmul(device: torch.device) -> bool:
cached = _fp8_mm_supported.get(index)
if cached is not None:
return cached
+ if index in _fp8_mm_inconclusive:
+ # A probe already failed to answer for this device and nothing has started a new load since.
+ # Re-running it here would run it on every quantized Linear of every step.
+ return False
# The capability check is only a cheap pre-filter that spares older CUDA cards the probe;
# it is deliberately not trusted on its own (see `_probe_fp8_matmul`).
if not (torch.version.hip is not None or torch.cuda.get_device_capability(index) >= (8, 9)):
@@ -851,16 +864,31 @@ def device_supports_fp8_matmul(device: torch.device) -> bool:
return False
probed = _probe_fp8_matmul(index)
if probed is None:
- # Inconclusive: answer this call conservatively but leave the cache empty so the next load
- # re-probes instead of the process being stuck without fp8 after one transient OOM.
+ # Inconclusive: answer conservatively, and record *that* rather than the verdict, so the next
+ # load re-probes while the forwards in between stay cheap.
+ _fp8_mm_inconclusive.add(index)
return False
_fp8_mm_supported[index] = probed
return probed
+def forget_inconclusive_fp8_matmul_probe(device: torch.device) -> None:
+ """Let the next support check re-probe a device whose probe could not be carried out.
+
+ Called at the head of a load. A probe that failed for want of VRAM, or during a driver hiccup,
+ must not outlive the load it happened on -- but it also must not be retried from the forward
+ path. This is the boundary between the two.
+ """
+ if device.type != "cuda" or not torch.cuda.is_available():
+ return
+ index = device.index if device.index is not None else torch.cuda.current_device()
+ _fp8_mm_inconclusive.discard(index)
+
+
def reset_fp8_matmul_support_cache() -> None:
"""Forget the probed per-device support. For tests; the answer cannot change at runtime."""
_fp8_mm_supported.clear()
+ _fp8_mm_inconclusive.clear()
def should_keep_fp8_weights(device: torch.device) -> bool:
@@ -869,8 +897,13 @@ def should_keep_fp8_weights(device: torch.device) -> bool:
Only true when the fp8 matmul is both enabled and usable, because keeping weights quantized
without it is the worst of both worlds: the same VRAM as fp8 but a dequantize round trip on
every forward (measured slower than plain bf16).
+
+ This is the load path's only way in, so it is where an inconclusive probe is given another go.
"""
- return is_fp8_matmul_enabled() and device_supports_fp8_matmul(device)
+ if not is_fp8_matmul_enabled():
+ return False
+ forget_inconclusive_fp8_matmul_probe(device)
+ return device_supports_fp8_matmul(device)
def _is_fp8_matmul_weight(key: str, tensor: Any, model: torch.nn.Module | None) -> bool:
diff --git a/tests/backend/model_manager/load/test_load_default_fp8.py b/tests/backend/model_manager/load/test_load_default_fp8.py
index 4547e77538..0f5e0d0794 100644
--- a/tests/backend/model_manager/load/test_load_default_fp8.py
+++ b/tests/backend/model_manager/load/test_load_default_fp8.py
@@ -688,9 +688,23 @@ def _clear_fp8_probe_cache():
_FP8_PROBE_FAILURE_REPORTED.clear()
-def test_device_supports_fp8_storage_cuda_is_unconditional():
- """CUDA is answered without probing, so the result holds on machines with no GPU."""
- assert _device_supports_fp8_storage(torch.device("cuda")) is True
+def test_device_supports_fp8_storage_probes_cuda_too():
+ """ROCm reports `device.type == "cuda"` and its float8 coverage varies by architecture.
+
+ Answering the whole CUDA branch True without asking let such a build pass the gate, have its
+ weights cast on the CPU -- which always works -- and moved to VRAM, and then raise
+ "not implemented for 'Float8_e4m3fn'" on the first forward, after the VRAM was committed.
+ """
+ ok, log = _probe_with_recorder(torch.device("cuda", 1))
+ assert ok is True
+ assert log == [torch.float8_e4m3fn, torch.device("cuda", 1), torch.bfloat16, torch.float16]
+
+
+def test_device_supports_fp8_storage_rejects_a_cuda_build_without_an_e4m3fn_upcast():
+ """Older gfx has no `e4m3fn` conversion at all, and gfx90a prefers `e4m3fnuz`. The fallback has
+ to be chosen here, not discovered mid-generation."""
+ ok, _ = _probe_with_recorder(torch.device("cuda"), fail_on=torch.bfloat16)
+ assert ok is False
def test_device_supports_fp8_storage_rejects_cpu():
diff --git a/tests/backend/quantization/test_fp8_scaled.py b/tests/backend/quantization/test_fp8_scaled.py
index ad96eb5215..0caec17603 100644
--- a/tests/backend/quantization/test_fp8_scaled.py
+++ b/tests/backend/quantization/test_fp8_scaled.py
@@ -22,6 +22,7 @@ from invokeai.backend.quantization.fp8_scaled import (
expand_weight_scale,
extract_comfy_quant_hints,
extract_fp8_scaled_layers,
+ forget_inconclusive_fp8_matmul_probe,
is_matmul_usable_scale,
is_scale_metadata_key,
iter_weight_scale_pairs,
@@ -32,6 +33,7 @@ from invokeai.backend.quantization.fp8_scaled import (
scaled_mm_linear,
set_fp8_matmul_enabled,
set_full_precision_hints_respected,
+ should_keep_fp8_weights,
split_fp8_scaled_layers,
strip_layer_path_prefix,
warn_on_unattached_scales,
@@ -1013,7 +1015,9 @@ class TestProbeFailureCaching:
with _probe_on_cpu():
with mock.patch("torch._scaled_mm", side_effect=torch.OutOfMemoryError("transient")):
assert device_supports_fp8_matmul(device) is False
- # A momentary OOM must not disable fp8 for the rest of the process.
+ # A momentary OOM must not disable fp8 for the rest of the process. The next *load* is
+ # what gives it another go; the forwards in between are answered from the record.
+ forget_inconclusive_fp8_matmul_probe(device)
with mock.patch("torch._scaled_mm", return_value=torch.zeros(1)):
assert device_supports_fp8_matmul(device) is True
reset_fp8_matmul_support_cache()
@@ -1320,11 +1324,45 @@ class TestProbeTransientFailures:
with _probe_on_cpu():
with mock.patch("torch._scaled_mm", side_effect=RuntimeError("CUDA driver reset")):
assert device_supports_fp8_matmul(device) is False
- # Inconclusive, so the next load re-probes rather than the process losing fp8.
+ # Inconclusive, so the next *load* re-probes rather than the process losing fp8.
+ forget_inconclusive_fp8_matmul_probe(device)
with mock.patch("torch._scaled_mm", return_value=torch.zeros(1)):
assert device_supports_fp8_matmul(device) is True
reset_fp8_matmul_support_cache()
+ def test_an_inconclusive_probe_is_not_repeated_on_the_forward_path(self) -> None:
+ """`CustomLinear._can_use_fp8_matmul` asks once per quantized fp8 Linear per step.
+
+ Leaving an inconclusive answer unrecorded meant re-probing every one of them, every step,
+ for the whole generation -- measured on a 4090 at 32 probes/step for 32 Linears, against 1
+ in total once it is recorded. Each probe allocates three device tensors and launches a
+ `_scaled_mm` that is about to fail.
+ """
+ reset_fp8_matmul_support_cache()
+ device = torch.device("cuda", 0)
+ with _probe_on_cpu():
+ with mock.patch("torch._scaled_mm", side_effect=RuntimeError("CUDA driver reset")) as probe:
+ for _ in range(5):
+ assert device_supports_fp8_matmul(device) is False
+ assert probe.call_count == 1, "the forward path re-probed"
+ reset_fp8_matmul_support_cache()
+
+ def test_a_load_gives_an_inconclusive_probe_another_go(self) -> None:
+ """The retry belongs to the load, which can afford one probe, and not to the forward."""
+ reset_fp8_matmul_support_cache()
+ device = torch.device("cuda", 0)
+ set_fp8_matmul_enabled(True)
+ try:
+ with _probe_on_cpu():
+ with mock.patch("torch._scaled_mm", side_effect=torch.OutOfMemoryError("transient")):
+ assert should_keep_fp8_weights(device) is False
+ with mock.patch("torch._scaled_mm", return_value=torch.zeros(1)) as probe:
+ assert should_keep_fp8_weights(device) is True
+ assert probe.call_count == 1
+ finally:
+ set_fp8_matmul_enabled(None)
+ reset_fp8_matmul_support_cache()
+
def test_a_capability_error_is_cached(self) -> None:
reset_fp8_matmul_support_cache()
device = torch.device("cuda", 0)