Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Say when attention has no fused kernel, and log the request behind a failed video (#8233)

Daniel Han749437314eff
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 61526be2c64..614356e0823 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -3076,6 +3076,7 @@ class DiffusionBackend:
target, attention_backend, speed_active = effective_speed != SPEED_OFF
),
logger = logger,
+ target = target,
)
# Step caching (First-Block-Cache), also before compile: reuses the transformer tail across steps (~1.4x on Flux,
# LPIPS ~0.08) and drops compile fullgraph. Tri-state: unset/auto -> FBCACHE_MIN_STEPS policy; off/fbcache pinned.
@@ -4132,6 +4133,7 @@ class DiffusionBackend:
state.pipe,
select_attention_backend(target, state.attention_request, speed_active = True),
logger = logger,
+ target = target,
)
object.__setattr__(state, "attention_backend", attention_engaged)
# Keep the badge in step with the state it describes: the top-level field moved, so leaving
diff --git a/studio/backend/core/inference/diffusion_attention.py b/studio/backend/core/inference/diffusion_attention.py
index d8b3371b982..72efc467ed5 100644
--- a/studio/backend/core/inference/diffusion_attention.py
+++ b/studio/backend/core/inference/diffusion_attention.py
@@ -113,6 +113,132 @@ def _is_cuda_nvidia(target: Any) -> bool:
return False
+# ── what the native SDPA dispatch can actually run (#8225) ───────────────────
+#
+# torch's ``flash_sdp_enabled()`` / ``mem_efficient_sdp_enabled()`` report the USER TOGGLE, not
+# whether a kernel exists for this device. On the ROCm build in #8225 (gfx1200, torch 2.11+rocm7)
+# both answer True while every dispatch to them raises "No available kernel. Aborting execution.",
+# so the dispatcher degrades silently to MATH -- and MATH is the one backend that materialises the
+# whole B x heads x N x N score matrix. That is how a 3.4 GB Q4_K_M video model asked a 16 GB card
+# for a single 66.54 GiB allocation 70 seconds into a generation.
+#
+# So do not read the flags. Run one tiny attention per backend and record what happens.
+SDPA_FLASH = "flash"
+SDPA_MEM_EFFICIENT = "mem_efficient"
+SDPA_CUDNN = "cudnn"
+SDPA_MATH = "math"
+
+# Backends whose working set is O(N): they never materialise the score matrix.
+_SDPA_SUBQUADRATIC = (SDPA_FLASH, SDPA_MEM_EFFICIENT, SDPA_CUDNN)
+
+_SDPA_PROBE_LOCK = threading.Lock()
+# (device type, dtype name) -> the kernels that ran. A kernel cannot appear or vanish under a
+# running interpreter, so one probe per device/dtype for the life of the process.
+_SDPA_PROBE_CACHE: dict[tuple[str, str], tuple[str, ...]] = {}
+
+
+def _probe_sdpa_kernels(device: str, dtype: Any) -> tuple[str, ...]:
+ """Run a 4 KB attention under each SDPA backend; return the ones that did not raise."""
+ import torch
+ from torch.nn.attention import SDPBackend, sdpa_kernel
+
+ candidates = (
+ (SDPA_FLASH, getattr(SDPBackend, "FLASH_ATTENTION", None)),
+ (SDPA_MEM_EFFICIENT, getattr(SDPBackend, "EFFICIENT_ATTENTION", None)),
+ (SDPA_CUDNN, getattr(SDPBackend, "CUDNN_ATTENTION", None)),
+ (SDPA_MATH, getattr(SDPBackend, "MATH", None)),
+ )
+ # Small enough to be free, but shaped like real attention: the fused kernels reject head_dim
+ # they cannot serve, and a degenerate 1-element tensor would not exercise that.
+ q = torch.zeros((1, 2, 8, 64), device = device, dtype = dtype)
+ available: list[str] = []
+ for name, backend in candidates:
+ if backend is None:
+ continue
+ try:
+ with sdpa_kernel([backend]):
+ torch.nn.functional.scaled_dot_product_attention(q, q, q)
+ available.append(name)
+ except Exception: # noqa: BLE001 — "No available kernel" is the answer, not an error
+ continue
+ return tuple(available)
+
+
+def available_sdpa_kernels(target: Any) -> tuple[str, ...]:
+ """The SDPA backends that actually EXECUTE on ``target``, cheapest source of truth available.
+
+ Empty when the probe could not run at all (no torch, no device, an allocator failure) -- an
+ unanswerable probe must never be read as "only math", which is a claim about the hardware."""
+ device = str(getattr(target, "device", "") or "")
+ if not device:
+ return ()
+ dtype = getattr(target, "dtype", None)
+ if dtype is None:
+ try:
+ import torch
+
+ # fp16 rather than fp32: the fused kernels are half-precision only, so probing at fp32
+ # would report "math only" on hardware where flash is perfectly healthy.
+ dtype = torch.float16
+ except Exception: # noqa: BLE001
+ return ()
+ key = (device.split(":")[0], str(dtype))
+ with _SDPA_PROBE_LOCK:
+ cached = _SDPA_PROBE_CACHE.get(key)
+ if cached is not None:
+ return cached
+ try:
+ available = _probe_sdpa_kernels(device, dtype)
+ except Exception: # noqa: BLE001 — a probe is a diagnostic; it may never fail a load
+ available = ()
+ # Memoize only an ANSWER. The "kernels cannot change under a running interpreter" argument
+ # justifies caching what the probe found, not caching its failure to run: an empty result means
+ # the probe itself could not complete (a transient allocator failure while the device was full
+ # -- exactly when this warning matters most), and caching that would disable the warning for
+ # the rest of the process even after memory frees.
+ if not available:
+ return ()
+ with _SDPA_PROBE_LOCK:
+ _SDPA_PROBE_CACHE.setdefault(key, available)
+ return _SDPA_PROBE_CACHE[key]
+
+
+def sdpa_math_only(target: Any) -> bool:
+ """True only when MATH ran and every sub-quadratic backend refused.
+
+ A probe that answered nothing at all returns False: silence is not evidence."""
+ available = available_sdpa_kernels(target)
+ if not available:
+ return False
+ return SDPA_MATH in available and not any(k in available for k in _SDPA_SUBQUADRATIC)
+
+
+SDPA_MATH_ONLY_MESSAGE = (
+ "attention has no fused kernel on this device, so it will run on the SDPA math backend, "
+ "which materialises the full attention score matrix (batch x heads x tokens x tokens, 4 bytes "
+ "per element). Peak VRAM then grows with the SQUARE of the token count -- resolution x frames "
+ "for video -- and can exceed the card by many times even for a small model. Lower the "
+ "resolution or the frame count, or install a backend with a working kernel for this GPU."
+)
+
+
+def warn_if_sdpa_math_only(target: Any, logger: Any = None) -> bool:
+ """Log the math-only diagnosis at LOAD, not 70 seconds into a doomed generation.
+
+ Returns whether the warning fired, so callers can carry it into their resolved controls."""
+ if not sdpa_math_only(target):
+ return False
+ if logger is not None:
+ logger.warning(
+ "diffusion.attention.math_only: device=%s dtype=%s kernels=%s -- %s",
+ getattr(target, "device", None),
+ getattr(target, "dtype", None),
+ ",".join(available_sdpa_kernels(target)) or "none",
+ SDPA_MATH_ONLY_MESSAGE,
+ )
+ return True
+
+
def select_attention_backend(
target: Any, requested: Optional[str], *, speed_active: bool
) -> Optional[str]:
@@ -455,12 +581,17 @@ def apply_attention_backend(
backend: Optional[str],
*,
logger: Any = None,
+ target: Any = None,
) -> Optional[str]:
"""Set ``backend`` on EVERY denoiser DiT via the diffusers dispatcher.
Returns the backend engaged, or None when left at native (``backend`` was None or the kernel
was unavailable -> graceful fallback, never a load failure).
+ ``target`` is the resolved device target. Given, and only when the result is native, the SDPA
+ backends are probed and a math-only device is reported here rather than discovered as a
+ six-figure-MiB allocation mid-generation (#8225). Optional so existing callers are unaffected.
+
diffusers keeps a process-wide active backend that ``set_attention_backend`` also updates, and
a fresh transformer's processors follow it (default None). So a load wanting native must
restore it explicitly, else it inherits a backend an earlier load pinned (e.g. cuDNN under a
@@ -471,6 +602,11 @@ def apply_attention_backend(
if callable(s)
]
if not setters:
+ # A U-Net pipeline (SDXL) exposes no dispatcher setter, so there is no backend to set --
+ # but its attention still runs through torch SDPA, so the math-only diagnosis applies
+ # exactly as it does to a DiT. Report it here or an SDXL load gets no warning at all.
+ if target is not None:
+ warn_if_sdpa_math_only(target, logger)
return None
if backend is not None:
_ensure_attention_backend_installed(backend, logger)
@@ -489,6 +625,10 @@ def apply_attention_backend(
return backend
# No backend requested, or every set failed: pin native so a stale process-wide backend cannot leak in. One reset covers every fresh DiT.
_restore_native_backend(setters[0], logger)
+ # Native means torch's SDPA dispatch decides per call, and on a device with no fused kernel
+ # that decision is MATH. Say so now; the flags this would otherwise be read off lie (#8225).
+ if target is not None:
+ warn_if_sdpa_math_only(target, logger)
return None
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index e771949ff82..dbd7a54fd4e 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -36,6 +36,7 @@ import os
import tempfile
import threading
import time
+import types
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Optional
@@ -43,8 +44,10 @@ from typing import Any, Optional
from loggers import get_logger
from .diffusion_attention import (
+ SDPA_MATH_ONLY_MESSAGE,
apply_attention_backend,
install_hunyuan_attention_trim,
+ sdpa_math_only,
select_attention_backend,
)
from .diffusion_cache import (
@@ -464,6 +467,80 @@ def _views_for(pipe: Any, fam: VideoFamily) -> tuple[Any, ...]:
return (pipe,)
+def _log_failed_generation(request_shape: Optional[dict[str, Any]], exc: BaseException) -> None:
+ """Record WHAT was being generated when it failed, next to the exception.
+
+ ``video.generate_failed`` logs the error and nothing else, which for the OOM in #8225 meant the
+ only server-side evidence was "Tried to allocate 66.54 GiB" -- the resolution and frame count
+ behind it had to be recovered by dividing that number by the head count. This is the missing
+ half of that record.
+
+ Cancels and "not loaded" are outcomes, not failures, so they are not reported. Never raises:
+ logging a failure must not replace it with a different one."""
+ if request_shape is None:
+ return
+ try:
+ if str(exc) in (VIDEO_CANCELLED_MSG, VIDEO_NOT_LOADED_MSG):
+ return
+ if type(exc).__name__ == "_VideoGenerationCancelled":
+ return
+ # A ValueError is client input feedback here, exactly as _run_generate treats it: it is
+ # returned to the caller as a validation message and deliberately gets no
+ # video.generate_failed record. Logging the request shape at ERROR for one would turn a
+ # rejected resolution or frame count into a server-error entry.
+ if isinstance(exc, ValueError):
+ return
+ logger.error(
+ "video.generate_failed_request: %s",
+ " ".join(f"{k}={v}" for k, v in request_shape.items()),
+ )
+ # An OOM under the math SDPA backend is the #8225 shape exactly: the score matrix is
+ # quadratic in the token count, so the fix is fewer tokens, not a smaller checkpoint.
+ # Named here so the next report arrives with the diagnosis already in it.
+ #
+ # Only when the run was on NATIVE SDPA. A recorded attention_backend means an explicit
+ # kernel (AITER, xFormers, ...) engaged and torch's own dispatch was not what ran, so
+ # probing native kernels would answer about code this generation never executed -- on a
+ # ROCm card with AITER active that turns every OOM into a confident false diagnosis.
+ if (
+ _is_out_of_memory(exc)
+ and request_shape.get("attention_backend") is None
+ and sdpa_math_only(_probe_target(request_shape))
+ ):
+ logger.error("video.generate_failed_request: %s", SDPA_MATH_ONLY_MESSAGE)
+ except Exception: # noqa: BLE001 — diagnostics never mask the real failure
+ pass
+
+
+def _is_out_of_memory(exc: BaseException) -> bool:
+ """Whether ``exc`` is an allocator failure, by name and text rather than by class: torch
+ raises ``torch.OutOfMemoryError`` on CUDA and a plain RuntimeError on some backends."""
+ if any(cls.__name__ in ("OutOfMemoryError", "OutOfMemoryError_") for cls in type(exc).__mro__):
+ return True
+ text = str(exc).lower()
+ return "out of memory" in text or "tried to allocate" in text
+
+
+def _probe_target(request_shape: dict[str, Any]) -> Any:
+ """A minimal device target for the SDPA probe, built from the recorded request.
+
+ Carries the dtype the failed generation actually ran in. Leaving it None defaults the probe to
+ fp16, but every video family promotes a resolved fp16 to fp32, so the probe would answer for a
+ precision the run never used -- and the fused kernels are half-precision only, so that is the
+ difference between "fused kernels exist here" and "this run had none"."""
+ dtype = None
+ recorded = request_shape.get("dtype")
+ if recorded:
+ try:
+ import torch
+ candidate = getattr(torch, str(recorded).replace("torch.", ""), None)
+ if isinstance(candidate, torch.dtype):
+ dtype = candidate
+ except Exception: # noqa: BLE001 — fall back to the probe's own default
+ dtype = None
+ return types.SimpleNamespace(device = request_shape.get("device"), dtype = dtype)
+
+
class VideoBackend:
"""One loaded video pipeline; loads swap it atomically (same model as images)."""
@@ -1705,6 +1782,11 @@ class VideoBackend:
target, attention_backend, speed_active = effective_speed != SPEED_OFF
),
logger = logger,
+ # The probe behind this must see the dtype the pipeline actually RUNS in. Every
+ # video family promotes a resolved fp16 to fp32 above, and the fused SDPA kernels
+ # are half-precision only, so probing the pre-promotion fp16 would report a healthy
+ # device for a generation that is in fact dispatching to the quadratic math backend.
+ target = types.SimpleNamespace(device = target.device, dtype = dtype),
)
applied = apply_speed_optims(
view,
@@ -2090,6 +2172,9 @@ class VideoBackend:
if state is None:
raise RuntimeError(VIDEO_NOT_LOADED_MSG)
self._active_generate_cancel = cancel
+ # Bound below, once the request is resolved. None means the failure beat the
+ # resolution, and there is nothing truthful to report.
+ request_shape: Optional[dict[str, Any]] = None
try:
fam = state.family
width, height = snap_video_size(
@@ -2113,6 +2198,32 @@ class VideoBackend:
seed = int(generator.seed()) % (2**53)
generator = generator.manual_seed(int(seed))
+ # The RESOLVED request, snapshotted the moment it is known, so a failure logs what
+ # actually ran rather than the caller's Nones. Without it the whole server-side
+ # record of a failed video is the exception string: #8225 reported an OOM whose
+ # resolution and frame count had to be reverse-engineered out of the allocation
+ # size by hand. No prompt text -- a length is enough to tell an empty prompt from
+ # a long one, and the log is not the place for user content.
+ request_shape = {
+ "family": fam.name,
+ "repo_id": state.repo_id,
+ "gguf": state.gguf_filename,
+ "width": width,
+ "height": height,
+ "frames": frames,
+ "fps": out_fps,
+ "steps": steps,
+ "guidance": guidance,
+ "guidance_2": guidance_2,
+ "seed": int(seed),
+ "prompt_chars": len(prompt or ""),
+ "negative_prompt_chars": len(negative_prompt or ""),
+ "device": state.device,
+ "dtype": state.dtype,
+ "offload": state.offload_policy,
+ "attention_backend": state.attention_backend,
+ }
+
pipe = state.pipe
call_params = inspect.signature(pipe.__call__).parameters
kwargs: dict[str, Any] = {
@@ -2262,8 +2373,9 @@ class VideoBackend:
"memory_mode": state.memory_mode,
"offload_policy": state.offload_policy,
}
- except Exception:
+ except Exception as exc:
self._gen = {"active": False}
+ _log_failed_generation(request_shape, exc)
raise
finally:
with self._lock:
diff --git a/studio/backend/tests/test_diffusion_attention.py b/studio/backend/tests/test_diffusion_attention.py
index 47508e8a132..2fb894f849b 100644
--- a/studio/backend/tests/test_diffusion_attention.py
+++ b/studio/backend/tests/test_diffusion_attention.py
@@ -795,3 +795,207 @@ def test_probe_timeout_matches_the_other_wheel_callers(monkeypatch):
monkeypatch.setattr(wu, "probe_torch_wheel_env", _probe)
att._xformers_wheel_target()
assert seen == {"timeout": 30, "include_windows": True}
+
+
+# ── the native dispatch's real kernel set (#8225) ────────────────────────────────
+
+
[email protected](autouse = True)
+def _clear_sdpa_probe_cache():
+ """The probe memoises per (device, dtype) for the process; tests must not inherit it."""
+ att._SDPA_PROBE_CACHE.clear()
+ yield
+ att._SDPA_PROBE_CACHE.clear()
+
+
+def _stub_probe(
+ monkeypatch,
+ kernels,
+ *,
+ record = None,
+):
+ def _probe(device, dtype):
+ if record is not None:
+ record.append((device, dtype))
+ return tuple(kernels)
+
+ monkeypatch.setattr(att, "_probe_sdpa_kernels", _probe)
+
+
+def test_math_only_is_read_off_a_probe_not_the_flags(monkeypatch):
+ # The bug: on the reporter's gfx1200 build flash_sdp_enabled() and mem_efficient_sdp_enabled()
+ # both answer True while every dispatch to them raises "No available kernel", so dispatch
+ # degrades to math and materialises the whole N x N score matrix. Only a probe sees that.
+ _stub_probe(monkeypatch, ("math",))
+ assert att.sdpa_math_only(_target()) is True
+ assert att.available_sdpa_kernels(_target()) == ("math",)
+
+
+ "kernels",
+ [
+ ("flash", "mem_efficient", "cudnn", "math"),
+ ("flash", "math"),
+ ("mem_efficient", "math"),
+ ("cudnn", "math"),
+ ],
+)
+def test_any_subquadratic_kernel_means_not_math_only(kernels, monkeypatch):
+ # Flash / mem-efficient / cuDNN are all O(N) in working set, so any one of them present means
+ # the score matrix is never materialised and there is nothing to warn about.
+ _stub_probe(monkeypatch, kernels)
+ assert att.sdpa_math_only(_target()) is False
+
+
+def test_an_unanswerable_probe_is_not_a_math_only_verdict(monkeypatch):
+ # "Only math" is a claim about the hardware. A probe that could not run (no torch, no device,
+ # an allocator failure) has made no such claim, and must not refuse or warn on a guess.
+ _stub_probe(monkeypatch, ())
+ assert att.sdpa_math_only(_target()) is False
+ assert att.warn_if_sdpa_math_only(_target(), None) is False
+
+
+def test_a_probe_that_raises_is_swallowed(monkeypatch):
+ # A diagnostic may never be the thing that fails a load.
+ def _boom(device, dtype):
+ raise RuntimeError("probe exploded")
+
+ monkeypatch.setattr(att, "_probe_sdpa_kernels", _boom)
+ assert att.available_sdpa_kernels(_target()) == ()
+ assert att.sdpa_math_only(_target()) is False
+
+
+def test_a_target_with_no_device_is_never_probed(monkeypatch):
+ seen: list = []
+ _stub_probe(monkeypatch, ("math",), record = seen)
+ assert att.available_sdpa_kernels(types.SimpleNamespace(device = "", dtype = None)) == ()
+ assert att.available_sdpa_kernels(types.SimpleNamespace(device = None, dtype = None)) == ()
+ assert seen == []
+
+
+def test_the_probe_runs_once_per_device_and_dtype(monkeypatch):
+ # A kernel cannot appear or vanish under a running interpreter, and this sits on the load
+ # path, so the probe is memoised. cuda:0 and cuda:1 are the same device TYPE.
+ seen: list = []
+ _stub_probe(monkeypatch, ("math",), record = seen)
+ for device in ("cuda", "cuda:0", "cuda:1"):
+ assert att.sdpa_math_only(types.SimpleNamespace(device = device, dtype = "fp16")) is True
+ assert len(seen) == 1
+ # A different dtype is a different question: fused kernels are half-precision only.
+ att.sdpa_math_only(types.SimpleNamespace(device = "cuda", dtype = "fp32"))
+ assert len(seen) == 2
+
+
+def test_a_dtypeless_target_probes_in_half_precision(monkeypatch):
+ # fp32 has no fused kernel anywhere, so probing at fp32 would report "math only" on hardware
+ # where flash is perfectly healthy.
+ import torch
+
+ seen: list = []
+ _stub_probe(monkeypatch, ("flash", "math"), record = seen)
+ att.available_sdpa_kernels(types.SimpleNamespace(device = "cuda", dtype = None))
+ assert seen == [("cuda", torch.float16)]
+
+
+def test_warn_names_the_quadratic_cost(monkeypatch):
+ # The message has to say WHY a 3.4 GB model asked for 66.54 GiB, or the next report is another
+ # allocation size to divide by hand.
+ _stub_probe(monkeypatch, ("math",))
+ logged: list = []
+ logger = types.SimpleNamespace(warning = lambda fmt, *a: logged.append(fmt % a))
+
+ assert att.warn_if_sdpa_math_only(_target(), logger) is True
+ assert len(logged) == 1
+ assert "math_only" in logged[0]
+ assert "score matrix" in logged[0] and "SQUARE" in logged[0]
+
+
+def test_warn_is_silent_on_a_healthy_device(monkeypatch):
+ _stub_probe(monkeypatch, ("flash", "math"))
+ logged: list = []
+ logger = types.SimpleNamespace(warning = lambda fmt, *a: logged.append(fmt % a))
+ assert att.warn_if_sdpa_math_only(_target(), logger) is False
+ assert logged == []
+
+
+def test_apply_native_reports_a_math_only_device(monkeypatch):
+ # select_attention_backend returns None on every non-NVIDIA device, so ROCm lands on the
+ # diffusers default and torch's dispatch decides. On a card with no fused kernel that decision
+ # is math, and today nothing says so until the OOM 70 seconds later.
+ monkeypatch.setattr(att, "_active_attention_backend", lambda: "native")
+ _stub_probe(monkeypatch, ("math",))
+ logged: list = []
+ logger = types.SimpleNamespace(
+ warning = lambda fmt, *a: logged.append(fmt % a),
+ info = lambda *a, **k: None,
+ )
+
+ assert (
+ apply_attention_backend(_pipe(_FakeTransformer()), None, logger = logger, target = _target())
+ is None
+ )
+ assert len(logged) == 1 and "math_only" in logged[0]
+
+
+def test_apply_reports_a_math_only_device_for_a_unet_pipeline(monkeypatch):
+ # SDXL denoises with pipe.unet, which carries no dispatcher setter, so there is no backend to
+ # set -- but its attention runs on the same torch SDPA and has the same quadratic blow-up, so
+ # the diagnosis has to be reported for it too.
+ _stub_probe(monkeypatch, ("math",))
+ logged: list = []
+ logger = types.SimpleNamespace(
+ warning = lambda fmt, *a: logged.append(fmt % a),
+ info = lambda *a, **k: None,
+ )
+ unet_pipe = types.SimpleNamespace(unet = object())
+
+ assert apply_attention_backend(unet_pipe, None, logger = logger, target = _target()) is None
+ assert len(logged) == 1 and "math_only" in logged[0]
+
+
+def test_apply_without_a_target_probes_nothing(monkeypatch):
+ # The parameter is optional, so every existing caller keeps its exact behaviour.
+ monkeypatch.setattr(att, "_active_attention_backend", lambda: "native")
+ seen: list = []
+ _stub_probe(monkeypatch, ("math",), record = seen)
+ assert apply_attention_backend(_pipe(_FakeTransformer()), None) is None
+ assert seen == []
+
+
+def test_apply_does_not_warn_when_a_real_backend_engaged(monkeypatch):
+ # A pinned kernel is the answer to the question the probe asks, so asking it is pointless.
+ seen: list = []
+ _stub_probe(monkeypatch, ("math",), record = seen)
+ logged: list = []
+ logger = types.SimpleNamespace(
+ warning = lambda fmt, *a: logged.append(fmt % a),
+ info = lambda *a, **k: None,
+ )
+ t = _FakeTransformer()
+ assert (
+ apply_attention_backend(_pipe(t), "_native_cudnn", logger = logger, target = _target())
+ == "_native_cudnn"
+ )
+ assert seen == [] and logged == []
+
+
+def test_an_unanswerable_probe_is_not_memoised(monkeypatch):
+ """A probe that could not RUN is not an answer about the hardware. Caching it disabled the
+ warning for the rest of the process, including after the memory that broke it was freed --
+ and a device under memory pressure is exactly when this warning matters."""
+ calls: list = []
+
+ def _flaky(device, dtype):
+ calls.append(dtype)
+ if len(calls) == 1:
+ raise RuntimeError("CUDA out of memory while allocating the probe tensor")
+ return ("flash", "math")
+
+ monkeypatch.setattr(att, "_probe_sdpa_kernels", _flaky)
+
+ assert att.available_sdpa_kernels(_target()) == ()
+ assert att.sdpa_math_only(_target()) is False # silence is still not evidence
+ # The retry answers, and only that answer is kept.
+ assert att.available_sdpa_kernels(_target()) == ("flash", "math")
+ assert att.available_sdpa_kernels(_target()) == ("flash", "math")
+ assert len(calls) == 2, "the answer must be memoised; the failure must not be"
diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.py
index 543fe3438d6..ff6c7cafdfd 100644
--- a/studio/backend/tests/test_diffusion_backend.py
+++ b/studio/backend/tests/test_diffusion_backend.py
@@ -873,7 +873,9 @@ def test_dense_speed_auto_defers_compile_to_third_generation(fake_runtime, tmp_p
"apply_speed_optims",
lambda pipe, target, **k: {"compiled": k.get("speed_mode") == "default"},
)
- monkeypatch.setattr(dmod, "apply_attention_backend", lambda pipe, backend, logger = None: backend)
+ monkeypatch.setattr(
+ dmod, "apply_attention_backend", lambda pipe, backend, logger = None, target = None: backend
+ )
monkeypatch.setattr(
dmod,
"select_attention_backend",
@@ -1001,7 +1003,9 @@ def test_deferred_speed_preserves_explicit_attention(fake_runtime, tmp_path, mon
"apply_speed_optims",
lambda pipe, target, **k: {"compiled": k.get("speed_mode") == "default"},
)
- monkeypatch.setattr(dmod, "apply_attention_backend", lambda pipe, backend, logger = None: backend)
+ monkeypatch.setattr(
+ dmod, "apply_attention_backend", lambda pipe, backend, logger = None, target = None: backend
+ )
# A select mock that HONORS an explicit request: only an unset request upgrades to cuDNN.
def fake_select(
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index dc172cb3ce7..488bb17e204 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -11,6 +11,7 @@ import sys
import threading
import time
import types
+from dataclasses import replace
import pytest
@@ -2443,6 +2444,323 @@ def test_attention_trim_skipped_for_static_shape_and_off_tiers(fake_runtime, mon
assert "hunyuan_attn_trim" not in status["speed_optims"], mode
+# ── a failed video must say what it was rendering (#8225) ────────────────────────
+
+
+def _failing_pipe_call(exc):
+ # The explicit signature matters: generate() inspects it, and a bare **kwargs would advertise
+ # no callback_on_step_end and route the call down the scheduler-wrapping path instead.
+ def _boom(
+ self,
+ *,
+ prompt = None,
+ negative_prompt = None,
+ num_inference_steps = None,
+ guidance_scale = None,
+ width = None,
+ height = None,
+ num_frames = None,
+ frame_rate = None,
+ generator = None,
+ callback_on_step_end = None,
+ **kwargs,
+ ):
+ raise exc
+
+ return _boom
+
+
+def _capture_generate_failures(monkeypatch):
+ """Collect the ``video.generate_failed_request`` lines.
+
+ The module logger is structlog, which caplog does not see, so wrap it and pass everything
+ else straight through to the real one."""
+ import core.inference.video as video_mod
+
+ lines: list = []
+ real = video_mod.logger
+
+ class _Recorder:
+ def error(self, fmt, *a, **k):
+ message = fmt % a if a else fmt
+ if "generate_failed_request" in message:
+ lines.append(message)
+ return real.error(fmt, *a, **k)
+
+ def __getattr__(self, name):
+ return getattr(real, name)
+
+ monkeypatch.setattr(video_mod, "logger", _Recorder())
+ return lines
+
+
+def test_a_failed_generation_logs_the_resolved_request(fake_runtime, tmp_path, monkeypatch):
+ # The reported bug: the entire server-side record of the OOM in #8225 was the exception string,
+ # so the resolution and frame count behind a 66.54 GiB allocation had to be recovered by
+ # dividing it by the head count. Log the request that produced it.
+ import core.inference.video as video_mod
+
+ backend = VideoBackend()
+ _load_gguf(backend, tmp_path)
+ monkeypatch.setattr(
+ type(backend._state.pipe),
+ "__call__",
+ _failing_pipe_call(RuntimeError("CUDA out of memory. Tried to allocate 66.54 GiB.")),
+ )
+ monkeypatch.setattr(video_mod, "sdpa_math_only", lambda target: False)
+ records = _capture_generate_failures(monkeypatch)
+
+ with pytest.raises(RuntimeError):
+ backend.generate(prompt = "a sloth surfing", width = 1000, height = 700, num_frames = 120)
+
+ assert len(records) == 1
+ line = records[0]
+ # The SNAPPED shape, which is what actually ran, not the caller's raw request.
+ assert "width=992" in line and "height=672" in line and "frames=113" in line
+ assert "steps=" in line and "seed=" in line and "family=ltx-2" in line
+ assert "device=" in line and "offload=" in line
+
+
+def test_a_rejected_request_is_not_recorded_as_a_server_failure(
+ fake_runtime, tmp_path, monkeypatch
+):
+ # _run_generate maps every ValueError from the pipeline to client input feedback and gives it
+ # no video.generate_failed record, so the request-shape log must not turn the same rejection
+ # into an ERROR entry: a user asking for a shape the pipeline refuses is not a server failure.
+ import core.inference.video as video_mod
+
+ backend = VideoBackend()
+ _load_gguf(backend, tmp_path)
+ monkeypatch.setattr(
+ type(backend._state.pipe),
+ "__call__",
+ _failing_pipe_call(ValueError("`height` and `width` have to be divisible by 32")),
+ )
+ records = _capture_generate_failures(monkeypatch)
+
+ with pytest.raises(ValueError):
+ backend.generate(prompt = "a sloth surfing", width = 1000, height = 700, num_frames = 120)
+
+ assert records == []
+
+
+def test_the_failure_log_carries_no_prompt_text(fake_runtime, tmp_path, monkeypatch):
+ # A length distinguishes an empty prompt from a long one, which is all a bug report needs; the
+ # server log is not the place for user content.
+ import core.inference.video as video_mod
+
+ backend = VideoBackend()
+ _load_gguf(backend, tmp_path)
+ monkeypatch.setattr(
+ type(backend._state.pipe), "__call__", _failing_pipe_call(RuntimeError("kaboom"))
+ )
+ monkeypatch.setattr(video_mod, "sdpa_math_only", lambda target: False)
+ records = _capture_generate_failures(monkeypatch)
+
+ with pytest.raises(RuntimeError):
+ backend.generate(prompt = "a secret about oranges", negative_prompt = "blurry")
+
+ line = records[0]
+ assert "oranges" not in line and "blurry" not in line
+ assert "prompt_chars=22" in line and "negative_prompt_chars=6" in line
+
+
+def test_an_oom_on_a_math_only_device_names_the_quadratic_cost(fake_runtime, tmp_path, monkeypatch):
+ # The whole point of #8225: the model was not too big, the score matrix was. When the device
+ # has no fused kernel, an OOM should arrive with that diagnosis attached.
+ import core.inference.video as video_mod
+
+ backend = VideoBackend()
+ _load_gguf(backend, tmp_path)
+ monkeypatch.setattr(
+ type(backend._state.pipe),
+ "__call__",
+ _failing_pipe_call(RuntimeError("CUDA out of memory. Tried to allocate 66.54 GiB.")),
+ )
+ monkeypatch.setattr(video_mod, "sdpa_math_only", lambda target: True)
+ records = _capture_generate_failures(monkeypatch)
+
+ with pytest.raises(RuntimeError):
+ backend.generate(prompt = "a clip")
+
+ assert len(records) == 2
+ assert "score matrix" in records[1] and "SQUARE" in records[1]
+
+
+def test_a_non_oom_failure_does_not_blame_attention(fake_runtime, tmp_path, monkeypatch):
+ # Math-only is a real condition, but it did not cause a scheduler bug. Only allocator failures
+ # get the diagnosis, or it becomes noise on every unrelated crash.
+ import core.inference.video as video_mod
+
+ backend = VideoBackend()
+ _load_gguf(backend, tmp_path)
+ monkeypatch.setattr(
+ type(backend._state.pipe),
+ "__call__",
+ _failing_pipe_call(RuntimeError("scheduler produced NaN sigmas")),
+ )
+ monkeypatch.setattr(video_mod, "sdpa_math_only", lambda target: True)
+ records = _capture_generate_failures(monkeypatch)
+
+ with pytest.raises(RuntimeError):
+ backend.generate(prompt = "a clip")
+
+ assert len(records) == 1
+ assert "score matrix" not in records[0]
+
+
+def test_a_cancel_is_not_logged_as_a_failure(fake_runtime, tmp_path, monkeypatch):
+ # Cancels unwind through the same handler. A user pressing stop is an outcome, not a bug
+ # report, and logging it would bury the real ones.
+ from core.inference.video_families import VIDEO_CANCELLED_MSG
+
+ backend = VideoBackend()
+ _load_gguf(backend, tmp_path)
+ records = _capture_generate_failures(monkeypatch)
+ cancel = threading.Event()
+ cancel.set()
+
+ with pytest.raises(RuntimeError, match = VIDEO_CANCELLED_MSG):
+ backend.generate(prompt = "a clip", cancel_event = cancel)
+
+ assert records == []
+
+
+def test_a_failure_before_the_request_resolves_logs_nothing(fake_runtime, tmp_path, monkeypatch):
+ # There is nothing truthful to report until the shape is snapped, and a half-bound record
+ # would be worse than none.
+ import core.inference.video as video_mod
+
+ backend = VideoBackend()
+ _load_gguf(backend, tmp_path)
+ records = _capture_generate_failures(monkeypatch)
+
+ def _broken(fam, w, h):
+ raise RuntimeError("resolution table is broken")
+
+ monkeypatch.setattr(video_mod, "snap_video_size", _broken)
+
+ with pytest.raises(RuntimeError, match = "resolution table"):
+ backend.generate(prompt = "a clip")
+
+ assert records == []
+
+
+def test_a_broken_diagnostic_never_replaces_the_real_failure(fake_runtime, tmp_path, monkeypatch):
+ # If the probe or the formatting raises, the caller must still see the original exception.
+ import core.inference.video as video_mod
+
+ backend = VideoBackend()
+ _load_gguf(backend, tmp_path)
+ monkeypatch.setattr(
+ type(backend._state.pipe),
+ "__call__",
+ _failing_pipe_call(RuntimeError("CUDA out of memory. Tried to allocate 66.54 GiB.")),
+ )
+
+ def _boom(target):
+ raise RuntimeError("the probe itself is broken")
+
+ monkeypatch.setattr(video_mod, "sdpa_math_only", _boom)
+
+ with pytest.raises(RuntimeError, match = "66.54 GiB"):
+ backend.generate(prompt = "a clip")
+
+
+ "exc, expected",
+ [
+ (RuntimeError("CUDA out of memory. Tried to allocate 66.54 GiB."), True),
+ (RuntimeError("HIP out of memory"), True),
+ (RuntimeError("Tried to allocate 2.00 GiB"), True),
+ (RuntimeError("scheduler produced NaN sigmas"), False),
+ (ValueError("bad prompt"), False),
+ ],
+)
+def test_out_of_memory_is_recognised_by_text_not_only_by_class(exc, expected):
+ # torch raises torch.OutOfMemoryError on CUDA but a plain RuntimeError on some backends, so
+ # an isinstance check alone would miss exactly the reports this is for.
+ import core.inference.video as video_mod
+ assert video_mod._is_out_of_memory(exc) is expected
+
+
+def test_the_oom_diagnosis_is_skipped_when_an_external_backend_ran(
+ fake_runtime, tmp_path, monkeypatch
+):
+ """AITER / xFormers replace torch's own dispatch, so probing native SDPA answers about code the
+ generation never executed. On a ROCm card with AITER engaged that turned every OOM into a
+ confident false statement that attention ran on the quadratic math backend."""
+ import core.inference.video as video_mod
+
+ backend = VideoBackend()
+ _load_gguf(backend, tmp_path)
+ backend._state = replace(backend._state, attention_backend = "aiter")
+ monkeypatch.setattr(
+ type(backend._state.pipe),
+ "__call__",
+ _failing_pipe_call(RuntimeError("HIP out of memory. Tried to allocate 66.54 GiB.")),
+ )
+ probed: list = []
+
+ def _never(target):
+ probed.append(target)
+ return True
+
+ monkeypatch.setattr(video_mod, "sdpa_math_only", _never)
+ records = _capture_generate_failures(monkeypatch)
+
+ with pytest.raises(RuntimeError):
+ backend.generate(prompt = "a clip")
+
+ assert probed == [], "an engaged external backend must not be diagnosed as native SDPA"
+ assert not any(video_mod.SDPA_MATH_ONLY_MESSAGE in line for line in records)
+ # The request record itself is still logged; only the diagnosis is withheld.
+ assert any("family=ltx-2" in line for line in records)
+
+
+def test_the_oom_probe_uses_the_dtype_the_run_actually_used(fake_runtime, tmp_path, monkeypatch):
+ """Video families promote a resolved fp16 to fp32, and the fused SDPA kernels are
+ half-precision only. A dtypeless probe target defaults to fp16, so it would answer for a
+ precision the run never used."""
+ import torch
+
+ import core.inference.video as video_mod
+
+ backend = VideoBackend()
+ _load_gguf(backend, tmp_path)
+ backend._state = replace(backend._state, dtype = "float32", attention_backend = None)
+ monkeypatch.setattr(
+ type(backend._state.pipe),
+ "__call__",
+ _failing_pipe_call(RuntimeError("CUDA out of memory. Tried to allocate 66.54 GiB.")),
+ )
+ seen: list = []
+ monkeypatch.setattr(video_mod, "sdpa_math_only", lambda target: seen.append(target) or True)
+ records = _capture_generate_failures(monkeypatch)
+
+ with pytest.raises(RuntimeError):
+ backend.generate(prompt = "a clip")
+
+ # The run's dtype reaches the record, which is what the probe target is built from.
+ assert any("dtype=float32" in line for line in records)
+ assert len(seen) == 1
+
+
+def test_the_probe_target_resolves_the_recorded_dtype():
+ """The other half: that recorded string becomes the real torch dtype the probe asks about."""
+ import torch
+
+ import core.inference.video as video_mod
+
+ assert video_mod._probe_target({"device": "cuda", "dtype": "float32"}).dtype is torch.float32
+ assert video_mod._probe_target({"device": "cuda", "dtype": "bfloat16"}).dtype is torch.bfloat16
+ # No recorded dtype keeps the probe's own half-precision default.
+ assert video_mod._probe_target({"device": "cuda"}).dtype is None
+ # A junk value, or a torch attribute that is not a dtype, can never become a bogus dtype.
+ assert video_mod._probe_target({"device": "cuda", "dtype": "nonsense"}).dtype is None
+ assert video_mod._probe_target({"device": "cuda", "dtype": "nn"}).dtype is None
+
+
# ── text-encoder budgeting ───────────────────────────────────────────────────
# The plan sizes companions from the family's bf16 (transformer, text_encoder, vae) table. A pick
# that takes its encoder PRE-CAST from a hosted fp8 checkpoint loads roughly half that encoder, and