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: fused fp16 Wan block kernels on T4 (Wan2.2-5B 11.7 to 10.0 s per step, within base's spread) (#12531)

Daniel Han0f14c9ec9508
diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.py
index 0c739dedbb4..c564794f0ea 100644
--- a/studio/backend/core/inference/diffusion_memory.py
+++ b/studio/backend/core/inference/diffusion_memory.py
@@ -3453,6 +3453,7 @@ def _pin_top_level_group(
or getattr(group, "offload_to_disk_path", None)
or getattr(getattr(group, "onload_device", None), "type", None) != "cuda"
or getattr(group, "_unsloth_pinned_top", False)
+ or getattr(group, "_unsloth_top_no_copy_back", False)
):
return False
tensors: list = []
@@ -3531,6 +3532,87 @@ def _pin_top_level_group(
return False
+def _skip_top_level_copy_back(module: Any, logger: Any = None) -> bool:
+ """Fallback when ``_pin_top_level_group`` cannot pin: offload re-points to the group's existing host tensors
+ instead of copying the (inference-constant) weights back on the compute stream. Same kill switch as the pinned path."""
+ if (os.environ.get(PIN_TOP_GROUP_ENV) or "").strip().lower() in ("0", "off", "false", "no"):
+ return False
+ try:
+ import torch
+ from diffusers.hooks import group_offloading as go
+
+ registry = getattr(module, "_diffusers_hook", None)
+ get_hook = getattr(registry, "get_hook", None)
+ hook = (
+ get_hook(getattr(go, "_GROUP_OFFLOADING", "group_offloading"))
+ if callable(get_hook)
+ else None
+ )
+ group = getattr(hook, "group", None)
+ if (
+ group is None
+ or getattr(group, "stream", None) is not None
+ or getattr(group, "offload_to_disk_path", None)
+ or getattr(getattr(group, "onload_device", None), "type", None) != "cuda"
+ or getattr(group, "_unsloth_pinned_top", False)
+ or getattr(group, "_unsloth_top_no_copy_back", False)
+ ):
+ return False
+ tensors: list = []
+ seen: set = set()
+ for tensor in (
+ [p for m in group.modules for p in m.parameters()]
+ + [b for m in group.modules for b in m.buffers()]
+ + list(group.parameters or [])
+ + list(group.buffers or [])
+ ):
+ if id(tensor) not in seen:
+ seen.add(id(tensor))
+ tensors.append(tensor)
+ is_torchao = getattr(go, "_is_torchao_tensor", None)
+ if not tensors or (callable(is_torchao) and any(is_torchao(t) for t in tensors)):
+ return False
+ if any(type(t) not in (torch.Tensor, torch.nn.Parameter) for t in tensors):
+ return False
+ host = {t: (t.data if t.data.device.type == "cpu" else t.data.cpu()) for t in tensors}
+ device = group.onload_device
+
+ def onload_() -> None:
+ for tensor, cpu in list(host.items()):
+ current = tensor.data
+ if current.device.type == "cpu" and current.data_ptr() != cpu.data_ptr():
+ # replaced while offloaded (a .to() conversion, an adapter fused on the host): upload that instead
+ cpu = current
+ host[tensor] = cpu
+ tensor.data = cpu.to(device)
+
+ def offload_() -> None:
+ for tensor, cpu in host.items():
+ tensor.data = cpu
+
+ disable = getattr(getattr(torch, "compiler", None), "disable", None)
+ if callable(disable):
+ onload_, offload_ = disable(onload_), disable(offload_)
+ offload_()
+ group.onload_ = onload_
+ group.offload_ = offload_
+ group._unsloth_top_no_copy_back = True
+ if logger is not None:
+ logger.info(
+ "diffusion.memory: %s top-level weights (%d MiB) not pinnable here; offload re-points to the host "
+ "copy instead of copying them back",
+ type(module).__name__,
+ sum(int(t.numel()) * int(t.element_size()) for t in tensors) >> 20,
+ )
+ return True
+ except Exception as exc: # noqa: BLE001 - diffusers keeps its own path
+ if logger is not None:
+ logger.debug(
+ "diffusion.memory: top-level group copy-back left as diffusers built it (%s)", exc
+ )
+ return False
+
+
def _apply_group_offload(
pipe: Any,
device: str,
@@ -3659,8 +3741,8 @@ def _apply_group_offload(
module, **_torchao_group_offload_kwargs(module, gkwargs, pinned_mib)
)
installed += 1
- if use_stream:
- _pin_top_level_group(module, logger, pinned_mib)
+ if use_stream and not _pin_top_level_group(module, logger, pinned_mib):
+ _skip_top_level_copy_back(module, logger)
if resident_transformer_mib:
room = int(resident_transformer_mib)
for module in streamed.values():
@@ -4320,8 +4402,12 @@ def _apply_streaming_offload(
if pin and defer and kwargs.get("use_stream") and kwargs.get("low_cpu_mem_usage"):
_defer_pinning(pipe, module, onload, logger)
installed += 1
- if use_stream and offload_type == "block_level":
- _pin_top_level_group(module, logger, pinned_mib)
+ if (
+ use_stream
+ and offload_type == "block_level"
+ and not _pin_top_level_group(module, logger, pinned_mib)
+ ):
+ _skip_top_level_copy_back(module, logger)
if offload_type == "leaf_level":
_pin_vision_embedding_device(module)
if resident_transformer_mib:
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index ef73841f874..48da7d76205 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -3720,8 +3720,10 @@ class VideoBackend:
self._precommit_globals = None
restore_backend_flags(flags)
from . import diffusion_gguf_compile
+ from . import video_wan_fused
diffusion_gguf_compile.uninstall_all()
+ video_wan_fused.uninstall()
# LTX-2.3 gets DiT/connectors/VAEs/vocoder from the checkpoint + extras, so only the 2.0 base scheduler / text
# encoder / tokenizer are pulled.
@@ -6273,6 +6275,16 @@ class VideoBackend:
"(quantized transformer must be compiled; eager is ~30x slower)"
)
effective_speed = SPEED_DEFAULT
+ # Before the step cache and apply_memory_plan: their hooks capture the block forward when they attach.
+ from . import video_wan_fused
+
+ wan_fused_engaged = False
+ if effective_speed != SPEED_OFF:
+ wan_fused_engaged = video_wan_fused.install_for_pipe(
+ pipe, dtype, getattr(target, "device", "cuda"), logger = logger
+ )
+ else:
+ video_wan_fused.uninstall()
# "off"/"fbcache" pinned; unset/"auto" only on max, by FBCACHE_MIN_STEPS. Run per expert.
cache_request = normalize_transformer_cache(transformer_cache)
cache_auto = transformer_cache is None or cache_request == TC_AUTO
@@ -6415,6 +6427,8 @@ class VideoBackend:
speed_optims += ("hunyuan_attn_trim",)
if hv15_mask_engaged:
speed_optims += ("hv15_vae_vector_mask",)
+ if wan_fused_engaged:
+ speed_optims += ("wan_fused_adaln",)
with self._generate_lock:
# A cancelled/superseded load must not place weights on a GPU the arbiter may have reassigned; recheck
# before placement.
@@ -9391,8 +9405,11 @@ class VideoBackend:
# speed=off load is bit-identical.
from . import diffusion_gguf_compile
from . import diffusion_cuda_graph
+ from . import video_wan_fused
diffusion_gguf_compile.uninstall_all()
+ # The fused Wan block forward is class-level: a later bf16 / speed=off load gets the stock one back.
+ video_wan_fused.uninstall()
from . import diffusion_prompt_cache
diffusion_prompt_cache.release(getattr(state, "pipe", None))
diff --git a/studio/backend/core/inference/video_wan_fused.py b/studio/backend/core/inference/video_wan_fused.py
new file mode 100644
index 00000000000..212b50c4e20
--- /dev/null
+++ b/studio/backend/core/inference/video_wan_fused.py
@@ -0,0 +1,698 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Fused fp16 Triton kernels for diffusers' ``WanTransformerBlock`` (T4 and other fp16-only GPUs).
+
+Stock keeps norm / AdaLN modulation / gated residuals / rotary in float32 tensors (a float32 ``[B, L, 6, D]`` table per
+block for TI2V-5B). The kernels do the same per-element math, rounding in float32 exactly where the stock op chain does
+and to fp16 once, so the output is bit-identical (self-checked once per device before use). LayerNorm stats come from
+``native_layer_norm`` on the fp16 rows, bit-identical to ``layer_norm(x.float())`` (4-wide vectorised loads either way).
+Scope: fingerprinted block, fp16 CUDA (non-ROCm), no grad, not compiling. Kill switches
+``UNSLOTH_DIFFUSION_WAN_FUSED_ADALN=0`` (all), ``UNSLOTH_DIFFUSION_WAN_FUSED_ROPE=0`` (rotary only).
+"""
+
+from __future__ import annotations
+
+import functools
+import os
+import threading
+from typing import Any, Callable, Optional
+
+WAN_FUSED_ENV = "UNSLOTH_DIFFUSION_WAN_FUSED_ADALN"
+# rotary only (the block fusion stays): UNSLOTH_DIFFUSION_WAN_FUSED_ROPE=0
+WAN_FUSED_ROPE_ENV = "UNSLOTH_DIFFUSION_WAN_FUSED_ROPE"
+_MODULE = "diffusers.models.transformers.transformer_wan"
+_CLASS = "WanTransformerBlock"
+# ``_digest(WanTransformerBlock.forward)``: identical in diffusers 0.36.0, 0.37.0, 0.40.0 and main (80c7ed26).
+_FINGERPRINTS = frozenset({"69aa0565fb00eeae"})
+# ``_digest(WanAttnProcessor.__call__)``: identical in diffusers 0.37.0, 0.40.0 and main (80c7ed26); 0.36.0 differs
+# and keeps the stock attention (the block fusion still applies).
+_ATTN_FINGERPRINTS = frozenset({"6c5a5095338dfe67"})
+
+_LOCK = threading.Lock()
+_STATE: dict = {}
+# (device index, temb rank, has norm2 affine) -> True once the fused block matched the stock block bit for bit
+_VERIFIED: dict = {}
+# keys whose self-check ran out of memory once (a second OOM caches stock)
+_VERIFY_OOM: set = set()
+# fused block calls since install (engagement evidence for tests and the A/B harness)
+_COUNTS = {"fused": 0, "stock": 0}
+
+
+def disabled() -> bool:
+ return (os.environ.get(WAN_FUSED_ENV) or "").strip().lower() in ("0", "off", "false", "no")
+
+
+def wanted(dtype: Any, device: Any = "cuda") -> bool:
+ """Only an fp16 CUDA (non-ROCm) load with Triton available: bf16 / fp32 loads keep the stock forward."""
+ 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(getattr(torch, "version", None), "hip", None):
+ return False
+ return _kernels() is not None
+
+
[email protected]_cache(maxsize = 1)
+def _kernels() -> Optional[dict]:
+ """Build the Triton kernels once; None when Triton is unavailable (the stock forward then stays)."""
+ try:
+ import triton
+ import triton.language as tl
+ except Exception: # noqa: BLE001
+ return None
+
+ @triton.jit
+ def _mul_rn(a, b):
+ # A product rounded on its own. ``enable_fp_fusion=False`` alone is not enough: ptxas still contracts
+ # ``mul.rn.f32x2`` + ``add.rn.f32x2`` into FFMA2 on sm_100, so the multiply is opaque inline PTX.
+ return tl.inline_asm_elementwise(
+ "mul.rn.f32 $0, $1, $2;", "=r,r,r", [a, b], dtype = tl.float32, is_pure = True, pack = 1
+ )
+
+ @triton.jit
+ def _modnorm(
+ X,
+ MEAN,
+ RSTD,
+ T,
+ TBL,
+ OUT,
+ D,
+ L,
+ stb,
+ stl,
+ stk,
+ sbk,
+ K_SHIFT: tl.constexpr,
+ K_SCALE: tl.constexpr,
+ BLOCK: tl.constexpr,
+ ):
+ # out = fp16((rstd * (x - mean)) * (1 + (tbl[scale] + temb[scale])) + (tbl[shift] + temb[shift]))
+ # int64: the per-token temb offset l * 6 * D passes 2**31 from 116,510 tokens at D=3072 (a 529-frame 1280x704
+ # TI2V-5B clip), and an int32 product wraps to a read outside temb.
+ row = tl.program_id(0).to(tl.int64)
+ col = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK)
+ mask = col < D
+ b = row // L
+ l = row - b * L
+ x = tl.load(X + row * D + col, mask = mask, other = 0.0).to(tl.float32)
+ mean = tl.load(MEAN + row)
+ rstd = tl.load(RSTD + row)
+ trow = T + b * stb + l * stl + col
+ t_sh = tl.load(trow + K_SHIFT * stk, mask = mask, other = 0.0).to(tl.float32)
+ t_sc = tl.load(trow + K_SCALE * stk, mask = mask, other = 0.0).to(tl.float32)
+ g_sh = tl.load(TBL + K_SHIFT * sbk + col, mask = mask, other = 0.0).to(tl.float32)
+ g_sc = tl.load(TBL + K_SCALE * sbk + col, mask = mask, other = 0.0).to(tl.float32)
+ ln = _mul_rn(rstd, x - mean)
+ scale = 1.0 + (g_sc + t_sc)
+ shift = g_sh + t_sh
+ y = _mul_rn(ln, scale)
+ y = y + shift
+ tl.store(OUT + row * D + col, y.to(OUT.dtype.element_ty), mask = mask)
+
+ @triton.jit
+ def _gate_residual(
+ X, A, T, TBL, OUT, D, L, stb, stl, stk, sbk, K_GATE: tl.constexpr, BLOCK: tl.constexpr
+ ):
+ # out = fp16(x.float() + a.float() * (tbl[gate] + temb[gate]))
+ row = tl.program_id(0).to(tl.int64) # int64 temb offset, as in _modnorm
+ col = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK)
+ mask = col < D
+ b = row // L
+ l = row - b * L
+ x = tl.load(X + row * D + col, mask = mask, other = 0.0).to(tl.float32)
+ a = tl.load(A + row * D + col, mask = mask, other = 0.0).to(tl.float32)
+ t_g = tl.load(T + b * stb + l * stl + K_GATE * stk + col, mask = mask, other = 0.0).to(
+ tl.float32
+ )
+ g_g = tl.load(TBL + K_GATE * sbk + col, mask = mask, other = 0.0).to(tl.float32)
+ gate = g_g + t_g
+ y = _mul_rn(a, gate)
+ y = x + y
+ tl.store(OUT + row * D + col, y.to(OUT.dtype.element_ty), mask = mask)
+
+ @triton.jit
+ def _affine_norm(X, MEAN, RSTD, W, BIAS, OUT, D, BLOCK: tl.constexpr):
+ # out = fp16(fma(w, rstd * (x - mean), b)): PyTorch's vectorised kernel writes ``gamma * (...) + beta``, which
+ # nvcc contracts to one fma; checked bit for bit by the self-check.
+ row = tl.program_id(0)
+ col = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK)
+ mask = col < D
+ x = tl.load(X + row * D + col, mask = mask, other = 0.0).to(tl.float32)
+ mean = tl.load(MEAN + row)
+ rstd = tl.load(RSTD + row)
+ w = tl.load(W + col, mask = mask, other = 0.0).to(tl.float32)
+ bb = tl.load(BIAS + col, mask = mask, other = 0.0).to(tl.float32)
+ y = tl.fma(w, _mul_rn(rstd, x - mean), bb)
+ tl.store(OUT + row * D + col, y.to(OUT.dtype.element_ty), mask = mask)
+
+ @triton.jit
+ def _rope(
+ X, COS, SIN, OUT, L, scl, ssl, PAIRS: tl.constexpr, HALF: tl.constexpr, BLOCK: tl.constexpr
+ ):
+ # WanAttnProcessor's rotary on one (batch, position) row of a contiguous [B, L, H, D] fp16 q / k:
+ # out[0::2] = x1 * cos[0::2] - x2 * sin[1::2]; out[1::2] = x1 * sin[1::2] + x2 * cos[0::2]
+ # each product a float32 multiply of the fp16 input by the float32 table, rounded on its own; then one fp16
+ # rounding where the stock assignment into the fp16 ``out`` casts.
+ row = tl.program_id(0)
+ l = row % L
+ idx = tl.arange(0, BLOCK)
+ mask = idx < PAIRS
+ i = idx % HALF
+ xo = X + row * (2 * PAIRS) + 2 * idx
+ x1 = tl.load(xo, mask = mask, other = 0.0).to(tl.float32)
+ x2 = tl.load(xo + 1, mask = mask, other = 0.0).to(tl.float32)
+ c = tl.load(COS + l * scl + 2 * i, mask = mask, other = 0.0).to(tl.float32)
+ sn = tl.load(SIN + l * ssl + 2 * i + 1, mask = mask, other = 0.0).to(tl.float32)
+ even = _mul_rn(x1, c) - _mul_rn(x2, sn)
+ odd = _mul_rn(x1, sn) + _mul_rn(x2, c)
+ oo = OUT + row * (2 * PAIRS) + 2 * idx
+ tl.store(oo, even.to(OUT.dtype.element_ty), mask = mask)
+ tl.store(oo + 1, odd.to(OUT.dtype.element_ty), mask = mask)
+
+ block = 1024
+
+ def _grid(rows: int, d: int) -> tuple:
+ return (rows, triton.cdiv(d, block))
+
+ def _temb_strides(temb: Any) -> tuple:
+ # [B, L, 6, D] (Wan2.2-TI2V per-token) or [B, 6, D] (one modulation per sample: L stride 0)
+ if temb.dim() == 4:
+ return temb.stride(0), temb.stride(1), temb.stride(2)
+ return temb.stride(0), 0, temb.stride(1)
+
+ def modnorm(x, mean, rstd, temb, table, k_shift: int, k_scale: int):
+ import torch
+
+ B, L, D = x.shape
+ out = torch.empty_like(x)
+ stb, stl, stk = _temb_strides(temb)
+ _modnorm[_grid(B * L, D)](
+ x,
+ mean,
+ rstd,
+ temb,
+ table,
+ out,
+ D,
+ L,
+ stb,
+ stl,
+ stk,
+ table.stride(-2),
+ K_SHIFT = k_shift,
+ K_SCALE = k_scale,
+ BLOCK = block,
+ num_warps = 4,
+ enable_fp_fusion = False,
+ )
+ return out
+
+ def gate_residual(x, a, temb, table, k_gate: int):
+ import torch
+
+ B, L, D = x.shape
+ out = torch.empty_like(x)
+ stb, stl, stk = _temb_strides(temb)
+ _gate_residual[_grid(B * L, D)](
+ x,
+ a,
+ temb,
+ table,
+ out,
+ D,
+ L,
+ stb,
+ stl,
+ stk,
+ table.stride(-2),
+ K_GATE = k_gate,
+ BLOCK = block,
+ num_warps = 4,
+ enable_fp_fusion = False,
+ )
+ return out
+
+ def affine_norm(x, mean, rstd, weight, bias):
+ import torch
+
+ B, L, D = x.shape
+ out = torch.empty_like(x)
+ _affine_norm[_grid(B * L, D)](
+ x,
+ mean,
+ rstd,
+ weight,
+ bias,
+ out,
+ D,
+ BLOCK = block,
+ num_warps = 4,
+ enable_fp_fusion = False,
+ )
+ return out
+
+ def rope(x, cos, sin):
+ import torch
+
+ B, L, H, D = x.shape
+ out = torch.empty_like(x)
+ pairs = H * (D // 2)
+ _rope[(B * L,)](
+ x,
+ cos,
+ sin,
+ out,
+ L,
+ cos.stride(1),
+ sin.stride(1),
+ PAIRS = pairs,
+ HALF = D // 2,
+ BLOCK = triton.next_power_of_2(pairs),
+ num_warps = 4 if pairs <= 2048 else 8,
+ enable_fp_fusion = False,
+ )
+ return out
+
+ return {
+ "modnorm": modnorm,
+ "gate_residual": gate_residual,
+ "affine_norm": affine_norm,
+ "rope": rope,
+ }
+
+
+def _stats(x: Any, eps: float) -> tuple:
+ """Per-row (mean, rstd) from PyTorch's own layer norm on the fp16 rows: bit-identical to ``layer_norm(x.float())``."""
+ import torch
+
+ D = x.shape[-1]
+ _, mean, rstd = torch.native_layer_norm(x, (D,), None, None, eps)
+ return mean.reshape(-1).contiguous(), rstd.reshape(-1).contiguous()
+
+
+def _plain_fp32_norm(norm: Any) -> bool:
+ """diffusers' FP32LayerNorm over the last dim without affine params (norm1 / norm3)."""
+ return (
+ type(norm).__name__ == "FP32LayerNorm"
+ and getattr(norm, "weight", None) is None
+ and getattr(norm, "bias", None) is None
+ and len(tuple(getattr(norm, "normalized_shape", ()))) == 1
+ )
+
+
+def _affine_fp32_norm(norm: Any, dim: int) -> bool:
+ import torch
+ w, b = getattr(norm, "weight", None), getattr(norm, "bias", None)
+ return (
+ type(norm).__name__ == "FP32LayerNorm"
+ and len(tuple(getattr(norm, "normalized_shape", ()))) == 1
+ and torch.is_tensor(w)
+ and torch.is_tensor(b)
+ and w.dtype in (torch.float32, torch.float16)
+ and b.dtype in (torch.float32, torch.float16)
+ and tuple(w.shape) == (dim,)
+ and tuple(b.shape) == (dim,)
+ and w.is_contiguous()
+ and b.is_contiguous()
+ )
+
+
+def _eligible(block: Any, x: Any, enc: Any, temb: Any) -> bool:
+ import torch
+
+ if not torch.is_tensor(x) or x.dtype is not torch.float16 or not x.is_cuda or x.dim() != 3:
+ return False
+ if torch.is_grad_enabled() and (
+ x.requires_grad or any(p.requires_grad for p in block.parameters(recurse = False))
+ ):
+ return False
+ if torch.compiler.is_compiling():
+ return False
+ B, L, D = x.shape
+ if D % 4 or not x.is_contiguous() or x.numel() == 0:
+ return False
+ table = getattr(block, "scale_shift_table", None)
+ # float32 as diffusers keeps it (_keep_in_fp32_modules); an fp16 table upcasts exactly in both paths
+ if (
+ not torch.is_tensor(table)
+ or table.dtype not in (torch.float32, torch.float16)
+ or tuple(table.shape) != (1, 6, D)
+ ):
+ return False
+ if table.device != x.device or table.stride(-1) != 1:
+ return False
+ if not torch.is_tensor(temb) or temb.device != x.device or temb.stride(-1) != 1:
+ return False
+ if temb.dtype not in (torch.float16, torch.float32):
+ return False
+ if temb.dim() == 4:
+ if tuple(temb.shape) != (B, L, 6, D):
+ return False
+ elif temb.dim() == 3:
+ if tuple(temb.shape) != (B, 6, D):
+ return False
+ else:
+ return False
+ if not (_plain_fp32_norm(block.norm1) and _plain_fp32_norm(block.norm3)):
+ return False
+ norm2 = block.norm2
+ if not (isinstance(norm2, torch.nn.Identity) or _affine_fp32_norm(norm2, D)):
+ return False
+ return True
+
+
+def _rope_ok(x: Any, freqs: Any) -> bool:
+ import torch
+ B, L, H, D = x.shape
+ return (
+ torch.is_tensor(freqs)
+ and freqs.dtype is torch.float32
+ and freqs.device == x.device
+ and freqs.dim() == 4
+ and tuple(freqs.shape) == (1, L, 1, D)
+ and freqs.stride(-1) == 1
+ )
+
+
+def _self_attention(attn: Any, hidden_states: Any, rotary_emb: Any) -> Any:
+ """``WanAttnProcessor.__call__`` for self-attention (no mask, no image branch), step for step, with the rotary as
+ one kernel per q / k. None when the processor or the inputs are not the ones this reproduces; the caller then runs
+ the stock module."""
+ import torch
+
+ if (os.environ.get(WAN_FUSED_ROPE_ENV) or "").strip().lower() in ("0", "off", "false", "no"):
+ return None
+ stock_call = _STATE.get("attn_call")
+ proc = getattr(attn, "processor", None)
+ if stock_call is None or type(proc).__call__ is not stock_call:
+ return None
+ if (
+ getattr(attn, "add_k_proj", None) is not None
+ or not isinstance(rotary_emb, (tuple, list))
+ or len(rotary_emb) != 2
+ ):
+ return None
+ cos, sin = rotary_emb
+ L = hidden_states.shape[1]
+ for f in (cos, sin):
+ if (
+ not torch.is_tensor(f)
+ or f.dtype is not torch.float32
+ or f.dim() != 4
+ or f.shape[1] != L
+ ):
+ return None
+ mod = _STATE.get("module")
+ query, key, value = mod._get_qkv_projections(attn, hidden_states, None)
+ query = attn.norm_q(query)
+ key = attn.norm_k(key)
+ query = query.unflatten(2, (attn.heads, -1))
+ key = key.unflatten(2, (attn.heads, -1))
+ value = value.unflatten(2, (attn.heads, -1))
+ if (
+ query.dtype is not torch.float16
+ or key.dtype is not torch.float16
+ or not query.is_contiguous()
+ or not key.is_contiguous()
+ or query.shape[-1] % 2
+ or not _rope_ok(query, cos)
+ or not _rope_ok(query, sin)
+ ):
+ return None
+ k = _kernels()
+ query = k["rope"](query, cos, sin)
+ key = k["rope"](key, cos, sin)
+ out = mod.dispatch_attention_fn(
+ query,
+ key,
+ value,
+ attn_mask = None,
+ dropout_p = 0.0,
+ is_causal = False,
+ backend = proc._attention_backend,
+ parallel_config = proc._parallel_config,
+ )
+ out = out.flatten(2, 3)
+ out = out.type_as(query)
+ out = attn.to_out[0](out)
+ out = attn.to_out[1](out)
+ return out
+
+
+def _fused_forward(
+ block: Any, hidden_states: Any, encoder_hidden_states: Any, temb: Any, rotary_emb: Any
+) -> Any:
+ import torch
+
+ # Triton launches on the current device's stream; a load on another GPU (cuda:1 of a T4x2) must switch to it
+ with torch.cuda.device(hidden_states.device):
+ return _fused_block(block, hidden_states, encoder_hidden_states, temb, rotary_emb)
+
+
+def _fused_block(
+ block: Any, hidden_states: Any, encoder_hidden_states: Any, temb: Any, rotary_emb: Any
+) -> Any:
+ """The stock block, step for step, with the float32 elementwise chains replaced by the kernels above."""
+ import torch
+
+ k = _kernels()
+ table = block.scale_shift_table
+ x = hidden_states
+ # 1. self-attention: norm1 + (shift, scale) = chunks 0, 1; gate = chunk 2
+ mean, rstd = _stats(x, block.norm1.eps)
+ n = k["modnorm"](x, mean, rstd, temb, table, 0, 1)
+ attn = _self_attention(block.attn1, n, rotary_emb) if rotary_emb is not None else None
+ if attn is None:
+ attn = block.attn1(n, None, None, rotary_emb)
+ attn = attn if attn.dtype is torch.float16 and attn.is_contiguous() else None
+ if attn is None:
+ raise _Fallback()
+ x = k["gate_residual"](x, attn, temb, table, 2)
+ # 2. cross-attention: norm2 (affine FP32LayerNorm, or Identity), plain fp16 residual add
+ norm2 = block.norm2
+ if isinstance(norm2, torch.nn.Identity):
+ n = x
+ else:
+ mean, rstd = _stats(x, norm2.eps)
+ n = k["affine_norm"](x, mean, rstd, norm2.weight, norm2.bias)
+ attn = block.attn2(n, encoder_hidden_states, None, None)
+ x = x + attn
+ if x.dtype is not torch.float16 or not x.is_contiguous():
+ raise _Fallback()
+ # 3. feed-forward: norm3 + (c_shift, c_scale) = chunks 3, 4; c_gate = chunk 5
+ mean, rstd = _stats(x, block.norm3.eps)
+ n = k["modnorm"](x, mean, rstd, temb, table, 3, 4)
+ ff = block.ffn(n)
+ if ff.dtype is not torch.float16 or not ff.is_contiguous() or ff.shape != x.shape:
+ raise _Fallback()
+ return k["gate_residual"](x, ff, temb, table, 5)
+
+
+class _Fallback(Exception):
+ """A sub-module returned a layout the kernels do not take; recompute the block on the stock path."""
+
+
+def _verify(block: Any, args: tuple, stock: Callable) -> Optional[bool]:
+ """Run the fused and stock block once on the same inputs; trust the fused path only on a bit-for-bit match.
+ None when the check itself ran out of memory (retried once on the next call)."""
+ import torch
+ try:
+ # a streamed group's onload can still be in flight on the copy stream: a half-copied reference fails the check
+ torch.cuda.synchronize(args[0].device)
+ with torch.no_grad():
+ ref = stock(block, *args)
+ got = _fused_forward(block, *args)
+ return bool(torch.equal(ref, got))
+ except torch.OutOfMemoryError:
+ return None
+ except Exception: # noqa: BLE001
+ return False
+
+
+def _make_forward(stock: Callable) -> Callable:
+ def forward(self, hidden_states, encoder_hidden_states, temb, rotary_emb):
+ import torch
+
+ # Under a regional compile, trace the stock block and leave the counters alone: dynamo guards on the module
+ # globals it reads, so a counter bumped inside the traced frame recompiles the block on every call.
+ if torch.compiler.is_compiling():
+ return stock(self, hidden_states, encoder_hidden_states, temb, rotary_emb)
+ if _kernels() is None or not _eligible(self, hidden_states, encoder_hidden_states, temb):
+ _COUNTS["stock"] += 1
+ return stock(self, hidden_states, encoder_hidden_states, temb, rotary_emb)
+ key = (
+ hidden_states.device.index,
+ temb.dim(),
+ temb.dtype,
+ not hasattr(self.norm2, "weight") or self.norm2.weight is None,
+ )
+ ok = _VERIFIED.get(key)
+ if ok is None:
+ ok = _verify(self, (hidden_states, encoder_hidden_states, temb, rotary_emb), stock)
+ if ok is None and key not in _VERIFY_OOM:
+ _VERIFY_OOM.add(key)
+ _COUNTS["stock"] += 1
+ return stock(self, hidden_states, encoder_hidden_states, temb, rotary_emb)
+ ok = bool(ok)
+ _VERIFIED[key] = ok
+ logger = _STATE.get("logger")
+ if logger is not None:
+ try:
+ if ok:
+ logger.info(
+ "video.wan_fused: fused fp16 modulation matched the stock block bit for bit"
+ )
+ else:
+ logger.warning(
+ "video.wan_fused: fused fp16 modulation did not match the stock block; keeping stock"
+ )
+ except Exception: # noqa: BLE001
+ pass
+ if not ok:
+ _COUNTS["stock"] += 1
+ return stock(self, hidden_states, encoder_hidden_states, temb, rotary_emb)
+ try:
+ out = _fused_forward(self, hidden_states, encoder_hidden_states, temb, rotary_emb)
+ except _Fallback:
+ _COUNTS["stock"] += 1
+ return stock(self, hidden_states, encoder_hidden_states, temb, rotary_emb)
+ except torch.OutOfMemoryError:
+ raise
+ except Exception as exc: # noqa: BLE001
+ # JIT / launch failure on a specialization the self-check missed: stock for this key, not a failed render
+ _VERIFIED[key] = False
+ logger = _STATE.get("logger")
+ if logger is not None:
+ try:
+ logger.warning("video.wan_fused: fused block failed (%s); keeping stock", exc)
+ except Exception: # noqa: BLE001
+ pass
+ _COUNTS["stock"] += 1
+ return stock(self, hidden_states, encoder_hidden_states, temb, rotary_emb)
+ _COUNTS["fused"] += 1
+ return out
+
+ forward._unsloth_wan_fused = True # type: ignore[attr-defined]
+ forward.__wrapped__ = stock # type: ignore[attr-defined]
+ return forward
+
+
+def _attn_supported(cls: Any) -> bool:
+ try:
+ from .diffusion_qwenimage21_rope import _digest
+ except Exception: # noqa: BLE001
+ return False
+ return _digest(cls.__call__) in _ATTN_FINGERPRINTS
+
+
+def _stock_supported(cls: Any) -> bool:
+ try:
+ from .diffusion_qwenimage21_rope import _digest
+ except Exception: # noqa: BLE001
+ return False
+ return _digest(cls.forward) in _FINGERPRINTS
+
+
+def install(
+ dtype: Any,
+ device: Any = "cuda",
+ logger: Any = None,
+) -> bool:
+ """Point ``WanTransformerBlock.forward`` at the fused version for an fp16 load. Idempotent; False (and nothing
+ patched) when not wanted, disabled, or the installed diffusers block is not the one this was built for. Must run
+ before group-offload hooks are attached: they capture the block's bound forward at registration."""
+ if not wanted(dtype, device):
+ uninstall()
+ return False
+ import importlib
+
+ with _LOCK:
+ if "forward" in _STATE:
+ if logger is not None:
+ _STATE["logger"] = logger
+ return True
+ try:
+ mod = importlib.import_module(_MODULE)
+ except Exception: # noqa: BLE001
+ return False
+ cls = getattr(mod, _CLASS, None)
+ if cls is None or getattr(cls.forward, "_unsloth_wan_fused", False):
+ return False
+ if not _stock_supported(cls):
+ if logger is not None:
+ try:
+ logger.info(
+ "video.wan_fused: diffusers' WanTransformerBlock changed; keeping the stock forward"
+ )
+ except Exception: # noqa: BLE001
+ pass
+ return False
+ stock = cls.forward
+ _STATE["forward"] = stock
+ _STATE["cls"] = cls
+ _STATE["module"] = mod
+ # the rotary rides along only while WanAttnProcessor.__call__ is the version reproduced in _self_attention
+ proc_cls = getattr(mod, "WanAttnProcessor", None)
+ if (
+ proc_cls is not None
+ and _attn_supported(proc_cls)
+ and hasattr(mod, "_get_qkv_projections")
+ ):
+ _STATE["attn_call"] = proc_cls.__call__
+ _STATE["logger"] = logger
+ _VERIFIED.clear()
+ _VERIFY_OOM.clear()
+ _COUNTS["fused"] = _COUNTS["stock"] = 0
+ cls.forward = _make_forward(stock)
+ if logger is not None:
+ try:
+ logger.info(
+ "video.wan_fused: fused fp16 norm / modulation / gated-residual kernels installed"
+ )
+ except Exception: # noqa: BLE001
+ pass
+ return True
+
+
+def install_for_pipe(
+ pipe: Any,
+ dtype: Any,
+ device: Any = "cuda",
+ logger: Any = None,
+) -> bool:
+ """Per-load entry: install for an fp16 Wan denoiser, otherwise make sure the stock forward is back."""
+ dits = [getattr(pipe, name, None) for name in ("transformer", "transformer_2")]
+ if not any(d is not None and type(d).__module__ == _MODULE for d in dits):
+ uninstall()
+ return False
+ return install(dtype, device, logger)
+
+
+def uninstall() -> None:
+ """Restore the stock forward (idempotent)."""
+ with _LOCK:
+ stock = _STATE.pop("forward", None)
+ cls = _STATE.pop("cls", None)
+ for key in ("logger", "module", "attn_call"):
+ _STATE.pop(key, None)
+ _VERIFIED.clear()
+ _VERIFY_OOM.clear()
+ if stock is None or cls is None:
+ return
+ if getattr(cls.forward, "_unsloth_wan_fused", False):
+ cls.forward = stock
+
+
+def is_installed() -> bool:
+ return "forward" in _STATE
+
+
+def counts() -> dict:
+ return dict(_COUNTS)
diff --git a/studio/backend/tests/test_diffusion_memory.py b/studio/backend/tests/test_diffusion_memory.py
index 9426a4efab7..98a21982437 100644
--- a/studio/backend/tests/test_diffusion_memory.py
+++ b/studio/backend/tests/test_diffusion_memory.py
@@ -3112,3 +3112,102 @@ def test_streaming_counts_pinned_encoders_before_a_torchao_denoiser_pins(monkeyp
_streaming_apply_kwargs(monkeypatch, 40_000)
# the 7500 MiB encoder, rounded up to a power of two like the pinned allocator
assert seen_totals["transformer"] == 8192
+
+
[email protected]("tier", ["group", "streaming"])
+def test_top_level_weights_never_copied_back_when_the_pin_budget_is_spent(monkeypatch, tier):
+ """No pinnable host RAM (a 31 GB Kaggle host holding a 10 GB DiT and an 11 GB encoder reports 0 MiB): the top-level
+ group still must not copy its weights device to host on every offload. It re-points to the host tensors it was
+ loaded from, so the host pointer survives every forward and the output is unchanged."""
+ torch = pytest.importorskip("torch")
+ if not torch.cuda.is_available():
+ pytest.skip("needs a CUDA device")
+ pytest.importorskip("diffusers.hooks")
+ import core.inference.diffusion_memory as mem
+
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_PIN_TOP_GROUP", raising = False)
+ monkeypatch.delenv(mem.GROUP_OFFLOAD_PIN_ENV, raising = False)
+ monkeypatch.setattr(mem, "_pin_budget_mib", lambda: 0)
+ monkeypatch.setattr(mem, "_pinned_memory_capped", lambda: False)
+
+ class Net(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.proj_in = torch.nn.Linear(1024, 1024)
+ self.blocks = torch.nn.ModuleList(torch.nn.Linear(1024, 1024) for _ in range(4))
+ self.proj_out = torch.nn.Linear(1024, 1024)
+
+ def forward(self, x):
+ x = self.proj_in(x)
+ for block in self.blocks:
+ x = x + torch.tanh(block(x))
+ return self.proj_out(x)
+
+ torch.manual_seed(0)
+ net = Net().eval() # 4 MiB per Linear: a whole MiB, so a 0 MiB budget really refuses the pin
+ x = torch.randn(8, 1024)
+ with torch.no_grad():
+ want = net(x)
+ ptr = net.proj_out.weight.data_ptr()
+ pipe = types.SimpleNamespace(transformer = net, components = {"transformer": net})
+ if tier == "group":
+ assert mem._apply_group_offload(pipe, "cuda", logger = None) is True
+ else:
+ mem._apply_streaming_offload(pipe, "cuda", None)
+ groups = [g for g in mem._offload_groups(net) if getattr(g, "offload_leader", None) is net]
+ assert groups and all(getattr(g, "_unsloth_top_no_copy_back", False) for g in groups)
+ assert not any(getattr(g, "_unsloth_pinned_top", False) for g in groups)
+ got = []
+ for _ in range(3):
+ with torch.no_grad():
+ got.append(net(x.cuda()).cpu())
+ torch.cuda.synchronize()
+ # offloaded onto the very host tensor it was loaded from: no device-to-host copy into a fresh buffer
+ assert net.proj_out.weight.device.type == "cpu"
+ assert net.proj_out.weight.data_ptr() == ptr
+ assert all(torch.equal(g, got[0]) for g in got)
+ assert all(torch.allclose(g, want, atol = 1e-5) for g in got)
+
+
+def test_top_level_copy_back_skip_kill_switch_and_scope(monkeypatch):
+ import core.inference.diffusion_memory as mem
+
+ module, group = _top_group_module(monkeypatch)
+ monkeypatch.setenv(mem.PIN_TOP_GROUP_ENV, "0")
+ assert mem._skip_top_level_copy_back(module) is False
+ assert group.onload_ == "diffusers" and group.offload_ == "diffusers"
+ monkeypatch.delenv(mem.PIN_TOP_GROUP_ENV, raising = False)
+ # a streamed group or torchao weights are not the streamless top group this replaces
+ for kind in ("streamed_group", "torchao"):
+ module, group = _top_group_module(
+ monkeypatch,
+ stream = object() if kind == "streamed_group" else None,
+ torchao = kind == "torchao",
+ )
+ assert mem._skip_top_level_copy_back(module) is False
+ assert group.onload_ == "diffusers"
+ # the plain top group: offload re-points, it does not copy
+ module, group = _top_group_module(monkeypatch)
+ weight = group.modules[0].weight
+ host_ptr = weight.data_ptr()
+ assert mem._skip_top_level_copy_back(module) is True
+ assert group.onload_ != "diffusers" and group._unsloth_top_no_copy_back is True
+ group.offload_()
+ assert weight.data_ptr() == host_ptr
+ # idempotent, and the pinned path no longer claims a group that already re-points
+ assert mem._skip_top_level_copy_back(module) is False
+ monkeypatch.setattr(mem, "_pin_budget_mib", lambda: 1 << 20)
+ monkeypatch.setattr(mem, "_pinned_memory_capped", lambda: False)
+ assert mem._pin_top_level_group(module) is False
+
+
+def test_both_offload_tiers_fall_back_to_the_no_copy_back_top_group():
+ import ast
+ import inspect
+
+ import core.inference.diffusion_memory as mem
+
+ for fn in (mem._apply_group_offload, mem._apply_streaming_offload):
+ src = ast.unparse(ast.parse(inspect.getsource(fn).lstrip()))
+ assert "_skip_top_level_copy_back(module, logger)" in src, fn.__name__
+ assert "not _pin_top_level_group(module, logger, pinned_mib)" in src, fn.__name__
diff --git a/studio/backend/tests/test_video_wan_fused.py b/studio/backend/tests/test_video_wan_fused.py
new file mode 100644
index 00000000000..3d7d7d55907
--- /dev/null
+++ b/studio/backend/tests/test_video_wan_fused.py
@@ -0,0 +1,517 @@
+# 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 ``video_wan_fused.py``: the fused Wan block forward engages only for an fp16 Wan load (bf16 / fp32 keep
+the stock forward), is bit-identical to the stock block on a real GPU, survives group-offload hooks, falls back to
+stock on a self-check mismatch, and is restored on teardown."""
+
+from __future__ import annotations
+
+import ast
+import inspect
+
+import pytest
+
+from core.inference import video_wan_fused as wf
+
+torch = pytest.importorskip("torch")
+transformer_wan = pytest.importorskip("diffusers.models.transformers.transformer_wan")
+WanTransformerBlock = transformer_wan.WanTransformerBlock
+
+_CUDA = torch.cuda.is_available() and not getattr(torch.version, "hip", None)
+needs_cuda = pytest.mark.skipif(not _CUDA, reason = "needs an NVIDIA GPU")
+
+
[email protected](autouse = True)
+def _clean(monkeypatch):
+ monkeypatch.delenv(wf.WAN_FUSED_ENV, raising = False)
+ wf.uninstall()
+ stock = WanTransformerBlock.forward
+ yield
+ wf.uninstall()
+ assert WanTransformerBlock.forward is stock
+
+
+def _fake_kernels(monkeypatch):
+ # install logic without a GPU; on ROCm torch wanted() refuses HIP, so pretend a CUDA build too
+ monkeypatch.setattr(wf, "_kernels", lambda: {"modnorm": None})
+ monkeypatch.setattr(torch.version, "hip", None)
+
+
+def test_stock_block_matches_the_fingerprint():
+ from core.inference.diffusion_qwenimage21_rope import _digest
+ assert _digest(WanTransformerBlock.forward) in wf._FINGERPRINTS
+
+
[email protected]("dtype", ["bfloat16", "float32"])
+def test_bf16_and_fp32_loads_keep_the_stock_forward(dtype):
+ stock = WanTransformerBlock.forward
+ assert wf.install(getattr(torch, dtype), "cuda") is False
+ assert WanTransformerBlock.forward is stock and not wf.is_installed()
+
+
+def test_cpu_load_keeps_the_stock_forward():
+ stock = WanTransformerBlock.forward
+ assert wf.install(torch.float16, "cpu") is False
+ assert WanTransformerBlock.forward is stock
+
+
[email protected]("value", ["0", "off", "false", "no"])
+def test_kill_switch(monkeypatch, value):
+ monkeypatch.setenv(wf.WAN_FUSED_ENV, value)
+ stock = WanTransformerBlock.forward
+ assert wf.install(torch.float16, "cuda") is False
+ assert WanTransformerBlock.forward is stock
+
+
+def test_changed_diffusers_block_keeps_the_stock_forward(monkeypatch):
+ monkeypatch.setattr(wf, "_FINGERPRINTS", frozenset({"not-this-block"}))
+ _fake_kernels(monkeypatch)
+ stock = WanTransformerBlock.forward
+ assert wf.install(torch.float16, "cuda") is False
+ assert WanTransformerBlock.forward is stock
+
+
+def test_install_is_idempotent_and_uninstall_restores(monkeypatch):
+ _fake_kernels(monkeypatch)
+ stock = WanTransformerBlock.forward
+ assert wf.install(torch.float16, "cuda") is True
+ patched = WanTransformerBlock.forward
+ assert patched is not stock and getattr(patched, "_unsloth_wan_fused", False)
+ assert wf.install(torch.float16, "cuda") is True
+ assert WanTransformerBlock.forward is patched
+ wf.uninstall()
+ assert WanTransformerBlock.forward is stock
+ wf.uninstall()
+
+
+def test_install_for_pipe_scopes_to_wan(monkeypatch):
+ import types
+
+ _fake_kernels(monkeypatch)
+ stock = WanTransformerBlock.forward
+ other = types.SimpleNamespace(transformer = torch.nn.Linear(2, 2))
+ assert wf.install_for_pipe(other, torch.float16, "cuda") is False
+ assert WanTransformerBlock.forward is stock
+
+ class _Wan(torch.nn.Module):
+ pass
+
+ _Wan.__module__ = wf._MODULE
+ wan = types.SimpleNamespace(transformer = _Wan())
+ assert wf.install_for_pipe(wan, torch.float16, "cuda") is True
+ assert WanTransformerBlock.forward is not stock
+ # a later non-Wan load puts the stock forward back
+ assert wf.install_for_pipe(other, torch.float16, "cuda") is False
+ assert WanTransformerBlock.forward is stock
+
+
+def test_cpu_tensors_take_the_stock_path(monkeypatch):
+ _fake_kernels(monkeypatch)
+ blk = _block(dim = 32, ffn = 64, heads = 2, device = "cpu", dtype = torch.float32)
+ x, enc, temb, rot = _inputs(blk, 1, 8, 32, "cpu", torch.float32)
+ with torch.no_grad():
+ want = WanTransformerBlock.forward(blk, x, enc, temb, rot)
+ assert wf.install(torch.float16, "cuda") is True
+ got = blk(x, enc, temb, rot)
+ assert torch.equal(want, got)
+ assert wf.counts()["fused"] == 0 and wf.counts()["stock"] == 1
+
+
+def _block(
+ dim,
+ ffn,
+ heads,
+ device,
+ dtype,
+ cross_attn_norm = True,
+):
+ torch.manual_seed(0)
+ blk = WanTransformerBlock(
+ dim, ffn, heads, "rms_norm_across_heads", cross_attn_norm = cross_attn_norm, eps = 1e-6
+ )
+ blk = blk.to(device = device, dtype = dtype).eval()
+ # diffusers keeps these in float32 (WanTransformer3DModel._keep_in_fp32_modules)
+ blk.scale_shift_table.data = blk.scale_shift_table.data.float()
+ if cross_attn_norm:
+ blk.norm2.float()
+ with torch.no_grad():
+ blk.norm2.weight.normal_(1.0, 0.1)
+ blk.norm2.bias.normal_(0.0, 0.1)
+ return blk
+
+
+def _inputs(
+ blk,
+ B,
+ L,
+ D,
+ device,
+ dtype,
+ per_token = True,
+):
+ g = torch.Generator(device = "cpu").manual_seed(1)
+ x = (torch.randn(B, L, D, generator = g) * 8).to(device = device, dtype = dtype)
+ enc = torch.randn(B, 16, D, generator = g).to(device = device, dtype = dtype)
+ shape = (B, L, 6, D) if per_token else (B, 6, D)
+ temb = (torch.randn(*shape, generator = g) * 0.5).to(device = device, dtype = dtype)
+ head_dim = D // blk.attn1.heads
+ freqs = torch.randn(1, L, 1, head_dim, generator = g).to(device)
+ return x, enc, temb, (freqs.cos(), freqs.sin())
+
+
+@needs_cuda
[email protected]("per_token", [True, False], ids = ["temb_per_token", "temb_per_sample"])
[email protected]("cross_attn_norm", [True, False], ids = ["norm2_affine", "norm2_identity"])
[email protected]("batch", [1, 2])
+def test_fused_block_is_bit_identical_to_stock_on_gpu(per_token, cross_attn_norm, batch):
+ D = 256
+ blk = _block(
+ dim = D, ffn = 512, heads = 4, device = "cuda", dtype = torch.float16, cross_attn_norm = cross_attn_norm
+ )
+ x, enc, temb, rot = _inputs(blk, batch, 300, D, "cuda", torch.float16, per_token = per_token)
+ x[0, :3, :5] = 300.0 # rows far from zero mean, where a different reduction order would show
+ with torch.no_grad():
+ want = WanTransformerBlock.forward(blk, x, enc, temb, rot)
+ assert wf.install(torch.float16, "cuda") is True
+ got = blk(x, enc, temb, rot)
+ direct = wf._fused_forward(blk, x, enc, temb, rot)
+ assert torch.equal(want, got)
+ assert torch.equal(want, direct)
+ assert wf.counts()["fused"] == 1
+
+
+@needs_cuda
+def test_fused_kernels_match_the_stock_op_chain_elementwise():
+ """Each kernel against the exact stock expression, on Wan2.2-TI2V-5B's width (3072)."""
+ import torch.nn.functional as F
+
+ B, L, D = 1, 512, 3072
+ g = torch.Generator(device = "cpu").manual_seed(3)
+ x = (torch.randn(B, L, D, generator = g) * 8).half().cuda()
+ a = (torch.randn(B, L, D, generator = g) * 3).half().cuda()
+ t = (torch.randn(B, L, 6, D, generator = g) * 0.5).half().cuda()
+ tbl = (torch.randn(1, 6, D, generator = g) / D**0.5).cuda()
+ k = wf._kernels()
+ sh, sc, gate, csh, csc, cgate = (tbl.unsqueeze(0) + t.float()).chunk(6, dim = 2)
+ ln = F.layer_norm(x.float(), (D,), None, None, 1e-6)
+ want = (ln * (1 + sc.squeeze(2)) + sh.squeeze(2)).type_as(x)
+ mean, rstd = wf._stats(x, 1e-6)
+ assert torch.equal(k["modnorm"](x, mean, rstd, t, tbl, 0, 1), want)
+ want = (x.float() + a * gate.squeeze(2)).type_as(x)
+ assert torch.equal(k["gate_residual"](x, a, t, tbl, 2), want)
+ w = (1 + 0.1 * torch.randn(D, generator = g)).cuda()
+ b = (0.1 * torch.randn(D, generator = g)).cuda()
+ want = F.layer_norm(x.float(), (D,), w, b, 1e-6).type_as(x)
+ assert torch.equal(k["affine_norm"](x, mean, rstd, w, b), want)
+
+
+@needs_cuda
+def test_modulation_kernels_index_past_two_gib_of_temb():
+ """A per-token temb past 2**31 elements (1280x704, 529 frames: 116,510+ tokens at D=3072) must not wrap the row
+ offset: the tail rows, beyond the int32 limit, still equal the stock expression."""
+ import torch.nn.functional as F
+
+ B, L, D = 1, 116_512, 3072
+ if torch.cuda.mem_get_info()[0] < 8 << 30:
+ pytest.skip("needs ~8 GiB free on the GPU")
+ g = torch.Generator(device = "cuda").manual_seed(5)
+ # fp16 straight from randn (and scaled in place): an fp32 temb here alone would be 8 GiB, twice over with "* 0.5"
+ x = torch.randn(B, L, D, device = "cuda", dtype = torch.half, generator = g)
+ a = torch.randn(B, L, D, device = "cuda", dtype = torch.half, generator = g)
+ t = torch.randn(B, L, 6, D, device = "cuda", dtype = torch.half, generator = g).mul_(0.5)
+ tbl = torch.randn(1, 6, D, device = "cuda", generator = g) / D**0.5
+ k = wf._kernels()
+ mean, rstd = wf._stats(x, 1e-6)
+ got_n = k["modnorm"](x, mean, rstd, t, tbl, 0, 1)[:, -64:]
+ got_g = k["gate_residual"](x, a, t, tbl, 2)[:, -64:]
+ x, a, t = x[:, -64:], a[:, -64:], t[:, -64:]
+ sh, sc, gate = (tbl.unsqueeze(0) + t.float()).chunk(6, dim = 2)[:3]
+ ln = F.layer_norm(x.float(), (D,), None, None, 1e-6)
+ assert torch.equal(got_n, (ln * (1 + sc.squeeze(2)) + sh.squeeze(2)).type_as(x))
+ assert torch.equal(got_g, (x.float() + a * gate.squeeze(2)).type_as(x))
+
+
+@needs_cuda
+def test_fused_forward_survives_group_offload_hooks():
+ """Installed before the offload hooks attach (as the loader does), the streamed blocks run the fused path."""
+ pytest.importorskip("diffusers.hooks")
+ from diffusers.hooks import apply_group_offloading
+
+ D = 128
+
+ class Net(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.blocks = torch.nn.ModuleList(
+ _block(dim = D, ffn = 256, heads = 2, device = "cpu", dtype = torch.float16) for _ in range(3)
+ )
+
+ def forward(self, x, enc, temb, rot):
+ for blk in self.blocks:
+ x = blk(x, enc, temb, rot)
+ return x
+
+ net = Net().eval()
+ x, enc, temb, rot = _inputs(net.blocks[0], 1, 64, D, "cuda", torch.float16)
+ with torch.no_grad():
+ ref = Net().eval()
+ ref.load_state_dict(net.state_dict())
+ ref.cuda()
+ want = ref(x, enc, temb, rot)
+ assert wf.install(torch.float16, "cuda") is True
+ apply_group_offloading(
+ net,
+ onload_device = torch.device("cuda"),
+ offload_device = torch.device("cpu"),
+ offload_type = "block_level",
+ num_blocks_per_group = 1,
+ use_stream = True,
+ )
+ with torch.no_grad():
+ got = net(x, enc, temb, rot)
+ assert torch.equal(want, got)
+ assert wf.counts()["fused"] == 3
+
+
+@needs_cuda
+def test_self_check_mismatch_keeps_the_stock_forward(monkeypatch):
+ blk = _block(dim = 128, ffn = 256, heads = 2, device = "cuda", dtype = torch.float16)
+ x, enc, temb, rot = _inputs(blk, 1, 32, 128, "cuda", torch.float16)
+ real = wf._fused_forward
+
+ def _off_by_one(*args):
+ return real(*args) + 1
+
+ monkeypatch.setattr(wf, "_fused_forward", _off_by_one)
+ with torch.no_grad():
+ want = WanTransformerBlock.forward(blk, x, enc, temb, rot)
+ assert wf.install(torch.float16, "cuda") is True
+ got = [blk(x, enc, temb, rot) for _ in range(2)]
+ assert all(torch.equal(want, g) for g in got)
+ assert wf.counts()["fused"] == 0 and False in wf._VERIFIED.values()
+
+
+@needs_cuda
+def test_kernel_failure_after_the_self_check_keeps_the_stock_forward(monkeypatch):
+ blk = _block(dim = 128, ffn = 256, heads = 2, device = "cuda", dtype = torch.float16)
+ x, enc, temb, rot = _inputs(blk, 1, 32, 128, "cuda", torch.float16)
+ real = wf._fused_forward
+ calls = []
+
+ def _jit_fails_after_verify(*args):
+ calls.append(1)
+ if len(calls) > 1:
+ raise RuntimeError("PTX JIT compilation failed")
+ return real(*args)
+
+ monkeypatch.setattr(wf, "_fused_forward", _jit_fails_after_verify)
+ with torch.no_grad():
+ want = WanTransformerBlock.forward(blk, x, enc, temb, rot)
+ assert wf.install(torch.float16, "cuda") is True
+ got = [blk(x, enc, temb, rot) for _ in range(2)]
+ assert all(torch.equal(want, g) for g in got)
+ assert len(calls) == 2 and wf.counts() == {"fused": 0, "stock": 2}
+ assert list(wf._VERIFIED.values()) == [False]
+
+
+@needs_cuda
+def test_self_check_out_of_memory_retries_instead_of_disabling(monkeypatch):
+ blk = _block(dim = 128, ffn = 256, heads = 2, device = "cuda", dtype = torch.float16)
+ x, enc, temb, rot = _inputs(blk, 1, 32, 128, "cuda", torch.float16)
+ real = wf._fused_forward
+ calls = []
+
+ def _oom_once(*args):
+ calls.append(1)
+ if len(calls) == 1:
+ raise torch.OutOfMemoryError("CUDA out of memory")
+ return real(*args)
+
+ monkeypatch.setattr(wf, "_fused_forward", _oom_once)
+ with torch.no_grad():
+ want = WanTransformerBlock.forward(blk, x, enc, temb, rot)
+ assert wf.install(torch.float16, "cuda") is True
+ got = [blk(x, enc, temb, rot) for _ in range(2)]
+ assert all(torch.equal(want, g) for g in got)
+ assert wf.counts() == {"fused": 1, "stock": 1}
+ assert list(wf._VERIFIED.values()) == [True]
+
+
+@needs_cuda
+def test_self_check_out_of_memory_twice_keeps_stock(monkeypatch):
+ blk = _block(dim = 128, ffn = 256, heads = 2, device = "cuda", dtype = torch.float16)
+ x, enc, temb, rot = _inputs(blk, 1, 32, 128, "cuda", torch.float16)
+ calls = []
+
+ def _always_oom(*args):
+ calls.append(1)
+ raise torch.OutOfMemoryError("CUDA out of memory")
+
+ monkeypatch.setattr(wf, "_fused_forward", _always_oom)
+ with torch.no_grad():
+ want = WanTransformerBlock.forward(blk, x, enc, temb, rot)
+ assert wf.install(torch.float16, "cuda") is True
+ got = [blk(x, enc, temb, rot) for _ in range(4)]
+ assert all(torch.equal(want, g) for g in got)
+ assert len(calls) == 2 and wf.counts() == {"fused": 0, "stock": 4}
+ assert list(wf._VERIFIED.values()) == [False]
+
+
+ not _CUDA or torch.cuda.device_count() < 2, reason = "needs two NVIDIA GPUs (non-current device)"
+)
+def test_kernels_launch_on_the_tensors_device(monkeypatch):
+ blk = _block(dim = 128, ffn = 256, heads = 2, device = "cuda:1", dtype = torch.float16)
+ x, enc, temb, rot = _inputs(blk, 1, 32, 128, "cuda:1", torch.float16)
+ kernels = wf._kernels()
+ seen = []
+ for name in ("modnorm", "gate_residual", "rope"):
+ real = kernels[name]
+
+ def _record(
+ *args,
+ _real = real,
+ **kwargs,
+ ):
+ seen.append(torch.cuda.current_device())
+ return _real(*args, **kwargs)
+
+ monkeypatch.setitem(kernels, name, _record)
+ assert torch.cuda.current_device() == 0
+ with torch.no_grad():
+ want = WanTransformerBlock.forward(blk, x, enc, temb, rot)
+ assert wf.install(torch.float16, "cuda:1") is True
+ got = blk(x, enc, temb, rot)
+ assert torch.equal(want, got) and wf.counts()["fused"] == 1
+ assert seen and set(seen) == {1}
+
+
+@needs_cuda
+def test_grad_and_non_fp16_inputs_take_the_stock_path():
+ blk = _block(dim = 128, ffn = 256, heads = 2, device = "cuda", dtype = torch.float16)
+ x, enc, temb, rot = _inputs(blk, 1, 32, 128, "cuda", torch.float16)
+ assert wf.install(torch.float16, "cuda") is True
+ with torch.enable_grad():
+ xg = x.clone().requires_grad_(True)
+ blk(xg, enc, temb, rot)
+ assert wf.counts() == {"fused": 0, "stock": 1}
+ blk32 = _block(dim = 128, ffn = 256, heads = 2, device = "cuda", dtype = torch.float32)
+ x32, enc32, temb32, rot32 = _inputs(blk32, 1, 32, 128, "cuda", torch.float32)
+ with torch.no_grad():
+ blk32(x32, enc32, temb32, rot32)
+ assert wf.counts() == {"fused": 0, "stock": 2}
+
+
+def _video_src() -> ast.AST:
+ from core.inference import video
+ return ast.parse(inspect.getsource(video))
+
+
+def test_loader_installs_before_the_step_cache_and_offload_hooks():
+ from core.inference import video
+
+ src = (
+ inspect.getsource(video.VideoBackend.load_pipeline)
+ if hasattr(video, "VideoBackend")
+ else None
+ )
+ if src is None:
+ cls = next(
+ c for c in vars(video).values() if inspect.isclass(c) and hasattr(c, "load_pipeline")
+ )
+ src = inspect.getsource(cls.load_pipeline)
+ install = src.index("video_wan_fused.install_for_pipe(")
+ assert install < src.index("apply_step_cache(")
+ assert install < src.index("apply_memory_plan(")
+ # held off on speed_mode=off, like every other optimisation layer
+ head = src[src.rindex("if effective_speed != SPEED_OFF:", 0, install) : install]
+ assert "video_wan_fused" in src[:install] and head
+ assert '"wan_fused_adaln"' in src
+
+
+def test_teardown_and_rollback_restore_the_stock_forward():
+ from core.inference import video
+ cls = next(
+ c
+ for c in vars(video).values()
+ if inspect.isclass(c) and hasattr(c, "_teardown_state_locked")
+ )
+ for name in ("_teardown_state_locked", "_rollback_precommit_globals"):
+ body = ast.unparse(ast.parse(inspect.getsource(getattr(cls, name)).lstrip()))
+ assert "video_wan_fused.uninstall()" in body, name
+
+
+@needs_cuda
+def test_fp16_cast_table_and_norm2_stay_bit_identical():
+ """A pipeline moved with ``.to(float16)`` casts the float32-kept table and norm2 too; both upcast exactly."""
+ D = 128
+ blk = _block(dim = D, ffn = 256, heads = 2, device = "cuda", dtype = torch.float16)
+ blk.scale_shift_table.data = blk.scale_shift_table.data.half()
+ blk.norm2.half()
+ x, enc, temb, rot = _inputs(blk, 1, 64, D, "cuda", torch.float16)
+ with torch.no_grad():
+ want = WanTransformerBlock.forward(blk, x, enc, temb, rot)
+ assert wf.install(torch.float16, "cuda") is True
+ got = blk(x, enc, temb, rot)
+ assert torch.equal(want, got) and wf.counts()["fused"] == 1
+
+
+@needs_cuda
+def test_self_attention_rotary_is_bit_identical_and_scoped(monkeypatch):
+ D = 256
+ blk = _block(dim = D, ffn = 512, heads = 4, device = "cuda", dtype = torch.float16)
+ x, enc, temb, rot = _inputs(blk, 2, 300, D, "cuda", torch.float16)
+ assert wf.install(torch.float16, "cuda") is True
+ assert wf._STATE.get("attn_call") is transformer_wan.WanAttnProcessor.__call__
+ calls = []
+ real = wf._kernels()["rope"]
+ monkeypatch.setitem(wf._kernels(), "rope", lambda *a: calls.append(1) or real(*a))
+ with torch.no_grad():
+ want = blk.attn1(x, None, None, rot)
+ got = wf._self_attention(blk.attn1, x, rot)
+ assert got is not None and torch.equal(want, got) and len(calls) == 2
+ # an fp16 table rounds each product to fp16 in the stock path: not this kernel's arithmetic
+ assert wf._self_attention(blk.attn1, x, (rot[0].half(), rot[1].half())) is None
+ # a replaced processor (another attention backend's) is left alone
+ blk.attn1.processor = type(
+ "OtherProcessor",
+ (transformer_wan.WanAttnProcessor,),
+ {"__call__": lambda *a, **k: None},
+ )()
+ assert wf._self_attention(blk.attn1, x, rot) is None
+ monkeypatch.setenv(wf.WAN_FUSED_ROPE_ENV, "0")
+ assert wf._self_attention(blk.attn1, x, rot) is None
+
+
+def test_changed_attention_processor_keeps_the_stock_rotary(monkeypatch):
+ monkeypatch.setattr(wf, "_ATTN_FINGERPRINTS", frozenset({"not-this-processor"}))
+ _fake_kernels(monkeypatch)
+ assert wf.install(torch.float16, "cuda") is True
+ assert "attn_call" not in wf._STATE
+
+
+def test_attention_processor_matches_the_fingerprint():
+ from core.inference.diffusion_qwenimage21_rope import _digest
+ assert _digest(transformer_wan.WanAttnProcessor.__call__) in wf._ATTN_FINGERPRINTS
+
+
+def test_regional_compile_traces_the_stock_block_without_recompiles(monkeypatch):
+ """Under torch.compile the installed forward must trace the stock block and leave the module counters alone:
+ dynamo guards on the globals a traced frame reads, so a bumped counter recompiles the block on every call (it hit
+ the recompile limit and dropped the Wan regional compile to eager)."""
+ import torch._dynamo as dynamo
+
+ _fake_kernels(monkeypatch)
+ blk = _block(dim = 32, ffn = 64, heads = 2, device = "cpu", dtype = torch.float32)
+ x, enc, temb, rot = _inputs(blk, 1, 8, 32, "cpu", torch.float32)
+ dynamo.reset()
+ with torch.no_grad():
+ want = WanTransformerBlock.forward(blk, x, enc, temb, rot)
+ assert wf.install(torch.float16, "cuda") is True
+ blk.compile(backend = "eager", fullgraph = True)
+ with dynamo.config.patch(error_on_recompile = True):
+ outs = [blk(x, enc, temb, rot) for _ in range(4)]
+ dynamo.reset()
+ assert all(torch.equal(want, o) for o in outs)
+ assert wf.counts() == {"fused": 0, "stock": 0}