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.

Studio: fp8 denoisers on sm_89 no longer hang on the first render (CUDA graph replay under torch < 2.12) (#17166)

Daniel Han2092c0306148
diff --git a/studio/backend/core/inference/diffusion_cuda_graph.py b/studio/backend/core/inference/diffusion_cuda_graph.py
index c992a179530..0753a42a2ae 100644
--- a/studio/backend/core/inference/diffusion_cuda_graph.py
+++ b/studio/backend/core/inference/diffusion_cuda_graph.py
@@ -2622,6 +2622,71 @@ def prompt_length_reason(pipe: Any, family: Any = None) -> Optional[str]:
)
+# torch < 2.12, sm_89: row-wise fp8 _scaled_mm (stream-K) memsets its barrier outside capture, so replay hangs (pytorch/pytorch#177573).
+FP8_ROWWISE_STREAMK_CAPS = ((8, 9),)
+FP8_ROWWISE_STREAMK_FIXED = (2, 12)
+
+
+def _fp8_rowwise_weight(t: Any, activation: bool = False) -> bool:
+ """A torchao fp8 weight whose linear runs the row-wise ``_scaled_mm`` (dynamic activation, per-row scale)."""
+ name = type(t).__name__
+ if name == "LinearActivationQuantizedTensor":
+ inner = getattr(t, "original_weight_tensor", None)
+ return inner is not None and _fp8_rowwise_weight(inner, activation = True)
+ if name == "Float8Tensor":
+ scale = getattr(t, "scale", None)
+ dynamic = activation or getattr(t, "act_quant_kwargs", None) is not None
+ elif name == "AffineQuantizedTensor" and activation:
+ impl = getattr(t, "tensor_impl", None)
+ if "Float8" not in type(impl).__name__:
+ return False
+ scale = getattr(impl, "scale", None)
+ dynamic = True
+ else:
+ return False
+ try:
+ return bool(dynamic and scale is not None and int(scale.numel()) > 1)
+ except Exception: # noqa: BLE001
+ return False
+
+
+def fp8_rowwise_capture_refusal(modules: Any, device: Any = None) -> Optional[str]:
+ """Why ``modules`` must not be graphed on ``device``, else None (also None when unreadable)."""
+ if sys.platform == "win32":
+ return None # not built on Windows
+ try:
+ torch = _torch()
+ from .rocm_bf16 import is_rocm_torch
+
+ if is_rocm_torch(torch):
+ return None
+ major, minor = (int(x) for x in str(torch.__version__).split("+")[0].split(".")[:2])
+ if (major, minor) >= FP8_ROWWISE_STREAMK_FIXED:
+ return None
+ cap = tuple(torch.cuda.get_device_capability(device))
+ except Exception: # noqa: BLE001
+ return None
+ if cap not in FP8_ROWWISE_STREAMK_CAPS:
+ return None
+ for module in modules or ():
+ try:
+ weights = list(module.parameters())
+ except Exception: # noqa: BLE001
+ continue
+ if any(_fp8_rowwise_weight(w) for w in weights):
+ return (
+ f"the row-wise fp8 GEMM on this sm_{cap[0]}{cap[1]} card cannot replay in a CUDA graph under torch "
+ f"{major}.{minor} (it hangs; fixed in torch {FP8_ROWWISE_STREAMK_FIXED[0]}."
+ f"{FP8_ROWWISE_STREAMK_FIXED[1]}, pytorch/pytorch#177573)"
+ )
+ return None
+
+
+def _graph_device(target: Any) -> Any:
+ device = getattr(target, "torch_device", None)
+ return device if isinstance(device, str) and device.startswith("cuda") else None
+
+
def graph_eligible(
target: Any,
*,
@@ -2701,6 +2766,10 @@ def graph_eligible(
except Exception as exc: # noqa: BLE001 - the capture itself still poisons safely
_warn(logger, "capture-safe probe", exc)
+ why = fp8_rowwise_capture_refusal(_denoiser_modules(pipe), _graph_device(target))
+ if why is not None:
+ return False, why
+
return True, "eligible"
@@ -3032,8 +3101,11 @@ def arm_block_graphs(
# Nothing moves the denoiser: the speed layer's decision stands, except a forward that is not capture-safe,
# whose blocks still record.
return handles
- why = _block_basics(target, family, cache_engaged, speed_mode, family_default) or (
- None if split else prompt_length_reason(pipe, family)
+ why = (
+ _block_basics(target, family, cache_engaged, speed_mode, family_default)
+ # Ahead of the prompt-length reason: an env var forces past that one, never this.
+ or fp8_rowwise_capture_refusal(_denoiser_modules(pipe), _graph_device(target))
+ or (None if split else prompt_length_reason(pipe, family))
)
if whole:
uninstall_all(whole, logger = logger)
diff --git a/studio/backend/tests/test_diffusion_block_graph.py b/studio/backend/tests/test_diffusion_block_graph.py
index 55382b8868d..4e46fba6144 100644
--- a/studio/backend/tests/test_diffusion_block_graph.py
+++ b/studio/backend/tests/test_diffusion_block_graph.py
@@ -1232,6 +1232,20 @@ def test_a_variable_length_denoiser_records_no_block_graphs(monkeypatch):
assert not any(isinstance(b.__dict__.get("forward"), bg.BlockGraph) for b in net.blocks)
+def test_the_streamk_fp8_refusal_outranks_the_prompt_length_reason(monkeypatch):
+ monkeypatch.delenv(bg.BLOCK_GRAPHS_ENV, raising = False)
+ monkeypatch.delenv(cg.FORCE_FAMILIES_ENV, raising = False)
+ why = "the row-wise fp8 GEMM on this sm_89 card cannot replay in a CUDA graph"
+ monkeypatch.setattr(cg, "fp8_rowwise_capture_refusal", lambda modules, device = None: why)
+ net = type("QwenImageTransformer2DModel", (Net,), {})(blocks = 3)
+ pipe = _pipe_with(net)
+ pipe._unsloth_cuda_graph_reason = "offload active"
+ handles, applied = _arm(pipe, monkeypatch, hooked = True, pinned = True, opt_in = True)
+ assert handles == () and not applied["cuda_graph"]
+ assert cg.status_reason(pipe, False).startswith(why)
+ assert not any(isinstance(b.__dict__.get("forward"), bg.BlockGraph) for b in net.blocks)
+
+
def test_a_model_offloaded_denoiser_reason_names_both_opt_ins(monkeypatch):
pipe = _pipe_with(Net(blocks = 3))
pipe.transformer._hf_hook = types.SimpleNamespace()
diff --git a/studio/backend/tests/test_diffusion_cuda_graph.py b/studio/backend/tests/test_diffusion_cuda_graph.py
index d3f07fb8577..ae154291d37 100644
--- a/studio/backend/tests/test_diffusion_cuda_graph.py
+++ b/studio/backend/tests/test_diffusion_cuda_graph.py
@@ -798,6 +798,128 @@ def test_graph_eligible_refuses_under_the_kill_switch(stub_torch, monkeypatch):
assert reason == f"disabled by {cg.CUDA_GRAPH_DISABLE_ENV}"
+class _Scale:
+ def __init__(self, n):
+ self.n = n
+
+ def numel(self):
+ return self.n
+
+
+# Named like torchao's classes: the check matches by class name.
+Float8Tensor = type("Float8Tensor", (), {})
+Int8Tensor = type("Int8Tensor", (), {})
+LinearActivationQuantizedTensor = type("LinearActivationQuantizedTensor", (), {})
+AffineQuantizedTensor = type("AffineQuantizedTensor", (), {})
+Float8AQTTensorImpl = type("Float8AQTTensorImpl", (), {})
+
+
+def _fp8_weight(*, rows = 3072, dynamic = True):
+ w = Float8Tensor()
+ w.scale = _Scale(rows)
+ w.act_quant_kwargs = types.SimpleNamespace(hp_value_lb = 1e-12) if dynamic else None
+ return w
+
+
+def _legacy_fp8_weight(rows = 3072):
+ impl = Float8AQTTensorImpl()
+ impl.scale = _Scale(rows)
+ inner = AffineQuantizedTensor()
+ inner.tensor_impl = impl
+ w = LinearActivationQuantizedTensor()
+ w.original_weight_tensor = inner
+ return w
+
+
+class _QuantDiT(_FakeDiT):
+ def __init__(self, *weights):
+ super().__init__()
+ self.weights = list(weights)
+
+ def parameters(self):
+ return iter(self.weights)
+
+
+def _hazard_torch(
+ stub_torch,
+ monkeypatch,
+ *,
+ version = "2.10.0+cu130",
+ cap = (8, 9),
+ hip = None,
+):
+ stub_torch.__version__ = version
+ stub_torch.version = types.SimpleNamespace(hip = hip, cuda = "13.0")
+ stub_torch.cuda.get_device_capability = lambda device = None: cap
+ monkeypatch.setattr(cg.sys, "platform", "linux")
+
+
+def test_graph_eligible_refuses_row_wise_fp8_on_sm89_under_torch_without_the_streamk_fix(
+ stub_torch, monkeypatch
+):
+ _hazard_torch(stub_torch, monkeypatch)
+ ok, reason = _eligible(
+ monkeypatch, pipe = types.SimpleNamespace(transformer = _QuantDiT(_fp8_weight()))
+ )
+ assert ok is False
+ assert "sm_89" in reason and "torch 2.10" in reason and "pytorch/pytorch#177573" in reason
+ legacy = types.SimpleNamespace(transformer = _QuantDiT(_legacy_fp8_weight()))
+ assert _eligible(monkeypatch, pipe = legacy)[0] is False
+
+
+ "torch_kw, weights",
+ [
+ ({"version": "2.12.0+cu130"}, [_fp8_weight()]),
+ ({"version": "2.13.1"}, [_fp8_weight()]),
+ ({"cap": (9, 0)}, [_fp8_weight()]),
+ ({"cap": (12, 0)}, [_fp8_weight()]),
+ ({"cap": (8, 6)}, [_fp8_weight()]),
+ ({"hip": "7.1"}, [_fp8_weight()]),
+ ({}, [_fp8_weight(rows = 1)]), # per-tensor scale: cuBLASLt, no stream-K
+ ({}, [_fp8_weight(dynamic = False)]), # weight-only fp8: dequantised, no _scaled_mm
+ ({}, [Int8Tensor()]),
+ ({}, []),
+ ],
+)
+def test_graph_eligible_keeps_graphs_outside_the_streamk_fp8_hazard(
+ stub_torch, monkeypatch, torch_kw, weights
+):
+ _hazard_torch(stub_torch, monkeypatch, **torch_kw)
+ ok, reason = _eligible(monkeypatch, pipe = types.SimpleNamespace(transformer = _QuantDiT(*weights)))
+ assert (ok, reason) == (True, "eligible")
+
+
+def test_fp8_streamk_check_skips_windows_and_unreadable_torch(stub_torch, monkeypatch):
+ _hazard_torch(stub_torch, monkeypatch)
+ dit = _QuantDiT(_fp8_weight())
+ assert cg.fp8_rowwise_capture_refusal([dit]) is not None
+ monkeypatch.setattr(cg.sys, "platform", "win32")
+ assert cg.fp8_rowwise_capture_refusal([dit]) is None
+ monkeypatch.setattr(cg.sys, "platform", "linux")
+
+ def boom(device = None):
+ raise RuntimeError("no device")
+
+ stub_torch.cuda.get_device_capability = boom
+ assert cg.fp8_rowwise_capture_refusal([dit]) is None
+ stub_torch.cuda.get_device_capability = lambda device = None: (8, 9)
+ stub_torch.__version__ = "weird"
+ assert cg.fp8_rowwise_capture_refusal([dit]) is None
+
+
+def test_fp8_streamk_check_reads_the_onload_card(stub_torch, monkeypatch):
+ _hazard_torch(stub_torch, monkeypatch)
+ seen = []
+ stub_torch.cuda.get_device_capability = lambda device = None: seen.append(device) or (8, 9)
+ target = types.SimpleNamespace(
+ device = "cuda", backend = "cuda", dtype = "bfloat16", torch_device = "cuda:1"
+ )
+ pipe = types.SimpleNamespace(transformer = _QuantDiT(_fp8_weight()))
+ assert _eligible(monkeypatch, target = target, pipe = pipe)[0] is False
+ assert seen == ["cuda:1"]
+
+
def test_graph_eligible_needs_torch_cuda(stub_torch, monkeypatch):
stub_torch.cuda.is_available = lambda: False
assert _eligible(monkeypatch)[1] == "torch.cuda unavailable"