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.

Diffusion: four fixes salvaged from the stale #7021 (#8006)

Daniel Han17fe73cd9e27
diff --git a/scripts/sdpa_mask_backend_probe.py b/scripts/sdpa_mask_backend_probe.py
new file mode 100644
index 00000000000..0dfd25ea7c7
--- /dev/null
+++ b/scripts/sdpa_mask_backend_probe.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+"""Which SDPA backends tolerate a dense bool attn_mask, and at what cost, at Hunyuan's real
+joint shape (B=1, H=16, N=50345, D=128, bf16)? Decides whether nulling the all-True mask is
+the real win on the PRODUCTION cuDNN path (not just the native math fallback)."""
+
+import time
+import torch
+import torch.nn.functional as F
+from torch.nn.attention import SDPBackend, sdpa_kernel
+
+B, H, N, D = 1, 16, 50345, 128
+dev, dt = "cuda:0", torch.bfloat16
+
+
+def mk():
+ return torch.randn(B, H, N, D, device = dev, dtype = dt)
+
+
+def timed(fn, iters = 20):
+ try:
+ torch.cuda.synchronize()
+ for _ in range(3):
+ fn()
+ torch.cuda.synchronize()
+ t0 = time.perf_counter()
+ for _ in range(iters):
+ fn()
+ torch.cuda.synchronize()
+ return (time.perf_counter() - t0) / iters * 1e3
+ except torch.OutOfMemoryError:
+ # OOM on the dense NxN mask is a memory limit, not a backend rejecting it; don't mislabel UNSUPPORTED.
+ torch.cuda.empty_cache()
+ return "OOM"
+ except Exception as e: # noqa: BLE001
+ return f"UNSUPPORTED ({type(e).__name__})"
+
+
+q, k, v = mk(), mk(), mk()
+dense = torch.ones(B, 1, N, N, dtype = torch.bool, device = dev)
+
+backends = {
+ "default(dispatch)": None,
+ "MATH": [SDPBackend.MATH],
+ "FLASH": [SDPBackend.FLASH_ATTENTION],
+ "EFFICIENT": [SDPBackend.EFFICIENT_ATTENTION],
+ "CUDNN": [SDPBackend.CUDNN_ATTENTION],
+}
+
+print(f"shape B={B} H={H} N={N} D={D} {dt}\n")
+print(f"{'backend':<20}{'mask=dense(ms)':>18}{'mask=None(ms)':>18}")
+for name, bk in backends.items():
+
+ def run_dense():
+ if bk is None:
+ return F.scaled_dot_product_attention(q, k, v, attn_mask = dense)
+ with sdpa_kernel(bk):
+ return F.scaled_dot_product_attention(q, k, v, attn_mask = dense)
+
+ def run_none():
+ if bk is None:
+ return F.scaled_dot_product_attention(q, k, v, attn_mask = None)
+ with sdpa_kernel(bk):
+ return F.scaled_dot_product_attention(q, k, v, attn_mask = None)
+
+ dms = timed(run_dense)
+ nms = timed(run_none)
+ d_s = f"{dms:.2f}" if isinstance(dms, float) else dms
+ n_s = f"{nms:.2f}" if isinstance(nms, float) else nms
+ print(f"{name:<20}{d_s:>18}{n_s:>18}")
diff --git a/studio/backend/core/inference/diffusion_attention.py b/studio/backend/core/inference/diffusion_attention.py
index cded7dbc1a8..5df20de742b 100644
--- a/studio/backend/core/inference/diffusion_attention.py
+++ b/studio/backend/core/inference/diffusion_attention.py
@@ -177,6 +177,40 @@ def _pip_requirement(backend: str, package: str) -> str:
return package
+# The huggingface_hub floor the current `kernels` wheels declare (kernels >= 0.14.1 requires
+# huggingface-hub >= 1.10.0). A (major, minor) pair, compared against the resident hub below.
+_KERNELS_HUB_FLOOR = (1, 10)
+
+
+def _kernels_hub_compatible() -> bool:
+ """Whether installing the ``kernels`` package is SAFE next to the resident huggingface_hub.
+
+ Current ``kernels`` wheels declare ``huggingface_hub >= 1.10`` and build their dependency
+ tables against that API, and with an older hub the breakage is NOT contained to the requested
+ backend: ``import kernels`` raises at module scope, and diffusers imports ``kernels`` whenever
+ it is installed, so EVERY later pipeline import in every process fails until the package is
+ uninstalled. Measured with kernels 0.16.0: hub 1.0.0-1.2.4 raise
+ ``StrictDataclassFieldValidationError`` on ``import kernels`` (the strict dataclasses only
+ learned ``str | None`` unions in hub 1.3.0), and 1.3-1.9 merely happen to work today, below
+ the floor kernels supports. The whole 1.x range under 1.10 is therefore refused rather than
+ trusted, since the install is unpinned and a future kernels may use any 1.10 API. The
+ requested hub backend falls back to native instead. An undeterminable hub version allows the
+ install, which keeps the previous behaviour.
+
+ A ``--no-deps`` install cannot self-correct here: pip writes the wheel without ever reading
+ its ``Requires-Dist``, so this predicate is the only thing enforcing that floor."""
+ try:
+ import re
+ from importlib.metadata import version
+
+ m = re.match(r"\s*(\d+)(?:\.(\d+))?", version("huggingface_hub"))
+ if m is None:
+ return True
+ return (int(m.group(1)), int(m.group(2) or 0)) >= _KERNELS_HUB_FLOOR
+ except Exception: # noqa: BLE001 — unknown hub -> keep the previous permissive behaviour
+ return True
+
+
def _ensure_attention_backend_installed(backend: str, logger: Any = None) -> None:
"""Best-effort wheel-only install of the package ``backend`` needs, when allowed.
@@ -193,6 +227,20 @@ def _ensure_attention_backend_installed(backend: str, logger: Any = None) -> Non
gate = os.environ.get(_ATTENTION_INSTALL_ENV, "auto").strip().lower()
if gate in ("0", "false", "no", "off"):
return
+ # Refusing is a POLICY decision, not a failed attempt, so it is checked before the
+ # _INSTALL_ATTEMPTED memo below and records nothing: a later request on a fixed environment
+ # must still be able to install. Scoped to kernels; the sage / flash-attn / xformers wheels
+ # do not import huggingface_hub at module scope.
+ if package == "kernels" and not _kernels_hub_compatible():
+ if logger is not None:
+ logger.warning(
+ "diffusion.attention: not installing 'kernels' for backend=%s — the resident "
+ "huggingface_hub is below %d.%d and a kernels install would break every later "
+ "diffusers pipeline import; using the default backend",
+ backend,
+ *_KERNELS_HUB_FLOOR,
+ )
+ return
try:
if importlib.util.find_spec(module) is not None:
return
@@ -346,3 +394,325 @@ def _restore_native_backend(set_backend_fn: Any, logger: Any) -> None:
def _warn(logger: Any, what: str, exc: Exception) -> None:
if logger is not None:
logger.warning("diffusion.attention: %s unavailable (%s); using default", what, exc)
+
+
+# --------------------------------------------------------------------------------------
+# HunyuanVideo-1.5 joint-attention padding trim (accuracy-exact speed win)
+#
+# HunyuanVideo15AttnProcessor2_0 runs a JOINT [video ; text] self-attention and, on EVERY block
+# and step, materialises a dense [B,1,N,N] boolean mask so the video never attends to padded text.
+# But a dense bool attn_mask DISABLES every fused SDPA kernel (flash rejects it; cuDNN/efficient
+# fall back) and forces the slow math path: on a B200 at the production shape (N~=50k, 121 frames
+# 480p) the SAME attention is 421 ms WITH the dense mask vs 19 ms with attn_mask=None -- a ~22x tax
+# purely to mask padding. And the text is ~99.5% padding: a t2v prompt fills only ~9 of ~1985 slots
+# (image 729 + byt5 256 + mllm 1000, almost all zero-padded).
+#
+# The fix is exact: the model already masks the padded text and DISCARDS its attention output (only
+# the video split feeds proj_out), so removing the padded tokens before attention changes nothing
+# for the video. Done in an eager forward pre-hook (outside the compiled blocks): drop the all-zero
+# image stream (t2v), trim the mllm/byt5 streams to their globally-valid columns, and -- when
+# nothing partially-padded remains (the common batch-1 / per-branch call) -- flag the DiT so the
+# processor skips the dense mask and runs the fused path. The only numeric change is the SDPA kernel
+# (masked -> fused), on par with the shipped cuDNN backend swap. Mixed-padding batches fall back to
+# the stock dense mask.
+#
+# SHAPE NOTE: the trimmed text length is prompt-dependent, so the compiled blocks see a new shape
+# per prompt. That is free on the default speed tier (compiled with dynamic=True) but not on ``max``
+# (dynamic=False), where each length is its own graph and a fullgraph region hard-errors once
+# dynamo's recompile limit is reached. The caller therefore only installs the trim on a tier that
+# compiles dynamically; see the call site in video.py.
+_HUNYUAN15_TRANSFORMER_CLS = "HunyuanVideo15Transformer3DModel"
+_HUNYUAN15_PROCESSOR_CLS = "HunyuanVideo15AttnProcessor2_0"
+_NULL_ATTN_FLAG = "_unsloth_null_attn_mask"
+
+_NULL_PROCESSOR_CACHE: dict = {}
+
+
+def _set_hunyuan_null_mask(module: Any, enabled: bool) -> None:
+ """Set the null-mask flag on every block's attention of ``module``. The flag is valid ONLY for
+ the forward whose pre-hook removed the padding, so a post-hook clears it back to False after
+ each call (see the module note and _hunyuan_trim_post_hook)."""
+ for blk in getattr(module, "transformer_blocks", []):
+ attn = getattr(blk, "attn", None)
+ if attn is not None:
+ setattr(attn, _NULL_ATTN_FLAG, enabled)
+
+
+def _null_mask_processor_cls():
+ """Build (once, lazily) a HunyuanVideo15AttnProcessor2_0 subclass whose ``__call__`` runs
+ attn_mask=None when the DiT is flagged (padding already removed by the pre-hook); otherwise it
+ delegates to the stock processor, so a mixed-padding batch and future diffusers changes stay
+ correct."""
+ cached = _NULL_PROCESSOR_CACHE.get("cls")
+ if cached is not None:
+ return cached
+
+ import torch
+ from diffusers.models.attention_dispatch import dispatch_attention_fn
+ from diffusers.models.transformers.transformer_hunyuan_video15 import (
+ HunyuanVideo15AttnProcessor2_0,
+ )
+
+ class _HunyuanNullMaskProcessor(HunyuanVideo15AttnProcessor2_0):
+ def __call__(
+ self,
+ attn,
+ hidden_states,
+ encoder_hidden_states = None,
+ attention_mask = None,
+ image_rotary_emb = None,
+ ):
+ # Fast path only when the pre-hook removed all padding (attn_mask redundant); a
+ # constant python bool so torch.compile const-folds the branch (no graph break).
+ if not getattr(attn, _NULL_ATTN_FLAG, False):
+ return super().__call__(
+ attn,
+ hidden_states,
+ encoder_hidden_states = encoder_hidden_states,
+ attention_mask = attention_mask,
+ image_rotary_emb = image_rotary_emb,
+ )
+
+ # Null path = the stock body with the mask block removed and attn_mask=None.
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(hidden_states)
+ value = attn.to_v(hidden_states)
+
+ query = query.unflatten(2, (attn.heads, -1))
+ key = key.unflatten(2, (attn.heads, -1))
+ value = value.unflatten(2, (attn.heads, -1))
+
+ query = attn.norm_q(query)
+ key = attn.norm_k(key)
+
+ if image_rotary_emb is not None:
+ from diffusers.models.embeddings import apply_rotary_emb
+ query = apply_rotary_emb(query, image_rotary_emb, sequence_dim = 1)
+ key = apply_rotary_emb(key, image_rotary_emb, sequence_dim = 1)
+
+ if encoder_hidden_states is not None:
+ encoder_query = attn.add_q_proj(encoder_hidden_states)
+ encoder_key = attn.add_k_proj(encoder_hidden_states)
+ encoder_value = attn.add_v_proj(encoder_hidden_states)
+
+ encoder_query = encoder_query.unflatten(2, (attn.heads, -1))
+ encoder_key = encoder_key.unflatten(2, (attn.heads, -1))
+ encoder_value = encoder_value.unflatten(2, (attn.heads, -1))
+
+ if attn.norm_added_q is not None:
+ encoder_query = attn.norm_added_q(encoder_query)
+ if attn.norm_added_k is not None:
+ encoder_key = attn.norm_added_k(encoder_key)
+
+ query = torch.cat([query, encoder_query], dim = 1)
+ key = torch.cat([key, encoder_key], dim = 1)
+ value = torch.cat([value, encoder_value], dim = 1)
+
+ hidden_states = dispatch_attention_fn(
+ query,
+ key,
+ value,
+ attn_mask = None,
+ dropout_p = 0.0,
+ is_causal = False,
+ backend = self._attention_backend,
+ parallel_config = self._parallel_config,
+ )
+
+ hidden_states = hidden_states.flatten(2, 3)
+ hidden_states = hidden_states.to(query.dtype)
+
+ if encoder_hidden_states is not None:
+ enc_len = encoder_hidden_states.shape[1]
+ hidden_states, encoder_hidden_states = (
+ hidden_states[:, :-enc_len],
+ hidden_states[:, -enc_len:],
+ )
+ if getattr(attn, "to_out", None) is not None:
+ hidden_states = attn.to_out[0](hidden_states)
+ hidden_states = attn.to_out[1](hidden_states)
+ if getattr(attn, "to_add_out", None) is not None:
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
+
+ # Always the 2-tuple, matching the stock processor's return contract (it returns
+ # (hidden_states, encoder_hidden_states) outside its own `if`), so the calling block
+ # unpacks identically on either path.
+ return hidden_states, encoder_hidden_states
+
+ _NULL_PROCESSOR_CACHE["cls"] = _HunyuanNullMaskProcessor
+ return _HunyuanNullMaskProcessor
+
+
+def _trim_stream(states, mask):
+ """Drop the columns of a [B, S, D] text stream + its [B, S] mask that are padding for EVERY
+ batch element (globally invalid). Returns (states, mask, all_valid): all_valid is True when
+ the trimmed stream has NO partially-padded column left (so it needs no attention mask)."""
+ if states is None or mask is None or mask.dim() != 2:
+ return states, mask, True # nothing to mask -> treat as no-padding
+ mb = mask.bool()
+ keep = mb.any(dim = 0) # column valid for at least one batch element
+ if not bool(keep.all()):
+ states = states[:, keep]
+ mask = mask[:, keep]
+ mb = mb[:, keep]
+ # All remaining slots valid for every element (vacuously True for a 0-length stream, fine
+ # for an unused secondary stream e.g. byt5 in t2v).
+ all_valid = bool(mb.all().item())
+ return states, mask, all_valid
+
+
+def _hunyuan_trim_pre_hook(module, args, kwargs):
+ """Eager forward pre-hook: strip padded text tokens so the joint attention runs fused.
+
+ - Drop the image stream when it is entirely zero (t2v): those ~729 tokens are pure padding.
+ This is upstream's own t2v sentinel (``is_t2v = torch.all(image_embeds == 0)``), and
+ ``torch.all`` of an empty tensor is vacuously True, so emptying the axis keeps it True.
+ - Trim the mllm/byt5 text streams to their globally-valid columns.
+ - Flag every block's attention so the null-mask processor skips the dense mask when nothing
+ partially-padded remains (the batch-1 / per-guidance-branch case); otherwise leave the
+ flag False and the stock dense-mask path handles the residual padding correctly.
+
+ This hook is the correctness choke point: the null-mask flag is valid only because the padding
+ was removed HERE, on the same call. It fires on ``module(...)`` (``__call__``), which the
+ pipeline/guider/cache_context/compile all use. Do NOT invoke a hooked DiT via
+ ``module.forward(...)`` directly: that skips pre-hooks, so a stale True flag would null the mask
+ over un-trimmed padding and corrupt the output.
+
+ The three ``.item()`` reads below are host syncs, but this hook runs eagerly outside the
+ compiled blocks (~3 syncs against a ~1.3 s forward), so they must stay here and not be folded
+ into the graph.
+
+ Best-effort: any anomaly leaves the inputs untouched and the flag False."""
+ import torch
+
+ original = dict(kwargs)
+ try:
+ null_ok = True
+
+ image = kwargs.get("image_embeds")
+ if image is not None and image.numel() > 0 and bool(torch.all(image == 0).item()):
+ # All-zero image == "no image" (t2v). Emptying the token axis removes the 729 padded
+ # image tokens; is_t2v stays True in forward (all() of empty is vacuously True).
+ kwargs["image_embeds"] = image[:, :0]
+
+ for skey, mkey, required in (
+ ("encoder_hidden_states", "encoder_attention_mask", True),
+ ("encoder_hidden_states_2", "encoder_attention_mask_2", False),
+ ):
+ # Only touch streams passed by keyword (the pipeline always does); never write back an
+ # absent key (a positional encoder_hidden_states would collide). An absent REQUIRED
+ # primary stream drops the fast path; an absent optional byt5 is fine.
+ if skey not in kwargs:
+ null_ok = null_ok and not required
+ continue
+ states, mask, all_valid = _trim_stream(kwargs.get(skey), kwargs.get(mkey))
+ kwargs[skey] = states
+ kwargs[mkey] = mask
+ null_ok = null_ok and all_valid
+
+ # The primary mllm stream flows through the TokenRefiner's own attention, whose pooling
+ # divides by the mask sum; never hand it a 0-length sequence (pathological empty prompt).
+ # Revert and take the stock dense-mask path.
+ primary = kwargs.get("encoder_hidden_states")
+ if primary is not None and primary.dim() == 3 and primary.shape[1] == 0:
+ kwargs.clear()
+ kwargs.update(original)
+ null_ok = False
+
+ _set_hunyuan_null_mask(module, null_ok)
+ return args, kwargs
+ except Exception: # noqa: BLE001 — optimisation only; never break the forward
+ # We may have trimmed some kwargs before failing. Restore the caller's untrimmed inputs so
+ # the stock dense-mask path (flag False) runs on exactly what it expects.
+ kwargs.clear()
+ kwargs.update(original)
+ _set_hunyuan_null_mask(module, False)
+ return args, kwargs
+
+
+def _hunyuan_trim_post_hook(module, _args, output):
+ """Clear the null-mask flag after each hooked forward, scoping the authorisation to exactly the
+ call whose pre-hook removed the padding. Registered with ``always_call=True`` so the flag is
+ also cleared when the forward raises -- otherwise a latched True would null the mask over
+ un-trimmed padding on any later direct ``module.forward(...)``. Returns the output unchanged."""
+ _set_hunyuan_null_mask(module, False)
+ return output
+
+
+def _install_null_processors(dit: Any, logger: Any) -> bool:
+ """Swap every stock block attention processor on ``dit`` for the null-mask subclass. Only
+ touches blocks whose processor is exactly the stock class (so a diffusers change or an
+ already-installed run is a no-op). Preserves any pinned attention backend."""
+ try:
+ cls = _null_mask_processor_cls()
+ except Exception as exc: # noqa: BLE001 — diffusers moved / unavailable -> skip
+ _warn(logger, "hunyuan_attn_trim", exc)
+ return False
+ installed = 0
+ for blk in getattr(dit, "transformer_blocks", []):
+ attn = getattr(blk, "attn", None)
+ proc = getattr(attn, "processor", None) if attn is not None else None
+ if proc is None:
+ continue
+ if isinstance(proc, cls):
+ installed += 1 # already ours (idempotent)
+ continue
+ if type(proc).__name__ != _HUNYUAN15_PROCESSOR_CLS:
+ continue # unknown processor -> leave it alone
+ new = cls()
+ # carry over any backend/parallel config the stock processor already held
+ new._attention_backend = getattr(proc, "_attention_backend", None)
+ new._parallel_config = getattr(proc, "_parallel_config", None)
+ try:
+ attn.set_processor(new)
+ except Exception: # noqa: BLE001 — fall back to direct assignment
+ attn.processor = new
+ installed += 1
+ return installed > 0
+
+
+def install_hunyuan_attention_trim(
+ pipe: Any,
+ family: Any,
+ *,
+ logger: Any = None,
+) -> bool:
+ """HunyuanVideo-1.5 only: make the joint attention skip padded text tokens (see module note).
+
+ Installs a null-mask processor on every denoiser DiT block plus an eager pre-hook that trims the
+ padded text/image streams each forward. Exact for the video output (the fused-vs-masked SDPA
+ swap is the only numeric change). Returns True when engaged; No-op (False) for any other family,
+ an unexpected class, or any failure -- the stock dense-mask path stays, so correctness never
+ depends on this. Call BEFORE apply_attention_backend so the kernel pins onto the new processor.
+
+ The caller must NOT install this when the denoiser blocks are compiled with static shapes: the
+ trimmed text length varies per prompt (see the SHAPE NOTE in the module header)."""
+ if getattr(family, "transformer_class", None) != _HUNYUAN15_TRANSFORMER_CLS:
+ return False
+ engaged = False
+ for dit in _attention_dits(pipe):
+ if type(dit).__name__ != _HUNYUAN15_TRANSFORMER_CLS:
+ continue
+ if not _install_null_processors(dit, logger):
+ continue
+ # Installation (and every idle period between generations) starts in the conservative
+ # state: the flag is only ever True inside the exact forward its pre-hook trimmed.
+ _set_hunyuan_null_mask(dit, False)
+ if getattr(dit, "_unsloth_trim_hook", None) is None:
+ pre_handle = None
+ try:
+ pre_handle = dit.register_forward_pre_hook(_hunyuan_trim_pre_hook, with_kwargs = True)
+ # always_call: clear the flag even when the forward raises, so an exception can
+ # never leave the null-mask authorisation latched for a later direct forward.
+ post_handle = dit.register_forward_hook(_hunyuan_trim_post_hook, always_call = True)
+ dit._unsloth_trim_hook = (pre_handle, post_handle)
+ except Exception as exc: # noqa: BLE001 — optimisation only
+ if pre_handle is not None:
+ pre_handle.remove()
+ _set_hunyuan_null_mask(dit, False)
+ _warn(logger, "hunyuan_attn_trim", exc)
+ continue
+ engaged = True
+ if engaged and logger is not None:
+ logger.info("diffusion.attention: hunyuan padded-text trim engaged")
+ return engaged
diff --git a/studio/backend/core/inference/diffusion_transformer_quant.py b/studio/backend/core/inference/diffusion_transformer_quant.py
index 7672fae415a..fdd18d57a9a 100644
--- a/studio/backend/core/inference/diffusion_transformer_quant.py
+++ b/studio/backend/core/inference/diffusion_transformer_quant.py
@@ -67,9 +67,31 @@ _QWENIMAGE_INT8_EXCLUDES = (
"to_add_out",
"txt_mlp",
)
+# HunyuanVideo-1.5's attention trim (this PR) shrinks the text / image streams from their padded
+# lengths to the VALID token counts, so every text-stream Linear runs at a tiny M the int8 dynamic
+# path cannot handle. Both failures measured on B200:
+# - M = 0 (t2v byt5 / image streams trim to zero tokens): torchao returns the input UNPROJECTED
+# (a quantized 1472 -> 2048 Linear maps [1, 0, 1472] to [1, 0, 1472]), so the 2048-wide
+# cond-type add crashes -> context_embedder_2 / image_embedder;
+# - M <= 16 (a short prompt, or the empty negative prompt's ~6 tokens): torch._int_mm requires
+# M > 16 and raises -> the TokenRefiner and every block's context-stream projections.
+# These run at M = text tokens (tens) against the video stream's M ~ 32k+, so bf16 here costs
+# nothing measurable and the video-stream linears keep full int8 coverage. "context_embedder"
+# also matches "context_embedder_2" (substring check).
+_HUNYUAN15_INT8_EXCLUDES = (
+ "context_embedder",
+ "image_embedder",
+ "add_q_proj",
+ "add_k_proj",
+ "add_v_proj",
+ "to_add_out",
+ "ff_context",
+)
_INT8_FAMILY_EXCLUDE_NAME_TOKENS: dict[str, tuple[str, ...]] = {
"qwen-image": _QWENIMAGE_INT8_EXCLUDES,
"qwen-image-edit": _QWENIMAGE_INT8_EXCLUDES, # same DiT class + unpadded text stream
+ "hunyuanvideo-1.5": _HUNYUAN15_INT8_EXCLUDES,
+ "hunyuanvideo-1.5-720p": _HUNYUAN15_INT8_EXCLUDES,
}
@@ -90,9 +112,13 @@ def exclude_tokens_for_scheme(scheme: str, family: Optional[str] = None) -> tupl
# Per-arch preference for ``auto``, best first. On Blackwell fp8 leads: on B200 plain fp8 dynamic is faster AND more accurate at DiT shapes,
# while mxfp8 block scaling only adds overhead. nvfp4's FP4 GEMM is real with torch>=2.11 but wins only on very large GEMMs (0.81x on Z-Image
-# 1024px, LPIPS 0.166 vs fp8 0.044), so it stays an explicit opt-in. Consumer / workstation GPUs move int8 first: they halve fp8/fp16 FP32-accumulate.
+# 1024px, LPIPS 0.166 vs fp8 0.044), so it is kept OUT of the ladder below and stays an explicit opt-in (transformer_quant="nvfp4"): auto must
+# never silently drop to a scheme that is both slower and less accurate. Restore the commented Blackwell tier to re-enable it once the FP4
+# tensor-core GEMM wins at the DiT's real shapes (hidden ~3072, MLP ~12288, M ~4096) and its accuracy is validated by the prequant gate.
+# Consumer / workstation GPUs move int8 first: they halve fp8/fp16 FP32-accumulate.
_AUTO_LADDER: tuple[tuple[tuple[int, int], tuple[str, ...]], ...] = (
- ((10, 0), (TQ_FP8, TQ_NVFP4, TQ_MXFP8, TQ_INT8)), # Blackwell sm_100+
+ ((10, 0), (TQ_FP8, TQ_MXFP8, TQ_INT8)), # Blackwell sm_100+ (nvfp4 is explicit opt-in only)
+ # ((10, 0), (TQ_FP8, TQ_NVFP4, TQ_MXFP8, TQ_INT8)), # restore to re-enable nvfp4 under auto
((8, 9), (TQ_FP8, TQ_INT8)), # Ada sm_89 / Hopper sm_90
((8, 0), (TQ_INT8,)), # Ampere sm_80 / sm_86
)
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 2b52cc66797..4e5a9892898 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -42,7 +42,11 @@ from typing import Any, Optional
from loggers import get_logger
-from .diffusion_attention import apply_attention_backend, select_attention_backend
+from .diffusion_attention import (
+ apply_attention_backend,
+ install_hunyuan_attention_trim,
+ select_attention_backend,
+)
from .diffusion_cache import (
FBCACHE_MIN_STEPS,
TC_AUTO,
@@ -64,6 +68,7 @@ from .diffusion_memory import (
)
from .diffusion_speed import (
SPEED_DEFAULT,
+ SPEED_MAX,
SPEED_OFF,
apply_speed_optims,
resolve_speed_mode,
@@ -1429,6 +1434,16 @@ class VideoBackend:
else:
cache_reason = "requested"
attention_engaged = None
+ # HunyuanVideo-1.5 only, and once for the whole pipe (the installer fans out over every
+ # denoiser DiT itself). Before apply_attention_backend below, so the requested kernel pins
+ # onto the new processors. Held off on SPEED_OFF (which must stay bit-identical) and on
+ # SPEED_MAX (its blocks compile with dynamic=False, and the trimmed text length varies per
+ # prompt, so every prompt would be a fresh graph).
+ attention_trim_engaged = (
+ install_hunyuan_attention_trim(pipe, fam, logger = logger)
+ if effective_speed not in (SPEED_OFF, SPEED_MAX)
+ else False
+ )
speed_optims: tuple = ()
for view in views:
# Both helpers act on ``view.transformer``; call once per view (engaged values match, so record the first). is_gguf needs kind==gguf AND no quant engaged.
@@ -1453,6 +1468,8 @@ class VideoBackend:
if view is pipe:
attention_engaged = engaged
speed_optims = tuple(k for k, v in applied.items() if v)
+ if attention_trim_engaged:
+ speed_optims += ("hunyuan_attn_trim",)
with self._generate_lock:
# A cancelled/superseded load must not place weights on a GPU the arbiter may have reassigned; recheck before placement.
if _load_token is not None and _load_token != self._load_token:
diff --git a/studio/backend/tests/test_diffusion_attention.py b/studio/backend/tests/test_diffusion_attention.py
index e58f23c2e09..7b696174f86 100644
--- a/studio/backend/tests/test_diffusion_attention.py
+++ b/studio/backend/tests/test_diffusion_attention.py
@@ -441,3 +441,73 @@ def test_install_failure_falls_back_to_native(monkeypatch):
monkeypatch.setattr(att, "_active_attention_backend", lambda: "native")
t = _FakeTransformer(fail = True)
assert apply_attention_backend(_pipe(t), "sage") is None
+
+
+# ── kernels-package install gate (huggingface_hub compatibility) ─────────────────
+
+
+def test_kernels_install_skipped_on_old_hub(monkeypatch):
+ # Current `kernels` wheels require huggingface_hub >= 1.10, and with an older hub the damage
+ # is NOT contained to the requested backend: `import kernels` raises at module scope and
+ # diffusers imports kernels whenever it is installed, so a single auto-install would break
+ # every later pipeline import on the box. The installer must refuse.
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_ATTENTION_INSTALL", "auto")
+ import importlib.util
+
+ monkeypatch.setattr(importlib.util, "find_spec", lambda name: None)
+ monkeypatch.setattr(att, "_kernels_hub_compatible", lambda: False)
+ run = _Recorder()
+ _stub_subprocess(monkeypatch, run)
+ att._ensure_attention_backend_installed("flash_4_hub")
+ assert run.calls == []
+ # The refusal is a policy decision, not a failed attempt: nothing is memoised, so a later
+ # request on a fixed environment can still install.
+ assert "kernels" not in att._INSTALL_ATTEMPTED
+
+
+def test_kernels_install_allowed_on_supported_hub(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_ATTENTION_INSTALL", "auto")
+ import importlib.util
+
+ monkeypatch.setattr(importlib.util, "find_spec", lambda name: None)
+ monkeypatch.setattr(att, "_kernels_hub_compatible", lambda: True)
+ run = _Recorder()
+ _stub_subprocess(monkeypatch, run)
+ att._ensure_attention_backend_installed("flash_4_hub")
+ assert len(run.calls) == 1 and "kernels" in run.calls[0]
+
+
+def test_kernels_gate_only_applies_to_kernels_package(monkeypatch):
+ # sage / xformers / flash-attn wheels do not import huggingface_hub at module scope, so the
+ # hub gate must not block them.
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_ATTENTION_INSTALL", "auto")
+ import importlib.util
+
+ monkeypatch.setattr(importlib.util, "find_spec", lambda name: None)
+ monkeypatch.setattr(att, "_kernels_hub_compatible", lambda: False)
+ run = _Recorder()
+ _stub_subprocess(monkeypatch, run)
+ att._ensure_attention_backend_installed("sage")
+ assert len(run.calls) == 1 and any("sageattention" in part for part in run.calls[0])
+
+
+def test_kernels_hub_compatible_reads_hub_version(monkeypatch):
+ import importlib.metadata
+
+ # The gate is (major, minor) >= 1.10, the floor the kernels wheels declare -- a major-only
+ # check would pass every 1.x. Measured with kernels 0.16.0: hub 1.0.0-1.2.4 fail
+ # `import kernels` outright (strict dataclasses gained `str | None` in hub 1.3.0), and
+ # 1.3-1.9 sit below the supported floor, so the whole sub-1.10 range is refused.
+ for bad in ("0.36.2", "1.0.0", "1.2.4", "1.3.5", "1.9.2", "1.9"):
+ monkeypatch.setattr(importlib.metadata, "version", lambda name, v = bad: v)
+ assert att._kernels_hub_compatible() is False, bad
+ for good in ("1.10.0", "1.10.0rc0", "1.23.0", "2.0.0"):
+ monkeypatch.setattr(importlib.metadata, "version", lambda name, v = good: v)
+ assert att._kernels_hub_compatible() is True, good
+
+ def _boom(name):
+ raise importlib.metadata.PackageNotFoundError(name)
+
+ # Undeterminable hub -> keep the previous (permissive) behaviour.
+ monkeypatch.setattr(importlib.metadata, "version", _boom)
+ assert att._kernels_hub_compatible() is True
diff --git a/studio/backend/tests/test_diffusion_attention_trim.py b/studio/backend/tests/test_diffusion_attention_trim.py
new file mode 100644
index 00000000000..0f816ae11f1
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_attention_trim.py
@@ -0,0 +1,252 @@
+# 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 the HunyuanVideo-1.5 padded-text attention trim.
+
+``_trim_stream`` / ``_hunyuan_trim_pre_hook`` / ``install_hunyuan_attention_trim`` use real torch
+tensor ops, so unlike the attention-backend policy tests in ``test_diffusion_attention.py`` these
+require torch. Kept in a separate module so that file stays collectable without torch installed.
+"""
+
+from __future__ import annotations
+
+import types
+
+import pytest
+
+# Skip at collection (not abort) when torch is absent so the rest of the backend suite
+# stays collectable, matching how the policy tests next door gate their heavy imports.
+torch = pytest.importorskip("torch")
+
+import core.inference.diffusion_attention as att # noqa: E402
+
+
+def test_trim_stream_drops_trailing_padding():
+ # right-padded (valid prefix): drop the globally-invalid tail, keep valid, flag all_valid.
+ states = torch.arange(6.0).reshape(1, 6, 1)
+ mask = torch.tensor([[1, 1, 1, 0, 0, 0]])
+ out_s, out_m, all_valid = att._trim_stream(states, mask)
+ assert out_s.shape == (1, 3, 1)
+ assert torch.equal(out_s[0, :, 0], torch.tensor([0.0, 1.0, 2.0]))
+ assert out_m.shape == (1, 3) and all_valid is True
+
+
+def test_trim_stream_layout_agnostic_drops_only_global_padding():
+ # left-padded (valid suffix): any(dim=0) keeps positions valid for at least one element,
+ # so the leading globally-invalid columns are dropped regardless of padding side.
+ states = torch.arange(4.0).reshape(1, 4, 1)
+ mask = torch.tensor([[0, 0, 1, 1]])
+ out_s, out_m, all_valid = att._trim_stream(states, mask)
+ assert torch.equal(out_s[0, :, 0], torch.tensor([2.0, 3.0])) and all_valid is True
+
+
+def test_trim_stream_full_mask_is_noop():
+ states = torch.ones(1, 4, 2)
+ mask = torch.ones(1, 4, dtype = torch.long)
+ out_s, out_m, all_valid = att._trim_stream(states, mask)
+ assert out_s.shape == (1, 4, 2) and all_valid is True
+
+
+def test_trim_stream_none_mask_passthrough():
+ states = torch.ones(1, 4, 2)
+ out_s, out_m, all_valid = att._trim_stream(states, None)
+ assert out_s is states and out_m is None and all_valid is True
+
+
+def test_trim_stream_mixed_batch_not_all_valid():
+ # batch>1 with different valid sets: the union is kept, but a column valid for only one
+ # element remains partially padded -> all_valid False -> caller keeps the dense mask.
+ states = torch.ones(2, 4, 1)
+ mask = torch.tensor([[1, 1, 0, 0], [1, 1, 1, 0]]) # elem1 has 2 valid, elem2 has 3
+ out_s, out_m, all_valid = att._trim_stream(states, mask)
+ assert out_s.shape == (2, 3, 1) # dropped the last col (invalid for both)
+ assert all_valid is False
+
+
+def _fake_dit(n_blocks = 2):
+ blocks = [types.SimpleNamespace(attn = types.SimpleNamespace()) for _ in range(n_blocks)]
+ return types.SimpleNamespace(transformer_blocks = blocks)
+
+
+def test_trim_pre_hook_empties_t2v_image_and_trims_and_flags():
+ dit = _fake_dit()
+ kwargs = {
+ "image_embeds": torch.zeros(1, 5, 3), # all-zero -> t2v -> emptied
+ "encoder_hidden_states": torch.arange(4.0).reshape(1, 4, 1),
+ "encoder_attention_mask": torch.tensor([[1, 1, 0, 0]]),
+ "encoder_hidden_states_2": torch.arange(3.0).reshape(1, 3, 1),
+ "encoder_attention_mask_2": torch.tensor([[1, 0, 0]]),
+ }
+ args, out = att._hunyuan_trim_pre_hook(dit, (), kwargs)
+ assert out["image_embeds"].shape == (1, 0, 3) # image tokens dropped
+ assert out["encoder_hidden_states"].shape == (1, 2, 1) # mllm trimmed to 2 valid
+ assert out["encoder_hidden_states_2"].shape == (1, 1, 1) # byt5 trimmed to 1 valid
+ assert all(getattr(b.attn, att._NULL_ATTN_FLAG) is True for b in dit.transformer_blocks)
+
+
+def test_trim_stream_all_invalid_yields_empty_but_valid():
+ # A fully-padded secondary stream (e.g. unused byt5 in t2v) trims to 0 length and reports
+ # all_valid True (vacuous) so it does NOT drop the fast path -- it just contributes no tokens.
+ states = torch.ones(1, 5, 2)
+ mask = torch.zeros(1, 5, dtype = torch.long)
+ out_s, out_m, all_valid = att._trim_stream(states, mask)
+ assert out_s.shape == (1, 0, 2) and all_valid is True
+
+
+def test_trim_pre_hook_byt5_all_invalid_keeps_fast_path():
+ # The real t2v case: byt5 is entirely padding (valid=0). It must be emptied WITHOUT dropping
+ # the null-mask fast path, since mllm still carries the prompt.
+ dit = _fake_dit()
+ kwargs = {
+ "image_embeds": torch.zeros(1, 5, 3),
+ "encoder_hidden_states": torch.arange(4.0).reshape(1, 4, 1),
+ "encoder_attention_mask": torch.tensor([[1, 1, 1, 0]]),
+ "encoder_hidden_states_2": torch.ones(1, 6, 1),
+ "encoder_attention_mask_2": torch.zeros(1, 6, dtype = torch.long), # all padding
+ }
+ _, out = att._hunyuan_trim_pre_hook(dit, (), kwargs)
+ assert out["encoder_hidden_states"].shape == (1, 3, 1)
+ assert out["encoder_hidden_states_2"].shape == (1, 0, 1) # byt5 emptied
+ assert all(getattr(b.attn, att._NULL_ATTN_FLAG) is True for b in dit.transformer_blocks)
+
+
+def test_trim_pre_hook_empty_primary_reverts_and_disables():
+ # Pathological empty prompt: mllm has 0 valid tokens. The TokenRefiner must not get a
+ # 0-length sequence -> revert all inputs to original and take the stock dense-mask path.
+ dit = _fake_dit()
+ mllm = torch.ones(1, 4, 1)
+ kwargs = {
+ "image_embeds": torch.zeros(1, 5, 3),
+ "encoder_hidden_states": mllm,
+ "encoder_attention_mask": torch.zeros(1, 4, dtype = torch.long), # 0 valid
+ }
+ _, out = att._hunyuan_trim_pre_hook(dit, (), kwargs)
+ assert out["encoder_hidden_states"] is mllm # reverted (not emptied)
+ assert out["image_embeds"].shape == (1, 5, 3) # image revert too
+ assert all(getattr(b.attn, att._NULL_ATTN_FLAG) is False for b in dit.transformer_blocks)
+
+
+def test_trim_pre_hook_keeps_i2v_image():
+ dit = _fake_dit()
+ img = torch.ones(1, 5, 3) # nonzero -> i2v -> kept
+ kwargs = {
+ "image_embeds": img,
+ "encoder_hidden_states": torch.arange(4.0).reshape(1, 4, 1),
+ "encoder_attention_mask": torch.tensor([[1, 1, 1, 1]]),
+ }
+ _, out = att._hunyuan_trim_pre_hook(dit, (), kwargs)
+ assert out["image_embeds"] is img # not emptied
+ assert all(getattr(b.attn, att._NULL_ATTN_FLAG) is True for b in dit.transformer_blocks)
+
+
+def test_trim_pre_hook_mixed_batch_flags_false():
+ dit = _fake_dit()
+ kwargs = {
+ "image_embeds": torch.zeros(2, 2, 3),
+ "encoder_hidden_states": torch.ones(2, 4, 1),
+ "encoder_attention_mask": torch.tensor([[1, 1, 0, 0], [1, 1, 1, 0]]),
+ }
+ _, out = att._hunyuan_trim_pre_hook(dit, (), kwargs)
+ assert all(getattr(b.attn, att._NULL_ATTN_FLAG) is False for b in dit.transformer_blocks)
+
+
+def test_trim_pre_hook_never_raises_sets_flag_false():
+ # A malformed mask (not a tensor) must not break the forward: flag False, no exception.
+ dit = _fake_dit()
+ kwargs = {"encoder_hidden_states": torch.ones(1, 2, 1), "encoder_attention_mask": "oops"}
+ args, out = att._hunyuan_trim_pre_hook(dit, (), kwargs)
+ assert all(getattr(b.attn, att._NULL_ATTN_FLAG) is False for b in dit.transformer_blocks)
+
+
+def test_trim_pre_hook_restores_inputs_on_midtrim_failure():
+ # A later stream trips the trim AFTER earlier inputs were mutated. The fallback must restore
+ # the ORIGINAL kwargs so the stock dense-mask path runs on them, never a half-trimmed mix.
+ dit = _fake_dit()
+ img = torch.zeros(1, 5, 3)
+ mllm = torch.arange(4.0).reshape(1, 4, 1)
+ mllm_mask = torch.tensor([[1, 1, 0, 0]])
+ byt5 = torch.ones(1, 3, 1)
+ kwargs = {
+ "image_embeds": img,
+ "encoder_hidden_states": mllm,
+ "encoder_attention_mask": mllm_mask,
+ "encoder_hidden_states_2": byt5,
+ "encoder_attention_mask_2": "oops", # malformed -> _trim_stream raises after mllm is trimmed
+ }
+ _, out = att._hunyuan_trim_pre_hook(dit, (), kwargs)
+ assert out["image_embeds"] is img # emptied then restored
+ assert out["encoder_hidden_states"] is mllm # trimmed then restored
+ assert out["encoder_attention_mask"] is mllm_mask
+ assert out["encoder_hidden_states_2"] is byt5
+ assert out["encoder_attention_mask_2"] == "oops"
+ assert all(getattr(b.attn, att._NULL_ATTN_FLAG) is False for b in dit.transformer_blocks)
+
+
+def test_trim_pre_hook_absent_stream_not_written_back():
+ # If encoder_hidden_states is absent (passed positionally), the hook must NOT write it back
+ # (would collide) and must drop the fast path rather than null a mask it never verified.
+ dit = _fake_dit()
+ kwargs = {"image_embeds": torch.zeros(1, 4, 3)} # no encoder_hidden_states key
+ _, out = att._hunyuan_trim_pre_hook(dit, (torch.ones(1, 5, 1),), kwargs)
+ assert "encoder_hidden_states" not in out
+ assert all(getattr(b.attn, att._NULL_ATTN_FLAG) is False for b in dit.transformer_blocks)
+
+
+def test_install_trim_noop_for_non_hunyuan_family():
+ fam = types.SimpleNamespace(transformer_class = "WanTransformer3DModel")
+ pipe = types.SimpleNamespace(transformer = types.SimpleNamespace())
+ assert att.install_hunyuan_attention_trim(pipe, fam) is False
+
+
+def test_install_trim_noop_when_transformer_class_mismatch():
+ # Family claims Hunyuan but the loaded module isn't -> no processors touched, no diffusers
+ # import; returns False rather than swapping an unknown attention processor.
+ fam = types.SimpleNamespace(transformer_class = "HunyuanVideo15Transformer3DModel")
+ pipe = types.SimpleNamespace(transformer = types.SimpleNamespace()) # class name mismatch
+ assert att.install_hunyuan_attention_trim(pipe, fam) is False
+
+
+# ── null-mask flag lifecycle (scoped to one hooked forward) ───────────────────────
+def test_set_and_post_hook_clear_null_mask_flag():
+ # _set_hunyuan_null_mask flips every block's flag; the post-hook clears it and returns
+ # the output unchanged.
+ dit = _fake_dit()
+ att._set_hunyuan_null_mask(dit, True)
+ assert all(getattr(b.attn, att._NULL_ATTN_FLAG) is True for b in dit.transformer_blocks)
+ sentinel = object()
+ returned = att._hunyuan_trim_post_hook(dit, (), sentinel)
+ assert returned is sentinel
+ assert all(getattr(b.attn, att._NULL_ATTN_FLAG) is False for b in dit.transformer_blocks)
+
+
+def test_post_hook_always_clears_flag_after_forward_and_on_exception():
+ # Wire the pre+post hooks the way install_hunyuan_attention_trim does on a real module: the
+ # flag is only ever True DURING the forward its pre-hook set up. After the call it is False,
+ # so a later direct dit.forward(...) can never run unmasked over untrimmed padding -- and the
+ # always_call post-hook clears it even when the forward raises (no latch across exceptions).
+ class _DiT(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.transformer_blocks = [
+ types.SimpleNamespace(attn = types.SimpleNamespace()) for _ in range(2)
+ ]
+ self.boom = False
+
+ def forward(self):
+ # The processor would read a True flag here (padding removed by the pre-hook).
+ assert all(getattr(b.attn, att._NULL_ATTN_FLAG) for b in self.transformer_blocks)
+ if self.boom:
+ raise RuntimeError("mid-forward boom")
+ return "ok"
+
+ dit = _DiT()
+ dit.register_forward_pre_hook(lambda m, _a: att._set_hunyuan_null_mask(m, True))
+ dit.register_forward_hook(att._hunyuan_trim_post_hook, always_call = True)
+
+ assert dit() == "ok"
+ assert all(getattr(b.attn, att._NULL_ATTN_FLAG) is False for b in dit.transformer_blocks)
+
+ dit.boom = True
+ with pytest.raises(RuntimeError):
+ dit()
+ assert all(getattr(b.attn, att._NULL_ATTN_FLAG) is False for b in dit.transformer_blocks)
diff --git a/studio/backend/tests/test_diffusion_transformer_quant.py b/studio/backend/tests/test_diffusion_transformer_quant.py
index 84979e8cd99..b0a323daef9 100644
--- a/studio/backend/tests/test_diffusion_transformer_quant.py
+++ b/studio/backend/tests/test_diffusion_transformer_quant.py
@@ -94,9 +94,10 @@ def test_auto_blackwell_prefers_fp8_then_falls_back(monkeypatch):
# Even with every scheme available, auto picks fp8 on Blackwell: measured on a B200 it is faster AND more accurate than nvfp4 at DiT shapes.
_allow(monkeypatch, {TQ_NVFP4, TQ_MXFP8, TQ_FP8, TQ_INT8})
assert select_transformer_quant_scheme(_target(), "auto") == TQ_FP8
- # fp8 unavailable: nvfp4 is the next pick (above mxfp8 / int8).
+ # fp8 unavailable: auto skips nvfp4 even though the hardware runs it, because nvfp4 is an
+ # explicit opt-in only (slower AND less accurate at DiT shapes), and lands on mxfp8.
_allow(monkeypatch, {TQ_NVFP4, TQ_MXFP8, TQ_INT8})
- assert select_transformer_quant_scheme(_target(), "auto") == TQ_NVFP4
+ assert select_transformer_quant_scheme(_target(), "auto") == TQ_MXFP8
# Only mxfp8 + int8 left -> mxfp8 (still above int8).
_allow(monkeypatch, {TQ_MXFP8, TQ_INT8})
assert select_transformer_quant_scheme(_target(), "auto") == TQ_MXFP8
@@ -666,3 +667,33 @@ def test_quantize_transformer_threads_family(monkeypatch):
monkeypatch.setitem(sys.modules, "torchao.quantization", tqz)
assert quantize_transformer(pipe, _target(), mode = "fp8", family = "qwen-image") is None
assert called == {}
+
+
+def test_the_attention_trim_families_exclude_their_small_m_text_streams():
+ """The trim in this PR is what makes these excludes necessary, so they ship together.
+
+ It shrinks HunyuanVideo-1.5's text / image streams from padded length to valid tokens, and
+ quantize_transformer runs BEFORE the trim hook is installed, so those tiny-M activations flow
+ through already-int8 linears: M = 0 comes back unprojected (torchao passes the input through,
+ so the 2048-wide cond-type add crashes) and M <= 16 trips torch._int_mm's floor."""
+ from core.inference.diffusion_transformer_quant import TQ_INT8, exclude_tokens_for_scheme
+
+ for family in ("hunyuanvideo-1.5", "hunyuanvideo-1.5-720p"):
+ tokens = exclude_tokens_for_scheme(TQ_INT8, family)
+ for name in (
+ "context_embedder", # also matches context_embedder_2, by substring
+ "image_embedder",
+ "add_q_proj",
+ "add_k_proj",
+ "add_v_proj",
+ "to_add_out",
+ "ff_context",
+ ):
+ assert name in tokens, f"{family} must exclude {name}"
+
+ # Only int8 has the M floor: the per-row scaled_mm schemes are unaffected, and an unrelated
+ # family keeps exactly the generic set.
+ from core.inference.diffusion_transformer_quant import _INT8_EXCLUDE_NAME_TOKENS
+
+ assert exclude_tokens_for_scheme("fp8", "hunyuanvideo-1.5") == ()
+ assert exclude_tokens_for_scheme(TQ_INT8, "ltx-2") == _INT8_EXCLUDE_NAME_TOKENS
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index 021d74bb81e..fddde6b4f00 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -2273,3 +2273,49 @@ def test_a_raising_teardown_still_drains_the_fence(fake_runtime, tmp_path, monke
monkeypatch.setattr(video_mod, "clear_gpu_cache", lambda: None)
_load_gguf(backend, tmp_path)
assert backend.generate(prompt = "after", steps = 2)["mp4_bytes"] == b"MP4"
+
+
+def _trim_spy(monkeypatch):
+ """Record every install_hunyuan_attention_trim call and report it as engaged."""
+ from core.inference import video as video_mod
+
+ calls: list = []
+
+ def _fake(
+ pipe,
+ family,
+ *,
+ logger = None,
+ ):
+ calls.append(getattr(family, "name", None))
+ return True
+
+ monkeypatch.setattr(video_mod, "install_hunyuan_attention_trim", _fake)
+ return calls
+
+
+def test_attention_trim_installed_and_reported(fake_runtime, monkeypatch):
+ # The padded-text trim is installed once per pipe (the installer fans out over the DiTs itself)
+ # and, when it engages, is reported as a speed optim.
+ calls = _trim_spy(monkeypatch)
+ backend = VideoBackend()
+ status = backend.load_pipeline(
+ "Wan-AI/Wan2.2-TI2V-5B-Diffusers", model_kind = "pipeline", speed_mode = "default"
+ )
+ assert status["loaded"] is True
+ assert len(calls) == 1
+ assert "hunyuan_attn_trim" in status["speed_optims"]
+
+
+def test_attention_trim_skipped_for_static_shape_and_off_tiers(fake_runtime, monkeypatch):
+ # speed=off must stay bit-identical, and speed=max compiles the blocks with dynamic=False,
+ # where the prompt-dependent trimmed text length would make every prompt a fresh graph.
+ for mode in ("off", "max"):
+ calls = _trim_spy(monkeypatch)
+ backend = VideoBackend()
+ status = backend.load_pipeline(
+ "Wan-AI/Wan2.2-TI2V-5B-Diffusers", model_kind = "pipeline", speed_mode = mode
+ )
+ assert status["loaded"] is True, mode
+ assert calls == [], mode
+ assert "hunyuan_attn_trim" not in status["speed_optims"], mode
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index 21240dcb38a..445548d2438 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -2840,7 +2840,12 @@ export function ImagesPage({ active = true }: { active?: boolean }) {
)}
{loras.map((sel, i) => (
<div
- key={sel.id || i}
+ // Key on the index, not sel.id: sel.id is the value of the editable repo-id
+ // Input below, so keying on it changes the key on the first character typed,
+ // which remounts the row and drops input focus. The list is index-addressed
+ // (every mutation matches j === i) and rows are removed explicitly, so the
+ // index is stable for as long as the row lives.
+ key={i}
className="space-y-1.5 rounded-lg border border-border bg-muted/30 p-2"
>
<div className="flex items-center gap-2">