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: build Qwen-Image-2.1's token layout once per render instead of every step (#11887)
Daniel Han59b68c46ffd8
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 2a945aaf87a..7b3842e2410 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -5549,6 +5549,9 @@ class DiffusionBackend:else:uninstall_patches()uninstall_arch_patches()+ from .diffusion_qwenimage21 import install_for_pipe as install_q21_fast_step++ install_q21_fast_step(pipe, logger)self._raise_if_load_cancelled(_load_token)# Pre-warmed torch.compile cache: a per-fingerprint inductor dir plus a bundle loaded before the@@ -7785,6 +7788,9 @@ class DiffusionBackend:from core.inference import diffusion_controlnet, diffusion_lorafrom hub.utils.gguf import extract_quant_token+ resolved, speed_optims = cuda_graph.live_status(+ state.resolved, state.speed_optims, getattr(state, "cuda_graphs", ())+ )return {"loaded": True,"repo_id": state.repo_id,@@ -7804,12 +7810,12 @@ class DiffusionBackend:"vae_tiling": state.vae_tiling,"memory_mode": state.memory_mode,"speed_mode": state.speed_mode,- "speed_optims": list(state.speed_optims),+ "speed_optims": speed_optims,"text_encoder_quant": state.text_encoder_quant,"transformer_quant": state.transformer_quant,"attention_backend": state.attention_backend,"transformer_cache": state.transformer_cache,- "resolved": state.resolved,+ "resolved": resolved,# Workflows the loaded family supports, so the UI can gate its tabs."workflows": _family_workflows(state.family),"conditioning": conditioning_capabilities(diff --git a/studio/backend/core/inference/diffusion_capture_safe.py b/studio/backend/core/inference/diffusion_capture_safe.pyindex fb3b57cdf94..56e8f373cdc 100644--- a/studio/backend/core/inference/diffusion_capture_safe.py+++ b/studio/backend/core/inference/diffusion_capture_safe.py@@ -204,6 +204,12 @@ _REWRITES: dict[str, tuple[str, Callable[[Callable], Callable]]] = {),}+# Declined at load so status says "off" instead of arming a wrapper that refuses every step.+_UNCAPTURABLE: dict[str, str] = {+ "QwenImage21Transformer2DModel": "its pipeline passes the prefix KV cache as a Python object "+ "on every step and its forward syncs the host",+}+_CACHE: dict = {}_CACHE_LOCK = threading.Lock()@@ -223,6 +229,11 @@ def resolve(cls: type) -> tuple[Optional[Callable], Optional[str]]:Never raises. Cheap for an unknown class: a name lookup, no torch import."""owner = _defining_class(cls)+ if owner is not None and owner.__name__ in _UNCAPTURABLE and owner.__name__ not in _REWRITES:+ return (+ None,+ f"{owner.__name__} forward is not capture-safe ({_UNCAPTURABLE[owner.__name__]})",+ )if owner is None or owner.__name__ not in _REWRITES:return None, Nonewhy, rewrite = _REWRITES[owner.__name__]diff --git a/studio/backend/core/inference/diffusion_cuda_graph.py b/studio/backend/core/inference/diffusion_cuda_graph.pyindex c013d6a5eab..34909524c8a 100644--- a/studio/backend/core/inference/diffusion_cuda_graph.py+++ b/studio/backend/core/inference/diffusion_cuda_graph.py@@ -612,6 +612,9 @@ def uninstall_all(handles: Any, *, logger: Any = None) -> None:_drop_pool_if_unused()+_REFUSALS = ("refused_float", "refused_host_tensor", "refused_object")++def stats(handles: Any) -> dict:"""JSON-safe aggregate over the handles, for the status payload."""out = {@@ -621,13 +624,21 @@ def stats(handles: Any) -> dict:"eager_calls": 0,"fallbacks": 0,"cap_skips": 0,+ **{field: 0 for field in _REFUSALS},"poisoned": False,"capture_error": None,}for handle in handles or ():try:out["graphs"] += len(handle.cache)- for field in ("captures", "replays", "eager_calls", "fallbacks", "cap_skips"):+ for field in (+ "captures",+ "replays",+ "eager_calls",+ "fallbacks",+ "cap_skips",+ *_REFUSALS,+ ):out[field] += int(handle.stats.get(field, 0))if handle.poisoned:out["poisoned"] = True@@ -640,3 +651,42 @@ def stats(handles: Any) -> dict:except Exception: # noqa: BLE001passreturn out+++def never_engaged(handles: Any) -> Optional[str]:+ """Why the armed graphs never replayed a step; None before the first call or once any engaged."""+ if not handles:+ return None+ s = stats(handles)+ if all(getattr(h, "poisoned", False) for h in handles):+ error = s["capture_error"] or {}+ return f"capture failed ({error.get('type') or 'error'}); every denoiser step runs eager"+ if s["captures"] or s["replays"] or not s["eager_calls"]:+ return None+ parts = [+ f"{s[field]} {label}"+ for field, label in (+ ("refused_object", "with a non-tensor argument"),+ ("refused_float", "with a float argument"),+ ("refused_host_tensor", "with a host tensor"),+ ("cap_skips", "past the graph cap"),+ )+ if s[field]+ ]+ detail = ", ".join(parts) if parts else "bypassed"+ return f"armed, but all {s['eager_calls']} denoiser call(s) so far ran eager ({detail})"+++def live_status(resolved: Any, speed_optims: Any, handles: Any) -> tuple:+ """Copies, never mutates: the load-time record stays as recorded."""+ why = never_engaged(handles)+ optims = list(speed_optims or ())+ if why is None:+ return resolved, optims+ optims = [o for o in optims if o != "cuda_graph"]+ if isinstance(resolved, dict) and isinstance(resolved.get("cuda_graph"), dict):+ resolved = {+ **resolved,+ "cuda_graph": {**resolved["cuda_graph"], "value": "off", "reason": why},+ }+ return resolved, optimsdiff --git a/studio/backend/core/inference/diffusion_qwenimage21.py b/studio/backend/core/inference/diffusion_qwenimage21.pynew file mode 100644index 00000000000..77d300655a5--- /dev/null+++ b/studio/backend/core/inference/diffusion_qwenimage21.py@@ -0,0 +1,481 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Qwen-Image-2.1 denoiser forward with the per-step token layout built once (bit-identical).++Kill switch: ``UNSLOTH_DIFFUSION_Q21_FAST_STEP=0``."""++from __future__ import annotations++import ast+import functools+import hashlib+import inspect+import io+import math+import os+import textwrap+import threading+import tokenize+import weakref+from typing import Any, Optional++FAST_STEP_ENV = "UNSLOTH_DIFFUSION_Q21_FAST_STEP"++_MODULE = "diffusers.models.transformers.transformer_qwenimage21"+_CLASS = "QwenImage21Transformer2DModel"++# Stock diffusers sources the fast forward relies on; any drift keeps the stock forward.+_FINGERPRINTS: dict[str, frozenset] = {+ "forward": frozenset({"7c1fd48f75efbe41"}),+ "build_token_metadata": frozenset({"51818c1674e0d406"}),+ "rope_forward": frozenset({"f9e064940341e3ee"}),+ "prefix_segments": frozenset({"27729cffc22b0aa5"}),+}++_LAYOUTS_PER_MODULE = 8+_RECENT_PER_MODULE = 4++_LOCK = threading.Lock()+_INSTALLED: dict = {}+++def fast_step_disabled() -> bool:+ return (os.environ.get(FAST_STEP_ENV) or "").strip().lower() in ("0", "off", "false", "no")+++def _digest(fn: Any) -> Optional[str]:+ """Source text, not ``ast.dump``, whose output changes between Python versions."""+ try:+ src = textwrap.dedent(inspect.getsource(inspect.unwrap(fn)))+ tree = ast.parse(src)+ comments = [+ tok.start+ for tok in tokenize.generate_tokens(io.StringIO(src).readline)+ if tok.type == tokenize.COMMENT+ ]+ except (OSError, TypeError, SyntaxError, ValueError, tokenize.TokenError):+ return None+ lines = src.splitlines()+ for row, col in comments:+ lines[row - 1] = lines[row - 1][:col]+ for node in ast.walk(tree):+ body = getattr(node, "body", None)+ if (+ isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef))+ and body+ and isinstance(body[0], ast.Expr)+ and isinstance(getattr(body[0], "value", None), ast.Constant)+ and isinstance(body[0].value.value, str)+ ):+ for row in range(body[0].lineno, body[0].end_lineno + 1):+ lines[row - 1] = ""+ text = "\n".join(line.rstrip() for line in lines if line.strip())+ return hashlib.sha256(text.encode()).hexdigest()[:16]+++def stock_digests(module: Any) -> dict[str, Optional[str]]:+ cls = getattr(module, _CLASS, None)+ rope = getattr(module, "QwenImage21Rope", None)+ return {+ "forward": _digest(vars(cls)["forward"])+ if cls is not None and "forward" in vars(cls)+ else None,+ "build_token_metadata": _digest(getattr(cls, "build_token_metadata", None))+ if cls is not None+ else None,+ "rope_forward": _digest(vars(rope)["forward"])+ if rope is not None and "forward" in vars(rope)+ else None,+ "prefix_segments": _digest(getattr(module, "_qwenimage21_prefix_segments", None)),+ }+++def why_unsupported(module: Any) -> Optional[str]:+ got = stock_digests(module)+ for name, want in _FINGERPRINTS.items():+ if got.get(name) not in want:+ return f"{name} differs from the version this was written against ({got.get(name)})"+ return None+++class _Layout:+ __slots__ = (+ "repeats",+ "image_pad_mask",+ "total",+ "image_positions",+ "text_positions",+ "rotary_emb",+ "image_ids",+ "target_token_mask",+ "prefix_len",+ "tail_is_image",+ "vlm_row",+ "_segments",+ "_vlm_text",+ "__weakref__",+ )+++def _build_layout(model: Any, mod: Any, img_mask: Any, shapes: list, device: Any) -> _Layout:+ import torch++ lay = _Layout()+ lay.repeats = torch.where(img_mask, mod._IMG_TOKENS_PER_SLOT, 1)[0]+ lay.image_pad_mask = torch.repeat_interleave(img_mask[0], lay.repeats)+ lay.total = int(lay.image_pad_mask.shape[0])+ lay.image_positions = lay.image_pad_mask.nonzero(as_tuple = True)[0]+ lay.text_positions = (~lay.image_pad_mask).nonzero(as_tuple = True)[0]+ lay.rotary_emb = model.pos_embed(shapes, lay.image_pad_mask, device = device)+ lay.image_ids, lay.target_token_mask = model.build_token_metadata(lay.image_pad_mask, shapes)+ lay.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.vlm_row = img_mask[0].clone() # the caller may reuse and rewrite its mask+ lay._segments = None+ lay._vlm_text = {}+ return lay+++def _segments(lay: _Layout, mod: Any) -> list:+ if lay._segments is None:+ lay._segments = mod._qwenimage21_prefix_segments(lay.image_ids, lay.prefix_len)+ return lay._segments+++def _vlm_text(lay: _Layout, length: int) -> Any:+ idx = lay._vlm_text.get(length)+ if idx is None:+ idx = (~lay.vlm_row[:length]).nonzero(as_tuple = True)[0]+ lay._vlm_text[length] = idx+ return idx+++def _mask_version(img_mask: Any) -> Any:+ try:+ return img_mask._version+ except Exception: # noqa: BLE001 - inference tensors do not track versions+ return None+++def _layout_for(+ model: Any,+ mod: Any,+ img_mask: Any,+ img_shapes: Any,+ device: Any,+ *,+ reuse_identity: bool = False,+) -> _Layout:+ shapes = img_shapes[0]+ shapes_key = tuple(tuple(int(v) for v in s) for s in shapes)+ state = model.__dict__.get("_unsloth_q21_layouts")+ if state is None:+ state = {"recent": [], "by_content": {}}+ model.__dict__["_unsloth_q21_layouts"] = state+ # Only a cached step may trust img_mask identity (its KV cache fixes the prefix); others check content.+ version = _mask_version(img_mask)+ if reuse_identity:+ for ref, key, lay in state["recent"]:+ if ref() is img_mask and key == (shapes_key, device, version):+ return lay+ content = (+ tuple(img_mask.shape),+ str(img_mask.dtype),+ img_mask[0].detach().to("cpu").numpy().tobytes(),+ shapes_key,+ str(device),+ )+ lay = state["by_content"].pop(content, None)+ if lay is None:+ lay = _build_layout(model, mod, img_mask, shapes, device)+ state["by_content"][content] = lay+ while len(state["by_content"]) > _LAYOUTS_PER_MODULE:+ state["by_content"].pop(next(iter(state["by_content"])))+ state["recent"].insert(0, (weakref.ref(img_mask), (shapes_key, device, version), lay))+ del state["recent"][_RECENT_PER_MODULE:]+ return lay+++def _cached_step(+ model: Any,+ lay: _Layout,+ text_dtype: Any,+ hidden_states: Any,+ timestep: Any,+ encoder_hidden_states_mask: Any,+ kv_cache: Any,+) -> Any:+ import torch++ batch_size = hidden_states.shape[0]+ device = hidden_states.device+ prefix_len = lay.prefix_len+ hidden_states = model.img_in(hidden_states)+ # Keep the stock (batch, total, dim) layout so the blocks see the same strides.+ full = torch.empty(+ (batch_size, lay.total, hidden_states.shape[2]), dtype = text_dtype, device = device+ )+ full[:, prefix_len:] = hidden_states[:, hidden_states.shape[1] - (lay.total - prefix_len) :]++ timestep = timestep.to(hidden_states.dtype)+ timestep = torch.cat([timestep, timestep.new_zeros(1)], dim = 0)+ temb = model.time_text_embed(timestep, hidden_states)+ modulation = model.modulation(temb)++ attention_mask = None+ if encoder_hidden_states_mask is not None:+ joint_key_valid = torch.ones(batch_size, lay.total, dtype = torch.bool, device = device)+ joint_key_valid[:, lay.text_positions] = encoder_hidden_states_mask.bool()[+ :, _vlm_text(lay, encoder_hidden_states_mask.shape[1])+ ]+ attention_mask = joint_key_valid[:, None, None, :]++ joint_hidden_states = full[:, prefix_len:]+ rotary_emb = lay.rotary_emb[prefix_len:]+ modulation_mask = lay.target_token_mask[prefix_len:]+ for index_block, block in enumerate(model.transformer_blocks):+ joint_hidden_states = block(+ hidden_states = joint_hidden_states,+ modulation = modulation,+ rotary_emb = rotary_emb,+ attention_mask = attention_mask,+ target_token_mask = modulation_mask,+ layer_cache = kv_cache.get_layer(index_block),+ kv_cache_mode = "cached",+ cache_write_slice = None,+ segments = None,+ key_valid = None,+ )+ joint_hidden_states = model.norm_out(joint_hidden_states, temb, modulation_mask)+ return model.proj_out(joint_hidden_states)+++def _autocast_state(device_type: str) -> tuple:+ """Autocast decides the text projection's output dtype as much as the weights do."""+ import torch+ try:+ return torch.is_autocast_enabled(device_type), torch.get_autocast_dtype(device_type)+ except Exception: # noqa: BLE001 - older signature: CUDA state only+ return torch.is_autocast_enabled(), None+++def _text_dtype(model: Any, encoder_hidden_states: Any) -> tuple:+ weight = getattr(getattr(model.txt_in, "out_layer", None), "weight", None)+ key = (+ encoder_hidden_states.dtype,+ id(weight),+ getattr(weight, "dtype", None),+ _autocast_state(encoder_hidden_states.device.type),+ )+ return key, model.__dict__.setdefault("_unsloth_q21_text_dtype", {}).get(key)+++def _make_forward(mod: Any, stock: Any) -> Any:+ import torch++ stock_inner = inspect.unwrap(stock)+ lora_scale = getattr(mod, "apply_lora_scale", None)+ flex_cls = getattr(mod, "QwenImage21FlexAttnProcessor")+ build_block_mask = getattr(mod, "build_qwenimage21_block_causal_mask")++ def forward(+ self,+ hidden_states,+ encoder_hidden_states,+ timestep,+ img_shapes,+ img_mask,+ encoder_hidden_states_mask = None,+ attention_kwargs = None,+ kv_cache = None,+ kv_cache_mode = None,+ return_dict = True,+ ):+ if torch.is_grad_enabled() or torch.compiler.is_compiling() or fast_step_disabled():+ return stock_inner(+ self,+ hidden_states,+ encoder_hidden_states,+ timestep,+ img_shapes,+ img_mask,+ encoder_hidden_states_mask = encoder_hidden_states_mask,+ attention_kwargs = attention_kwargs,+ kv_cache = kv_cache,+ kv_cache_mode = kv_cache_mode,+ return_dict = return_dict,+ )++ batch_size = hidden_states.shape[0]+ if kv_cache is not None and not self.config.causal_condition:+ raise ValueError(+ "kv_cache requires `causal_condition=True`. The cache is only valid because text and condition-image "+ "tokens modulate from t=0, which makes their activations independent of the denoising step."+ )+ if kv_cache is not None and kv_cache_mode not in ("extract", "cached"):+ raise ValueError(+ f"kv_cache_mode must be 'extract' or 'cached' when kv_cache is provided, got {kv_cache_mode!r}."+ )+ if kv_cache is None and kv_cache_mode is not None:+ raise ValueError(+ f"kv_cache_mode is {kv_cache_mode!r} but no kv_cache was passed to hold the prefix."+ )++ device = hidden_states.device+ lay = _layout_for(+ self, mod, img_mask, img_shapes, device, reuse_identity = kv_cache_mode == "cached"+ )+ dtype_key, text_dtype = _text_dtype(self, encoder_hidden_states)+ if (+ kv_cache_mode == "cached"+ and lay.tail_is_image+ and text_dtype is not None+ and self.config.causal_condition+ ):+ output = _cached_step(+ self, lay, text_dtype, hidden_states, timestep, encoder_hidden_states_mask, kv_cache+ )+ return (output,) if not return_dict else mod.Transformer2DModelOutput(sample = output)++ hidden_states = self.img_in(hidden_states)+ prefix_len = lay.prefix_len+ encoder_hidden_states = self.txt_in(encoder_hidden_states)+ self.__dict__["_unsloth_q21_text_dtype"][dtype_key] = encoder_hidden_states.dtype+ target_tokens = math.prod(img_shapes[0][-1])+ joint_hidden_states = torch.cat(+ [+ encoder_hidden_states,+ encoder_hidden_states.new_zeros(+ batch_size, target_tokens // 4, encoder_hidden_states.shape[2]+ ),+ ],+ dim = 1,+ )+ joint_hidden_states = joint_hidden_states.repeat_interleave(+ lay.repeats, dim = 1, output_size = lay.total+ )+ joint_hidden_states[:, lay.image_positions] = hidden_states++ rotary_emb = lay.rotary_emb+ target_token_mask = lay.target_token_mask++ timestep = timestep.to(hidden_states.dtype)+ if self.config.causal_condition:+ timestep = torch.cat([timestep, timestep.new_zeros(1)], dim = 0)+ modulation_mask = target_token_mask+ else:+ modulation_mask = None+ temb = self.time_text_embed(timestep, hidden_states)+ modulation = self.modulation(temb)++ joint_key_valid = None+ if encoder_hidden_states_mask is not None:+ joint_key_valid = torch.ones(batch_size, lay.total, dtype = torch.bool, device = device)+ joint_key_valid[:, lay.text_positions] = encoder_hidden_states_mask.bool()[+ :, _vlm_text(lay, encoder_hidden_states_mask.shape[1])+ ]++ if kv_cache_mode == "cached":+ joint_hidden_states = joint_hidden_states[:, prefix_len:]+ rotary_emb = rotary_emb[prefix_len:]+ modulation_mask = modulation_mask[prefix_len:]+ attention_mask = None if joint_key_valid is None else joint_key_valid[:, None, None, :]+ cache_write_slice = None+ block_segments, block_key_valid = None, None+ else:+ processors = [block.attn.processor for block in self.transformer_blocks]+ needs_block_mask = any(isinstance(processor, flex_cls) for processor in processors)+ attention_mask = (+ build_block_mask(lay.image_ids, joint_key_valid, batch_size, device)+ if needs_block_mask+ else None+ )+ block_segments = (+ None+ if all(isinstance(processor, flex_cls) for processor in processors)+ else _segments(lay, mod)+ )+ cache_write_slice = slice(0, prefix_len) if kv_cache_mode == "extract" else None+ block_key_valid = joint_key_valid++ for index_block, block in enumerate(self.transformer_blocks):+ layer_cache = kv_cache.get_layer(index_block) if kv_cache is not None else None+ joint_hidden_states = block(+ hidden_states = joint_hidden_states,+ modulation = modulation,+ rotary_emb = rotary_emb,+ attention_mask = attention_mask,+ target_token_mask = modulation_mask,+ layer_cache = layer_cache,+ kv_cache_mode = kv_cache_mode,+ cache_write_slice = cache_write_slice,+ segments = block_segments,+ key_valid = block_key_valid,+ )++ joint_hidden_states = self.norm_out(joint_hidden_states, temb, modulation_mask)+ output = self.proj_out(joint_hidden_states)++ if not return_dict:+ return (output,)+ return mod.Transformer2DModelOutput(sample = output)++ functools.update_wrapper(forward, stock_inner, assigned = ("__name__", "__doc__"), updated = ())+ wrapped = lora_scale("attention_kwargs")(forward) if callable(lora_scale) else forward+ wrapped.__unsloth_q21_fast_step__ = True+ wrapped.__unsloth_stock_forward__ = stock+ return wrapped+++def install(logger: Any = None) -> bool:+ if fast_step_disabled():+ return False+ try:+ import importlib+ mod = importlib.import_module(_MODULE)+ except Exception: # noqa: BLE001 - diffusers without Qwen-Image 2.1+ return False+ cls = getattr(mod, _CLASS, None)+ if cls is None:+ return False+ with _LOCK:+ current = vars(cls).get("forward")+ if getattr(current, "__unsloth_q21_fast_step__", False):+ return True+ why = why_unsupported(mod)+ if why is not None:+ if logger is not None:+ logger.info("diffusion.qwenimage21: stock forward kept: %s", why)+ return False+ try:+ fast = _make_forward(mod, current)+ except Exception as exc: # noqa: BLE001 - optimisation only+ if logger is not None:+ logger.warning("diffusion.qwenimage21: fast step unavailable: %s", exc)+ return False+ _INSTALLED[cls] = current+ cls.forward = fast+ if logger is not None:+ logger.info("diffusion.qwenimage21: denoiser step layout built once per render")+ return True+++def install_for_pipe(pipe: Any, logger: Any = None) -> bool:+ if type(getattr(pipe, "transformer", None)).__name__ != _CLASS:+ return False+ try:+ return install(logger)+ except Exception as exc: # noqa: BLE001 - optimisation only: the stock forward still runs+ if logger is not None:+ logger.warning("diffusion.qwenimage21: fast step unavailable: %s", exc)+ return False+++def uninstall() -> None:+ with _LOCK:+ for cls, stock in list(_INSTALLED.items()):+ if getattr(vars(cls).get("forward"), "__unsloth_q21_fast_step__", False):+ cls.forward = stock+ _INSTALLED.pop(cls, None)diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex ad79ab30520..d863f07ff8d 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -11704,3 +11704,52 @@ def test_a_prequant_repo_missing_its_artifact_marks_the_plan_incomplete(monkeypafailures), "a configured prequant that is not in its repo left the plan calling itself complete"assert "prequant artifact missing" in str(failures[0])+++def test_status_reports_cuda_graph_off_once_every_armed_step_ran_eager():+ backend = DiffusionBackend()+ handle = types.SimpleNamespace(+ cache = {},+ stats = {"captures": 0, "replays": 0, "eager_calls": 0, "refused_object": 0},+ poisoned = False,+ capture_error = None,+ )+ resolved = {+ "cuda_graph": {+ "value": "on",+ "requested": None,+ "source": "auto",+ "status": "applied",+ "reason": "denoiser step captured per input shape, replayed bit-identically",+ }+ }+ backend._state = _LoadState(+ pipe = object(),+ family = detect_family("unsloth/Z-Image-GGUF"),+ repo_id = "r",+ base_repo = "b",+ device = "cuda",+ dtype = "bfloat16",+ cpu_offload = False,+ speed_optims = ("compiled", "cuda_graph"),+ resolved = resolved,+ cuda_graphs = (handle,),+ )++ st = backend.status()+ assert st["resolved"]["cuda_graph"]["value"] == "on"+ assert st["speed_optims"] == ["compiled", "cuda_graph"]++ handle.stats.update(eager_calls = 25, refused_object = 25)+ st = backend.status()+ assert st["resolved"]["cuda_graph"]["value"] == "off"+ assert st["resolved"]["cuda_graph"]["reason"] == (+ "armed, but all 25 denoiser call(s) so far ran eager (25 with a non-tensor argument)"+ )+ assert st["speed_optims"] == ["compiled"]+ assert resolved["cuda_graph"]["value"] == "on"++ handle.stats.update(captures = 1, replays = 24)+ st = backend.status()+ assert st["resolved"]["cuda_graph"]["value"] == "on"+ assert st["speed_optims"] == ["compiled", "cuda_graph"]diff --git a/studio/backend/tests/test_diffusion_capture_safe.py b/studio/backend/tests/test_diffusion_capture_safe.pyindex 8e2e5454e19..cf6f8fe656a 100644--- a/studio/backend/tests/test_diffusion_capture_safe.py+++ b/studio/backend/tests/test_diffusion_capture_safe.py@@ -394,3 +394,28 @@ def test_real_diffusers_hunyuanimage_rewrite_is_bit_identical(fresh_cache):want = cls.forward(model, latents, timestep, **kw)[0]got = safe(model, latents, timestep, **kw)[0]assert torch.equal(want, got)+++def test_qwen_image_21_is_declined_with_the_reason(fresh_cache):+ QwenImage21Transformer2DModel = type(+ "QwenImage21Transformer2DModel", (), {"forward": lambda self, hidden_states: hidden_states}+ )+ forward, why = cs.resolve(QwenImage21Transformer2DModel)+ assert forward is None+ assert why == (+ "QwenImage21Transformer2DModel forward is not capture-safe (its pipeline passes the prefix KV "+ "cache as a Python object on every step and its forward syncs the host)"+ )+ Sub = type("Sub", (QwenImage21Transformer2DModel,), {"forward": lambda self, x: x})+ assert cs.resolve(Sub) == (None, None)+++def test_graph_eligible_declines_qwen_image_21_at_load(fresh_cache, monkeypatch):+ monkeypatch.delenv(cg.CUDA_GRAPH_DISABLE_ENV, raising = False)+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ QwenImage21Transformer2DModel = type(+ "QwenImage21Transformer2DModel", (), {"forward": lambda self, hidden_states: hidden_states}+ )+ ok, why = _eligible_for(QwenImage21Transformer2DModel())+ assert ok is False+ assert why.startswith("QwenImage21Transformer2DModel forward is not capture-safe")diff --git a/studio/backend/tests/test_diffusion_cuda_graph.py b/studio/backend/tests/test_diffusion_cuda_graph.pyindex 527b02c73d6..b02100b7875 100644--- a/studio/backend/tests/test_diffusion_cuda_graph.py+++ b/studio/backend/tests/test_diffusion_cuda_graph.py@@ -735,6 +735,9 @@ def test_stats_and_describe_are_json_safe(stub_torch):"eager_calls": 1,"fallbacks": 0,"cap_skips": 0,+ "refused_float": 0,+ "refused_host_tensor": 0,+ "refused_object": 0,"poisoned": False,"capture_error": None,}@@ -823,3 +826,94 @@ def test_real_cuda_capture_replays_bit_identically():assert torch.equal(after, want)finally:cg.uninstall_all([handle])+++_RESOLVED_ON = {+ "cuda_graph": {+ "value": "on",+ "requested": None,+ "source": "auto",+ "status": "applied",+ "reason": "denoiser step captured per input shape, replayed bit-identically",+ },+ "speed_mode": {"value": "max"},+}+++def test_live_status_is_unchanged_before_the_first_call(stub_torch):+ handle = _armed()+ resolved, optims = cg.live_status(_RESOLVED_ON, ("compiled", "cuda_graph"), (handle,))+ assert resolved is _RESOLVED_ON+ assert optims == ["compiled", "cuda_graph"]+ assert cg.never_engaged((handle,)) is None+ assert cg.never_engaged(()) is None+++def test_live_status_turns_off_when_every_call_was_refused(stub_torch):+ class KVCache:+ pass++ handle = _armed()+ for _ in range(3):+ handle(_t(), timestep = KVCache(), return_dict = False)+ assert handle.stats["refused_object"] == 3++ resolved, optims = cg.live_status(_RESOLVED_ON, ("compiled", "cuda_graph"), (handle,))+ assert resolved["cuda_graph"]["value"] == "off"+ assert resolved["cuda_graph"]["reason"] == (+ "armed, but all 3 denoiser call(s) so far ran eager (3 with a non-tensor argument)"+ )+ assert resolved["cuda_graph"]["status"] == "applied"+ assert resolved["speed_mode"] is _RESOLVED_ON["speed_mode"]+ assert optims == ["compiled"]+ assert _RESOLVED_ON["cuda_graph"]["value"] == "on"+ assert json.loads(json.dumps(resolved)) == resolved+++def test_live_status_names_float_refusals_and_a_poisoned_capture(stub_torch):+ handle = _armed()+ handle(_t(), timestep = 0.5, return_dict = False)+ assert "1 with a float argument" in cg.never_engaged((handle,))++ poisoned = _armed()+ poisoned(_t(device_type = "cpu"), timestep = _t((1,)), return_dict = False)+ assert cg.never_engaged((poisoned,)) == (+ "capture failed (RuntimeError); every denoiser step runs eager"+ )+++def test_live_status_turns_off_when_a_graph_that_replayed_is_poisoned(stub_torch):+ handle = _armed()+ handle(_t(), timestep = _t((1,)), return_dict = False)+ handle(_t(), timestep = _t((1,)), return_dict = False)+ assert handle.stats["replays"] == 2 and cg.never_engaged((handle,)) is None+ # A later shape whose capture fails poisons the wrapper: it never replays again.+ handle(_t(device_type = "cpu"), timestep = _t((1,)), return_dict = False)+ assert handle.poisoned+ resolved, optims = cg.live_status(_RESOLVED_ON, ("compiled", "cuda_graph"), (handle,))+ assert resolved["cuda_graph"]["value"] == "off"+ assert resolved["cuda_graph"]["reason"] == (+ "capture failed (RuntimeError); every denoiser step runs eager"+ )+ assert optims == ["compiled"]+ other = _armed()+ other(_t(), timestep = _t((1,)), return_dict = False)+ assert cg.never_engaged((handle, other)) is None+++def test_live_status_keeps_on_once_a_graph_replayed(stub_torch):+ handle = _armed()+ handle(_t(), timestep = _t((1,)), return_dict = False)+ handle(_t(), timestep = _t((1,)), return_dict = False)+ handle(_t(), timestep = 0.25, return_dict = False)+ assert handle.stats["replays"] == 2+ resolved, optims = cg.live_status(_RESOLVED_ON, ("cuda_graph",), (handle,))+ assert resolved is _RESOLVED_ON+ assert optims == ["cuda_graph"]+++def test_live_status_tolerates_a_record_without_the_control(stub_torch):+ handle = _armed()+ handle(_t(), timestep = 0.5, return_dict = False)+ assert cg.live_status(None, ("cuda_graph",), (handle,)) == (None, [])+ assert cg.live_status({}, (), (handle,)) == ({}, [])diff --git a/studio/backend/tests/test_diffusion_qwenimage21.py b/studio/backend/tests/test_diffusion_qwenimage21.pynew file mode 100644index 00000000000..77db17fd76a--- /dev/null+++ b/studio/backend/tests/test_diffusion_qwenimage21.py@@ -0,0 +1,387 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Stock vs fast Qwen-Image-2.1 forward, bit for bit; skipped without Qwen-Image 2.1 in diffusers."""++from __future__ import annotations++import importlib+import types++import pytest++from core.inference import diffusion_qwenimage21 as q++torch = pytest.importorskip("torch")+qmod = pytest.importorskip("diffusers.models.transformers.transformer_qwenimage21")++[email protected](autouse = True)+def _stock_after(monkeypatch):+ monkeypatch.delenv(q.FAST_STEP_ENV, raising = False)+ q.uninstall()+ yield+ q.uninstall()+++def _model():+ torch.manual_seed(0)+ m = qmod.QwenImage21Transformer2DModel(+ num_layers = 2,+ attention_head_dim = 16,+ num_attention_heads = 2,+ context_in_dim = 24,+ in_channels = 8,+ out_channels = 8,+ axes_dims_rope = (4, 6, 6),+ ).eval()+ with torch.no_grad():+ for p in m.parameters():+ p.normal_(0, 0.2)+ return m+++def _inputs(+ batch = 1,+ text = 9,+ cond = None,+ target = (4, 6),+ pad = 0,+ seed = 7,+):+ g = torch.Generator().manual_seed(seed)+ th, tw = target+ shapes = []+ latents = []+ if cond is None:+ vlm = torch.zeros(text, dtype = torch.bool)+ else:+ ch, cw = cond+ vlm = torch.cat(+ [+ torch.zeros(text // 2, dtype = torch.bool),+ torch.ones(ch * cw // 4, dtype = torch.bool),+ torch.zeros(text - text // 2, dtype = torch.bool),+ ]+ )+ shapes.append((1, ch, cw))+ latents.append(torch.randn(batch, ch * cw, 8, generator = g))+ shapes.append((1, th, tw))+ img_mask = torch.cat([vlm, torch.ones(th * tw // 4, dtype = torch.bool)])[None].repeat(batch, 1)+ mask = None+ if pad:+ mask = torch.ones(batch, vlm.numel(), dtype = torch.long)+ mask[-1, -pad:] = 0+ return {+ "encoder_hidden_states": torch.randn(batch, vlm.numel(), 24, generator = g),+ "encoder_hidden_states_mask": mask,+ "img_shapes": [shapes] * batch,+ "img_mask": img_mask,+ "cond": torch.cat(latents, 1) if latents else None,+ "latents": torch.randn(batch, th * tw, 8, generator = g),+ }+++def _render(+ m,+ inp,+ steps = 4,+ cache = True,+):+ outs = []+ kv = qmod.QwenImage21KVCache(len(m.transformer_blocks)) if cache else None+ lat = inp["latents"]+ with torch.inference_mode():+ for i in range(steps):+ hs = lat if inp["cond"] is None else torch.cat([inp["cond"], lat], 1)+ out = m(+ hidden_states = hs,+ timestep = torch.full((hs.shape[0],), 1.0 - i / steps),+ encoder_hidden_states = inp["encoder_hidden_states"],+ encoder_hidden_states_mask = inp["encoder_hidden_states_mask"],+ img_shapes = inp["img_shapes"],+ img_mask = inp["img_mask"],+ kv_cache = kv,+ kv_cache_mode = None if not cache else ("extract" if i == 0 else "cached"),+ return_dict = False,+ )[0]+ outs.append(out.clone())+ lat = lat - 0.1 * out[:, -lat.shape[1] :]+ return outs+++CASES = [+ {},+ {"batch": 2, "pad": 3},+ {"cond": (4, 4)},+ {"batch": 2, "cond": (4, 8), "target": (6, 4), "pad": 2},+]++[email protected]("case", CASES)[email protected]("cache", [True, False])+def test_fast_step_is_bit_identical_to_the_stock_forward(case, cache):+ m = _model()+ inp = _inputs(**case)+ ref = _render(m, inp, cache = cache)+ assert q.install()+ assert getattr(type(m).forward, "__unsloth_q21_fast_step__", False)+ first = _render(m, inp, cache = cache)+ again = _render(m, _inputs(**case), cache = cache)+ for a, b, c in zip(ref, first, again):+ assert torch.equal(a, b)+ assert torch.equal(a, c)+++def test_layout_is_built_once_per_render_and_found_by_content():+ m = _model()+ assert q.install()+ calls = {"n": 0}+ real = q._build_layout++ def counting(*a, **k):+ calls["n"] += 1+ return real(*a, **k)++ q._build_layout = counting+ try:+ inp = _inputs()+ _render(m, inp, steps = 5)+ assert calls["n"] == 1+ _render(m, _inputs(), steps = 5)+ assert calls["n"] == 1+ _render(m, _inputs(text = 11), steps = 3)+ assert calls["n"] == 2+ finally:+ q._build_layout = real+++def test_a_different_layout_of_the_same_length_is_not_reused():+ m = _model()+ a = _inputs(text = 8, cond = (4, 4))+ b = _inputs(text = 8, cond = (4, 4))+ vlm = b["img_mask"][0, :12].clone()+ b["img_mask"][:, :12] = vlm.roll(3)+ ref_b = _render(m, b)+ assert q.install()+ _render(m, a)+ got_b = _render(m, b)+ for x, y in zip(ref_b, got_b):+ assert torch.equal(x, y)+++def test_grad_and_kill_switch_take_the_stock_forward(monkeypatch):+ m = _model()+ assert q.install()+ inp = _inputs()+ seen = []+ real = q._layout_for+ monkeypatch.setattr(q, "_layout_for", lambda *a, **k: seen.append(1) or real(*a, **k))+ kv = qmod.QwenImage21KVCache(len(m.transformer_blocks))+ with torch.enable_grad():+ m(+ hidden_states = inp["latents"],+ timestep = torch.ones(1),+ encoder_hidden_states = inp["encoder_hidden_states"],+ img_shapes = inp["img_shapes"],+ img_mask = inp["img_mask"],+ kv_cache = kv,+ kv_cache_mode = "extract",+ return_dict = False,+ )+ assert seen == []+ monkeypatch.setenv(q.FAST_STEP_ENV, "0")+ _render(m, inp, steps = 2)+ assert seen == []+ monkeypatch.delenv(q.FAST_STEP_ENV)+ _render(m, inp, steps = 2)+ assert seen+++def test_stock_errors_are_kept():+ m = _model()+ assert q.install()+ inp = _inputs()+ with pytest.raises(ValueError, match = "kv_cache_mode"):+ with torch.inference_mode():+ m(+ hidden_states = inp["latents"],+ timestep = torch.ones(1),+ encoder_hidden_states = inp["encoder_hidden_states"],+ img_shapes = inp["img_shapes"],+ img_mask = inp["img_mask"],+ kv_cache_mode = "cached",+ )+++def test_install_is_idempotent_and_uninstall_restores_the_stock_forward():+ cls = qmod.QwenImage21Transformer2DModel+ stock = vars(cls)["forward"]+ assert q.install() and q.install()+ patched = vars(cls)["forward"]+ assert patched is not stock+ assert patched.__unsloth_stock_forward__ is stock+ import inspect++ assert inspect.signature(patched) == inspect.signature(stock)+ q.uninstall()+ assert vars(cls)["forward"] is stock+ q.uninstall()+ assert vars(cls)["forward"] is stock+++def test_installed_diffusers_matches_the_fingerprints():+ """On failure: re-check the fast forward against the new stock function, then add its digest."""+ assert q.why_unsupported(qmod) is None+++def test_a_drifted_function_keeps_the_stock_forward(monkeypatch):+ fake = types.SimpleNamespace(**vars(qmod))++ def _qwenimage21_prefix_segments(image_ids, prefix_len):+ return []++ fake._qwenimage21_prefix_segments = _qwenimage21_prefix_segments+ assert "prefix_segments differs" in q.why_unsupported(fake)+ real_import = importlib.import_module+ monkeypatch.setattr(+ importlib,+ "import_module",+ lambda name, *a: fake if name == q._MODULE else real_import(name, *a),+ )+ cls = qmod.QwenImage21Transformer2DModel+ stock = vars(cls)["forward"]+ assert q.install() is False+ assert vars(cls)["forward"] is stock+++def test_kill_switch_blocks_install(monkeypatch):+ monkeypatch.setenv(q.FAST_STEP_ENV, "off")+ assert q.install() is False+ assert not getattr(+ vars(qmod.QwenImage21Transformer2DModel)["forward"], "__unsloth_q21_fast_step__", False+ )++[email protected](not torch.cuda.is_available(), reason = "needs CUDA for the sync check")+def test_cached_steps_do_not_sync_the_host():+ m = _model().to("cuda")+ inp = {+ k: (v.to("cuda") if torch.is_tensor(v) else v) for k, v in _inputs(batch = 2, pad = 2).items()+ }+ assert q.install()+ kv = qmod.QwenImage21KVCache(len(m.transformer_blocks))+ with torch.inference_mode():+ for i in range(4):+ if i >= 2:+ torch.cuda.set_sync_debug_mode("error")+ try:+ m(+ hidden_states = inp["latents"],+ timestep = torch.full((2,), 0.5, device = "cuda"),+ encoder_hidden_states = inp["encoder_hidden_states"],+ encoder_hidden_states_mask = inp["encoder_hidden_states_mask"],+ img_shapes = inp["img_shapes"],+ img_mask = inp["img_mask"],+ kv_cache = kv,+ kv_cache_mode = "extract" if i == 0 else "cached",+ return_dict = False,+ )+ finally:+ torch.cuda.set_sync_debug_mode("default")+++def test_digest_ignores_docstrings_comments_and_blank_lines_only():+ import linecache++ src = "def f(x):\n '''doc'''\n # note\n y = x + 1 # why\n\n return y\n"+ other = "def f(x):\n y = x + 1\n return y\n"+ changed = "def f(x):\n y = x + 2\n return y\n"+ digests = []+ for i, text in enumerate((src, other, changed)):+ name = f"<q21-digest-{i}>"+ linecache.cache[name] = (len(text), None, text.splitlines(True), name)+ scope: dict = {}+ exec(compile(text, name, "exec"), scope)+ digests.append(q._digest(scope["f"]))+ assert digests[0] == digests[1] != digests[2]+++def test_install_for_pipe_only_touches_qwen_image_21_and_never_raises(monkeypatch):+ calls = []+ monkeypatch.setattr(q, "install", lambda logger = None: calls.append(1) or True)+ assert q.install_for_pipe(types.SimpleNamespace(transformer = object())) is False+ assert q.install_for_pipe(types.SimpleNamespace()) is False+ assert calls == []+ pipe = types.SimpleNamespace(+ transformer = qmod.QwenImage21Transformer2DModel.__new__(qmod.QwenImage21Transformer2DModel)+ )+ assert q.install_for_pipe(pipe) is True and calls == [1]+ monkeypatch.setattr(+ q, "install", lambda logger = None: (_ for _ in ()).throw(RuntimeError("boom"))+ )+ assert q.install_for_pipe(pipe) is False+++def test_a_mask_rewritten_in_place_between_renders_gets_its_new_layout():+ m = _model()+ inp = _inputs(text = 8, cond = (4, 4), pad = 2)+ assert q.install()+ _render(m, inp)+ inp["img_mask"][:, :12] = inp["img_mask"][:, :12].roll(3, dims = 1).clone()+ got = _render(m, inp)+ q.uninstall()+ ref = _render(m, inp)+ for a, b in zip(ref, got):+ assert torch.equal(a, b)+++def test_a_cached_layout_does_not_alias_the_callers_mask():+ m = _model()+ inp = _inputs(text = 8, cond = (4, 4), pad = 2)+ assert q.install()+ _render(m, dict(inp, encoder_hidden_states_mask = None))+ original = inp["img_mask"].clone()+ inp["img_mask"][:, :12] = inp["img_mask"][:, :12].roll(3, dims = 1).clone()+ fresh = dict(inp, img_mask = original)+ got = _render(m, fresh)+ q.uninstall()+ ref = _render(m, fresh)+ for a, b in zip(ref, got):+ assert torch.equal(a, b)++[email protected]("prefill, decode", [(False, True), (True, False), (True, True)])+def test_an_autocast_change_between_steps_matches_the_stock_forward(prefill, decode):+ m = _model()+ inp = _inputs(pad = 2)++ def render():+ outs = []+ kv = qmod.QwenImage21KVCache(len(m.transformer_blocks))+ lat = inp["latents"]+ with torch.inference_mode():+ for i in range(3):+ with torch.autocast(+ "cpu", dtype = torch.bfloat16, enabled = prefill if i == 0 else decode+ ):+ out = m(+ hidden_states = lat,+ timestep = torch.full((1,), 1.0 - i / 3),+ encoder_hidden_states = inp["encoder_hidden_states"],+ encoder_hidden_states_mask = inp["encoder_hidden_states_mask"],+ img_shapes = inp["img_shapes"],+ img_mask = inp["img_mask"],+ kv_cache = kv,+ kv_cache_mode = "extract" if i == 0 else "cached",+ return_dict = False,+ )[0]+ outs.append(out.float().clone())+ lat = lat - 0.1 * out.float()[:, -lat.shape[1] :]+ return outs++ ref = render()+ assert q.install()+ got = render()+ for a, b in zip(ref, got):+ assert torch.equal(a, b)