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: MiniMax-H3 attention fast path and fused q/k norm + RoPE (5-7% faster per step) (#12459)
Daniel Han366d907a1dc7
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex d54e4e6ea39..d4acd2aec1e 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -7406,16 +7406,53 @@ class VideoBackend:)except Exception: # noqa: BLE001 -- optimisation only, never fail a loadpass+ h3_attn_levers: tuple = ()try:+ from .video_minimax_h3_attn import (+ fuse_h3_qkv_,+ h3_attention_backend,+ install_strided_attention,+ )+ h3_denoiser = getattr(pipe, denoiser_component, None)+ # Resident only: a streamed denoiser's offload hooks are keyed to the three projections.+ if (+ effective_speed != SPEED_OFF+ and denoiser_pinned+ and not denoiser_streamed+ and transformer_quant_engaged == "int8"+ and h3_denoiser is not None+ and fuse_h3_qkv_(h3_denoiser, logger = logger)+ ):+ h3_attn_levers += ("h3_fused_qkv",)+ except Exception as exc: # noqa: BLE001 -- optimisation only, the stock projections stay+ logger.warning("video.h3_attn: QKV fusion skipped: %s", exc)+ try:+ h3_attn_backend = select_attention_backend(+ umem_target, attention_backend, speed_active = effective_speed != SPEED_OFF+ )+ try:+ h3_attn_backend = h3_attention_backend(h3_attn_backend, requested = attention_backend)+ except Exception: # noqa: BLE001 -- keep the generic pick+ passattention_engaged = apply_attention_backend(speed_view,- select_attention_backend(- umem_target, attention_backend, speed_active = effective_speed != SPEED_OFF- ),+ h3_attn_backend,logger = logger,# The probe behind this must see the dtype the pipeline actually RUNS in.target = types.SimpleNamespace(device = device, dtype = dtype),)+ # speed off stays bit-identical: the fused q/k norm + RoPE only matches stock within a rounding step+ if effective_speed != SPEED_OFF and attention_engaged in (+ "_native_cudnn",+ "_native_flash",+ ):+ try:+ if install_strided_attention(+ getattr(pipe, denoiser_component, None), logger = logger+ ):+ h3_attn_levers += ("h3_strided_attn",)+ except Exception as exc: # noqa: BLE001 -- stock processor stays+ logger.warning("video.h3_attn: strided attention skipped: %s", exc)applied = apply_speed_optims(speed_view,types.SimpleNamespace(@@ -7437,7 +7474,7 @@ class VideoBackend:cuda_graph_default = False,logger = logger,)- speed_optims = tuple(k for k, v in applied.items() if v)+ speed_optims = tuple(k for k, v in applied.items() if v) + h3_attn_leversif denoiser_streamed and "compiled" in speed_optims:from .video_minimax_h3_residency import compile_blocks_below_offload_hookscompile_blocks_below_offload_hooks(diff --git a/studio/backend/core/inference/video_minimax_h3_attn.py b/studio/backend/core/inference/video_minimax_h3_attn.pynew file mode 100644index 00000000000..9f6d579143b--- /dev/null+++ b/studio/backend/core/inference/video_minimax_h3_attn.py@@ -0,0 +1,411 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""MiniMax-H3 attention fast path, one kill switch (``=0``) per lever:++1. ``UNSLOTH_H3_STRIDED_ATTN``: torch cuDNN / flash SDPA take the permuted (B, S, H, D) views, so the q / k / v and+ output copies disappear; bit-identical (attention kernels are layout-invariant).+2. ``UNSLOTH_H3_FUSED_QKV``: one row-concatenated int8 ``to_qkv`` (one rotation, act quant and GEMM instead of three);+ bit-identical because int accumulation is exact and the dequant epilogue is per row.+3. ``UNSLOTH_H3_ATTN_ARCH``: flash instead of cuDNN on the archs in ``H3_FLASH_FASTER_ARCHS`` only.+"""++from __future__ import annotations++import os+from functools import lru_cache+from typing import Any, Optional++STRIDED_ATTN_ENV = "UNSLOTH_H3_STRIDED_ATTN"+FUSED_QKV_ENV = "UNSLOTH_H3_FUSED_QKV"+ATTN_ARCH_ENV = "UNSLOTH_H3_ATTN_ARCH"++# Measured at H3's shape (torch 2.11): flash beats cuDNN on sm80 / sm89, ties or loses on sm120; unmeasured keep cuDNN.+H3_FLASH_FASTER_ARCHS = frozenset({(8, 0), (8, 9)})++_CUDNN = "_native_cudnn"+_FLASH = "_native_flash"+++def _enabled(env: str) -> bool:+ return (os.environ.get(env) or "1").strip().lower() not in ("0", "off", "false", "no")+++def _capability(device: Any = None) -> Optional[tuple[int, int]]:+ try:+ import torch+ if not torch.cuda.is_available() or torch.version.hip is not None:+ return None+ return tuple(torch.cuda.get_device_capability(device)) # type: ignore[return-value]+ except Exception: # noqa: BLE001+ return None+++def h3_attention_backend(+ selected: Optional[str],+ capability: Optional[tuple[int, int]] = None,+ requested: Optional[str] = None,+) -> Optional[str]:+ """Moves only the automatic cuDNN pick (``requested`` auto / unset), and only to flash on a measured-faster arch;+ anything else unchanged."""+ if selected != _CUDNN or not _enabled(ATTN_ARCH_ENV):+ return selected+ try:+ from .diffusion_attention import ATTN_AUTO, normalize_attention_backend+ if normalize_attention_backend(requested) != ATTN_AUTO:+ return selected+ except Exception: # noqa: BLE001 -- unparseable request: leave it alone+ return selected+ cap = capability if capability is not None else _capability()+ if cap is None or tuple(cap) not in H3_FLASH_FASTER_ARCHS:+ return selected+ return _FLASH+++def _backend_value(backend: Any) -> Optional[str]:+ if backend is None:+ return None+ return str(getattr(backend, "value", backend))+++@lru_cache(maxsize = None)+def strided_processor_class() -> Any:+ """Strided ``MiniMaxH3AttnProcessor`` subclass. Built once: dynamo guards on the class id, so a class per call+ would retrace every block. Masks, context parallelism and other backends take the stock ``__call__``."""+ import torch+ import torch.nn.functional as F+ from diffusers.models.transformers.transformer_minimax_h3 import (+ MiniMaxH3AttnProcessor,+ _apply_rotary_emb,+ )+ from torch.nn.attention import SDPBackend, sdpa_kernel++ def _fusable_norm(norm: Any) -> bool:+ return (+ isinstance(norm, torch.nn.RMSNorm)+ and norm.weight is not None+ and norm.eps is not None+ and tuple(norm.normalized_shape) == (attn_head_dim(norm),)+ )++ def attn_head_dim(norm: Any) -> int:+ return int(norm.weight.shape[-1])++ kernels = {+ _CUDNN: SDPBackend.CUDNN_ATTENTION,+ _FLASH: SDPBackend.FLASH_ATTENTION,+ "_native_math": SDPBackend.MATH,+ "_native_efficient": SDPBackend.EFFICIENT_ATTENTION,+ }++ class UnslothH3StridedAttnProcessor(MiniMaxH3AttnProcessor):+ _unsloth_qk_rope = False++ def __call__(+ self,+ attn: Any,+ hidden_states: Any,+ rotary_emb: Any = None,+ attention_mask: Any = None,+ ) -> Any:+ kernel = kernels.get(_backend_value(self._attention_backend))+ if kernel is None or attention_mask is not None or self._parallel_config is not None:+ return super().__call__(attn, hidden_states, rotary_emb, attention_mask)+ if attn.fused_projections:+ query, key, value = attn.to_qkv(hidden_states).chunk(3, dim = -1)+ else:+ query = attn.to_q(hidden_states)+ key = attn.to_k(hidden_states)+ value = attn.to_v(hidden_states)++ query = query.unflatten(-1, (attn.heads, -1))+ key = key.unflatten(-1, (attn.heads, -1))+ value = value.unflatten(-1, (attn.heads, -1))++ if (+ rotary_emb is not None+ and self._unsloth_qk_rope+ and _fusable_norm(attn.norm_q)+ and _fusable_norm(attn.norm_k)+ ):+ # Through torch.ops, not the Python wrapper: dynamo graph-breaks inside the wrapper's lru_cache.+ cos, sin = rotary_emb+ op = torch.ops.unsloth_h3.qk_norm_rope+ query = op(query, attn.norm_q.weight, cos, sin, float(attn.norm_q.eps))+ key = op(key, attn.norm_k.weight, cos, sin, float(attn.norm_k.eps))+ else:+ query = attn.norm_q(query)+ key = attn.norm_k(key)+ if rotary_emb is not None:+ query = _apply_rotary_emb(query, *rotary_emb)+ key = _apply_rotary_emb(key, *rotary_emb)++ with sdpa_kernel(kernel):+ out = F.scaled_dot_product_attention(+ query.permute(0, 2, 1, 3),+ key.permute(0, 2, 1, 3),+ value.permute(0, 2, 1, 3),+ dropout_p = 0.0,+ is_causal = False,+ )+ hidden_states = out.permute(0, 2, 1, 3).flatten(2, 3).type_as(query)+ hidden_states = attn.to_out[0](hidden_states)+ hidden_states = attn.to_out[1](hidden_states)+ return hidden_states++ return UnslothH3StridedAttnProcessor+++def _h3_attention_modules(transformer: Any) -> list:+ try:+ from diffusers.models.transformers.transformer_minimax_h3 import MiniMaxH3Attention+ except Exception: # noqa: BLE001+ return []+ modules = getattr(transformer, "modules", None)+ if not callable(modules):+ return []+ return [m for m in modules() if isinstance(m, MiniMaxH3Attention)]+++def install_strided_attention(transformer: Any, logger: Any = None) -> int:+ """Swap every H3 attention processor for the strided one, keeping its backend. Returns the count."""+ if not _enabled(STRIDED_ATTN_ENV):+ return 0+ try:+ cls = strided_processor_class()+ except Exception as exc: # noqa: BLE001 -- older diffusers without the H3 processor+ if logger is not None:+ logger.info("video.h3_attn: strided processor unavailable, keeping stock: %s", exc)+ return 0+ from .video_minimax_h3_qknorm import qk_norm_rope_op, qk_rope_enabled++ qk_rope_on = qk_rope_enabled()+ if qk_rope_on:+ try:+ qk_norm_rope_op()+ except Exception as exc: # noqa: BLE001 -- keep the stock norm + rope+ qk_rope_on = False+ if logger is not None:+ logger.info("video.h3_attn: fused q/k norm+rope unavailable: %s", exc)+ swapped = 0+ for module in _h3_attention_modules(transformer):+ old = getattr(module, "processor", None)+ if old is None or isinstance(old, cls):+ continue+ new = cls()+ new._unsloth_qk_rope = qk_rope_on+ new._attention_backend = getattr(old, "_attention_backend", None)+ new._parallel_config = getattr(old, "_parallel_config", None)+ module.set_processor(new)+ swapped += 1+ if logger is not None and swapped:+ logger.info("video.h3_attn: strided SDPA layout on %d attention modules", swapped)+ return swapped+++def strided_attention_count(transformer: Any) -> int:+ """Engagement census."""+ try:+ cls = strided_processor_class()+ except Exception: # noqa: BLE001+ return 0+ return sum(+ 1+ for m in _h3_attention_modules(transformer)+ if isinstance(getattr(m, "processor", None), cls)+ )+++def _per_token_int8(weight: Any) -> bool:+ """Per-token activation quant (depends on the input alone, so appending weight rows cannot change it)."""+ name = type(weight).__name__+ if name == "LinearActivationQuantizedTensor":+ fn = getattr(weight, "input_quant_func", None)+ inner = getattr(weight, "original_weight_tensor", None)+ return (+ getattr(fn, "__name__", "").startswith("_int8_symm_per_token")+ and not getattr(weight, "quant_kwargs", None)+ and type(inner).__name__ == "AffineQuantizedTensor"+ and tuple(getattr(inner, "block_size", ())) == (1, int(weight.shape[-1]))+ )+ if name == "Int8Tensor":+ from .diffusion_int8_fused import _plain_int8_weight+ return _plain_int8_weight(weight)+ return False+++def _same_attr(a: Any, b: Any) -> bool:+ try:+ if isinstance(a, dict) and isinstance(b, dict):+ return a.keys() == b.keys() and all(_same_attr(a[k], b[k]) for k in a)+ if isinstance(a, (list, tuple)) and isinstance(b, (list, tuple)):+ return len(a) == len(b) and all(_same_attr(x, y) for x, y in zip(a, b))+ return bool(a == b)+ except Exception: # noqa: BLE001 -- uncomparable: treat as different+ return False+++def _cat_rows(parts: list) -> Any:+ """Row-concatenate tensors or identically structured torchao subclasses. Every inner tensor must be per row (a+ per-tensor scale is refused); non-tensor attributes must match, except a recorded outer shape, which is rewritten."""+ import torch++ t0 = parts[0]+ rows = [int(p.shape[0]) for p in parts]+ if any(type(p) is not type(t0) for p in parts):+ raise ValueError("projection weights differ in type")+ if any(+ p.dim() != t0.dim() or tuple(p.shape[1:]) != tuple(t0.shape[1:]) or p.dtype != t0.dtype+ for p in parts+ ):+ raise ValueError("projection weights differ in shape or dtype")+ if type(t0) is torch.Tensor:+ if t0.dim() == 0:+ raise ValueError("scalar leaf")+ return torch.cat([p.detach() for p in parts], dim = 0)+ flatten = getattr(t0, "__tensor_flatten__", None)+ unflatten = getattr(type(t0), "__tensor_unflatten__", None)+ if flatten is None or unflatten is None:+ raise ValueError(f"{type(t0).__name__} is not a flattenable tensor subclass")+ names, ctx = flatten()+ own = tuple(t0.shape)++ def is_shape(x: Any, shape: tuple) -> bool:+ return isinstance(x, (tuple, list, torch.Size)) and tuple(x) == shape++ def normalised(c: Any, shape: tuple) -> Any:+ if isinstance(c, dict):+ return {k: ("<outer-shape>" if is_shape(v, shape) else v) for k, v in c.items()}+ return ["<outer-shape>" if is_shape(x, shape) else x for x in c]++ for p in parts[1:]:+ p_names, p_ctx = p.__tensor_flatten__()+ if list(p_names) != list(names) or not _same_attr(+ normalised(p_ctx, tuple(p.shape)), normalised(ctx, own)+ ):+ raise ValueError("projection weights differ in quantization attributes")+ inner = {}+ for n in names:+ leaves = [getattr(p, n) for p in parts]+ if any(leaf.dim() == 0 or int(leaf.shape[0]) != r for leaf, r in zip(leaves, rows)):+ raise ValueError(f"{type(t0).__name__}.{n} is not per-row")+ inner[n] = _cat_rows(leaves)+ size = torch.Size((sum(rows), *own[1:]))+ if isinstance(ctx, dict):+ new_ctx: Any = {k: (size if is_shape(v, own) else v) for k, v in ctx.items()}+ else:+ new_ctx = [size if is_shape(x, own) else x for x in ctx]+ if isinstance(ctx, tuple):+ new_ctx = tuple(new_ctx)+ return unflatten(inner, new_ctx, size, None)+++def _fusable_parts(module: Any) -> Optional[tuple]:+ """(to_q, to_k, to_v, rotation group or None), or None when not fusable."""+ from .diffusion_convrot import is_rotated_linear++ if getattr(module, "fused_projections", False):+ return None+ parts = tuple(getattr(module, name, None) for name in ("to_q", "to_k", "to_v"))+ if any(p is None for p in parts):+ return None+ from torch import nn++ # never a wrapper: an unpadded token refiner (PadToMinM) hits _int_mm's M > 16 assert on a short compiled prompt+ if not all(isinstance(p, nn.Linear) for p in parts):+ return None+ if not all(_per_token_int8(getattr(p, "weight", None)) for p in parts):+ return None+ if any(getattr(p, "bias", None) is not None for p in parts):+ return None+ # Hooks (offload, prefetch, LoRA) are keyed to the three modules; a fused module would silently drop them.+ if any(+ getattr(p, "_forward_pre_hooks", None) or getattr(p, "_forward_hooks", None) for p in parts+ ):+ return None+ if any(hasattr(p, "_hf_hook") or hasattr(p, "_diffusers_hook") for p in parts):+ return None+ if len({type(p) for p in parts}) != 1 or len({p.weight.device for p in parts}) != 1:+ return None+ rotated = [is_rotated_linear(p) for p in parts]+ if any(rotated) and not all(rotated):+ return None+ group = None+ if rotated[0]:+ groups = {int(p.convrot_groupsize) for p in parts}+ if len(groups) != 1:+ return None+ group = groups.pop()+ return parts[0], parts[1], parts[2], group+++def _self_check(parts: tuple, fused: Any) -> bool:+ """Bit-exact against the three projections on this device."""+ import torch++ w = parts[0].weight+ device = w.device+ dtype = getattr(w, "dtype", torch.bfloat16)+ g = torch.Generator(device = device).manual_seed(0)+ x = torch.randn(1, 33, int(w.shape[-1]), device = device, dtype = dtype, generator = g)+ with torch.no_grad():+ ref = torch.cat([p(x) for p in parts], dim = -1)+ out = fused(x)+ return out.shape == ref.shape and torch.equal(out, ref)+++def fuse_h3_qkv_(transformer: Any, logger: Any = None) -> int:+ """Fuse ``to_q``/``to_k``/``to_v`` into ``to_qkv`` in place where ``_fusable_parts`` allows and ``_self_check``+ passes; one module at a time, so the transient extra memory is one block's QKV."""+ if not _enabled(FUSED_QKV_ENV):+ return 0+ from torch import nn++ from .diffusion_convrot import _install_rotation++ fused = 0+ for module in _h3_attention_modules(transformer):+ try:+ spec = _fusable_parts(module)+ except Exception: # noqa: BLE001 -- not this layout+ spec = None+ if spec is None:+ continue+ to_q, to_k, to_v, group = spec+ try:+ weight = _cat_rows([to_q.weight, to_k.weight, to_v.weight])+ linear = nn.Linear(+ int(weight.shape[1]), int(weight.shape[0]), bias = False, device = "meta"+ )+ linear.weight = nn.Parameter(weight, requires_grad = False)+ if group is not None:+ _install_rotation(linear, group)+ if not _self_check((to_q, to_k, to_v), linear):+ raise ValueError("fused output differs from the three projections")+ except Exception as exc: # noqa: BLE001 -- leave this module unfused+ if logger is not None:+ logger.info("video.h3_attn: QKV left unfused: %s", exc)+ continue+ module.to_qkv = linear+ module.fused_projections = True+ for name in ("to_q", "to_k", "to_v"):+ delattr(module, name)+ fused += 1+ if fused:+ # The freed per-projection blocks are fragments the larger fused weights cannot reuse (~5.8 GB on G4).+ try:+ import torch+ if torch.cuda.is_available():+ torch.cuda.empty_cache()+ except Exception: # noqa: BLE001+ pass+ if logger is not None:+ logger.info("video.h3_attn: fused int8 QKV on %d attention modules", fused)+ return fused+++def fused_qkv_count(transformer: Any) -> int:+ """Engagement census."""+ return sum(+ 1 for m in _h3_attention_modules(transformer) if getattr(m, "fused_projections", False)+ )diff --git a/studio/backend/core/inference/video_minimax_h3_qknorm.py b/studio/backend/core/inference/video_minimax_h3_qknorm.pynew file mode 100644index 00000000000..f3207dc087d--- /dev/null+++ b/studio/backend/core/inference/video_minimax_h3_qknorm.py@@ -0,0 +1,221 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""MiniMax-H3 fused q/k RMSNorm + partial RoPE, one read and one write per row (``UNSLOTH_H3_QK_ROPE=0`` = off).++Rounds where the eager bf16 chain rounds; only the order of the sum of squares is free, so rstd can differ in the+last fp32 bit (bounded at one bf16 step by the tests). Opaque custom op with a fake kernel; Triton on NVIDIA CUDA+only, the stock math everywhere else.+"""++from __future__ import annotations++import os+from functools import lru_cache+from typing import Any++QK_ROPE_ENV = "UNSLOTH_H3_QK_ROPE"+_OP = "unsloth_h3::qk_norm_rope"+++def qk_rope_enabled() -> bool:+ return (os.environ.get(QK_ROPE_ENV) or "1").strip().lower() not in ("0", "off", "false", "no")+++def reference_qk_norm_rope(x: Any, weight: Any, cos: Any, sin: Any, eps: float) -> Any:+ """The stock math (RMSNorm then diffusers' ``_apply_rotary_emb``), contiguous."""+ import torch+ import torch.nn.functional as F++ x = F.rms_norm(x, (x.shape[-1],), weight, eps)+ rotary_dim = cos.shape[-1]+ xr = x[..., :rotary_dim]+ xp = x[..., rotary_dim:]+ cos = cos.to(x.dtype)[None, :, None, :]+ sin = sin.to(x.dtype)[None, :, None, :]+ x1, x2 = xr.chunk(2, dim = -1)+ rot = torch.cat((-x2, x1), dim = -1)+ xr = xr * cos + rot * sin+ return torch.cat((xr, xp), dim = -1).contiguous()+++@lru_cache(maxsize = None)+def _kernel() -> Any:+ import triton+ import triton.language as tl++ try:+ from triton.language.extra import libdevice+ except Exception: # noqa: BLE001 -- older Triton layout+ from triton.language.extra.cuda import libdevice++ # rsqrt as torch's norm (not 1/sqrt); *_rn because Triton otherwise FMA-contracts away eager's bf16 roundings.+ _rsqrt = libdevice.rsqrt+ _mul = libdevice.mul_rn+ _add = libdevice.add_rn++ @triton.jit+ def _qk_norm_rope_kernel(+ x_ptr,+ w_ptr,+ cos_ptr,+ sin_ptr,+ out_ptr,+ n_rows,+ n_heads,+ stride_s,+ stride_h,+ cos_stride,+ eps,+ D: tl.constexpr,+ HALF: tl.constexpr,+ ROWS: tl.constexpr,+ ):+ pid = tl.program_id(0).to(tl.int64)+ rows = pid * ROWS + tl.arange(0, ROWS).to(tl.int64)+ row_ok = rows < n_rows+ s = rows // n_heads+ h = rows % n_heads+ cols = tl.arange(0, D)+ partner = tl.where(cols < HALF, cols + HALF, tl.where(cols < 2 * HALF, cols - HALF, cols))+ base = s * stride_s + h * stride_h+ mask = row_ok[:, None]+ x = tl.load(x_ptr + base[:, None] + cols[None, :], mask = mask, other = 0.0).to(tl.float32)+ xpart = tl.load(x_ptr + base[:, None] + partner[None, :], mask = mask, other = 0.0).to(+ tl.float32+ )+ w = tl.load(w_ptr + cols).to(tl.float32)+ wpart = tl.load(w_ptr + partner).to(tl.float32)+ ms = tl.sum(x * x, axis = 1) / D+ rstd = _rsqrt(ms + eps)+ xn = _mul(_mul(x, rstd[:, None]), w[None, :]).to(out_ptr.dtype.element_ty)+ pn = _mul(_mul(xpart, rstd[:, None]), wpart[None, :]).to(out_ptr.dtype.element_ty)+ rot_cols = cols < 2 * HALF+ cmask = mask & rot_cols[None, :]+ c = tl.load(cos_ptr + s[:, None] * cos_stride + cols[None, :], mask = cmask, other = 0.0)+ sn = tl.load(sin_ptr + s[:, None] * cos_stride + cols[None, :], mask = cmask, other = 0.0)+ c = c.to(out_ptr.dtype.element_ty).to(tl.float32)+ sn = sn.to(out_ptr.dtype.element_ty).to(tl.float32)+ sign = tl.where(cols < HALF, -1.0, 1.0)+ a = _mul(xn.to(tl.float32), c).to(out_ptr.dtype.element_ty).to(tl.float32)+ b = _mul(pn.to(tl.float32) * sign[None, :], sn).to(out_ptr.dtype.element_ty).to(tl.float32)+ roped = _add(a, b).to(out_ptr.dtype.element_ty)+ y = tl.where(rot_cols[None, :], roped, xn)+ tl.store(out_ptr + rows[:, None] * D + cols[None, :], y, mask = mask)++ return _qk_norm_rope_kernel+++def _triton_ok(x: Any) -> bool:+ try:+ import torch+ if not (x.is_cuda and torch.version.hip is None):+ return False+ import triton # noqa: F401+ except Exception: # noqa: BLE001+ return False+ return (+ x.dim() == 4+ and x.dtype in (torch.bfloat16, torch.float16)+ and x.stride(-1) == 1+ and x.shape[0] == 1+ and x.shape[-1] in (64, 128, 256)+ )+++_ROWS = 16+_WARPS = 4+++def _launch(+ x: Any,+ weight: Any,+ cos: Any,+ sin: Any,+ eps: float,+ rows_per_program: int = 0,+ warps: int = 0,+) -> Any:+ import torch++ _, seq, heads, dim = x.shape+ half = cos.shape[-1] // 2+ out = torch.empty((1, seq, heads, dim), device = x.device, dtype = x.dtype)+ cos = cos.contiguous()+ sin = sin.contiguous()+ rows = seq * heads+ block = int(rows_per_program or _ROWS)+ grid = (triton_cdiv(rows, block),)+ with torch.cuda.device(x.device):+ _kernel()[grid](+ x,+ weight.contiguous(),+ cos,+ sin,+ out,+ rows,+ heads,+ x.stride(1),+ x.stride(2),+ cos.stride(0),+ float(eps),+ D = dim,+ HALF = half,+ ROWS = block,+ num_warps = int(warps or _WARPS),+ )+ return out+++def triton_cdiv(a: int, b: int) -> int:+ return (a + b - 1) // b+++def _supported_layout(x: Any, weight: Any, cos: Any) -> bool:+ return (+ cos.dim() == 2+ and cos.shape[0] == x.shape[1]+ and cos.shape[-1] % 2 == 0+ and cos.shape[-1] <= x.shape[-1]+ and weight is not None+ and weight.shape == (x.shape[-1],)+ )+++def qk_norm_rope_impl(x: Any, weight: Any, cos: Any, sin: Any, eps: float) -> Any:+ """Triton where it applies, the stock math elsewhere."""+ if _triton_ok(x) and _supported_layout(x, weight, cos):+ try:+ return _launch(x, weight, cos, sin, eps)+ except Exception: # noqa: BLE001+ pass+ return reference_qk_norm_rope(x, weight, cos, sin, eps)+++@lru_cache(maxsize = None)+def qk_norm_rope_op() -> Any:+ """Registered once per process."""+ import torch++ # explicit schema: the annotations here are strings+ @torch.library.custom_op(+ _OP,+ mutates_args = (),+ schema = "(Tensor x, Tensor weight, Tensor cos, Tensor sin, float eps) -> Tensor",+ )+ def qk_norm_rope(x, weight, cos, sin, eps):+ return qk_norm_rope_impl(x, weight, cos, sin, eps)++ @qk_norm_rope.register_fake+ def _(x, weight, cos, sin, eps):+ return x.new_empty(x.shape)++ return qk_norm_rope+++def qk_norm_rope(x: Any, weight: Any, cos: Any, sin: Any, eps: float) -> Any:+ """Eager only: compiled code calls ``torch.ops.unsloth_h3.qk_norm_rope`` (dynamo graph-breaks in here)."""+ import torch++ qk_norm_rope_op()+ return torch.ops.unsloth_h3.qk_norm_rope(x, weight, cos, sin, eps)diff --git a/studio/backend/tests/test_video_minimax_h3_attn.py b/studio/backend/tests/test_video_minimax_h3_attn.pynew file mode 100644index 00000000000..ac9e2c0fd08--- /dev/null+++ b/studio/backend/tests/test_video_minimax_h3_attn.py@@ -0,0 +1,422 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""MiniMax-H3 attention levers on a tiny real H3 transformer quantized like the hosted one: bit-identity vs stock,+kill switches, refusals."""++from __future__ import annotations++import copy++import pytest+import torch++h3 = pytest.importorskip("diffusers.models.transformers.transformer_minimax_h3")+pytest.importorskip("torchao")++from core.inference import video_minimax_h3_attn as A # noqa: E402+from core.inference.diffusion_convrot import is_rotated_linear, rotate_linears_ # noqa: E402++GROUP = 16++[email protected](autouse = True)+def _restore_process_flags():+ # set_attention_backend also sets diffusers' process-wide ACTIVE backend, and quantize_ sets inductor globals.+ import torch._inductor.config as inductor_config+ from diffusers.models.attention_dispatch import _AttentionBackendRegistry++ active_backend = _AttentionBackendRegistry._active_backend++ precision = torch.get_float32_matmul_precision()+ knobs = (+ "coordinate_descent_tuning",+ "coordinate_descent_check_all_directions",+ "force_fuse_int_mm_with_mul",+ "fx_graph_cache",+ )+ saved = {k: getattr(inductor_config, k) for k in knobs if hasattr(inductor_config, k)}+ yield+ if torch.cuda.is_available():+ torch.cuda.synchronize()+ torch.cuda.empty_cache()+ _AttentionBackendRegistry.set_active_backend(active_backend)+ torch.set_float32_matmul_precision(precision)+ for k, v in saved.items():+ setattr(inductor_config, k, v)+++def _tiny_model() -> torch.nn.Module:+ torch.manual_seed(0)+ model = h3.MiniMaxH3Transformer3DModel(+ num_attention_heads = 2,+ attention_head_dim = 32,+ hidden_size = 64,+ num_layers = 2,+ num_refiner_layers = 1,+ ffn_dim = 128,+ in_channels = 4,+ audio_in_channels = 4,+ patch_size = (1, 2, 2),+ text_dim = 32,+ freq_dim = 32,+ time_embed_hidden_dim = 64,+ time_embed_dim = 32,+ rope_freq_dim = 4,+ )+ return model.eval()+++def _quantize(+ model: torch.nn.Module,+ rotate: bool = True,+ version: int = 1,+) -> torch.nn.Module:+ from torchao.quantization import Int8DynamicActivationInt8WeightConfig, quantize_++ if rotate:+ fqns = [+ name+ for name, m in model.named_modules()+ if isinstance(m, torch.nn.Linear)+ and name.startswith("transformer_blocks.")+ and (".attn." in name or ".ff." in name)+ ]+ rotate_linears_(model, fqns, GROUP)++ def only_blocks(m, fqn):+ return isinstance(m, torch.nn.Linear) and fqn.startswith(+ ("transformer_blocks.", "token_refiner.")+ )++ try:+ config = Int8DynamicActivationInt8WeightConfig(version = version)+ except (TypeError, ValueError):+ if version != 1 or not hasattr(+ Int8DynamicActivationInt8WeightConfig, "__dataclass_fields__"+ ):+ pytest.skip(f"this torchao cannot build int8 weights version {version}")+ try:+ config = Int8DynamicActivationInt8WeightConfig()+ if getattr(config, "version", 1) != 1:+ pytest.skip("this torchao cannot build int8 weights version 1")+ except Exception:+ pytest.skip("this torchao cannot build int8 weights version 1")+ quantize_(model, config, filter_fn = only_blocks)+ return model+++def _inputs(seed: int = 1) -> dict:+ g = torch.Generator().manual_seed(seed)+ n_text, n_video, n_audio = 5, 8, 3+ seq = n_text + n_video + n_audio+ text_idx = torch.arange(0, n_text)+ video_idx = torch.arange(n_text, n_text + n_video)+ audio_idx = torch.arange(n_text + n_video, seq)+ tags = torch.zeros(seq, dtype = torch.long)+ tags[text_idx] = 1+ tags[audio_idx] = 2+ pos = torch.randint(0, 6, (seq, 3), generator = g)+ return dict(+ hidden_states = torch.randn(1, n_video, 16, generator = g),+ audio_hidden_states = torch.randn(1, n_audio, 4, generator = g),+ encoder_hidden_states = torch.randn(1, n_text, 32, generator = g),+ timestep = torch.tensor([0.7, 0.2]),+ timestep_indices = torch.randint(0, 2, (seq,), generator = g),+ token_tags = tags,+ position_ids = pos,+ video_indices = video_idx,+ audio_indices = audio_idx,+ text_indices = text_idx,+ return_dict = False,+ )+++def _run(model, **kw):+ with torch.no_grad():+ return model(**_inputs(), **kw)++[email protected](params = [1, 2], ids = ["v1_laqt", "v2_int8tensor"])+def quantized(request):+ return _quantize(_tiny_model(), version = request.param)+++def _equal(a, b) -> bool:+ return all(torch.equal(x, y) for x, y in zip(a, b))+++def test_fused_qkv_matches_the_three_projections_bit_for_bit(quantized):+ stock = copy.deepcopy(quantized)+ n = A.fuse_h3_qkv_(quantized)+ assert n == 3+ assert A.fused_qkv_count(quantized) == 3+ assert _equal(_run(stock), _run(quantized))+++def test_fused_module_keeps_the_rotation_and_a_per_row_int8_weight(quantized):+ kind = type(quantized.transformer_blocks[0].attn.to_q.weight)+ A.fuse_h3_qkv_(quantized)+ attn = quantized.transformer_blocks[0].attn+ assert attn.fused_projections is True+ for name in ("to_q", "to_k", "to_v"):+ assert not hasattr(attn, name)+ assert is_rotated_linear(attn.to_qkv) and attn.to_qkv.convrot_groupsize == GROUP+ assert type(attn.to_qkv.weight) is kind and A._per_token_int8(attn.to_qkv.weight)+ assert tuple(attn.to_qkv.weight.shape) == (3 * 64, 64)+ refiner_attn = quantized.token_refiner.refiner_blocks[0].attn+ assert refiner_attn.fused_projections is True and not is_rotated_linear(refiner_attn.to_qkv)+++def test_fused_qkv_kill_switch_leaves_the_model_alone(quantized, monkeypatch):+ monkeypatch.setenv(A.FUSED_QKV_ENV, "0")+ assert A.fuse_h3_qkv_(quantized) == 0+ assert A.fused_qkv_count(quantized) == 0+ assert hasattr(quantized.transformer_blocks[0].attn, "to_q")+++def test_dense_projections_are_not_fused():+ model = _tiny_model()+ assert A.fuse_h3_qkv_(model) == 0+ assert hasattr(model.transformer_blocks[0].attn, "to_q")+++def test_projections_with_a_hook_or_bias_are_not_fused(quantized):+ attn0 = quantized.transformer_blocks[0].attn+ attn1 = quantized.transformer_blocks[1].attn+ attn0.to_k.register_forward_pre_hook(lambda m, a: None)+ attn1.to_v.bias = torch.nn.Parameter(torch.zeros(64))+ A.fuse_h3_qkv_(quantized)+ assert not attn0.fused_projections and hasattr(attn0, "to_k")+ assert not attn1.fused_projections and hasattr(attn1, "to_v")+ assert quantized.token_refiner.refiner_blocks[0].attn.fused_projections+++def test_padded_projections_are_not_fused(quantized):+ from core.inference.diffusion_quant_pad import PadToMinM+ from core.inference.diffusion_transformer_quant import apply_small_m_padding++ assert apply_small_m_padding(quantized, "int8", "minimax-h3")+ refiner = quantized.token_refiner.refiner_blocks[0].attn+ assert isinstance(refiner.to_q, PadToMinM)+ assert A.fuse_h3_qkv_(quantized) == 2+ assert not refiner.fused_projections and isinstance(refiner.to_q, PadToMinM)+ assert quantized.transformer_blocks[0].attn.fused_projections+++def test_mixed_rotation_is_not_fused(quantized):+ attn = quantized.transformer_blocks[0].attn+ attn.to_k.convrot_groupsize = 64+ A.fuse_h3_qkv_(quantized)+ assert not attn.fused_projections++[email protected]("fuse", [False, True])+def test_strided_processor_matches_stock_bit_for_bit(quantized, fuse):+ quantized.set_attention_backend("_native_math")+ if fuse:+ A.fuse_h3_qkv_(quantized)+ stock = copy.deepcopy(quantized)+ n = A.install_strided_attention(quantized)+ assert n == 3 and A.strided_attention_count(quantized) == 3+ assert (+ A._backend_value(quantized.transformer_blocks[0].attn.processor._attention_backend)+ == "_native_math"+ )+ assert _equal(_run(stock), _run(quantized))+++def test_strided_processor_defers_to_stock_for_other_backends(quantized):+ A.install_strided_attention(quantized)+ proc = quantized.transformer_blocks[0].attn.processor+ proc._attention_backend = None+ stock = copy.deepcopy(quantized)+ for m in stock.modules():+ if isinstance(m, h3.MiniMaxH3Attention):+ m.set_processor(h3.MiniMaxH3AttnProcessor())+ assert _equal(_run(stock), _run(quantized))+++def test_strided_kill_switch(quantized, monkeypatch):+ monkeypatch.setenv(A.STRIDED_ATTN_ENV, "0")+ assert A.install_strided_attention(quantized) == 0+ assert A.strided_attention_count(quantized) == 0+++def test_install_is_idempotent(quantized):+ assert A.install_strided_attention(quantized) == 3+ assert A.install_strided_attention(quantized) == 0+ assert A.strided_attention_count(quantized) == 3+++ "selected,cap,expected",+ [+ ("_native_cudnn", (8, 0), "_native_flash"),+ ("_native_cudnn", (8, 9), "_native_flash"),+ ("_native_cudnn", (12, 0), "_native_cudnn"),+ ("_native_cudnn", (9, 0), "_native_cudnn"),+ ("_native_cudnn", (10, 0), "_native_cudnn"),+ ("_native_cudnn", (8, 6), "_native_cudnn"),+ ("flash", (8, 0), "flash"),+ ("sage", (8, 9), "sage"),+ (None, (8, 0), None),+ ],+)+def test_arch_pick_moves_only_the_automatic_cudnn_pick_on_measured_archs(selected, cap, expected):+ assert A.h3_attention_backend(selected, cap) == expected++[email protected]("requested", ["cudnn", "flash", "native"])+def test_arch_pick_keeps_an_explicit_request(requested):+ assert A.h3_attention_backend("_native_cudnn", (8, 0), requested = requested) == "_native_cudnn"+ assert A.h3_attention_backend("_native_cudnn", (8, 0), requested = "auto") == "_native_flash"+++def test_h3_load_wires_the_request_and_the_speed_gate():+ import ast+ import inspect+ import textwrap++ from core.inference.video import VideoBackend++ tree = ast.parse(textwrap.dedent(inspect.getsource(VideoBackend._load_h3_modular_pipeline)))+ calls = [+ n+ for n in ast.walk(tree)+ if isinstance(n, ast.Call) and getattr(n.func, "id", "") == "h3_attention_backend"+ ]+ assert calls and all(any(k.arg == "requested" for k in c.keywords) for c in calls)+ gates = [+ n+ for n in ast.walk(tree)+ if isinstance(n, ast.If)+ and any(+ getattr(c.func, "id", "") == "install_strided_attention"+ for c in ast.walk(n)+ if isinstance(c, ast.Call)+ )+ ]+ assert any("SPEED_OFF" in ast.unparse(g.test) for g in gates)+++def test_arch_pick_kill_switch(monkeypatch):+ monkeypatch.setenv(A.ATTN_ARCH_ENV, "0")+ assert A.h3_attention_backend("_native_cudnn", (8, 0)) == "_native_cudnn"++[email protected](not torch.cuda.is_available(), reason = "cuDNN / flash SDPA need CUDA")[email protected]("backend", ["_native_cudnn", "_native_flash"])+def test_strided_processor_on_cuda_matches_the_stock_backend(backend):+ model = _tiny_model().to("cuda", torch.bfloat16)+ model.set_attention_backend(backend)+ stock = copy.deepcopy(model)+ assert A.install_strided_attention(model) == 3+ kw = {k: (v.to("cuda") if torch.is_tensor(v) else v) for k, v in _inputs().items()}+ for k in ("hidden_states", "audio_hidden_states", "encoder_hidden_states"):+ kw[k] = kw[k].to(torch.bfloat16)+ with torch.no_grad():+ assert _equal(stock(**kw), model(**kw))+++from core.inference import video_minimax_h3_qknorm as Q # noqa: E402+++def _qk_inputs(+ device = "cpu",+ dtype = torch.bfloat16,+ seq = 37,+ heads = 3,+ dim = 128,+ rot = 96,+ strided = False,+):+ g = torch.Generator(device = device).manual_seed(3)+ if strided:+ qkv = torch.randn(1, seq, 3 * heads * dim, device = device, dtype = dtype, generator = g)+ x = qkv[..., : heads * dim].unflatten(-1, (heads, dim))+ else:+ x = torch.randn(1, seq, heads, dim, device = device, dtype = dtype, generator = g)+ w = (1 + 0.2 * torch.randn(dim, device = device, generator = g)).to(dtype)+ ang = torch.rand(seq, rot // 2, device = device, generator = g) * 30+ ang = torch.cat((ang, ang), dim = -1)+ return x, w, ang.cos(), ang.sin()+++def test_qk_norm_rope_reference_is_the_stock_module_chain():+ x, w, cos, sin = _qk_inputs()+ norm = torch.nn.RMSNorm(128, eps = 1e-5).to(torch.bfloat16)+ norm.weight.data.copy_(w)+ stock = h3._apply_rotary_emb(norm(x), cos, sin)+ assert torch.equal(Q.reference_qk_norm_rope(x, w, cos, sin, 1e-5), stock)+++def test_qk_norm_rope_op_off_cuda_is_the_stock_math():+ x, w, cos, sin = _qk_inputs()+ assert torch.equal(+ Q.qk_norm_rope(x, w, cos, sin, 1e-5), Q.reference_qk_norm_rope(x, w, cos, sin, 1e-5)+ )+++def test_strided_processor_with_fused_qk_rope_matches_stock(quantized):+ quantized.set_attention_backend("_native_math")+ stock = copy.deepcopy(quantized)+ A.install_strided_attention(quantized)+ assert quantized.transformer_blocks[0].attn.processor._unsloth_qk_rope is True+ assert _equal(_run(stock), _run(quantized))+++def test_fused_qk_rope_kill_switch(quantized, monkeypatch):+ monkeypatch.setenv(Q.QK_ROPE_ENV, "0")+ A.install_strided_attention(quantized)+ assert quantized.transformer_blocks[0].attn.processor._unsloth_qk_rope is False++[email protected](not torch.cuda.is_available(), reason = "the Triton kernel runs on CUDA only")[email protected]("dtype", [torch.bfloat16, torch.float16])[email protected]("strided", [False, True])[email protected]("seq", [1, 777])+def test_qk_kernel_matches_the_compiled_stock_math(dtype, strided, seq):+ import torch._inductor.config as ic++ x, w, cos, sin = _qk_inputs("cuda", dtype, seq = seq, heads = 56, strided = strided)+ ours = Q._launch(x, w, cos, sin, 1e-5)+ eager = Q.reference_qk_norm_rope(x, w, cos, sin, 1e-5)+ prev = ic.emulate_precision_casts+ ic.emulate_precision_casts = True+ try:+ compiled = torch.compile(Q.reference_qk_norm_rope, dynamic = False)(x, w, cos, sin, 1e-5)+ finally:+ ic.emulate_precision_casts = prev+ assert ours.is_contiguous() and ours.shape == x.shape+ # Only the sum-of-squares order is free: a few rows may land one rounding step away.+ budget = ours.numel() // (100000 if dtype == torch.bfloat16 else 20000)+ for ref in (eager, compiled):+ diff = (ours.float() - ref.float()).abs()+ assert int((ours != ref).sum()) <= max(2, budget)+ assert float(diff.max()) <= float((ref.float().abs().max() * 2**-7))+ # negative control: a one-ulp-scale perturbation must be caught+ bad = (ours.float() * (1 + 2**-7)).to(dtype)+ assert int((bad != eager).sum()) > ours.numel() // 2+++def _graph_breaks(model) -> int:+ import torch._dynamo++ torch._dynamo.reset()+ with torch.no_grad():+ explained = torch._dynamo.explain(model)(**_inputs())+ torch._dynamo.reset()+ return explained.graph_break_count++[email protected]("qk_rope", ["1", "0"])+def test_strided_processor_adds_no_graph_break(monkeypatch, qk_rope):+ # A break here splits every compiled block in two (2x slower steps).+ monkeypatch.setenv(Q.QK_ROPE_ENV, qk_rope)+ model = _tiny_model()+ model.set_attention_backend("_native_math")+ stock = _graph_breaks(model)+ assert A.install_strided_attention(model) > 0+ assert model.transformer_blocks[0].attn.processor._unsloth_qk_rope is (qk_rope == "1")+ assert _graph_breaks(model) == stock