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 diffusion: launch the VAE and MOSS Triton kernels on the input's own card (#17099)

Daniel Hanf4668b4c43e4
diff --git a/studio/backend/core/inference/diffusion_moss_fused.py b/studio/backend/core/inference/diffusion_moss_fused.py
index 4f450114e05..434739a0a05 100644
--- a/studio/backend/core/inference/diffusion_moss_fused.py
+++ b/studio/backend/core/inference/diffusion_moss_fused.py
@@ -249,35 +249,41 @@ def _launch_qk_rope(q, k, v, qw, kw, cos, sin, heads):
ok = torch_empty_like(oq)
ov = torch_empty_like(oq)
grid = (batch * seq, triton.cdiv(heads, _HEADS_PER_PROGRAM))
- _qk_rope_kernel()[grid](
- q,
- k,
- v,
- qw,
- kw,
- cos,
- sin,
- oq,
- ok,
- ov,
- seq,
- heads,
- q.stride(0),
- q.stride(1),
- k.stride(0),
- k.stride(1),
- v.stride(0),
- v.stride(1),
- cos.stride(1),
- EPS = 1e-6,
- D = dim,
- HB = _HEADS_PER_PROGRAM,
- # ptxas otherwise FMA-fuses the rounded products into the sum on sm_100
- enable_fp_fusion = False,
- )
+ with _on_card(q):
+ _qk_rope_kernel()[grid](
+ q,
+ k,
+ v,
+ qw,
+ kw,
+ cos,
+ sin,
+ oq,
+ ok,
+ ov,
+ seq,
+ heads,
+ q.stride(0),
+ q.stride(1),
+ k.stride(0),
+ k.stride(1),
+ v.stride(0),
+ v.stride(1),
+ cos.stride(1),
+ EPS = 1e-6,
+ D = dim,
+ HB = _HEADS_PER_PROGRAM,
+ # ptxas otherwise FMA-fuses the rounded products into the sum on sm_100
+ enable_fp_fusion = False,
+ )
return oq, ok, ov
+def _on_card(t):
+ from .diffusion_vae_fused import _on_card as on_card
+ return on_card(t)
+
+
def torch_empty_like(t):
import torch
return torch.empty_like(t)
diff --git a/studio/backend/core/inference/diffusion_vae_fused.py b/studio/backend/core/inference/diffusion_vae_fused.py
index 27fded25219..de80bd0e0ec 100644
--- a/studio/backend/core/inference/diffusion_vae_fused.py
+++ b/studio/backend/core/inference/diffusion_vae_fused.py
@@ -6,6 +6,7 @@ never classes; falls back to stock on new exception; UNSLOTH_VAE_FUSED=0 off"""
from __future__ import annotations
+import contextlib
import os
import sys
import threading
@@ -16,6 +17,7 @@ from typing import Any, Optional
from .rocm_bf16 import is_rocm_torch
VAE_FUSED_ENV = "UNSLOTH_VAE_FUSED"
+DEVICE_SCOPE_ENV = "UNSLOTH_DIFFUSION_TRITON_DEVICE_SCOPE"
_FALSE = ("0", "false", "no", "off")
_MIN_TRITON = (3, 3)
_MAX_C = 4096
@@ -515,6 +517,23 @@ def _torch():
return torch
+_NO_SCOPE = contextlib.nullcontext()
+
+
+def _on_card(t: Any) -> Any:
+ """Triton launches on the current device: a tensor on another card fails the launch."""
+ torch = _torch()
+ if not t.is_cuda or torch.compiler.is_compiling():
+ return _NO_SCOPE
+ index = t.device.index
+ # same card (every single-card render): no device switch, ~1 us instead of ~4 us per launch
+ if index is None or index == torch.cuda.current_device():
+ return _NO_SCOPE
+ if os.environ.get(DEVICE_SCOPE_ENV, "").strip().lower() in _FALSE:
+ return _NO_SCOPE
+ return torch.cuda.device(index)
+
+
def _stock_in(t: Any) -> Any:
"""A kernel input as the kernel may read it."""
cls = globals().get("_FusedActCls")
@@ -562,24 +581,27 @@ def group_norm_act(
rows = b * t
pmean, pm2 = torch.empty((2, rows * n_chunks * g), dtype = torch.float32, device = x.device)
pn = torch.empty(rows * n_chunks, dtype = torch.float32, device = x.device)
- k.gn_partials[(n_chunks, rows)](
- x5, ib, pn, pmean, pm2, t, hw, w, n_chunks, sb, sc, st, sh, sw,
- C = c, G = g, CPG = cpg, BLOCK_P = block_p, HAS_BIAS = in_bias is not None, num_warps = 4,
- ) # fmt: skip
+ with _on_card(x5):
+ k.gn_partials[(n_chunks, rows)](
+ x5, ib, pn, pmean, pm2, t, hw, w, n_chunks, sb, sc, st, sh, sw,
+ C = c, G = g, CPG = cpg, BLOCK_P = block_p, HAS_BIAS = in_bias is not None, num_warps = 4,
+ ) # fmt: skip
mean = torch.empty(rows * g, dtype = torch.float32, device = x.device)
rstd = torch.empty(rows * g, dtype = torch.float32, device = x.device)
- k.gn_combine[(rows * g,)](
- pn, pmean, pm2, mean, rstd, n_chunks, g, float(norm.eps), BLOCK = 1024, num_warps = 4
- )
+ with _on_card(pn):
+ k.gn_combine[(rows * g,)](
+ pn, pmean, pm2, mean, rstd, n_chunks, g, float(norm.eps), BLOCK = 1024, num_warps = 4
+ )
out = torch.empty((b, t, h, w, c), dtype = x.dtype, device = x.device)
block_c = min(128, _next_pow2(c))
block_p2 = max(1, 4096 // block_c)
grid = ((hw + block_p2 - 1) // block_p2, rows, (c + block_c - 1) // block_c)
- k.gn_apply[grid](
- x5, out, mean, rstd, norm.weight, norm.bias, ib, c, t, hw, w, g, sb, sc, st, sh, sw,
- CPG = cpg, ACT = bool(act), HAS_IN_BIAS = in_bias is not None, BLOCK_P = block_p2, BLOCK_C = block_c,
- num_warps = 4,
- ) # fmt: skip
+ with _on_card(x5):
+ k.gn_apply[grid](
+ x5, out, mean, rstd, norm.weight, norm.bias, ib, c, t, hw, w, g, sb, sc, st, sh, sw,
+ CPG = cpg, ACT = bool(act), HAS_IN_BIAS = in_bias is not None, BLOCK_P = block_p2, BLOCK_C = block_c,
+ num_warps = 4,
+ ) # fmt: skip
if on_kernel is not None and not torch.compiler.is_compiling():
on_kernel() # read by the structural calibration: only a completed Triton launch counts
out = out.permute(0, 4, 1, 2, 3) # B, C, T', H', W'
@@ -704,14 +726,15 @@ def rms_norm_act(
block_c = _next_pow2(c)
block_p = max(1, min(128, 8192 // block_c))
grid = ((ho * wo + block_p - 1) // block_p, b * to)
- k.rms_act[grid](
- x, out, gamma, bias, in_bias if in_bias is not None else x, cache_t,
- c, t, h, w, ho, wo, ph, pw, to, front, n_cache, scale, eps,
- *x.stride(), *cache_t.stride(),
- NORM = norm is not None, ACT = bool(act), HAS_BIAS = has_bias, HAS_IN_BIAS = in_bias is not None,
- REPLICATE = replicate_pad is not None, MEAN_SQ = mean_sq, BLOCK_P = block_p, BLOCK_C = block_c,
- num_warps = 4 if block_c * block_p <= 4096 else 8,
- ) # fmt: skip
+ with _on_card(x):
+ k.rms_act[grid](
+ x, out, gamma, bias, in_bias if in_bias is not None else x, cache_t,
+ c, t, h, w, ho, wo, ph, pw, to, front, n_cache, scale, eps,
+ *x.stride(), *cache_t.stride(),
+ NORM = norm is not None, ACT = bool(act), HAS_BIAS = has_bias, HAS_IN_BIAS = in_bias is not None,
+ REPLICATE = replicate_pad is not None, MEAN_SQ = mean_sq, BLOCK_P = block_p, BLOCK_C = block_c,
+ num_warps = 4 if block_c * block_p <= 4096 else 8,
+ ) # fmt: skip
return out.permute(0, 4, 1, 2, 3)
@@ -822,7 +845,8 @@ def single_head_attention(q: Any, k: Any, v: Any) -> Any:
scores = torch.bmm(q[:, i : i + rows], kt, out_dtype = torch.float32)
r = scores.shape[1]
probs = torch.empty((b, r, s_pad), dtype = v.dtype, device = v.device)
- kern.softmax_rows[(b * r,)](scores, probs, s_len, s_pad, scale, BLOCK = 2048, num_warps = 8)
+ with _on_card(scores):
+ kern.softmax_rows[(b * r,)](scores, probs, s_len, s_pad, scale, BLOCK = 2048, num_warps = 8)
del scores
torch.bmm(probs, v, out = out[:, i : i + rows])
return out
@@ -974,12 +998,13 @@ def add_bias_residual(
block_c = min(128, _next_pow2(c))
block_p = max(1, 4096 // block_c)
grid = ((pixels + block_p - 1) // block_p, (c + block_c - 1) // block_c)
- k.bias_residual[grid](
- out, out_bias if out_bias is not None else out, res, res_bias if res_bias is not None else res,
- pixels, c, t, h * w, w, *r5.stride(), 1.0 / float(scale),
- HAS_OB = out_bias is not None, HAS_RB = res_bias is not None, SCALE = float(scale) != 1.0,
- BLOCK_P = block_p, BLOCK_C = block_c, num_warps = 4,
- ) # fmt: skip
+ with _on_card(out):
+ k.bias_residual[grid](
+ out, out_bias if out_bias is not None else out, res, res_bias if res_bias is not None else res,
+ pixels, c, t, h * w, w, *r5.stride(), 1.0 / float(scale),
+ HAS_OB = out_bias is not None, HAS_RB = res_bias is not None, SCALE = float(scale) != 1.0,
+ BLOCK_P = block_p, BLOCK_C = block_c, num_warps = 4,
+ ) # fmt: skip
return out
@@ -1272,10 +1297,11 @@ def dup_up_add(out: Any, x: Any, dup: Any, first_chunk: bool) -> Any:
block_c = min(128, _next_pow2(c))
block_p = max(1, 4096 // block_c)
grid = ((h_o * w_o + block_p - 1) // block_p, b * t_o, (c + block_c - 1) // block_c)
- k.dup_up_add[grid](
- out, x, c, t_o, h_o, w_o, t_off, rep, *out.stride(), *x.stride(),
- FT = ft, FS = fs, BLOCK_P = block_p, BLOCK_C = block_c, num_warps = 4,
- ) # fmt: skip
+ with _on_card(out):
+ k.dup_up_add[grid](
+ out, x, c, t_o, h_o, w_o, t_off, rep, *out.stride(), *x.stride(),
+ FT = ft, FS = fs, BLOCK_P = block_p, BLOCK_C = block_c, num_warps = 4,
+ ) # fmt: skip
return out
@@ -1290,19 +1316,20 @@ def up_nearest2x(x: Any, interleave: bool) -> Any:
block_c = min(128, _next_pow2(c))
block_p = max(1, 4096 // block_c)
grid = ((4 * h * w + block_p - 1) // block_p, b * t_o, (c + block_c - 1) // block_c)
- k.up_nearest2x[grid](
- x,
- out,
- c,
- t_o,
- h,
- w,
- *x.stride(),
- INTERLEAVE = interleave,
- BLOCK_P = block_p,
- BLOCK_C = block_c,
- num_warps = 4,
- )
+ with _on_card(x):
+ k.up_nearest2x[grid](
+ x,
+ out,
+ c,
+ t_o,
+ h,
+ w,
+ *x.stride(),
+ INTERLEAVE = interleave,
+ BLOCK_P = block_p,
+ BLOCK_C = block_c,
+ num_warps = 4,
+ )
return out.permute(0, 3, 1, 2), t_o
@@ -1798,10 +1825,11 @@ def hv_upsample(up: Any, x: Any) -> Any:
block_p = max(1, 4096 // block_c)
grid = ((4 * hh * ww + block_p - 1) // block_p, b * fo, (c + block_c - 1) // block_c)
bias = conv.conv.bias
- k.dcae_up_add[grid](
- h, bias if bias is not None else h, x, out, c, cin, f, hh, ww, fo, rep, *h.stride(), *x.stride(),
- TEMPORAL = temporal, HAS_HB = bias is not None, BLOCK_P = block_p, BLOCK_C = block_c, num_warps = 4,
- ) # fmt: skip
+ with _on_card(h):
+ k.dcae_up_add[grid](
+ h, bias if bias is not None else h, x, out, c, cin, f, hh, ww, fo, rep, *h.stride(), *x.stride(),
+ TEMPORAL = temporal, HAS_HB = bias is not None, BLOCK_P = block_p, BLOCK_C = block_c, num_warps = 4,
+ ) # fmt: skip
return out.permute(0, 4, 1, 2, 3)
diff --git a/studio/backend/tests/test_diffusion_triton_device_scope.py b/studio/backend/tests/test_diffusion_triton_device_scope.py
new file mode 100644
index 00000000000..4a99043e69b
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_triton_device_scope.py
@@ -0,0 +1,92 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Every Triton launch in the VAE kernels and the MOSS QK-norm RoPE runs under the input's own card: Triton launches on
+the CURRENT device, so a tensor on another card fails the launch and the fused path drops to stock. CPU only."""
+
+from __future__ import annotations
+
+import ast
+import contextlib
+import inspect
+import types
+
+import pytest
+
+torch = pytest.importorskip("torch")
+
+from core.inference import diffusion_moss_fused as M # noqa: E402
+from core.inference import diffusion_vae_fused as V # noqa: E402
+
+
+def _launches(module) -> list:
+ """(line, inside a ``with _on_card(...)``) for every ``kernel[grid](...)`` call."""
+ tree = ast.parse(inspect.getsource(module))
+ parents = {}
+ for node in ast.walk(tree):
+ for child in ast.iter_child_nodes(node):
+ parents[child] = node
+ out = []
+ for node in ast.walk(tree):
+ # kernel[grid](...): a grid subscript, not an index like ``to_out[0](o)``
+ if not (
+ isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Subscript)
+ and not isinstance(node.func.slice, ast.Constant)
+ ):
+ continue
+ scoped, p = False, parents.get(node)
+ while p is not None and not isinstance(p, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ if isinstance(p, ast.With) and any(
+ isinstance(i.context_expr, ast.Call)
+ and getattr(i.context_expr.func, "id", None) == "_on_card"
+ for i in p.items
+ ):
+ scoped = True
+ p = parents.get(p)
+ out.append((node.lineno, scoped))
+ return out
+
+
[email protected]("module, count", [(V, 9), (M, 1)])
+def test_every_launch_is_scoped_to_its_card(module, count):
+ launches = _launches(module)
+ assert len(launches) == count
+ assert all(scoped for _line, scoped in launches), launches
+
+
+def _cuda_like(index: int):
+ return types.SimpleNamespace(is_cuda = True, device = torch.device("cuda", index))
+
+
[email protected](autouse = True)
+def _thread_on_card_0(monkeypatch):
+ monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)
+
+
+def test_scope_is_the_tensor_card(monkeypatch):
+ monkeypatch.delenv(V.DEVICE_SCOPE_ENV, raising = False)
+ scope = V._on_card(_cuda_like(1))
+ assert isinstance(scope, torch.cuda.device) and scope.idx == 1
+ scope = M._on_card(_cuda_like(3))
+ assert isinstance(scope, torch.cuda.device) and scope.idx == 3
+
+
+def test_the_current_card_needs_no_switch(monkeypatch):
+ monkeypatch.delenv(V.DEVICE_SCOPE_ENV, raising = False)
+ assert isinstance(V._on_card(_cuda_like(0)), contextlib.nullcontext)
+
+
[email protected]("off", ["0", "off", "false"])
+def test_kill_switch_and_cpu_launch_unscoped(monkeypatch, off):
+ monkeypatch.setenv(V.DEVICE_SCOPE_ENV, off)
+ assert isinstance(V._on_card(_cuda_like(1)), contextlib.nullcontext)
+ monkeypatch.delenv(V.DEVICE_SCOPE_ENV)
+ assert isinstance(V._on_card(torch.zeros(1)), contextlib.nullcontext)
+
+
+def test_traced_launch_left_to_inductor(monkeypatch):
+ """Under torch.compile Inductor guards the device itself; a torch.cuda.device here would break the graph."""
+ monkeypatch.delenv(V.DEVICE_SCOPE_ENV, raising = False)
+ monkeypatch.setattr(torch.compiler, "is_compiling", lambda: True)
+ assert isinstance(V._on_card(_cuda_like(1)), contextlib.nullcontext)