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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: judge the compiled ROCm W8A8 linear per card, not once per process (#17078)
Daniel Han0854cbe44820
diff --git a/studio/backend/core/inference/diffusion_native_quant.py b/studio/backend/core/inference/diffusion_native_quant.pyindex bda53720da7..d9712b86568 100644--- a/studio/backend/core/inference/diffusion_native_quant.py+++ b/studio/backend/core/inference/diffusion_native_quant.py@@ -304,7 +304,27 @@ def _w8a8_rows_into(out.copy_(_w8a8_rows(x2, rot_h, weight_q, weight_scale, bias))-_FUSED_STATE: dict = {"fn": None, "failed": None}+# "devices": per card, None once it may run the compiled linear, else why not (its arch, or its compile failed).+_FUSED_STATE: dict = {"fn": None, "failed": None, "devices": {}}+_UNSEEN = object()+++def _device_key(device: Any = None) -> Any:+ """Indexed ``torch.device``; None or an unindexed cuda = the current card (the CPU without one)."""+ import torch++ if isinstance(device, int):+ return torch.device("cuda", device)+ if device is not None:+ device = torch.device(device)+ if device.type != "cuda" or device.index is not None:+ return device+ try:+ if torch.cuda.is_available():+ return torch.device("cuda", int(torch.cuda.current_device()))+ except Exception: # noqa: BLE001+ pass+ return torch.device("cpu")# ROCm archs where the compiled W8A8 linear was measured: RDNA3 / RDNA3.5 / RDNA4 (gfx11xx / gfx12xx). On gfx1151 it@@ -312,18 +332,18 @@ _FUSED_STATE: dict = {"fn": None, "failed": None}_ROCM_FUSED_W8A8_ARCH = re.compile(r"^gfx1[12][0-9a-f]{2}$")-def _rocm_fused_w8a8_refusal(torch: Any) -> Optional[str]:- """None when the compiled linear may run on this ROCm device, else why not (other ROCm archs: unmeasured)."""+def _rocm_fused_w8a8_refusal(torch: Any, ordinal: Optional[int] = None) -> Optional[str]:+ """None when the compiled linear may run on ROCm card ``ordinal`` (current when None), else why not."""from .rocm_bf16 import _device_gfx_arch- arch = _device_gfx_arch(torch, None)+ arch = _device_gfx_arch(torch, ordinal)if _ROCM_FUSED_W8A8_ARCH.match(arch):return Nonereturn f"ROCm {arch or 'unknown arch'}"-def rocm_rdna_w8a8_ready() -> bool:- """ROCm RDNA device where the compiled W8A8 linear can run (UNSLOTH_NATIVE_INT8_FUSED not off)."""+def rocm_rdna_w8a8_ready(ordinal: Optional[int] = None) -> bool:+ """ROCm RDNA card ``ordinal`` (current when None) where the compiled W8A8 linear can run and has not failed."""if _FUSED_STATE["failed"] is not None or int8_fused_disabled():return Falsetry:@@ -333,7 +353,10 @@ def rocm_rdna_w8a8_ready() -> bool:if not is_rocm_torch(torch) or not torch.cuda.is_available():return False- if _rocm_fused_w8a8_refusal(torch) is not None:+ key = _device_key(ordinal)+ if _FUSED_STATE.get("devices", {}).get(key) is not None:+ return False+ if _rocm_fused_w8a8_refusal(torch, key.index) is not None:return Falsefrom .diffusion_speed import torch_compile_runtime_available@@ -342,14 +365,21 @@ def rocm_rdna_w8a8_ready() -> bool:return False-def _fused_w8a8() -> Optional[Callable[..., Any]]:- """Compiled ``_w8a8_rows``, or None if disabled, no inductor runtime, a ROCm arch other than RDNA3 / RDNA4, or- already failed."""+def _fused_w8a8(device: Any = None) -> Optional[Callable[..., Any]]:+ """Compiled ``_w8a8_rows`` for an input on ``device`` (current card when None), or None if disabled, no inductor+ runtime, a ROCm arch other than RDNA3 / RDNA4, or already failed on that card."""if _FUSED_STATE["failed"] is not None or int8_fused_disabled():return None+ devices = _FUSED_STATE.get("devices")+ if devices is None:+ devices = _FUSED_STATE.setdefault("devices", {})+ key = device if getattr(device, "index", None) is not None else _device_key(device)+ seen = devices.get(key, _UNSEEN)fn = _FUSED_STATE["fn"]- if fn is not None:+ if seen is None and fn is not None:return fn+ if seen is not _UNSEEN and seen is not None:+ return Noneimport torchfrom .rocm_bf16 import is_rocm_torch@@ -365,16 +395,24 @@ def _fused_w8a8() -> Optional[Callable[..., Any]]:except Exception: # noqa: BLE001import logginglog = logging.getLogger(__name__)- if not runtime:+ if fn is None and not runtime:_FUSED_STATE["failed"] = "no inductor runtime"log.info("diffusion.native_quant: int8 W8A8 linear stays eager (no inductor runtime)")return None- if is_rocm_torch(torch):- refusal = _rocm_fused_w8a8_refusal(torch)+ # The current card (no device) or a HIP input's card; a CPU input has no arch to judge.+ if is_rocm_torch(torch) and (device is None or key.type == "cuda"):+ refusal = _rocm_fused_w8a8_refusal(torch, key.index if key.type == "cuda" else None)if refusal is not None:- _FUSED_STATE["failed"] = refusal- log.info("diffusion.native_quant: int8 W8A8 linear stays eager (%s)", refusal)+ devices[key] = refusal+ log.info(+ "diffusion.native_quant: int8 W8A8 linear stays eager on %s (%s)",+ _key_label(key),+ refusal,+ )return None+ devices[key] = None+ if fn is not None:+ return fn# Registered in eager, before any trace reads the handle._FUSED_STATE["row_major"] = _row_major_op()# Every key exists before the first trace: older dynamo guards on len(_FUSED_STATE), so adding@@ -388,15 +426,20 @@ def _fused_w8a8() -> Optional[Callable[..., Any]]:return fn-def _fused_w8a8_failed(exc: BaseException) -> None:+def _key_label(key: Any) -> str:+ return str(key)+++def _fused_w8a8_failed(exc: BaseException, device: Any = None) -> None:+ """The compiled linear failed on ``device``'s card: eager there from here on (other cards keep it)."""import logging- _FUSED_STATE["failed"] = repr(exc)- _FUSED_STATE["fn"] = None- _FUSED_STATE["into"] = None+ key = _device_key(device)+ _FUSED_STATE.setdefault("devices", {})[key] = repr(exc)logging.getLogger(__name__).warning(- "diffusion.native_quant: the compiled int8 W8A8 linear failed (%s); eager kernels from here on "+ "diffusion.native_quant: the compiled int8 W8A8 linear failed on %s (%s); eager kernels there from here on ""(set %s=0 to skip it)",+ _key_label(key),exc,NATIVE_INT8_FUSED_ENV,)@@ -411,7 +454,16 @@ def _autocast_on(x: Any) -> bool:def fused_w8a8_state() -> dict:- return {"calls": _FUSED_STATE.get("calls", 0), "failed": _FUSED_STATE["failed"]}+ """``failed``: the process-wide reason, else the first card's; ``devices``: each card's (None = runs it)."""+ devices = dict(_FUSED_STATE.get("devices", {}))+ failed = _FUSED_STATE["failed"]+ if failed is None:+ failed = next((why for why in devices.values() if why is not None), None)+ return {+ "calls": _FUSED_STATE.get("calls", 0),+ "failed": failed,+ "devices": {_key_label(k): why for k, why in devices.items()},+ }@lru_cache(maxsize = 1)@@ -621,7 +673,7 @@ def native_linear_class():# Detailer crops and in-flight background compiles must not compile on this thread (#15063).if eager_forced():return None- fn = _fused_w8a8()+ fn = _fused_w8a8(x.device)if fn is None:return None# Detached: guards on a view's base / Parameter shape would recompile per layout / layer.@@ -662,7 +714,7 @@ def native_linear_class():except torch.cuda.OutOfMemoryError:raiseexcept Exception as exc: # noqa: BLE001 - a compile failure falls back to the eager kernels- _fused_w8a8_failed(exc)+ _fused_w8a8_failed(exc, x.device)return None_FUSED_STATE["calls"] = _FUSED_STATE.get("calls", 0) + 1return out.reshape(*x.shape[:-1], self.out_features)diff --git a/studio/backend/core/inference/diffusion_transformer_quant.py b/studio/backend/core/inference/diffusion_transformer_quant.pyindex 913bb4745e6..b8409145a06 100644--- a/studio/backend/core/inference/diffusion_transformer_quant.py+++ b/studio/backend/core/inference/diffusion_transformer_quant.py@@ -1283,7 +1283,7 @@ def rdna_auto_w8a8_reason(target: Any, family: Optional[str]) -> Optional[str]:# Linux only: Windows ROCm has no compile tier.if not _sys.platform.startswith("linux"):return None- if int8_act_disabled() or not rocm_rdna_w8a8_ready():+ if int8_act_disabled() or not rocm_rdna_w8a8_ready(getattr(target, "ordinal", None)):return Noneif native_quant_scheme(target, TQ_INT8, family = family) != TQ_INT8:return Nonediff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex 3bce326cc99..4cd110dea76 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -13315,7 +13315,7 @@ def _stub_rdna_w8a8_host(backend, monkeypatch):calls = _stub_amd_weight_only_host(backend, monkeypatch)monkeypatch.setattr(tq, "torch_is_rocm", lambda: True)- monkeypatch.setattr(tq, "rocm_rdna_w8a8_ready", lambda: True)+ monkeypatch.setattr(tq, "rocm_rdna_w8a8_ready", lambda *_a: True)monkeypatch.delenv(nq.NATIVE_INT8_ACT_ENV, raising = False)monkeypatch.setattr(tq._sys, "platform", "linux")recorded = dmod.quantize_transformerdiff --git a/studio/backend/tests/test_diffusion_native_quant.py b/studio/backend/tests/test_diffusion_native_quant.pyindex f9031f9c353..ee730a83930 100644--- a/studio/backend/tests/test_diffusion_native_quant.py+++ b/studio/backend/tests/test_diffusion_native_quant.py@@ -188,14 +188,14 @@ def test_w8a8_default_differs_by_route(monkeypatch, env, expect_amd, expect_nviddef test_explicit_int8_keeps_its_weight_only_default_on_rdna(rocm, monkeypatch):monkeypatch.delenv(nq.NATIVE_INT8_ACT_ENV, raising = False)- monkeypatch.setattr(tq, "rocm_rdna_w8a8_ready", lambda: True)+ monkeypatch.setattr(tq, "rocm_rdna_w8a8_ready", lambda *_a: True)assert tq.native_int8_act(_target()) is Falsedef test_rdna_auto_w8a8_reason_is_per_family_with_a_kill_switch(rocm, monkeypatch):monkeypatch.delenv(nq.NATIVE_INT8_ACT_ENV, raising = False)monkeypatch.setattr(tq._sys, "platform", "linux")- monkeypatch.setattr(tq, "rocm_rdna_w8a8_ready", lambda: True)+ monkeypatch.setattr(tq, "rocm_rdna_w8a8_ready", lambda *_a: True)monkeypatch.setitem(tq._FAMILY_RDNA_AUTO_W8A8, "toy-family", "measured")assert tq.rdna_auto_w8a8_reason(_target(), "toy-family") == "measured"assert tq.rdna_auto_w8a8_reason(_target(), "Toy-Family ") == "measured"@@ -205,9 +205,9 @@ def test_rdna_auto_w8a8_reason_is_per_family_with_a_kill_switch(rocm, monkeypatcmonkeypatch.setenv(nq.NATIVE_INT8_ACT_ENV, "0")assert tq.rdna_auto_w8a8_reason(_target(), "toy-family") is Nonemonkeypatch.delenv(nq.NATIVE_INT8_ACT_ENV)- monkeypatch.setattr(tq, "rocm_rdna_w8a8_ready", lambda: False)+ monkeypatch.setattr(tq, "rocm_rdna_w8a8_ready", lambda *_a: False)assert tq.rdna_auto_w8a8_reason(_target(), "toy-family") is None- monkeypatch.setattr(tq, "rocm_rdna_w8a8_ready", lambda: True)+ monkeypatch.setattr(tq, "rocm_rdna_w8a8_ready", lambda *_a: True)monkeypatch.setitem(tq._FAMILY_SCHEME_DENY, "toy-family", frozenset({tq.TQ_INT8}))assert tq.rdna_auto_w8a8_reason(_target(), "toy-family") is None@@ -219,14 +219,14 @@ def test_rdna_auto_w8a8_ships_only_for_the_measured_families():def test_rdna_auto_w8a8_reason_is_linux_only(rocm, monkeypatch):monkeypatch.delenv(nq.NATIVE_INT8_ACT_ENV, raising = False)- monkeypatch.setattr(tq, "rocm_rdna_w8a8_ready", lambda: True)+ monkeypatch.setattr(tq, "rocm_rdna_w8a8_ready", lambda *_a: True)monkeypatch.setitem(tq._FAMILY_RDNA_AUTO_W8A8, "toy-family", "measured")monkeypatch.setattr(tq._sys, "platform", "win32")assert tq.rdna_auto_w8a8_reason(_target(), "toy-family") is Nonedef test_rdna_auto_w8a8_reason_is_rocm_only(nvidia, monkeypatch):- monkeypatch.setattr(tq, "rocm_rdna_w8a8_ready", lambda: True)+ monkeypatch.setattr(tq, "rocm_rdna_w8a8_ready", lambda *_a: True)monkeypatch.setitem(tq._FAMILY_RDNA_AUTO_W8A8, "toy-family", "measured")assert tq.rdna_auto_w8a8_reason(_target(), "toy-family") is Nonediff --git a/studio/backend/tests/test_diffusion_native_quant_fused.py b/studio/backend/tests/test_diffusion_native_quant_fused.pyindex aef8a081ee5..00b97843dbd 100644--- a/studio/backend/tests/test_diffusion_native_quant_fused.py+++ b/studio/backend/tests/test_diffusion_native_quant_fused.py@@ -103,6 +103,68 @@ def test_other_rocm_archs_stay_eager(monkeypatch, arch):assert nq.fused_w8a8_state()["failed"] == f"ROCm {arch or 'unknown arch'}"+def _two_cards(monkeypatch, archs):+ import core.inference.diffusion_speed as sp+ import core.inference.rocm_bf16 as rb++ queried = []++ def arch(_torch, ordinal):+ queried.append(ordinal)+ return archs[ordinal]++ monkeypatch.setattr(sp, "torch_compile_runtime_available", lambda: True)+ monkeypatch.setattr(torch.version, "hip", "7.13", raising = False)+ monkeypatch.setattr(rb, "_device_gfx_arch", arch)+ return queried++[email protected]("order", [(0, 1), (1, 0)])+def test_each_rocm_card_is_judged_by_its_own_arch(monkeypatch, order):+ # RDNA3 card 0 and RDNA2 card 1 in one process: whichever runs first, each keeps its own answer.+ queried = _two_cards(monkeypatch, {0: "gfx1100", 1: "gfx1030"})+ got = {i: nq._fused_w8a8(torch.device("cuda", i)) for i in order}+ assert got[0] is not None and got[1] is None+ assert sorted(queried) == [0, 1]+ assert nq.fused_w8a8_state()["devices"] == {"cuda:0": None, "cuda:1": "ROCm gfx1030"}+ assert nq._fused_w8a8(torch.device("cuda", 0)) is got[0]+ assert nq._fused_w8a8(torch.device("cuda", 1)) is None+ assert sorted(queried) == [0, 1]++[email protected]("order", [(0, 1), (1, 0)])+def test_switching_the_current_card_rechecks_its_arch(monkeypatch, order):+ # Callers that scope each load to its card (torch.cuda.set_device) and pass no device.+ _two_cards(monkeypatch, {0: "gfx1100", 1: "gfx1030"})+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ got = {}+ for i in order:+ monkeypatch.setattr(torch.cuda, "current_device", lambda i = i: i)+ got[i] = (nq._fused_w8a8(), nq.rocm_rdna_w8a8_ready())+ assert got[0][0] is not None and got[0][1] is True+ assert got[1] == (None, False)+++def test_rdna_ready_is_per_card(monkeypatch):+ _two_cards(monkeypatch, {0: "gfx942", 1: "gfx1151"})+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ assert nq._fused_w8a8(torch.device("cuda", 0)) is None+ assert nq.rocm_rdna_w8a8_ready(1) is True+ assert nq.rocm_rdna_w8a8_ready(0) is False+++def test_a_compile_failure_on_one_card_keeps_the_other(monkeypatch):+ _two_cards(monkeypatch, {0: "gfx1100", 1: "gfx1151"})+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ fn = nq._fused_w8a8(torch.device("cuda", 0))+ assert fn is not None and nq._fused_w8a8(torch.device("cuda", 1)) is fn+ nq._fused_w8a8_failed(RuntimeError("codegen"), torch.device("cuda", 1))+ assert nq._fused_w8a8(torch.device("cuda", 1)) is None+ assert nq._fused_w8a8(torch.device("cuda", 0)) is fn+ assert nq.rocm_rdna_w8a8_ready(1) is False and nq.rocm_rdna_w8a8_ready(0) is True+ assert "codegen" in nq.fused_w8a8_state()["failed"]++def test_kill_switch_wins_on_rdna(monkeypatch):import core.inference.diffusion_speed as spimport core.inference.rocm_bf16 as rb@@ -125,9 +187,9 @@ def test_cpu_input_never_takes_the_compiled_linear(monkeypatch):def test_too_few_rows_or_switched_off_returns_none(monkeypatch):layer = _layer()- monkeypatch.setattr(nq, "_fused_w8a8", lambda: pytest.fail("no compile for a 16-row input"))+ monkeypatch.setattr(nq, "_fused_w8a8", lambda *_a: pytest.fail("no compile for a 16-row input"))assert layer._forward_fused(torch.randn(16, 512, dtype = torch.bfloat16)) is None- monkeypatch.setattr(nq, "_fused_w8a8", lambda: None)+ monkeypatch.setattr(nq, "_fused_w8a8", lambda *_a: None)assert layer._forward_fused(torch.randn(64, 512, dtype = torch.bfloat16)) is None@@ -138,10 +200,11 @@ def test_a_failing_compile_falls_back_once_and_stays_eager(monkeypatch):raise RuntimeError("inductor exploded")nq._FUSED_STATE["fn"] = boom- assert layer._forward_fused(torch.randn(64, 512, dtype = torch.bfloat16)) is None+ x = torch.randn(64, 512, dtype = torch.bfloat16)+ assert layer._forward_fused(x) is Nonestate = nq.fused_w8a8_state()assert "inductor exploded" in state["failed"]- assert nq._fused_w8a8() is None+ assert nq._fused_w8a8(x.device) is Nonedef test_an_oom_propagates_and_keeps_the_compiled_linear(monkeypatch):@@ -218,7 +281,7 @@ def test_fused_chunk_never_outgrows_the_eager_chunk(in_f, out_f):def test_eager_forced_pass_never_enters_the_compiled_linear(monkeypatch):layer = _layer()monkeypatch.setattr(- nq, "_fused_w8a8", lambda: pytest.fail("compiled linear inside a force-eager pass")+ nq, "_fused_w8a8", lambda *_a: pytest.fail("compiled linear inside a force-eager pass"))x = torch.randn(64, 512, dtype = torch.bfloat16)with bg.auxiliary_pass():@@ -418,3 +481,38 @@ def test_factory_creates_every_state_key_before_the_first_trace(monkeypatch):monkeypatch.setattr(rb, "is_rocm_torch", lambda _torch: False)assert nq._fused_w8a8() is not Noneassert {"fn", "into", "row_major", "calls", "failed"} <= set(nq._FUSED_STATE)+++ not has_real_cuda() or torch.cuda.device_count() < 2, reason = "needs two CUDA / HIP devices"+)+def test_each_real_card_runs_the_compiled_linear_bit_identical_to_eager(monkeypatch):+ _require_the_compiled_linear()+ torch._dynamo.reset()+ with torch.no_grad():+ for i in (1, 0):+ dev = torch.device("cuda", i)+ torch.manual_seed(0)+ lin = torch.nn.Linear(512, 1536).to(dev, torch.bfloat16)+ layer = nq.native_linear_class()(lin, "int8", act_int8 = True, rot_group = 256)+ x = torch.randn(4096, 512, device = dev, dtype = torch.bfloat16) * 3+ monkeypatch.setenv(nq.NATIVE_INT8_FUSED_ENV, "0")+ ref = layer(x)+ monkeypatch.delenv(nq.NATIVE_INT8_FUSED_ENV)+ calls = nq.fused_w8a8_state()["calls"]+ got = layer(x)+ assert nq.fused_w8a8_state()["calls"] == calls + 1+ assert got.device == dev and torch.equal(got, ref)+ assert nq.fused_w8a8_state()["devices"] == {"cuda:0": None, "cuda:1": None}+++def test_a_cpu_input_on_a_rocm_torch_is_not_judged_by_a_card_arch(monkeypatch):+ # ROCm torch, no visible card (HIP masked): a CPU input has no gfx arch to refuse on.+ import core.inference.rocm_bf16 as rb++ monkeypatch.setattr(torch.version, "hip", "7.13", raising = False)+ monkeypatch.setattr(+ rb, "_device_gfx_arch", lambda _torch, _ordinal: pytest.fail("arch read for a CPU input")+ )+ nq._FUSED_STATE["fn"] = fn = lambda *_a: None+ assert nq._fused_w8a8(torch.device("cpu")) is fn