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: Qwen-Image-2.1 eager renders before the deferred compile now match ComfyUI (#15908)
Daniel Handbf73e8493c6
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 1b8a9f9e87a..221455a1337 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -10099,6 +10099,9 @@ class DiffusionBackend:audit = load_audit,logger = logger,)+ if speed_deferred:+ from .diffusion_qwenimage21_eager import install_for_pipe as q21_eager+ q21_eager(pipe, logger)# fp16-only cards: a guarded family stays float16; patch its overflow sites.from .diffusion_fp16_guard import family_fp16_guard, install_fp16_guard@@ -12892,6 +12895,9 @@ class DiffusionBackend:def _engage_deferred_profile(self, state: _LoadState) -> None:"""Runs the deferred speed profile at the 3rd generation under _generate_lock; the flag clears first so it never retries."""object.__setattr__(state, "speed_deferred", False)+ from .diffusion_qwenimage21_eager import demote++ demote(getattr(state, "pipe", None))from . import diffusion_autoopt as autoopttarget = self._state_device_target(state)diff --git a/studio/backend/core/inference/diffusion_qwenimage21.py b/studio/backend/core/inference/diffusion_qwenimage21.pyindex fe6833c153e..83ab82600f8 100644--- a/studio/backend/core/inference/diffusion_qwenimage21.py+++ b/studio/backend/core/inference/diffusion_qwenimage21.py@@ -85,6 +85,7 @@ class _Layout:"target_token_mask","prefix_len","tail_is_image",+ "tail_all_target","vlm_row","_segments","_vlm_text",@@ -107,6 +108,7 @@ def _build_layout(model: Any, mod: Any, img_mask: Any, shapes: list, device: Anylay.prefix_len = int((~lay.target_token_mask).sum())# Decode steps read rows [prefix_len:] only; all-image tails never need the text projection.lay.tail_is_image = bool(lay.image_pad_mask[lay.prefix_len :].all())+ lay.tail_all_target = bool(lay.target_token_mask[lay.prefix_len :].all())lay.vlm_row = img_mask[0].clone() # the caller may reuse and rewrite its masklay._segments = Nonelay._vlm_text = {}@@ -174,6 +176,11 @@ def _layout_for(return lay+def _eager_fast(model: Any) -> bool:+ from .diffusion_qwenimage21_eager import active+ return active(model)++def _tails(lay: _Layout) -> tuple:"""The decode rows of the RoPE table and modulation mask; one view per layout, so a graph replay can tell byidentity that its copy is current."""@@ -195,9 +202,11 @@ def _cached_core(rotary_emb: Any,modulation_mask: Any,layer_cache: Any,+ broadcast_modulation: bool = False,) -> Any:"""One decode step from the prefix KV cache. Reads no host value off the device, so it records as a CUDA graph;- the eager step and the graph run this same code. ``layer_cache(i)`` returns block ``i``'s cache entry."""+ the eager step and the graph run this same code. ``layer_cache(i)`` returns block ``i``'s cache entry.+ ``broadcast_modulation``: every row is a target row, so the sampled-t row is read broadcast."""import torchbatch_size = hidden_states.shape[0]@@ -218,14 +227,17 @@ def _cached_core(joint_key_valid[:, text_positions] = encoder_hidden_states_mask.bool()[:, vlm_text]attention_mask = joint_key_valid[:, None, None, :]+ block_modulation, block_rows = modulation, modulation_mask+ if broadcast_modulation:+ block_modulation, block_rows = modulation[:-1], Nonejoint_hidden_states = full[:, prefix_len:]for index_block, block in enumerate(model.transformer_blocks):joint_hidden_states = block(hidden_states = joint_hidden_states,- modulation = modulation,+ modulation = block_modulation,rotary_emb = rotary_emb,attention_mask = attention_mask,- target_token_mask = modulation_mask,+ target_token_mask = block_rows,layer_cache = layer_cache(index_block),kv_cache_mode = "cached",cache_write_slice = None,@@ -246,6 +258,10 @@ def _cached_step(kv_cache: Any,) -> Any:rotary_emb, modulation_mask = _tails(lay)+ broadcast = lay.tail_all_target and _eager_fast(model)+ if broadcast:+ from .diffusion_qwenimage21_eager import STATS+ STATS["mod_broadcast"] += 1return _cached_core(model,text_dtype,@@ -261,6 +277,7 @@ def _cached_step(rotary_emb,modulation_mask,kv_cache.get_layer,+ broadcast_modulation = broadcast,)diff --git a/studio/backend/core/inference/diffusion_qwenimage21_eager.py b/studio/backend/core/inference/diffusion_qwenimage21_eager.pynew file mode 100644index 00000000000..1dd62aea674--- /dev/null+++ b/studio/backend/core/inference/diffusion_qwenimage21_eager.py@@ -0,0 +1,363 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Eager Qwen-Image-2.1 renders before the deferred profile: fused q/k RMSNorm + RoPE (fp32 sum of squares may+differ in the last bit) and bit-identical broadcast modulation. Kill switch UNSLOTH_DIFFUSION_Q21_EAGER_FAST=0"""++from __future__ import annotations++import functools+import os+import threading+from typing import Any, Optional++from .diffusion_autoopt.patches import source_digest+from .rocm_bf16 import is_rocm_torch++EAGER_FAST_ENV = "UNSLOTH_DIFFUSION_Q21_EAGER_FAST"++_CLASS = "QwenImage21Transformer2DModel"+# diffusers 0.41.0 / 0.42.1; the prepare copy below uses 0.42.1's head split, equal for both.+_FINGERPRINTS: dict[str, frozenset] = {+ "_qwenimage21_prepare_qkv": frozenset({"574bacc8f355456d", "4c3830595aef56a0"}),+ "RMSNorm.forward": frozenset({"2633294611ed3bdf"}),+ "_select_modulation_rows": frozenset({"7e12608919321d40"}),+ "QwenImage21TransformerBlock.forward": frozenset({"f2cdd58b41ad3441"}),+ "QwenImage21TransformerBlock._modulate": frozenset({"3bf1998487634f22"}),+ "QwenImage21AttnProcessor.__call__": frozenset({"2125e0b56c1490b6"}),+}++# EAGER: every eager render of this load. BG: only renders a pending background compile keeps eager.+_ATTR = "_unsloth_q21_eager_fast"+EAGER = "eager"+BG = "bg"++_LOCK = threading.Lock()+_STOCK: dict = {}+_FAILED = [False]+_FUSION: dict = {}+STATS = {"qk_fused": 0, "mod_broadcast": 0}+++def disabled() -> bool:+ return (os.environ.get(EAGER_FAST_ENV) or "").strip().lower() in ("0", "off", "false", "no")+++def active(module: Any) -> bool:+ import torch++ state = module.__dict__.get(_ATTR)+ if state is None or torch.compiler.is_compiling() or torch.is_grad_enabled():+ return False+ if state == EAGER:+ return True+ from .diffusion_bg_compile import eager_forced++ return eager_forced()+++def _modules(transformer: Any) -> list:+ out = [transformer]+ for block in getattr(transformer, "transformer_blocks", ()) or ():+ attn = getattr(block, "attn", None)+ if attn is not None:+ out.append(attn)+ return out+++def set_state(transformer: Any, state: Optional[str]) -> None:+ for module in _modules(transformer):+ if state is None:+ module.__dict__.pop(_ATTR, None)+ else:+ module.__dict__[_ATTR] = state++[email protected]_cache(maxsize = 1)+def _kernel() -> Any:+ import triton+ import triton.language as tl++ try:+ from triton.language.extra import libdevice+ except Exception: # noqa: BLE001 - older Triton layout+ from triton.language.extra.cuda import libdevice++ # Module globals, which the JIT resolves. *_rn: Triton would otherwise FMA-contract the products eager rounds.+ global _rsqrt, _mul, _add+ _rsqrt, _mul, _add = libdevice.rsqrt, libdevice.mul_rn, libdevice.add_rn++ @triton.jit+ def _norm_rope_kernel(+ x_ptr,+ w_ptr,+ f_ptr,+ out_ptr,+ n_rows,+ n_heads,+ n_seq,+ stride_b,+ stride_s,+ stride_h,+ f_stride,+ eps,+ HALF: tl.constexpr,+ ROWS: tl.constexpr,+ REAL_FMA_X: tl.constexpr,+ IMAG_FMA_X: tl.constexpr,+ ):+ pid = tl.program_id(0).to(tl.int64)+ rows = pid * ROWS + tl.arange(0, ROWS).to(tl.int64)+ ok = rows < n_rows+ h = rows % n_heads+ bs = rows // n_heads+ s = bs % n_seq+ b = bs // n_seq+ base = b * stride_b + s * stride_s + h * stride_h+ i = tl.arange(0, HALF)+ m = ok[:, None]+ xe = tl.load(x_ptr + base[:, None] + 2 * i[None, :], mask = m, other = 0.0)+ xo = tl.load(x_ptr + base[:, None] + 2 * i[None, :] + 1, mask = m, other = 0.0)+ dt = xe.dtype+ xe = xe.to(tl.float32)+ xo = xo.to(tl.float32)+ # diffusers RMSNorm: x * rsqrt in fp32, round, then * weight, round+ ms = (tl.sum(_mul(xe, xe), axis = 1) + tl.sum(_mul(xo, xo), axis = 1)) * (0.5 / HALF)+ r = _rsqrt(_add(ms, eps))[:, None]+ we = tl.load(w_ptr + 2 * i).to(tl.float32)[None, :]+ wo = tl.load(w_ptr + 2 * i + 1).to(tl.float32)[None, :]+ a = _mul(_mul(xe, r).to(dt).to(tl.float32), we).to(dt).to(tl.float32)+ bb = _mul(_mul(xo, r).to(dt).to(tl.float32), wo).to(dt).to(tl.float32)+ # the fma pairing this card's complex multiply uses+ fo = s[:, None] * f_stride + 2 * i[None, :]+ c = tl.load(f_ptr + fo, mask = m, other = 0.0)+ d = tl.load(f_ptr + fo + 1, mask = m, other = 0.0)+ if REAL_FMA_X:+ real = tl.fma(a, c, -_mul(bb, d))+ else:+ real = tl.fma(-bb, d, _mul(a, c))+ if IMAG_FMA_X:+ imag = tl.fma(bb, c, _mul(a, d))+ else:+ imag = tl.fma(a, d, _mul(bb, c))+ o = rows[:, None] * (2 * HALF) + 2 * i[None, :]+ tl.store(out_ptr + o, real.to(dt), mask = m)+ tl.store(out_ptr + o + 1, imag.to(dt), mask = m)++ return _norm_rope_kernel+++_ROWS = 16+_WARPS = 4+++def _fusion(device: Any) -> Optional[tuple]:+ index = device.index+ if index not in _FUSION:+ from .diffusion_qwenimage21_rope import probe_fusion+ try:+ _FUSION[index] = probe_fusion(device)+ except Exception: # noqa: BLE001 - unknown pairing: keep the stock RoPE+ _FUSION[index] = None+ return _FUSION[index]+++def _eligible(x: Any, norm: Any, freqs: Any) -> bool:+ import torch++ if (+ _FAILED[0]+ or not x.is_cuda+ or x.dim() != 4+ or x.dtype not in (torch.bfloat16, torch.float16)+ ):+ return False+ dim = x.shape[-1]+ weight = getattr(norm, "weight", None)+ if (+ dim not in (64, 128, 256)+ or x.stride(-1) != 1+ or x.stride(-2) != dim+ or not _stock_norm(norm)+ or getattr(norm, "bias", None) is not None+ or weight is None+ or weight.dtype != x.dtype+ or weight.device != x.device+ or tuple(weight.shape) != (dim,)+ ):+ return False+ return (+ torch.is_tensor(freqs)+ and freqs.dtype == torch.complex64+ and freqs.device == x.device+ and freqs.dim() == 2+ and freqs.shape[0] == x.shape[1]+ and freqs.shape[1] * 2 == dim+ and freqs.stride(1) == 1+ )+++def _stock_norm(norm: Any) -> bool:+ """Stock forward or the eager tier's RMSNorm (installed on render 3); they differ only in rounding x * rsqrt."""+ import inspect++ forward = getattr(type(norm), "forward", None)+ want = _STOCK.get("rmsnorm_forward")+ if want is None or forward is None:+ return False+ if forward is want:+ return True+ from .diffusion_eager_patches import _rmsnorm_forward++ return getattr(inspect.unwrap(forward), "__code__", None) is _rmsnorm_forward.__code__+++def _norm_rope(x: Any, norm: Any, freqs: Any) -> Optional[Any]:+ """``apply_rotary_emb_qwen(norm(x), freqs, use_real=False)`` in one kernel, or None to run the stock pair."""+ import torch++ if not _eligible(x, norm, freqs):+ return None+ fusion = _fusion(x.device)+ if fusion is None:+ return None+ batch, seq, heads, dim = x.shape+ out = torch.empty((batch, seq, heads, dim), device = x.device, dtype = x.dtype)+ rows = batch * seq * heads+ f = torch.view_as_real(freqs)+ try:+ with torch.cuda.device(x.device):+ _kernel()[((rows + _ROWS - 1) // _ROWS,)](+ x,+ norm.weight,+ f,+ out,+ rows,+ heads,+ seq,+ x.stride(0),+ x.stride(1),+ x.stride(2),+ f.stride(0),+ float(norm.eps),+ HALF = dim // 2,+ ROWS = _ROWS,+ REAL_FMA_X = fusion[0] == "x",+ IMAG_FMA_X = fusion[1] == "x",+ num_warps = _WARPS,+ )+ except Exception: # noqa: BLE001 - a JIT / driver failure: the stock math for the rest of the process+ _FAILED[0] = True+ return None+ STATS["qk_fused"] += 1+ return out+++def _make_prepare(mod: Any, stock: Any) -> Any:+ @functools.wraps(stock)+ def _qwenimage21_prepare_qkv(+ attn, hidden_states, rotary_emb, layer_cache, kv_cache_mode, cache_write_slice+ ):+ if rotary_emb is None or not active(attn):+ return stock(+ attn, hidden_states, rotary_emb, layer_cache, kv_cache_mode, cache_write_slice+ )+ import torch++ query = attn.to_q(hidden_states)+ key = attn.to_k(hidden_states)+ value = attn.to_v(hidden_states)+ head_dim = attn.inner_dim // attn.heads+ query = query.unflatten(-1, (-1, head_dim))+ key = key.unflatten(-1, (-1, head_dim))+ value = value.unflatten(-1, (-1, head_dim))+ fused_q = _norm_rope(query, attn.norm_q, rotary_emb) if query.dtype == value.dtype else None+ fused_k = _norm_rope(key, attn.norm_k, rotary_emb) if fused_q is not None else None+ if fused_k is None:+ rope = mod.apply_rotary_emb_qwen+ query = rope(attn.norm_q(query).to(value.dtype), rotary_emb, use_real = False)+ key = rope(attn.norm_k(key).to(value.dtype), rotary_emb, use_real = False)+ else:+ query, key = fused_q, fused_k++ if layer_cache is not None:+ if kv_cache_mode == "extract" and cache_write_slice is not None:+ layer_cache.store(+ key[:, cache_write_slice].clone(), value[:, cache_write_slice].clone()+ )+ elif kv_cache_mode == "cached":+ cached_k, cached_v = layer_cache.get()+ key = torch.cat([cached_k, key], dim = 1)+ value = torch.cat([cached_v, value], dim = 1)+ return query, key, value, query.shape[1]++ _qwenimage21_prepare_qkv.__unsloth_q21_eager__ = True+ return _qwenimage21_prepare_qkv+++def why_unsupported(mod: Any) -> Optional[str]:+ for name, want in _FINGERPRINTS.items():+ obj = mod+ for part in name.split("."):+ obj = getattr(obj, part, None)+ got = source_digest(obj)+ if got not in want:+ return f"{name} differs from the version this was written against ({got})"+ return None+++def install(logger: Any = None) -> bool:+ try:+ import torch+ if is_rocm_torch(torch) or not torch.cuda.is_available():+ return False+ from diffusers.models.transformers import transformer_qwenimage21 as mod+ except Exception: # noqa: BLE001 - no CUDA, or diffusers without Qwen-Image 2.1+ return False+ with _LOCK:+ current = getattr(mod, "_qwenimage21_prepare_qkv", None)+ if getattr(current, "__unsloth_q21_eager__", False):+ return True+ why = why_unsupported(mod)+ if why is not None:+ if logger is not None:+ logger.info("diffusion.q21_eager: stock eager step kept: %s", why)+ return False+ _STOCK["prepare"] = current+ _STOCK["rmsnorm_forward"] = mod.RMSNorm.forward+ mod._qwenimage21_prepare_qkv = _make_prepare(mod, current)+ return True+++def uninstall() -> None:+ try:+ from diffusers.models.transformers import transformer_qwenimage21 as mod+ except Exception: # noqa: BLE001+ return+ with _LOCK:+ stock = _STOCK.pop("prepare", None)+ if stock is not None and getattr(+ getattr(mod, "_qwenimage21_prepare_qkv", None), "__unsloth_q21_eager__", False+ ):+ mod._qwenimage21_prepare_qkv = stock+++def install_for_pipe(pipe: Any, logger: Any = None) -> bool:+ transformer = getattr(pipe, "transformer", None)+ if disabled() or type(transformer).__name__ != _CLASS:+ return False+ if not install(logger):+ return False+ set_state(transformer, EAGER)+ if logger is not None:+ logger.info(+ "diffusion.q21_eager: renders before the deferred compile run the fused q/k RMSNorm + RoPE "+ "and broadcast modulation"+ )+ return True+++def demote(pipe: Any) -> None:+ transformer = getattr(pipe, "transformer", None)+ if transformer is not None and getattr(transformer, "__dict__", {}).get(_ATTR) is not None:+ set_state(transformer, BG)diff --git a/studio/backend/tests/test_diffusion_qwenimage21_eager.py b/studio/backend/tests/test_diffusion_qwenimage21_eager.pynew file mode 100644index 00000000000..248b9c5f4f1--- /dev/null+++ b/studio/backend/tests/test_diffusion_qwenimage21_eager.py@@ -0,0 +1,153 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++from __future__ import annotations++import os+import sys+import types++import pytest++from core.inference import diffusion_qwenimage21 as q+from core.inference import diffusion_qwenimage21_eager as e++torch = pytest.importorskip("torch")+qmod = pytest.importorskip("diffusers.models.transformers.transformer_qwenimage21")++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from test_diffusion_qwenimage21 import _inputs, _model, _render # noqa: E402++[email protected](autouse = True)+def _clean(monkeypatch):+ monkeypatch.delenv(e.EAGER_FAST_ENV, raising = False)+ monkeypatch.delenv(q.FAST_STEP_ENV, raising = False)+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ q.uninstall()+ e.uninstall()+ yield+ q.uninstall()+ e.uninstall()+++def _valid(inp):+ inp["encoder_hidden_states_mask"] = torch.ones(+ inp["encoder_hidden_states"].shape[:2], dtype = torch.long+ )+ return inp+++def _armed(m):+ assert q.install()+ assert e.install_for_pipe(types.SimpleNamespace(transformer = m))+ return m+++ "case", [{}, {"cond": (4, 4)}, {"batch": 2, "pad": 3}, {"batch": 2, "cond": (4, 8), "pad": 2}]+)+def test_broadcast_modulation_and_the_eager_qkv_are_bit_identical(case):+ m = _model()+ inp = _valid(_inputs(**case)) if not case.get("pad") else _inputs(**case)+ ref = _render(m, inp)+ _armed(m)+ before = dict(e.STATS)+ got = _render(m, inp)+ for a, b in zip(ref, got):+ assert torch.equal(a, b)+ assert e.STATS["mod_broadcast"] > before["mod_broadcast"]+++def test_a_demoted_load_runs_stock_outside_a_pending_background_compile():+ m = _model()+ _armed(m)+ inp = _inputs()+ before = e.STATS["mod_broadcast"]+ e.demote(types.SimpleNamespace(transformer = m))+ _render(m, inp)+ assert e.STATS["mod_broadcast"] == before+++def test_state_rules(monkeypatch):+ m = _model()+ attn = m.transformer_blocks[0].attn+ with torch.inference_mode():+ assert not e.active(attn)+ _armed(m)+ assert e.active(m) and e.active(attn)+ monkeypatch.setattr(torch.compiler, "is_compiling", lambda: True)+ assert not e.active(attn)+ monkeypatch.undo()+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ e.demote(types.SimpleNamespace(transformer = m))+ assert not e.active(attn)+ from core.inference import diffusion_bg_compile as bg++ token = bg._FORCE_EAGER.set(True)+ try:+ assert e.active(attn) and e.active(m)+ finally:+ bg._FORCE_EAGER.reset(token)+ with torch.enable_grad():+ e.set_state(m, e.EAGER)+ assert not e.active(attn)+++def test_demote_leaves_an_unarmed_load_stock():+ m = _model()+ e.demote(types.SimpleNamespace(transformer = m))+ assert e._ATTR not in m.__dict__+++def test_kill_switch_and_other_models_stay_stock(monkeypatch):+ m = _model()+ monkeypatch.setenv(e.EAGER_FAST_ENV, "0")+ assert not e.install_for_pipe(types.SimpleNamespace(transformer = m))+ assert e._ATTR not in m.__dict__+ monkeypatch.delenv(e.EAGER_FAST_ENV)+ other = torch.nn.Linear(2, 2)+ assert not e.install_for_pipe(types.SimpleNamespace(transformer = other))+++def test_a_drifted_function_keeps_the_stock_step(monkeypatch):+ monkeypatch.setitem(e._FINGERPRINTS, "_qwenimage21_prepare_qkv", frozenset({"0" * 16}))+ stock = qmod._qwenimage21_prepare_qkv+ assert not e.install()+ assert qmod._qwenimage21_prepare_qkv is stock+++def test_install_is_idempotent_and_uninstall_restores():+ stock = qmod._qwenimage21_prepare_qkv+ assert e.install() and e.install()+ wrapped = qmod._qwenimage21_prepare_qkv+ assert wrapped is not stock and wrapped.__wrapped__ is stock+ from core.inference.diffusion_autoopt.patches import source_digest++ assert source_digest(wrapped) == source_digest(stock)+ e.uninstall()+ assert qmod._qwenimage21_prepare_qkv is stock+++def test_installed_diffusers_matches_the_fingerprints():+ assert e.why_unsupported(qmod) is None+++def test_cpu_tensors_never_reach_the_kernel():+ norm = qmod.RMSNorm(16, eps = 1e-6)+ x = torch.randn(1, 4, 2, 16)+ freqs = torch.polar(torch.ones(4, 8), torch.rand(4, 8))+ assert e.install()+ assert e._norm_rope(x, norm, freqs) is None+++def test_the_eager_tier_rmsnorm_patch_still_takes_the_kernel(monkeypatch):+ from core.inference import diffusion_eager_patches as ep++ assert e.install()+ norm = qmod.RMSNorm(16, eps = 1e-6)+ assert e._stock_norm(norm)+ monkeypatch.setattr(qmod.RMSNorm, "forward", ep._rmsnorm_forward)+ assert e._stock_norm(norm)+ monkeypatch.setattr(qmod.RMSNorm, "forward", lambda self, x: x)+ assert not e._stock_norm(norm)