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: run FLUX.2 RoPE as one fused kernel on fp16 GPUs (klein step 5% faster on T4, bit-identical) (#12503)
Daniel Han864ab9b55cb5
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 668d1f29c69..a2c997918f0 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -1864,11 +1864,13 @@ def _auto_quant_eager_reason(def _uninstall_fused_dit_patches() -> None:"""Restore the process-global fused DiT patches so the next load honours its own kill switches."""try:+ from .diffusion_flux2_rope import uninstall as uninstall_flux2_ropefrom .diffusion_qwenimage_rope import uninstall as uninstall_qwen_real_ropefrom .diffusion_zimage_fused import uninstall as uninstall_zimage_fuseduninstall_qwen_real_rope()uninstall_zimage_fused()+ uninstall_flux2_rope()except Exception: # noqa: BLE001 - teardown is best effortpass@@ -6806,6 +6808,9 @@ class DiffusionBackend:from .diffusion_qwenimage21 import install_for_pipe as install_q21_fast_stepinstall_q21_fast_step(pipe, logger)+ from .diffusion_flux2_rope import install_for_pipe as install_flux2_rope++ install_flux2_rope(pipe, dtype, device, logger)self._raise_if_load_cancelled(_load_token)# Pre-warmed torch.compile cache: a per-fingerprint inductor dir plus a bundle loaded before thediff --git a/studio/backend/core/inference/diffusion_flux2_rope.py b/studio/backend/core/inference/diffusion_flux2_rope.pynew file mode 100644index 00000000000..8f5f73bd904--- /dev/null+++ b/studio/backend/core/inference/diffusion_flux2_rope.py@@ -0,0 +1,257 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""FLUX.2 RoPE as one Triton kernel on fp16 GPUs (T4 and other pre-Ampere cards).++Same fp32 arithmetic and rounding order as stock ``apply_rotary_emb`` (FMA contraction off), so the output is+bit-identical. Patches only ``transformer_flux2``'s global for fp16 CUDA loads; any other call falls through to stock.+Kill switch: ``UNSLOTH_DIFFUSION_FLUX2_FUSED_ROPE=0``.+"""++from __future__ import annotations++import functools+import os+import threading+from typing import Any, Callable, Optional++FLUX2_FUSED_ROPE_ENV = "UNSLOTH_DIFFUSION_FLUX2_FUSED_ROPE"+_MODULE = "diffusers.models.transformers.transformer_flux2"+_ATTR = "apply_rotary_emb"+_LOCK = threading.Lock()+_STOCK: dict = {}+# Survives uninstall so a forward that looked up the patch just before teardown still reaches stock.+_ORIGINAL: list = [None]+++def disabled() -> bool:+ return (os.environ.get(FLUX2_FUSED_ROPE_ENV) or "").strip().lower() in (+ "0",+ "off",+ "false",+ "no",+ )+++def wanted(dtype: Any, device: Any = "cuda") -> bool:+ if disabled():+ return False+ try:+ import torch+ except Exception: # noqa: BLE001+ return False+ if dtype is not torch.float16 or not str(device).startswith("cuda"):+ return False+ if getattr(torch.version, "hip", None):+ return False+ return _kernel() is not None++[email protected]_cache(maxsize = 1)+def _kernel() -> Optional[Callable]:+ """None when Triton is unavailable."""+ try:+ import triton+ import triton.language as tl+ except Exception: # noqa: BLE001+ return None++ @triton.jit+ def _rope_fwd(+ X,+ COS,+ SIN,+ OUT,+ S,+ H,+ sxb,+ sxs,+ sxh,+ scs,+ sss,+ sob,+ sos,+ soh,+ HALF: tl.constexpr,+ BLOCK: tl.constexpr,+ ):+ row = tl.program_id(0)+ b = row // S+ s = row - b * S+ idx = tl.arange(0, BLOCK)+ mask = idx < H * HALF+ h = idx // HALF+ i = idx - h * HALF+ xo = X + b * sxb + s * sxs + h * sxh + 2 * i+ xe = tl.load(xo, mask = mask, other = 0.0).to(tl.float32)+ xd = tl.load(xo + 1, mask = mask, other = 0.0).to(tl.float32)+ ce = tl.load(COS + s * scs + 2 * i, mask = mask, other = 0.0).to(tl.float32)+ cd = tl.load(COS + s * scs + 2 * i + 1, mask = mask, other = 0.0).to(tl.float32)+ se = tl.load(SIN + s * sss + 2 * i, mask = mask, other = 0.0).to(tl.float32)+ sd = tl.load(SIN + s * sss + 2 * i + 1, mask = mask, other = 0.0).to(tl.float32)+ # stock: x.float() * cos + stack([-x_odd, x_even]).float() * sin, each product rounded on its own+ oe = xe * ce + (-xd) * se+ od = xd * cd + xe * sd+ oo = OUT + b * sob + s * sos + h * soh + 2 * i+ tl.store(oo, oe.to(OUT.dtype.element_ty), mask = mask)+ tl.store(oo + 1, od.to(OUT.dtype.element_ty), mask = mask)++ def launch(x: Any, cos: Any, sin: Any) -> Any:+ import torch++ B, S, H, D = x.shape+ # Same layout stock returns: a dense input keeps its strides, anything else comes back contiguous.+ out = torch.empty_like(x)+ if out.stride(3) != 1:+ out = torch.empty((B, S, H, D), dtype = x.dtype, device = x.device)+ half = D // 2+ block = triton.next_power_of_2(H * half)+ with torch.cuda.device(x.device):+ _rope_fwd[(B * S,)](+ x,+ cos,+ sin,+ out,+ S,+ H,+ x.stride(0),+ x.stride(1),+ x.stride(2),+ cos.stride(0),+ sin.stride(0),+ out.stride(0),+ out.stride(1),+ out.stride(2),+ HALF = half,+ BLOCK = block,+ num_warps = 4 if block <= 2048 else 8,+ enable_fp_fusion = False,+ )+ return out++ return launch+++def _eligible(+ x: Any, freqs_cis: Any, use_real: bool, use_real_unbind_dim: int, sequence_dim: int+) -> bool:+ import torch++ if not use_real or use_real_unbind_dim != -1 or sequence_dim != 1:+ return False+ if not isinstance(freqs_cis, (tuple, list)) or len(freqs_cis) != 2:+ return False+ if not torch.is_tensor(x) or x.dtype is not torch.float16 or not x.is_cuda or x.dim() != 4:+ return False+ if x.requires_grad and torch.is_grad_enabled():+ return False+ B, S, H, D = x.shape+ if D % 2 or x.stride(3) != 1 or x.numel() == 0:+ return False+ # Kernel offsets are int32.+ if x.storage_offset() + sum((n - 1) * st for n, st in zip(x.shape, x.stride())) >= 2**31 - 1:+ return False+ cos, sin = freqs_cis+ for f in (cos, sin):+ if not torch.is_tensor(f) or f.dim() != 2 or tuple(f.shape) != (S, D):+ return False+ if f.device != x.device or f.stride(1) != 1:+ return False+ if f.dtype not in (torch.float32, torch.float16):+ return False+ return True+++def _fused_apply_rotary_emb(+ x,+ freqs_cis,+ use_real: bool = True,+ use_real_unbind_dim: int = -1,+ sequence_dim: int = 2,+):+ import torch++ stock = _STOCK.get(_ATTR) or _ORIGINAL[0]+ # Checked before _kernel(): Dynamo graph-breaks on Triton's import path, so a compiled block stays whole on stock.+ if torch.compiler.is_compiling():+ return stock(+ x,+ freqs_cis,+ use_real = use_real,+ use_real_unbind_dim = use_real_unbind_dim,+ sequence_dim = sequence_dim,+ )+ launch = _kernel()+ if launch is not None and _eligible(x, freqs_cis, use_real, use_real_unbind_dim, sequence_dim):+ try:+ return launch(x, freqs_cis[0], freqs_cis[1])+ except Exception: # noqa: BLE001 -- never fail a render over the fast path+ pass+ return stock(+ x,+ freqs_cis,+ use_real = use_real,+ use_real_unbind_dim = use_real_unbind_dim,+ sequence_dim = sequence_dim,+ )+++def install(+ dtype: Any,+ device: Any = "cuda",+ logger: Any = None,+) -> bool:+ """Idempotent; False (nothing patched) when not wanted or diffusers' symbol is not the expected one."""+ if not wanted(dtype, device):+ uninstall()+ return False+ import importlib++ with _LOCK:+ if _ATTR in _STOCK:+ return True+ try:+ mod = importlib.import_module(_MODULE)+ except Exception: # noqa: BLE001+ return False+ stock = getattr(mod, _ATTR, None)+ if stock is None or getattr(stock, "__name__", "") != "apply_rotary_emb":+ return False+ _STOCK[_ATTR] = stock+ _ORIGINAL[0] = stock+ setattr(mod, _ATTR, _fused_apply_rotary_emb)+ if logger is not None:+ try:+ logger.info("diffusion.flux2_rope: fused fp16 RoPE kernel installed")+ except Exception: # noqa: BLE001+ pass+ return True+++def install_for_pipe(+ pipe: Any,+ dtype: Any,+ device: Any = "cuda",+ logger: Any = None,+) -> bool:+ """Install for an fp16 FLUX.2 denoiser, otherwise restore stock."""+ transformer = getattr(pipe, "transformer", None)+ if transformer is None or type(transformer).__module__ != _MODULE:+ uninstall()+ return False+ return install(dtype, device, logger)+++def uninstall() -> None:+ import sys+ with _LOCK:+ stock = _STOCK.pop(_ATTR, None)+ if stock is None:+ return+ mod = sys.modules.get(_MODULE)+ if mod is not None and getattr(mod, _ATTR, None) is _fused_apply_rotary_emb:+ setattr(mod, _ATTR, stock)+++def is_installed() -> bool:+ return _ATTR in _STOCKdiff --git a/studio/backend/tests/test_diffusion_flux2_rope.py b/studio/backend/tests/test_diffusion_flux2_rope.pynew file mode 100644index 00000000000..c2f006e1587--- /dev/null+++ b/studio/backend/tests/test_diffusion_flux2_rope.py@@ -0,0 +1,221 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Tests for ``diffusion_flux2_rope.py``: the fused FLUX.2 RoPE engages only for an fp16 FLUX.2 load (bf16 GPUs keep the+stock function), honours its kill switch, restores cleanly, and is bit-identical to stock (CUDA tests)."""++from __future__ import annotations++import ast+from pathlib import Path++import pytest++from core.inference import diffusion_flux2_rope as fr++torch = pytest.importorskip("torch")+fmod = pytest.importorskip("diffusers.models.transformers.transformer_flux2")+from diffusers.models.embeddings import apply_rotary_emb as stock_rope # noqa: E402++needs_cuda = pytest.mark.skipif(+ not torch.cuda.is_available()+ or bool(getattr(torch.version, "hip", None))+ or fr._kernel() is None,+ reason = "needs CUDA (not ROCm) and Triton",+)+++class _Flux2Like:+ """A pipe whose transformer reports the FLUX.2 module, without building the model."""++ def __init__(self, module = fr._MODULE):+ self.transformer = type("Flux2Transformer2DModel", (), {"__module__": module})()++[email protected](autouse = True)+def _restore(monkeypatch):+ monkeypatch.delenv(fr.FLUX2_FUSED_ROPE_ENV, raising = False)+ fr.uninstall()+ yield+ fr.uninstall()+ assert fmod.apply_rotary_emb is stock_rope+++def fake_kernel(monkeypatch):+ """Gate tests run without a GPU: pretend Triton built the kernel on a CUDA (non-ROCm) torch."""+ monkeypatch.setattr(fr, "_kernel", lambda: (lambda x, cos, sin: None))+ monkeypatch.setattr(torch.version, "hip", None, raising = False)+++def test_stock_symbol_is_the_one_flux2_calls():+ assert fmod.apply_rotary_emb is stock_rope+ src = Path(fmod.__file__).read_text(encoding = "utf-8")+ assert "apply_rotary_emb(query, image_rotary_emb, sequence_dim=1)" in src+++def test_fp16_flux2_load_installs(fake_kernel):+ assert fr.install_for_pipe(_Flux2Like(), torch.float16, "cuda")+ assert fr.is_installed()+ assert fmod.apply_rotary_emb is fr._fused_apply_rotary_emb++[email protected]("dtype", ["bfloat16", "float32"])+def test_bf16_and_fp32_loads_keep_stock(fake_kernel, dtype):+ assert not fr.install_for_pipe(_Flux2Like(), getattr(torch, dtype), "cuda")+ assert not fr.is_installed()+ assert fmod.apply_rotary_emb is stock_rope+++def test_fp16_load_after_bf16_load_and_back(fake_kernel):+ assert fr.install_for_pipe(_Flux2Like(), torch.float16, "cuda")+ assert not fr.install_for_pipe(_Flux2Like(), torch.bfloat16, "cuda")+ assert fmod.apply_rotary_emb is stock_rope++[email protected]("device", ["cpu", "mps", "xpu"])+def test_non_cuda_devices_keep_stock(fake_kernel, device):+ assert not fr.install_for_pipe(_Flux2Like(), torch.float16, device)+ assert fmod.apply_rotary_emb is stock_rope+++def test_rocm_keeps_stock(fake_kernel, monkeypatch):+ monkeypatch.setattr(torch.version, "hip", "6.4", raising = False)+ assert not fr.install_for_pipe(_Flux2Like(), torch.float16, "cuda")+++def test_other_families_keep_stock(fake_kernel):+ pipe = _Flux2Like(module = "diffusers.models.transformers.transformer_flux")+ assert not fr.install_for_pipe(pipe, torch.float16, "cuda")+ assert fmod.apply_rotary_emb is stock_rope+++def test_other_family_load_removes_a_previous_install(fake_kernel):+ assert fr.install_for_pipe(_Flux2Like(), torch.float16, "cuda")+ assert not fr.install_for_pipe(_Flux2Like(module = "x.y"), torch.float16, "cuda")+ assert fmod.apply_rotary_emb is stock_rope++[email protected]("value", ["0", "off", "false", "no"])+def test_kill_switch(fake_kernel, monkeypatch, value):+ monkeypatch.setenv(fr.FLUX2_FUSED_ROPE_ENV, value)+ assert not fr.install_for_pipe(_Flux2Like(), torch.float16, "cuda")+ assert fmod.apply_rotary_emb is stock_rope+++def test_no_triton_keeps_stock(monkeypatch):+ monkeypatch.setattr(fr, "_kernel", lambda: None)+ assert not fr.install_for_pipe(_Flux2Like(), torch.float16, "cuda")+++def test_install_is_idempotent_and_uninstall_restores(fake_kernel):+ assert fr.install(torch.float16, "cuda") and fr.install(torch.float16, "cuda")+ fr.uninstall()+ fr.uninstall()+ assert fmod.apply_rotary_emb is stock_rope+++def test_cpu_tensors_fall_through_to_stock(fake_kernel):+ assert fr.install(torch.float16, "cuda")+ x = torch.randn(1, 6, 2, 8, dtype = torch.float32)+ pos = torch.randn(6, 4, dtype = torch.float64)+ freqs = (pos.cos().repeat_interleave(2, -1).float(), pos.sin().repeat_interleave(2, -1).float())+ assert torch.equal(+ fmod.apply_rotary_emb(x, freqs, sequence_dim = 1), stock_rope(x, freqs, sequence_dim = 1)+ )+++def test_teardown_and_load_wiring():+ src = (Path(__file__).resolve().parents[1] / "core" / "inference" / "diffusion.py").read_text(+ encoding = "utf-8"+ )+ tree = ast.parse(src)+ teardown = next(+ n+ for n in ast.walk(tree)+ if isinstance(n, ast.FunctionDef) and n.name == "_uninstall_fused_dit_patches"+ )+ assert "uninstall_flux2_rope()" in ast.unparse(teardown)+ load = next(+ n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == "load_pipeline"+ )+ assert "install_flux2_rope(pipe, dtype, device, logger)" in ast.unparse(load)+++def _case(shape, layout, freq_dtype):+ B, S, H, D = shape+ g = torch.Generator("cuda").manual_seed(0)+ if layout == "qkv_chunk":+ x = (+ torch.randn(B, S, 3 * H * D, device = "cuda", dtype = torch.float16, generator = g) * 4+ ).chunk(3, -1)[1]+ x = x.unflatten(-1, (H, D))+ elif layout == "permuted":+ x = (+ torch.randn(B, H, S, D, device = "cuda", dtype = torch.float16, generator = g) * 4+ ).transpose(1, 2)+ else:+ x = torch.randn(B, S, H, D, device = "cuda", dtype = torch.float16, generator = g) * 4+ pos = torch.randn(S, D // 2, device = "cuda", dtype = torch.float64, generator = g) * 50+ return x, (+ pos.cos().repeat_interleave(2, -1).to(freq_dtype),+ pos.sin().repeat_interleave(2, -1).to(freq_dtype),+ )+++@needs_cuda+ "shape,layout,freq_dtype",+ [+ (+ (1, 4608, 24, 128),+ "contiguous",+ "float32",+ ), # klein-4B 1024px: 512 text + 4096 image tokens+ ((2, 1000, 24, 128), "qkv_chunk", "float32"),+ ((1, 333, 5, 64), "qkv_chunk", "float16"),+ ((1, 777, 24, 128), "permuted", "float32"),+ ],+)+def test_bit_identical_to_stock(shape, layout, freq_dtype):+ x, freqs = _case(shape, layout, getattr(torch, freq_dtype))+ ref = stock_rope(x, freqs, sequence_dim = 1)+ assert fr.install(torch.float16, "cuda")+ out = fmod.apply_rotary_emb(x, freqs, sequence_dim = 1)+ assert out.dtype == ref.dtype and out.stride() == ref.stride()+ assert torch.equal(out, ref)+++@needs_cuda+def test_grad_and_bf16_calls_use_stock():+ assert fr.install(torch.float16, "cuda")+ x, freqs = _case((1, 16, 2, 8), "contiguous", torch.float32)+ xg = x.clone().requires_grad_(True)+ fmod.apply_rotary_emb(xg, freqs, sequence_dim = 1).float().sum().backward()+ assert xg.grad is not None+ xb = x.bfloat16()+ assert torch.equal(+ fmod.apply_rotary_emb(xb, freqs, sequence_dim = 1), stock_rope(xb, freqs, sequence_dim = 1)+ )+++@needs_cuda+def test_compiled_block_has_no_graph_break():+ """Studio compiles FLUX.2 blocks on fp16 explicit tiers: the patch must trace as stock, never split the block."""+ assert fr.install(torch.float16, "cuda")+ x, freqs = _case((1, 64, 4, 32), "contiguous", torch.float32)+ torch._dynamo.reset()+ compiled = torch.compile(+ lambda t: fmod.apply_rotary_emb(t, freqs, sequence_dim = 1), fullgraph = True+ )+ ref = torch.compile(lambda t: stock_rope(t, freqs, sequence_dim = 1), fullgraph = True)+ assert torch.equal(compiled(x), ref(x))+++def test_call_after_uninstall_reaches_stock(fake_kernel):+ assert fr.install_for_pipe(_Flux2Like(), torch.float16, "cuda")+ patched = fmod.apply_rotary_emb+ fr.uninstall()+ x = torch.randn(1, 4, 2, 8)+ freqs = (torch.ones(4, 8), torch.zeros(4, 8))+ assert torch.equal(patched(x, freqs, sequence_dim = 1), x)