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: stop the dense torchao quant probe from crashing the backend on AMD ROCm (#9828)

oobaboogad899dcbc347e
diff --git a/studio/backend/core/_torchao_stub.py b/studio/backend/core/_torchao_stub.py
index e024027409b..7dd758f854a 100644
--- a/studio/backend/core/_torchao_stub.py
+++ b/studio/backend/core/_torchao_stub.py
@@ -169,11 +169,8 @@ def _installed_torch_is_rocm() -> Optional[bool]:
return False if (tagged is False and hip is False) else None
-def _is_windows_rocm() -> bool:
- """True on a Windows host whose active torch is a ROCm build."""
- # Gate on the active torch runtime, not env vars: HIP_PATH/ROCM_PATH outlive a revert to CUDA.
- if sys.platform != "win32":
- return False
+def torch_is_rocm() -> bool:
+ """True when the active torch is a ROCm/HIP build, using import-free checks when possible."""
mod = sys.modules.get("torch")
if mod is not None:
return _module_is_rocm(mod)
@@ -188,6 +185,11 @@ def _is_windows_rocm() -> bool:
return _module_is_rocm(torch)
+def _is_windows_rocm() -> bool:
+ """True on a Windows host whose active torch is a ROCm build."""
+ return sys.platform == "win32" and torch_is_rocm()
+
+
def _ensure_finder() -> None:
"""Register the subpackage finder once, however many stubs are installed."""
if not any(isinstance(f, _StubSubpackageFinder) for f in sys.meta_path):
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index dbd23ef9138..8a89861377b 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -175,6 +175,7 @@ from .diffusion_transformer_quant import (
TQ_AUTO,
DEFAULT_MIN_LINEAR_FEATURES,
dense_transformer_supported,
+ dense_transformer_unsupported_reason,
explain_unusable_scheme,
normalize_transformer_quant,
quantize_transformer,
@@ -1407,9 +1408,7 @@ class DiffusionBackend:
"quant is skipped"
)
elif not dense_transformer_supported(target):
- reason = (
- "this device cannot run a dense torchao quant (it needs a CUDA GPU in bf16)"
- )
+ reason = dense_transformer_unsupported_reason(target)
elif (
select_transformer_quant_scheme(
target,
diff --git a/studio/backend/core/inference/diffusion_precision.py b/studio/backend/core/inference/diffusion_precision.py
index de8b4808877..26cb172eb23 100644
--- a/studio/backend/core/inference/diffusion_precision.py
+++ b/studio/backend/core/inference/diffusion_precision.py
@@ -36,7 +36,7 @@ from .diffusion_auto_policy import (
# stdlib-only module (no torch), so this stays inside the "imported lazily" promise above.
from functools import lru_cache
-from core._torchao_stub import is_stubbed
+from core._torchao_stub import is_stubbed, torch_is_rocm
TE_QUANT_FP8 = "fp8"
TE_QUANT_NVFP4 = "nvfp4"
@@ -130,10 +130,9 @@ def te_quant_supported(target: Any, mode: str) -> bool:
Blackwell sm_100+ (nvfp4)."""
if getattr(target, "device", None) != "cuda":
return False
- # The Windows-ROCm torchao stub's quantize_ is a no-op, so the encoder stays bf16 while
- # quantize_text_encoders reports the mode applied. ROCm answers device "cuda" and a
- # capability pair, so nothing below would catch it.
- if mode in _TE_TORCHAO_MODES and is_stubbed("torchao"):
+ # Torchao modes cannot use the Windows stub or ROCm's non-SM capability values. Plain fp8 is
+ # only a dtype cast and remains supported.
+ if mode in _TE_TORCHAO_MODES and (is_stubbed("torchao") or torch_is_rocm()):
return False
try:
import torch
diff --git a/studio/backend/core/inference/diffusion_transformer_quant.py b/studio/backend/core/inference/diffusion_transformer_quant.py
index 0fdc7d3dbad..52fd54e91eb 100644
--- a/studio/backend/core/inference/diffusion_transformer_quant.py
+++ b/studio/backend/core/inference/diffusion_transformer_quant.py
@@ -24,11 +24,12 @@ probe is best-effort: an unsupported scheme yields None and the caller loads GGU
from __future__ import annotations
import re as _re
+import sys as _sys
import threading as _threading
from typing import Any, Optional
# stdlib-only module (no torch), so this stays inside the "imported lazily" promise above.
-from core._torchao_stub import is_stubbed
+from core._torchao_stub import is_stubbed, torch_is_rocm
TQ_INT8 = "int8"
TQ_FP8 = "fp8"
@@ -450,6 +451,10 @@ def dense_transformer_supported(target: Any) -> bool:
# giving the wrong VRAM budget and compile policy.
if is_stubbed("torchao"):
return False
+ # ROCm reports gfx versions through CUDA capability APIs, so _AUTO_LADDER's NVIDIA SM floors
+ # misclassify AMD GPUs. Keep ROCm on the GGUF path.
+ if torch_is_rocm():
+ return False
try:
import torch
return getattr(target, "dtype", None) is torch.bfloat16
@@ -457,6 +462,19 @@ def dense_transformer_supported(target: Any) -> bool:
return False
+def dense_transformer_unsupported_reason(target: Any) -> str:
+ """Why ``dense_transformer_supported`` rejected the target."""
+ if getattr(target, "device", None) == "cuda" and torch_is_rocm():
+ return (
+ "the dense torchao quant schemes are NVIDIA tensor-core paths (int8 sm_80+, fp8 "
+ "sm_89+, fp4/mx sm_100+) and this is a ROCm/AMD GPU, so the checkpoint runs at the "
+ "precision it ships with"
+ )
+ if is_stubbed("torchao"):
+ return "this platform ships a torchao stub whose quantize_ is a no-op"
+ return "this device cannot run a dense torchao quant (it needs a CUDA GPU in bf16)"
+
+
def select_transformer_quant_scheme(
target: Any,
requested: Optional[str],
@@ -561,21 +579,27 @@ def _scheme_supported(
# get_device_capability() (0 MiB after both, 614 MiB after the first tensor). Worth a child
# because /images/download-plan calls assert_precision_available while the user is only
# STAGING, so a plan alone cost the backend ~700 MiB it can never give back.
- if (scheme, device) not in _SMOKE_CACHE:
+ # _smoke_probe's card-qualified key, and the child is asked about that same card: a spawn
+ # starts on ordinal 0 whatever this thread is pinned to, so a bare "cuda" would file card 0's
+ # verdict under the card the load runs on (and a bare key hid child verdicts entirely).
+ card = _smoke_cache_device_key(device)
+ if (scheme, card) not in _SMOKE_CACHE:
with _CHILD_PROBE_LOCK:
# Re-checked under the lock: the route answers plans concurrently, and a burst of
# them must not each spawn a child that imports torch.
- if (scheme, device) not in _SMOKE_CACHE:
- table = _child_probe_table(device)
+ if (scheme, card) not in _SMOKE_CACHE:
+ table = _child_probe_table(card)
if table is not None:
for name, child_verdict in table.items():
# None is the child's out-of-memory: not a verdict, so not cached.
if child_verdict is not None:
- _SMOKE_CACHE[(name, device)] = child_verdict
- if table.get(scheme, False) is None:
- # Same answer the in-process probe gives an OOM, without re-running it
- # here: it would meet the same full GPU and pay the context on the way.
- return unproven_ok
+ _SMOKE_CACHE[(name, card)] = child_verdict
+ if scheme in table:
+ if table[scheme] is None:
+ # Repeating an OOM probe in the same memory state proves nothing.
+ return unproven_ok
+ # The child ran the same probe. Missing entries still fall through below.
+ return table[scheme]
return _smoke_probe(scheme, device, unproven_ok = unproven_ok)
@@ -696,7 +720,49 @@ def _child_probe_table(device: str) -> Optional[dict[str, Optional[bool]]]:
break
finally:
_close_probe_child(proc, queue)
- return table if isinstance(table, dict) else None
+ return table if isinstance(table, dict) else _crashed_child_verdict(proc, device)
+
+
+# SIGKILL may be OOM and SIGTERM is timeout cleanup, so neither is a scheme verdict.
+_PROBE_CRASH_SIGNALS = frozenset({4, 6, 7, 8, 11}) # ILL, ABRT, BUS, FPE, SEGV
+
+# Windows has no signal here: multiprocessing returns GetExitCodeProcess verbatim, so a fault is
+# the raw NTSTATUS (access violation 0xC0000005, UCRT abort 0xC0000409), never -SIGSEGV. Only
+# TERMINATE is negative, hence the sign test first; the severity bits then separate a fault from
+# a deliberate sys.exit.
+_NTSTATUS_ERROR_FLOOR = 0xC0000000
+
+
+def _crashed_child_verdict(proc: Any, device: str) -> Optional[dict[str, Optional[bool]]]:
+ """Return an all-false table after a fatal probe crash, otherwise None.
+
+ The child may die before identifying the scheme, and every scheme shares ``quantize_``. Disable
+ the table rather than repeating a proven-fatal probe in the backend.
+ """
+ try:
+ exitcode = proc.exitcode if proc is not None else None
+ except Exception: # noqa: BLE001 -- no handle left: nothing proven, fall back as before
+ return None
+ if exitcode is None:
+ return None
+ if exitcode < 0:
+ if -exitcode not in _PROBE_CRASH_SIGNALS:
+ return None
+ cause = f"signal {-exitcode}"
+ elif _sys.platform == "win32" and exitcode >= _NTSTATUS_ERROR_FLOOR:
+ cause = f"status 0x{exitcode:08X}"
+ else:
+ return None
+ import logging
+
+ logging.getLogger(__name__).warning(
+ "diffusion.transformer_quant: probe child died on %s quantising on %s; treating "
+ "every dense quant scheme as unusable here rather than re-running the same probe in this "
+ "process, which would take the server down the same way",
+ cause,
+ device,
+ )
+ return {scheme: False for scheme in TQ_SCHEMES}
def _adopt_probe_pid(pid: Optional[int]) -> None:
@@ -769,12 +835,29 @@ def _close_probe_child(proc: Any, queue: Any) -> bool:
return True
+def _select_probe_card(device: str) -> None:
+ """Make ``device``'s ordinal current in this child, so the probe's argument-less CUDA calls
+ -- ``synchronize()``, torchao's own capability lookups -- read the card the tensors are on.
+
+ Best-effort: an index this process cannot select still probes, and lands the same failure
+ the in-process fallback would."""
+ ordinal = device.partition(":")[2]
+ if not ordinal.isdigit():
+ return
+ try:
+ import torch
+ torch.cuda.set_device(int(ordinal))
+ except Exception: # noqa: BLE001 -- an unselectable index still probes, on the default card
+ pass
+
+
def _child_probe_entry(device: str, schemes: tuple[str, ...], out: Any) -> None:
"""Child side of ``_child_probe_table``: probe every scheme and post one table back.
Module-level and stdlib-signature so ``spawn`` can reach it by name. Every scheme is
attempted even after one fails, because the verdicts are independent and the whole point is
to pay the CUDA context once."""
+ _select_probe_card(device)
table: dict[str, Optional[bool]] = {}
for scheme in schemes:
try:
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index a4ae2dc0e0a..89d5ac27033 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -103,6 +103,7 @@ from .diffusion_auto_policy import (
from .diffusion_transformer_quant import (
TQ_AUTO,
dense_transformer_supported,
+ dense_transformer_unsupported_reason,
explain_unusable_scheme,
normalize_transformer_quant,
quantize_transformer,
@@ -273,7 +274,7 @@ def _assert_video_precision_for_target(
f"'{model_kind}' load, which runs the precision its checkpoint carries"
)
elif not dense_transformer_supported(target):
- reason = "this device cannot run a dense torchao quant (it needs a CUDA GPU in bf16)"
+ reason = dense_transformer_unsupported_reason(target)
elif forces_offload:
# balanced and low_vram name their offload policy without measuring anything, and
# offload hooks move modules with Module.to(), which torchao tensors do not survive.
diff --git a/studio/backend/core/training/diffusion_dit_trainer.py b/studio/backend/core/training/diffusion_dit_trainer.py
index 9395dbca38e..010ac0c9ab0 100644
--- a/studio/backend/core/training/diffusion_dit_trainer.py
+++ b/studio/backend/core/training/diffusion_dit_trainer.py
@@ -39,7 +39,7 @@ from dataclasses import dataclass, replace
from pathlib import Path
from typing import Any, Callable, Optional
-from core._torchao_stub import is_stubbed
+from core._torchao_stub import is_stubbed, torch_is_rocm
from core.training.diffusion_train_common import (
AUTO_FLOW_SHIFT_FAMILIES,
DEFAULT_LORA_FILENAME,
@@ -543,6 +543,13 @@ def _resolve_base_precision(cfg, spec, device) -> str:
f"base_precision={mode!r} needs a CUDA GPU; this host has none. "
f"Use base_precision='nf4' or 'auto'."
)
+ # Mirror the pre-eviction ROCm guard inside the trainer child.
+ if mode in ("int8", "fp8", "mxfp8") and torch_is_rocm():
+ raise ValueError(
+ f"base_precision={mode!r} is a torchao NVIDIA tensor-core path (int8 sm_80+, fp8 "
+ "sm_89+, mxfp8 sm_100+) and this is a ROCm/AMD GPU. Use base_precision='nf4', "
+ "'bf16', or 'auto'."
+ )
# int8 has no runtime fallback, so an explicit int8 against a missing torchao (or the Windows-ROCm stub) would leave the
# transformer dense with compile disabled. The auto pick and /info gate on a FUNCTIONAL torchao; do the same here.
if mode == "int8" and not has_functional_torchao():
@@ -579,7 +586,8 @@ def _resolve_base_precision(cfg, spec, device) -> str:
capability = None
has_fp8 = False
# int8 has no runtime fallback, so gate the auto pick on a FUNCTIONAL torchao: find_spec("torchao") is satisfied by the Windows-ROCm stub whose quantize_ is a no-op.
- has_torchao = has_functional_torchao()
+ # Auto must not select a torchao mode on ROCm.
+ has_torchao = has_functional_torchao() and not torch_is_rocm()
if device == "cuda":
try:
import torch
diff --git a/studio/backend/core/training/diffusion_train_common.py b/studio/backend/core/training/diffusion_train_common.py
index 5705092965a..ed44f1824dd 100644
--- a/studio/backend/core/training/diffusion_train_common.py
+++ b/studio/backend/core/training/diffusion_train_common.py
@@ -29,6 +29,7 @@ from core._torchao_stub import (
install_torchao_windows_rocm_stub,
install_xformers_windows_rocm_stub,
is_stubbed,
+ torch_is_rocm,
)
from core.inference.diffusion_families import (
detect_family,
@@ -463,7 +464,8 @@ def train_precision_modes() -> tuple[list[str], str]:
import torch
if native_bf16_supported():
modes.append("bf16")
- torchao_ok = has_functional_torchao()
+ # ROCm capability values are gfx versions, not the NVIDIA SM levels checked below.
+ torchao_ok = has_functional_torchao() and not torch_is_rocm()
if torchao_ok:
modes.append("int8")
major, minor = torch.cuda.get_device_capability()
@@ -779,9 +781,11 @@ def training_precision_preflight_error(resolved_family: str, base_precision: str
child, after eviction). Every gate mirrors one in _resolve_base_precision, so a doomed run is
rejected before teardown: the bf16-GPU requirement (bf16_unsupported_reason); no accelerator at
all (dit_accelerator_missing_reason, which covers nf4 too); the dense precisions
- (bf16/int8/fp8/mxfp8) needing CUDA; explicit int8 needing a FUNCTIONAL torchao (its
- _int8_quantize_base has no fallback); explicit fp8/mxfp8 against the Windows-ROCm torchao stub;
- explicit mxfp8 needing Blackwell (sm100+). Add a gate there, add it here. Never raises."""
+ (bf16/int8/fp8/mxfp8) needing CUDA; the torchao precisions (int8/fp8/mxfp8) against a ROCm
+ build, which clears the stub test and hands the sm100 floor an AMD gfx version; explicit int8
+ needing a FUNCTIONAL torchao (its _int8_quantize_base has no fallback); explicit fp8/mxfp8
+ against the Windows-ROCm torchao stub; explicit mxfp8 needing Blackwell (sm100+). Add a gate
+ there, add it here. Never raises."""
reason = bf16_unsupported_reason(resolved_family)
if reason:
return reason
@@ -803,6 +807,12 @@ def training_precision_preflight_error(resolved_family: str, base_precision: str
f"base_precision={mode!r} needs a CUDA GPU; this host has none. "
"Use base_precision='nf4' or 'auto'."
)
+ # Reject before eviction; _resolve_base_precision repeats this in the child.
+ if mode in ("int8", "fp8", "mxfp8") and torch_is_rocm():
+ return (
+ f"base_precision={mode!r} is a torchao NVIDIA tensor-core path (int8 sm_80+, fp8 "
+ "sm_89+, mxfp8 sm_100+) and this is a ROCm/AMD GPU. Use 'nf4', 'bf16', or 'auto'."
+ )
if mode == "int8" and not has_functional_torchao():
return (
"base_precision='int8' needs a functional torchao install; this host's torchao is "
diff --git a/studio/backend/tests/test_dense_quant_rocm_gate_9396.py b/studio/backend/tests/test_dense_quant_rocm_gate_9396.py
new file mode 100644
index 00000000000..0787d0a5893
--- /dev/null
+++ b/studio/backend/tests/test_dense_quant_rocm_gate_9396.py
@@ -0,0 +1,369 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Regression tests for #9396's ROCm capability misread and fatal child probe retry.
+
+Torch is stubbed through ``sys.modules`` and no process is spawned.
+"""
+
+from __future__ import annotations
+
+import sys
+import types
+
+import pytest
+
+import core.inference.diffusion_precision as dp
+import core.inference.diffusion_transformer_quant as tq
+
+
+def _target(*, device = "cuda", dtype = "bfloat16"):
+ return types.SimpleNamespace(device = device, dtype = dtype)
+
+
+def _stub_torch(
+ monkeypatch,
+ *,
+ hip = None,
+ version_str = "2.10.0+cu128",
+ cc = (11, 0),
+ current_device = 0,
+):
+ """A torch stub that answers like a ROCm build when ``hip`` is set.
+
+ ``current_device`` is the ordinal this thread is pinned to; ``torch.cuda.selected`` records
+ every ``set_device`` the code under test makes."""
+ torch = types.ModuleType("torch")
+ torch.bfloat16 = "bfloat16"
+ torch.float16 = "float16"
+ torch.float8_e4m3fn = "float8_e4m3fn"
+ torch.__version__ = version_str
+ torch.version = types.SimpleNamespace(hip = hip, cuda = None if hip else "12.8")
+ torch.cuda = types.SimpleNamespace(
+ is_available = lambda: True,
+ get_device_capability = lambda *a: cc,
+ get_device_name = lambda *a: "AMD Radeon 780M Graphics" if hip else "NVIDIA B200",
+ current_device = lambda: current_device,
+ selected = [],
+ )
+ torch.cuda.set_device = torch.cuda.selected.append
+ torch.nn = types.SimpleNamespace(
+ Embedding = type("Embedding", (), {}),
+ ModuleList = type("ModuleList", (list,), {}),
+ )
+ monkeypatch.setitem(sys.modules, "torch", torch)
+ monkeypatch.setattr(tq, "_SMOKE_CACHE", {}, raising = True)
+ return torch
+
+
+def _forbid_probe(monkeypatch):
+ """Fail loudly if anything reaches the smoke probe: on ROCm it is what segfaults."""
+
+ def _boom(*args, **kwargs):
+ raise AssertionError("the torchao smoke probe must not run on ROCm")
+
+ monkeypatch.setattr(tq, "_scheme_supported", _boom)
+ monkeypatch.setattr(tq, "_run_smoke_probe", _boom)
+
+
+# ── 1. the arch gate ──────────────────────────────────────────────────────────
+
+
+ "hip, version_str",
+ [
+ ("7.1.25424", "2.10.0+rocm7.1"), # the build in the report
+ (None, "2.10.0+rocm7.1"), # AMD wheels that tag only __version__
+ ],
+)
+def test_dense_transformer_unsupported_on_rocm(monkeypatch, hip, version_str):
+ _stub_torch(monkeypatch, hip = hip, version_str = version_str)
+ assert tq.torch_is_rocm() is True
+ assert tq.dense_transformer_supported(_target()) is False
+
+
+def test_dense_transformer_still_supported_on_cuda(monkeypatch):
+ _stub_torch(monkeypatch, hip = None, version_str = "2.10.0+cu128", cc = (10, 0))
+ assert tq.torch_is_rocm() is False
+ assert tq.dense_transformer_supported(_target()) is True
+
+
[email protected]("cc", [(11, 0), (11, 5), (9, 4)]) # gfx1103, gfx1151, gfx942
+def test_auto_selects_nothing_and_never_probes_on_rocm(monkeypatch, cc):
+ """The regression: (11, 0) is gfx1103, not sm_110, and must not clear the sm_100 tier."""
+ _stub_torch(monkeypatch, hip = "7.1.25424", version_str = "2.10.0+rocm7.1", cc = cc)
+ _forbid_probe(monkeypatch)
+ assert tq.select_transformer_quant_scheme(_target(), "auto") is None
+ assert tq.auto_scheme_candidates(_target()) == ()
+
+
[email protected]("scheme", list(tq.TQ_SCHEMES))
+def test_explicit_scheme_refused_without_probing_on_rocm(monkeypatch, scheme):
+ _stub_torch(monkeypatch, hip = "7.1.25424", version_str = "2.10.0+rocm7.1")
+ _forbid_probe(monkeypatch)
+ assert tq.select_transformer_quant_scheme(_target(), scheme) is None
+
+
+def test_refusal_reason_names_rocm(monkeypatch):
+ _stub_torch(monkeypatch, hip = "7.1.25424", version_str = "2.10.0+rocm7.1")
+ reason = tq.dense_transformer_unsupported_reason(_target())
+ assert "ROCm" in reason and "AMD" in reason
+
+
+def test_refusal_reason_unchanged_off_cuda(monkeypatch):
+ _stub_torch(monkeypatch, hip = None)
+ assert "CUDA GPU in bf16" in tq.dense_transformer_unsupported_reason(_target(device = "cpu"))
+
+
+# ── 2. the text-encoder gate has the same capability misread ──────────────────
+
+
[email protected]("mode", [dp.TE_QUANT_INT8, dp.TE_QUANT_FP8_DYNAMIC, dp.TE_QUANT_NVFP4])
+def test_torchao_text_encoder_modes_unsupported_on_rocm(monkeypatch, mode):
+ _stub_torch(monkeypatch, hip = "7.1.25424", version_str = "2.10.0+rocm7.1")
+ assert dp.te_quant_supported(_target(), mode) is False
+
+
+def test_layerwise_fp8_text_encoder_still_supported_on_rocm(monkeypatch):
+ """Plain fp8 is a torch dtype cast with no torchao in it, so ROCm keeps it."""
+ _stub_torch(monkeypatch, hip = "7.1.25424", version_str = "2.10.0+rocm7.1")
+ assert dp.te_quant_supported(_target(), dp.TE_QUANT_FP8) is True
+
+
[email protected]("mode", [dp.TE_QUANT_INT8, dp.TE_QUANT_FP8_DYNAMIC, dp.TE_QUANT_NVFP4])
+def test_torchao_text_encoder_modes_still_supported_on_cuda(monkeypatch, mode):
+ _stub_torch(monkeypatch, hip = None, version_str = "2.10.0+cu128", cc = (10, 0))
+ monkeypatch.setattr(dp, "is_stubbed", lambda name: False)
+ assert dp.te_quant_supported(_target(), mode) is True
+
+
+# ── 3. a crashed probe child is a verdict, not a reason to retry in-process ───
+
+
+class _Proc:
+ def __init__(self, exitcode):
+ self.exitcode = exitcode
+
+
[email protected]("signal_number", sorted(tq._PROBE_CRASH_SIGNALS))
+def test_crashed_child_marks_every_scheme_unusable(signal_number):
+ verdict = tq._crashed_child_verdict(_Proc(-signal_number), "cuda")
+ assert verdict == {scheme: False for scheme in tq.TQ_SCHEMES}
+
+
[email protected]("exitcode", [0, 1, -9, -15, None])
+def test_non_crash_exits_still_fall_back_in_process(exitcode):
+ """SIGKILL is the OOM killer, SIGTERM is our own timeout teardown; neither is a verdict."""
+ assert tq._crashed_child_verdict(_Proc(exitcode), "cuda") is None
+ assert tq._crashed_child_verdict(None, "cuda") is None
+
+
+ "status",
+ [
+ 0xC0000005, # STATUS_ACCESS_VIOLATION
+ 0xC000001D, # STATUS_ILLEGAL_INSTRUCTION
+ 0xC0000094, # STATUS_INTEGER_DIVIDE_BY_ZERO
+ 0xC0000374, # STATUS_HEAP_CORRUPTION
+ 0xC0000409, # STATUS_STACK_BUFFER_OVERRUN, where UCRT's abort() lands
+ ],
+)
+def test_a_windows_native_fault_is_a_crash_not_an_inconclusive_exit(monkeypatch, status):
+ """A faulting child on Windows is a positive NTSTATUS (0xC0000005 == 3221225477), never
+ -SIGSEGV; read as inconclusive, the parent re-runs the proven-fatal probe in the backend."""
+ monkeypatch.setattr(tq, "_sys", types.SimpleNamespace(platform = "win32"))
+ verdict = tq._crashed_child_verdict(_Proc(status), "cuda")
+ assert verdict == {scheme: False for scheme in tq.TQ_SCHEMES}
+
+
[email protected]("exitcode", [0, 1, 3, 42, -15, 0x40000015, 0x80000003])
+def test_a_windows_exit_that_is_not_an_error_status_still_falls_back(monkeypatch, exitcode):
+ """Below the error severity: a deliberate exit, TERMINATE, and the lesser severities."""
+ monkeypatch.setattr(tq, "_sys", types.SimpleNamespace(platform = "win32"))
+ assert tq._crashed_child_verdict(_Proc(exitcode), "cuda") is None
+
+
[email protected]("status", [0xC0000005, 0xC0000409])
+def test_a_positive_status_off_windows_is_not_a_crash(monkeypatch, status):
+ """POSIX encodes a fatal signal negatively, so a large positive code is the child's choice."""
+ monkeypatch.setattr(tq, "_sys", types.SimpleNamespace(platform = "linux"))
+ assert tq._crashed_child_verdict(_Proc(status), "cuda") is None
+
+
+def test_crash_verdict_stops_the_in_process_probe(monkeypatch):
+ """End of the #9396 chain: the child died, so the parent must not run the same probe."""
+ _stub_torch(monkeypatch, hip = "7.1.25424", version_str = "2.10.0+rocm7.1")
+ monkeypatch.setattr(
+ tq, "_child_probe_table", lambda device: tq._crashed_child_verdict(_Proc(-11), device)
+ )
+
+ def _boom(*args, **kwargs):
+ raise AssertionError("a crashed probe child must not be retried in this process")
+
+ monkeypatch.setattr(tq, "_run_smoke_probe", _boom)
+ assert tq._scheme_supported(tq.TQ_INT8, "cuda") is False
+ # Cached, so a second load answers from memory instead of spawning another child to die.
+ assert tq._SMOKE_CACHE[(tq.TQ_INT8, "cuda:0")] is False
+
+
+def test_child_verdict_is_used_instead_of_a_second_in_process_probe(monkeypatch):
+ """A child verdict stored for cuda:0 must prevent a second probe in the backend."""
+ _stub_torch(monkeypatch, hip = None, version_str = "2.10.0+cu128", cc = (10, 0))
+ monkeypatch.setattr(
+ tq, "_child_probe_table", lambda device: {s: (s == tq.TQ_INT8) for s in tq.TQ_SCHEMES}
+ )
+
+ def _boom(*args, **kwargs):
+ raise AssertionError("the child already answered; the parent must not probe again")
+
+ monkeypatch.setattr(tq, "_run_smoke_probe", _boom)
+ assert tq._scheme_supported(tq.TQ_INT8, "cuda") is True
+ assert tq._scheme_supported(tq.TQ_FP8, "cuda") is False
+ assert tq._SMOKE_CACHE[(tq.TQ_INT8, "cuda:0")] is True
+
+
[email protected]("unproven_ok", [True, False])
+def test_child_out_of_memory_is_still_not_a_verdict(monkeypatch, unproven_ok):
+ """None is the child's allocator failure: not cached, and not turned into "unsupported"."""
+ _stub_torch(monkeypatch, hip = None, version_str = "2.10.0+cu128", cc = (10, 0))
+ monkeypatch.setattr(tq, "_child_probe_table", lambda device: {s: None for s in tq.TQ_SCHEMES})
+ monkeypatch.setattr(tq, "_run_smoke_probe", lambda *a, **k: pytest.fail("no re-probe"))
+ assert tq._scheme_supported(tq.TQ_INT8, "cuda", unproven_ok = unproven_ok) is unproven_ok
+ assert (tq.TQ_INT8, "cuda:0") not in tq._SMOKE_CACHE
+
+
+def test_a_scheme_missing_from_the_table_is_still_not_an_answer(monkeypatch):
+ """Only a present key is the child's verdict; an absent one falls through as it always did."""
+ _stub_torch(monkeypatch, hip = None, version_str = "2.10.0+cu128", cc = (10, 0))
+ monkeypatch.setattr(tq, "_child_probe_table", lambda device: {tq.TQ_FP8: True})
+ probed: list = []
+ monkeypatch.setattr(
+ tq, "_run_smoke_probe", lambda scheme, device: probed.append(scheme) or True
+ )
+ assert tq._scheme_supported(tq.TQ_INT8, "cuda") is True
+ assert probed == [tq.TQ_INT8]
+
+
+# ── 3a. the child must probe the card the verdict is filed under ─────────────
+
+
+def test_child_is_asked_about_the_pinned_card_not_the_default_one(monkeypatch):
+ """A load pinned to GPU 1 caches under cuda:1, so the child has to be asked about cuda:1.
+
+ A freshly spawned child starts on ordinal 0 whatever this thread selected, so handing it a
+ bare "cuda" would file the default card's kernel support against the card the load runs on.
+ """
+ _stub_torch(
+ monkeypatch,
+ hip = None,
+ version_str = "2.10.0+cu128",
+ cc = (8, 6),
+ current_device = 1,
+ )
+ asked: list = []
+ # Only the pinned card runs the scheme here, which is the mixed-GPU box this guards.
+ monkeypatch.setattr(
+ tq,
+ "_child_probe_table",
+ lambda device: asked.append(device) or {s: device == "cuda:1" for s in tq.TQ_SCHEMES},
+ )
+ monkeypatch.setattr(
+ tq, "_run_smoke_probe", lambda *a, **k: pytest.fail("the child already answered")
+ )
+ assert tq._scheme_supported(tq.TQ_FP8, "cuda") is True
+ assert asked == ["cuda:1"]
+ assert tq._SMOKE_CACHE[(tq.TQ_FP8, "cuda:1")] is True
+ assert (tq.TQ_FP8, "cuda:0") not in tq._SMOKE_CACHE
+
+
+ "device, expected", [("cuda:1", [1]), ("cuda:0", [0]), ("cuda", []), ("cpu", [])]
+)
+def test_probe_child_selects_the_card_it_was_given(monkeypatch, device, expected):
+ """Argument-less CUDA calls inside the probe (synchronize, torchao's capability lookups)
+ read the CURRENT device, so the child pins it rather than only placing tensors."""
+ torch = _stub_torch(monkeypatch)
+ tq._select_probe_card(device)
+ assert torch.cuda.selected == expected
+
+
+# ── 4. the training gate has the same misread, at four entry points ───────────
+
+
+def _stub_train_torch(
+ monkeypatch,
+ *,
+ hip,
+ version_str,
+ cc = (11, 5),
+):
+ """As _stub_torch, plus what the training gates read (bf16 support, mem_get_info)."""
+ torch = _stub_torch(monkeypatch, hip = hip, version_str = version_str, cc = cc)
+ import core.training.diffusion_train_common as tc
+
+ monkeypatch.setattr(tc, "native_bf16_supported", lambda: True)
+ monkeypatch.setattr(tc, "has_functional_torchao", lambda: True)
+ return torch
+
+
+_TORCHAO_TRAIN_MODES = ("int8", "fp8", "mxfp8")
+
+
+def test_info_stops_advertising_the_torchao_train_modes_on_rocm(monkeypatch):
+ """The Train tab gates its selector on this list, so it is what users are offered."""
+ import core.training.diffusion_train_common as tc
+
+ _stub_train_torch(monkeypatch, hip = "7.1.25424", version_str = "2.10.0+rocm7.1")
+ modes, recommended = tc.train_precision_modes()
+ assert [m for m in modes if m in _TORCHAO_TRAIN_MODES] == []
+ # bf16 and the auto ladder are untouched: neither goes near torchao.
+ assert "bf16" in modes and "nf4" in modes and recommended == "auto"
+
+
+def test_info_still_advertises_them_on_cuda(monkeypatch):
+ """Regression guard: (11, 5) is a gfx version on ROCm but a real SM level on NVIDIA."""
+ import core.training.diffusion_train_common as tc
+
+ _stub_train_torch(monkeypatch, hip = None, version_str = "2.10.0+cu128", cc = (10, 0))
+ modes, _ = tc.train_precision_modes()
+ assert all(m in modes for m in _TORCHAO_TRAIN_MODES)
+
+
[email protected]("mode", _TORCHAO_TRAIN_MODES)
+def test_the_pre_eviction_guard_refuses_torchao_train_modes_on_rocm(monkeypatch, mode):
+ """Refused BEFORE the resident model is evicted, like every other doomed precision."""
+ import core.training.diffusion_train_common as tc
+
+ _stub_train_torch(monkeypatch, hip = "7.1.25424", version_str = "2.10.0+rocm7.1")
+ monkeypatch.setattr(tc, "bf16_unsupported_reason", lambda *a, **k: None, raising = False)
+ reason = tc.training_precision_preflight_error("z-image", mode)
+ assert reason is not None and "ROCm/AMD GPU" in reason
+
+
[email protected]("mode", _TORCHAO_TRAIN_MODES)
+def test_the_child_refuses_the_same_torchao_train_modes_on_rocm(monkeypatch, mode):
+ """The child re-check mirrors the parent guard, so a direct client fails the same way."""
+ import core.training.diffusion_dit_trainer as dit
+
+ _stub_train_torch(monkeypatch, hip = "7.1.25424", version_str = "2.10.0+rocm7.1")
+ cfg = types.SimpleNamespace(base_precision = mode, base_model = "unsloth/Z-Image")
+ with pytest.raises(ValueError, match = "ROCm/AMD GPU"):
+ dit._resolve_base_precision(cfg, types.SimpleNamespace(dense_bf16_gb = 12.0), "cuda")
+
+
+def test_auto_never_resolves_to_int8_on_rocm(monkeypatch):
+ """auto is the mode /info recommends, so it is the one users actually land on."""
+ import core.training.diffusion_dit_trainer as dit
+
+ # free VRAM inside int8's band (> 1.15x dense, < 1.5x dense): the pick auto would make.
+ assert dit._pick_auto_precision(False, "cuda", 13.8, 12.0, (11, 5), True, True) == "int8"
+ assert dit._pick_auto_precision(False, "cuda", 13.8, 12.0, (11, 5), True, False) == "nf4"
+
+ _stub_train_torch(monkeypatch, hip = "7.1.25424", version_str = "2.10.0+rocm7.1")
+ monkeypatch.setattr(dit, "repo_is_prequantized", lambda repo: False)
+ monkeypatch.setattr(dit, "trusted_mem_get_info", lambda: (13.8e9, 16e9), raising = False)
+ cfg = types.SimpleNamespace(
+ base_precision = "auto", base_model = "unsloth/Z-Image", mixed_precision = "bf16"
+ )
+ resolved = dit._resolve_base_precision(cfg, types.SimpleNamespace(dense_bf16_gb = 12.0), "cuda")
+ assert resolved != "int8"
diff --git a/studio/backend/tests/test_diffusion_base_precision.py b/studio/backend/tests/test_diffusion_base_precision.py
index f22546a9127..5be5f76421e 100644
--- a/studio/backend/tests/test_diffusion_base_precision.py
+++ b/studio/backend/tests/test_diffusion_base_precision.py
@@ -41,6 +41,17 @@ def _cfg(base_model = _FLUX_DENSE, **kw) -> DiffusionLoraConfig:
return DiffusionLoraConfig(base_model = base_model, data_dir = "d", output_dir = "o", **kw)
[email protected](autouse = True)
+def _not_rocm(monkeypatch):
+ """Pin the ROCm gate off: every case here describes an NVIDIA capability tier.
+
+ They simulate a card via get_device_capability, but the gate reads the INSTALLED torch, so on
+ an AMD box it short-circuits and the answers are about the real machine -- an environment
+ leak. test_dense_quant_rocm_gate_9396.py pins it the other way to exercise the gate."""
+ for _mod in (common, dit):
+ monkeypatch.setattr(_mod, "torch_is_rocm", lambda: False)
+
+
# ── base_precision validation ─────────────────────────────────────────────────
def test_base_precision_validation():
# Default normalizes to the nf4 memory floor.
diff --git a/studio/backend/tests/test_diffusion_dit_trainer.py b/studio/backend/tests/test_diffusion_dit_trainer.py
index eda4c7ffbe6..d01a3d01815 100644
--- a/studio/backend/tests/test_diffusion_dit_trainer.py
+++ b/studio/backend/tests/test_diffusion_dit_trainer.py
@@ -39,6 +39,20 @@ from core.training.diffusion_train_common import (
)
[email protected](autouse = True)
+def _not_rocm(monkeypatch):
+ """Pin the ROCm gate off: every case here describes an NVIDIA capability tier.
+
+ _patch_capability simulates a card, but the gate reads the INSTALLED torch, so on an AMD box
+ it short-circuits and the answers are about the real machine -- an environment leak.
+ test_dense_quant_rocm_gate_9396.py pins it the other way to exercise the gate."""
+ import core.training.diffusion_dit_trainer as _dit
+ import core.training.diffusion_train_common as _dtc
+
+ for _mod in (_dtc, _dit):
+ monkeypatch.setattr(_mod, "torch_is_rocm", lambda: False)
+
+
def test_specs_cover_the_dit_families():
assert set(_SPECS) == {
"flux.1",