[NPU][Quantization] Add RainFusion attention and INT8 online quantization for MiniMax H3 (#5706)

Signed-off-by: Zijun Huang <zijunhua@usc.edu>
Co-authored-by: WeiQing Chen <40507679+david6666666@users.noreply.github.com>
This commit is contained in:
Zijun HuangandWeiQing Chen authored and GitHub committed 2026-08-06 14:15:21 +08:00
1 parent bc95e7415f
commit 93457f29ff
22 files changed
+1055 -8

No files matched your search

@@ -20,6 +20,21 @@ class AttentionBackend(ABC):
# avoid a slower masked-attention plan when tail padding is not semantic.
supports_prefix_kv_slicing: bool = False
# ``OmniPlatformEnum`` values this backend runs on; None means unrestricted.
# Platform resolution rejects an explicit selection outside this set, so a
# hardware-specific backend fails before the model is built.
supported_platforms: tuple[str, ...] | None = None
@classmethod
def validate_available(cls) -> None:
"""Raise if this backend's optional dependencies are missing.
Called during platform resolution, i.e. before model construction, so a
backend that probes its kernel package lazily still reports the problem
while the user can still act on it.
"""
return None
@classmethod
def supports_attention_mask(cls) -> bool:
return False
@@ -63,6 +78,23 @@ class QueryRange:
global_start: int
@dataclass(frozen=True, slots=True)
class VideoTokenLayout:
"""Where the video segment sits inside a packed multimodal sequence.
A model that packs its sequence as ``[prefix | t*h*w video rows | padding]``
publishes this so backends can recover spatiotemporal locality; the prefix
holds everything that is not video (text, visual conditions, audio).
Publishing it also asserts that any ``attn_mask`` masks only the trailing
padding, so ``prefix_len + t*h*w`` is the used length of the sequence.
Plain ints, so reading it never forces a device-to-host sync.
"""
prefix_len: int
latent_grid: tuple[int, int, int]
@dataclass
class AttentionMetadata:
attn_mask: torch.Tensor | None = None
@@ -95,6 +127,10 @@ class AttentionMetadata:
full_attn_spans: list[list[tuple[int, int]]] | None = None
query_ranges: tuple[QueryRange, ...] | None = None
# Geometry of the video segment for backends that exploit spatiotemporal
# locality (block-sparse selection, tiled masks). Dense backends ignore it.
video_layout: VideoTokenLayout | None = None
T = TypeVar("T", bound=AttentionMetadata)
@@ -0,0 +1,366 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import Any
import torch
from vllm.logger import init_logger
from vllm.model_executor.models.utils import extract_layer_index
from vllm_omni.diffusion.attention.backends.abstract import (
AttentionBackend,
AttentionImpl,
AttentionMetadata,
)
from vllm_omni.diffusion.attention.backends.flash_attn import FlashAttentionBackend
from vllm_omni.diffusion.config import get_current_diffusion_config_or_none
from vllm_omni.diffusion.forward_context import get_forward_context, is_forward_context_available
logger = init_logger(__name__)
# The rf_v2 kernel only implements a 128-token block.
_BLOCK_SIZE = 128
# Below this many video blocks, the pooling and gather that block selection adds
# cost more than the QK work it removes, so stay dense.
_MIN_VIDEO_BLOCKS = 32
# rf_v2's ``input_layout`` describes the caller's tensors, and everything below
# slices the sequence on dim 1. vLLM-Omni diffusion attention hands the impl
# [B, S, N, D], so that is the only layout this backend accepts.
_INPUT_LAYOUT = "BSND"
# rf_v2 precision mode: 0 = high precision, 1 = high performance. Kept at the
# precise setting because the sparsity knob is the intended perf lever, and on
# A5 devices the kernel is routed to rf_v3, which overrides this anyway.
_INNER_PRECISE = 0
_WRONG_PLATFORM = (
"RAINFUSION_ATTN runs the MindIE-SD rf_v2 kernel and is available on Ascend NPU only. "
"Select FLASH_ATTN or TORCH_SDPA on this platform."
)
_MISSING_MINDIESD = (
"RAINFUSION_ATTN requires MindIE-SD. Please install MindIE-SD to enable RainFusion sparse "
"attention on Ascend NPU. For installation details, see https://gitcode.com/Ascend/MindIE-SD "
"Otherwise, use FlashAttention by setting DIFFUSION_ATTENTION_BACKEND=FLASH_ATTN"
)
def _try_extract_layer_index(prefix: str) -> int | None:
if not prefix:
return None
try:
return extract_layer_index(prefix)
except (AssertionError, ValueError):
return None
@dataclass(frozen=True)
class RainFusionConfig:
"""Resolved RainFusion controls for one attention layer.
``sparsity`` is the nominal fraction of key blocks dropped per query block.
The realized sparsity is lower because rf_v2 always keeps the prefix rows and
the first-frame blocks. ``start_step`` and ``skip_layers`` are the accuracy
knobs: early denoise steps and specific DiT blocks stay dense.
"""
sparsity: float = 0.0
start_step: int = 0
skip_layers: frozenset[int] = frozenset()
@classmethod
def from_backend_kwargs(cls, backend_kwargs: dict | None) -> RainFusionConfig:
bk = backend_kwargs or {}
return cls(
sparsity=float(bk.get("sparsity", 0.0)),
start_step=int(bk.get("start_step", 0)),
skip_layers=frozenset(bk.get("skip_layers") or ()),
)
@property
def enabled(self) -> bool:
return self.sparsity > 0.0
@dataclass(frozen=True)
class RainFusionPlan:
"""Per-forward geometry handed to the rf_v2 kernel."""
prefix_len: int
used_len: int
latent_shape: list[int]
class RainFusionAttentionBackend(AttentionBackend):
accept_output_buffer: bool = True
supported_platforms: tuple[str, ...] = ("npu",)
@classmethod
def validate_available(cls) -> None:
from importlib.util import find_spec
if find_spec("mindiesd") is None:
raise ValueError(_MISSING_MINDIESD)
@staticmethod
def get_supported_head_sizes() -> list[int]:
return [64, 96, 128, 192, 256]
@staticmethod
def get_name() -> str:
return "RAINFUSION_ATTN"
@staticmethod
def get_impl_cls() -> type[RainFusionAttentionImpl]:
return RainFusionAttentionImpl
class RainFusionAttentionImpl(AttentionImpl):
"""Block-sparse video attention via MindIE-SD RainFusion (rf_v2) on Ascend NPU.
Sparsity applies only to the video segment of a packed multimodal sequence,
whose extent the model publishes as ``AttentionMetadata.video_layout``. Every
other case — warmup denoise steps, exempt layers, a layer that does not declare
``qkv_layout="BSND"``, sequences without a published video segment, video
segments too short to pay for block selection or not aligned to the kernel's
block size — delegates to FlashAttention, so a model can select this backend
unconditionally.
"""
def __init__(
self,
num_heads: int,
head_size: int,
softmax_scale: float,
causal: bool = False,
num_kv_heads: int | None = None,
prefix: str = "",
qkv_layout: str | None = None,
backend_kwargs: dict[str, Any] | None = None,
**extra_impl_args,
) -> None:
self.num_heads = num_heads
self.causal = causal
self.softmax_scale = softmax_scale
self.qkv_layout = qkv_layout
self.rainfusion = RainFusionConfig.from_backend_kwargs(backend_kwargs)
self.layer_idx = _try_extract_layer_index(prefix)
if self.rainfusion.enabled:
self._validate_parallel_config()
if causal:
raise ValueError(
"RAINFUSION_ATTN does not support causal attention: rf_v2 selects key "
"blocks by pooled relevance and cannot express a causal mask. Select "
"FLASH_ATTN for causal roles."
)
if qkv_layout is not None and qkv_layout.upper() != _INPUT_LAYOUT:
raise ValueError(
f"RAINFUSION_ATTN needs {_INPUT_LAYOUT} tensors to locate the video segment along "
f"the sequence axis, but this layer declares qkv_layout={qkv_layout!r}. Select "
"FLASH_ATTN for this role."
)
self.dense_fallback = FlashAttentionBackend.get_impl_cls()(
num_heads=num_heads,
head_size=head_size,
softmax_scale=softmax_scale,
causal=causal,
num_kv_heads=num_kv_heads,
prefix=prefix,
qkv_layout=qkv_layout,
)
def _validate_parallel_config(self) -> None:
config = get_current_diffusion_config_or_none()
parallel_config = getattr(config, "parallel_config", None)
ring_degree = getattr(parallel_config, "ring_degree", 1)
if ring_degree > 1:
# Ring gives each rank a slice of the sequence, so block selection
# would score only local keys and the layer bypasses the backend
# entirely (see Attention._run_ring_attention).
raise ValueError(
"RAINFUSION_ATTN is not compatible with ring sequence parallelism "
f"(ring_degree={ring_degree}): rf_v2 needs the whole key sequence to rank "
"blocks. Use Ulysses SP (ring_degree=1) instead."
)
def forward_cuda(
self,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attn_metadata: AttentionMetadata | None = None,
) -> torch.Tensor:
# ROCm and MUSA route through forward_cuda by default, so this covers them too.
raise NotImplementedError(_WRONG_PLATFORM)
def forward_xpu(
self,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attn_metadata: AttentionMetadata | None = None,
) -> torch.Tensor:
raise NotImplementedError(_WRONG_PLATFORM)
def forward_npu(
self,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attn_metadata: AttentionMetadata | None = None,
) -> torch.Tensor:
plan = self._resolve_plan(attn_metadata)
if plan is None:
return self.dense_fallback.forward_npu(query, key, value, attn_metadata)
return self._forward_sparse_npu(query, key, value, plan)
def _resolve_plan(self, attn_metadata: AttentionMetadata | None) -> RainFusionPlan | None:
"""Return the rf_v2 geometry, or None when this forward must stay dense."""
rf = self.rainfusion
if not rf.enabled:
return None
if self.layer_idx is not None and self.layer_idx in rf.skip_layers:
return None
if is_forward_context_available():
step_idx = get_forward_context().denoise_step_idx
if step_idx is not None and step_idx < rf.start_step:
return None
if self.qkv_layout is None:
# The sparse path reads the sequence off dim 1, which the tensors alone
# do not establish, and the dense fallback resolves an absent layout its
# own way. Sparsifying on an assumption would put the two paths on
# different axes, so an undeclared layout stays dense.
logger.warning_once(
"RAINFUSION_ATTN staying dense: this layer does not declare qkv_layout, and rf_v2 "
"needs %s to locate the video segment along the sequence axis. Set qkv_layout=%r on "
"the Attention layer to enable sparsity.",
_INPUT_LAYOUT,
_INPUT_LAYOUT,
)
return None
if attn_metadata is None:
return None
layout = attn_metadata.video_layout
if layout is None:
logger.warning_once(
"RAINFUSION_ATTN staying dense: this attention role carries no video segment. The "
"model must publish AttentionMetadata.video_layout for the sequence to be sparsified."
)
return None
max_seqlen_q = attn_metadata.extra.get("max_seqlen_q")
if max_seqlen_q is None:
logger.warning_once(
"RAINFUSION_ATTN staying dense: attention metadata is missing max_seqlen_q, so the "
"video segment cannot be confirmed to be the tail of packed document 0."
)
return None
prefix_len = int(layout.prefix_len)
latent_shape = [int(dim) for dim in layout.latent_grid]
# rf_v2 splits the sequence as [prefix | t*h*w video rows]. Document 0 of
# the packed sequence holds those rows; anything past it is alignment
# padding that rf_v2 must not see.
video_len = math.prod(latent_shape)
used_len = prefix_len + video_len
if used_len != int(max_seqlen_q):
logger.warning_once(
"RAINFUSION_ATTN staying dense: prefix (%d) plus latent grid %s does not fill "
"packed document 0 (%d rows). rf_v2 requires the video segment to be its tail.",
prefix_len,
tuple(latent_shape),
int(max_seqlen_q),
)
return None
if video_len < _MIN_VIDEO_BLOCKS * _BLOCK_SIZE:
logger.warning_once(
"RAINFUSION_ATTN staying dense: %d video rows is under the %d-row "
"(%d block) threshold where sparse selection pays off.",
video_len,
_MIN_VIDEO_BLOCKS * _BLOCK_SIZE,
_MIN_VIDEO_BLOCKS,
)
return None
if video_len % _BLOCK_SIZE != 0:
# rf_v2 tiles the sequence into ceil((video + prefix) / 128) blocks but
# builds its block mask from the two segments pooled apart. The counts
# only agree when the video segment ends on a block boundary; otherwise
# a prefix block is forced on out of range, and the block straddling the
# seam holds real prefix rows that selection may drop. Padding the
# sequence to realign it is not an option because rf_v2 ignores
# attn_mask, so pad keys would take a share of every softmax denominator.
logger.warning_once(
"RAINFUSION_ATTN staying dense: latent grid %s gives %d video rows, which is not a "
"multiple of the %d-row kernel block. Choose a geometry whose latent_t * h * w is a "
"multiple of %d to enable sparsity.",
tuple(latent_shape),
video_len,
_BLOCK_SIZE,
_BLOCK_SIZE,
)
return None
logger.info_once(
"RAINFUSION_ATTN active: sparsity=%.2f, start_step=%d, exempt_layers=%d, "
"latent_grid=%s, prefix_rows=%d, video_rows=%d. Realized sparsity is lower than nominal "
"because prefix and first-frame blocks are always kept.",
rf.sparsity,
rf.start_step,
len(rf.skip_layers),
tuple(latent_shape),
prefix_len,
video_len,
)
return RainFusionPlan(
prefix_len=prefix_len,
used_len=used_len,
latent_shape=latent_shape,
)
def _forward_sparse_npu(
self,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
plan: RainFusionPlan,
) -> torch.Tensor:
try:
from mindiesd import sparse_attention
except ImportError:
raise ImportError(_MISSING_MINDIESD)
used = plan.used_len
q, k, v = (tensor[:, :used] for tensor in (query, key, value))
# Ulysses has already gathered the full sequence onto this rank and split
# the heads, so read the head count off the tensor rather than num_heads.
out = sparse_attention(
q,
k,
v,
scale=self.softmax_scale,
head_num=query.shape[-2],
input_layout=_INPUT_LAYOUT,
inner_precise=_INNER_PRECISE,
sparse_type="rf_v2",
txt_len=plan.prefix_len,
block_size=_BLOCK_SIZE,
latent_shape_q=plan.latent_shape,
latent_shape_k=plan.latent_shape,
sparsity=self.rainfusion.sparsity,
)
if used == query.shape[1]:
return out
padded = torch.zeros_like(query)
padded[:, :used] = out
return padded
@@ -65,6 +65,7 @@ class DiffusionAttentionBackendEnum(Enum, metaclass=_DiffusionBackendEnumMeta):
FLASH_ATTN_HUB = "vllm_omni.diffusion.attention.backends.flash_attn_hub.FlashAttentionHubBackend"
FLASH_ATTN_3_HUB = "vllm_omni.diffusion.attention.backends.flash_attn_hub.FlashAttention3HubBackend"
TRTLLM_ATTN = "vllm_omni.diffusion.attention.backends.trtllm_attn.TrtllmAttentionBackend"
RAINFUSION_ATTN = "vllm_omni.diffusion.attention.backends.rainfusion_attn.RainFusionAttentionBackend"
def get_path(self, include_classname: bool = True) -> str:
"""Get the class path for this backend (respects overrides).
+45 -1
View File
@@ -1461,6 +1461,33 @@ class AttnQuantSpec:
return self.dtype_qk is not None or self.dtype_vo is not None
# Backends that select key blocks instead of attending densely, and so accept
# a ``block_sparse`` spec. Each maps the same knobs onto its own kernel.
BLOCK_SPARSE_BACKENDS = frozenset({"RAINFUSION_ATTN"})
@dataclass
class BlockSparseSpec:
"""User-facing controls shared by block-sparse attention backends.
``sparsity`` is the nominal fraction of key blocks dropped per query block;
``start_step`` keeps the first N denoise steps dense and ``skip_layers`` (an
index selector such as "0-3,38") exempts individual DiT blocks. Those two are
the accuracy knobs to trade back quality at a fixed ``sparsity``.
"""
sparsity: float = 0.8
start_step: int = 0
skip_layers: str | list[int] | None = None
skip_layer_indices: set[int] | None = field(default=None, repr=False)
def __post_init__(self) -> None:
self.sparsity = _in_range(self.sparsity, "block_sparse.sparsity", 0.0, 1.0) or 0.0
if self.start_step < 0:
raise ValueError(f"block_sparse.start_step must be >= 0; got {self.start_step!r}.")
self.skip_layer_indices = parse_kv_cache_skip_selector(self.skip_layers)
@dataclass
class AttentionSpec:
"""Specifies a backend and its typed backend-specific config for one attention role."""
@@ -1468,6 +1495,7 @@ class AttentionSpec:
backend: str
skip_softmax: SkipSoftmaxSpec | None = None
quant: AttnQuantSpec | None = None
block_sparse: BlockSparseSpec | None = None
skip_calibration: dict | None = field(default=None, repr=False)
def __post_init__(self) -> None:
@@ -1475,6 +1503,7 @@ class AttentionSpec:
raise TypeError(f"Expected str for AttentionSpec.backend, got {type(self.backend)!r}")
self.skip_softmax = self._coerce(self.skip_softmax, SkipSoftmaxSpec, "skip_softmax")
self.quant = self._coerce(self.quant, AttnQuantSpec, "quant")
self.block_sparse = self._coerce(self.block_sparse, BlockSparseSpec, "block_sparse")
if self.skip_softmax is not None and self.backend.upper() != "TRTLLM_ATTN":
raise ValueError(
f"skip_softmax is only supported by the TRTLLM_ATTN backend, but backend={self.backend!r}. "
@@ -1485,6 +1514,15 @@ class AttentionSpec:
f"quant is only supported by the TRTLLM_ATTN and FLASHINFER_ATTN backends, but "
f"backend={self.backend!r}. Remove quant or set a supported backend."
)
if self.backend.upper() in BLOCK_SPARSE_BACKENDS:
# Selecting the backend is the opt-in; without an explicit block the
# defaults apply rather than silently running dense.
self.block_sparse = self.block_sparse or BlockSparseSpec()
elif self.block_sparse is not None:
raise ValueError(
f"block_sparse is only supported by the {sorted(BLOCK_SPARSE_BACKENDS)} backends, but "
f"backend={self.backend!r}. Remove block_sparse or set a supported backend."
)
@staticmethod
def _coerce(value: Any, cls: type, field_name: str) -> Any:
@@ -1517,6 +1555,12 @@ class AttentionSpec:
if q.flashinfer_backend is not None:
quant_kw["flashinfer_backend"] = q.flashinfer_backend
kw["quant"] = quant_kw
if self.block_sparse is not None:
bs = self.block_sparse
kw["sparsity"] = bs.sparsity
kw["start_step"] = bs.start_step
if bs.skip_layer_indices:
kw["skip_layers"] = sorted(bs.skip_layer_indices)
return kw or None
@@ -1586,7 +1630,7 @@ class AttentionConfig:
normalized[role] = node
return
spec_keys = {"backend", "skip_softmax", "quant"}
spec_keys = {"backend", "skip_softmax", "quant", "block_sparse"}
node_dict = dict(node)
node_keys = set(node_dict)
if node_keys & spec_keys:
@@ -393,6 +393,13 @@ class DiffusersPipelineLoader:
"DLO+AllGather active but model does not support mmap: loading weights via regular loader."
)
logger.debug("Loading weights on %s ...", load_device)
if offload_after_quant:
marked = self._request_offload_after_quant(model)
if marked:
logger.info(
"Online quantization will return each of %d layers to CPU as it is quantized",
marked,
)
if load_format == "diffusers":
cast(DiffusersAdapterPipeline, model).load_weights()
else:
@@ -406,6 +413,29 @@ class DiffusersPipelineLoader:
self._apply_skip_softmax_calibration(model)
return model.eval()
@staticmethod
def _request_offload_after_quant(model: nn.Module) -> int:
"""Ask online-quant layers to return to host memory once quantized.
The weights only visit the accelerator so the quant kernels can run on
them; ``load_model`` sends the model back to the host afterwards either
way. Without this the whole transformer accumulates on device until that
final move, which for MiniMax H3 is a ~43 GiB peak that no longer fits
beside a resident TP-sharded text encoder — even though layer-wise
offload means none of it is supposed to be resident at inference time.
Only quant methods that advertise ``supports_offload_after_quant`` are
asked, since the implementation has to know when a layer is finished.
Deferring materialization to the ``meta`` device does not imply that.
"""
marked = 0
for module in model.modules():
quant_method = getattr(module, "quant_method", None)
if getattr(quant_method, "supports_offload_after_quant", False):
quant_method.enable_offload_after_quant()
marked += 1
return marked
@staticmethod
def _has_online_quant(model: nn.Module) -> bool:
"""Whether any layer uses an online-quant method that defers weight
@@ -460,6 +490,13 @@ class DiffusersPipelineLoader:
if quant_method is None or not isinstance(quant_method, QuantizeMethodBase):
continue
# Layers finished during loading would only be staged onto the target
# device for a process call that immediately returns. That round trip
# is wasted work in general, and undoes the point of the offload for
# layers that already went back to the host.
if getattr(module, "_already_called_process_weights_after_loading", False):
continue
if has_online_quant:
# Online quant may leave straggler params on the ``meta`` device.
# Move only real (non-meta) params onto the target device for
@@ -14,6 +14,9 @@ from typing import Any
import torch
from vllm_omni.diffusion.attention.backends.abstract import VideoTokenLayout
from vllm_omni.diffusion.forward_context import set_forward_context_denoise_step_idx
from .scheduling_minimax_h3_euler_ancestral import (
minimax_h3_euler_eta0_step,
minimax_h3_rf_v_to_x0,
@@ -87,6 +90,13 @@ class MiniMaxH3DenoiseBranch:
"max_seqlen_q": text_len,
},
}
# Where the video segment sits in the packed sequence. Resolved to plain
# ints here so the attention layers never sync on it per step.
grid = packed["latent_grid"].tolist()
self.static_kwargs["video_token_layout"] = VideoTokenLayout(
prefix_len=int(packed["video_row_start"]),
latent_grid=(int(grid[0]), int(grid[1]), int(grid[2])),
)
def forward_kwargs(
self,
@@ -191,6 +201,9 @@ def minimax_h3_denoise_loop(
for step in range(num_steps):
step_cm = step_profiler(step) if step_profiler is not None else nullcontext()
with step_cm:
# Publish the step index so step-gated attention features (e.g. the
# dense warmup of RAINFUSION_ATTN) can see where we are.
set_forward_context_denoise_step_idx(step)
s_v, s_v_next = sigmas_video[step], sigmas_video[step + 1]
s_a, s_a_next = sigmas_audio[step], sigmas_audio[step + 1]
t_v, t_a = 1.0 - s_v, 1.0 - s_a
@@ -236,6 +249,7 @@ def minimax_h3_denoise_loop(
if on_step is not None:
on_step(step, video_rows, audio_rows)
set_forward_context_denoise_step_idx(None)
return video_rows, audio_rows
@@ -26,7 +26,7 @@ from vllm.model_executor.layers.linear import (
)
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata, VideoTokenLayout
from vllm_omni.diffusion.attention.layer import Attention
from vllm_omni.diffusion.cache.cachedit import CacheDiTAdapterConfig
from vllm_omni.diffusion.distributed.sp_plan import (
@@ -134,6 +134,7 @@ _FORWARD_SUPPORTED_KWARGS = frozenset(
"img_pos_for_infer_output_info",
"packed_seq_params",
"refiner_packed_seq_params",
"video_token_layout",
}
)
@@ -348,7 +349,11 @@ class MiniMaxH3Attention(nn.Module):
head_size=self.head_dim,
softmax_scale=self.softmax_scale,
causal=False,
# Packed rows reach the impl as [B, S, N, D].
qkv_layout="BSND",
skip_sequence_parallel=skip_sequence_parallel,
role="self",
prefix=prefix,
)
def _apply_rope(self, x: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:
@@ -374,6 +379,7 @@ class MiniMaxH3Attention(nn.Module):
cu_seqlens: torch.Tensor,
max_seqlen: int,
packed_total: int,
video_layout: VideoTokenLayout | None = None,
) -> torch.Tensor:
"""Run packed attention as a small eager island.
@@ -407,6 +413,7 @@ class MiniMaxH3Attention(nn.Module):
"max_seqlen_k": max_seqlen,
"valid_kv_length": used,
},
video_layout=video_layout,
)
return self.attention(
q.unsqueeze(0),
@@ -424,6 +431,7 @@ class MiniMaxH3Attention(nn.Module):
max_seqlen: int,
packed_total: int | None = None,
sp_seq_lens: list[int] | None = None,
video_layout: VideoTokenLayout | None = None,
) -> torch.Tensor:
"""x: [T, hidden] packed thd rows -> [T, hidden].
@@ -463,6 +471,7 @@ class MiniMaxH3Attention(nn.Module):
# backend receives the global sequence after all-to-all, so carry
# its Python length explicitly instead of inferring it from q.
packed_total=packed_total if packed_total is not None else q.shape[0],
video_layout=video_layout,
)
out = out.reshape(total, self.num_heads * self.head_dim)
out, _ = self.out_proj(out)
@@ -642,6 +651,8 @@ class MiniMaxH3DiTBlock(nn.Module):
super().__init__()
self.norm1 = _norm(arch.hidden_size, eps=arch.norm_eps)
self.norm2 = _norm(arch.hidden_size, eps=arch.norm_eps)
# The prefix also carries the block index that block-sparse attention
# backends match against their skip_layers selector.
self.attn = MiniMaxH3Attention(
arch,
quant_config,
@@ -672,6 +683,7 @@ class MiniMaxH3DiTBlock(nn.Module):
max_seqlen: int,
packed_total: int,
sp_seq_lens: list[int] | None = None,
video_layout: VideoTokenLayout | None = None,
) -> torch.Tensor:
"""x: [T, H]; t_emb: [M, t_dim]; combined_indices: [T]
(= inverse_indices * modality_num + token_tags.clamp(min=0)).
@@ -699,6 +711,7 @@ class MiniMaxH3DiTBlock(nn.Module):
max_seqlen=max_seqlen,
packed_total=packed_total,
sp_seq_lens=sp_seq_lens,
video_layout=video_layout,
)
x = _modulate_gate(residual, gate_msa, h, combined_indices, dtype=_BF16_DTYPE)
@@ -831,6 +844,10 @@ class MiniMaxH3DiTModel(nn.Module):
},
"sp_gather": SequenceParallelOutput(gather_dim=0, expected_dims=2),
}
# The checkpoint already stores qkv and the MLP gate/up as single tensors
# (see the reordering in load_weights), so there are no unfused names for
# quantization or LoRA to map onto. Address the fused layers directly, e.g.
# ignored_layers=["blocks.0.attn.qkv_proj"].
packed_modules_mapping = {}
def _validate_tp_config(self, *, arch: MiniMaxH3DiTArchConfig, tp_size: int) -> None:
@@ -1097,6 +1114,7 @@ class MiniMaxH3DiTModel(nn.Module):
refiner_psp = _required_kwarg(kwargs, "refiner_packed_seq_params")
refiner_cu = self._psp_field(refiner_psp, "refiner_packed_seq_params", "cu_seqlens_q").to(torch.int32)
refiner_max = int(self._psp_field(refiner_psp, "refiner_packed_seq_params", "max_seqlen_q"))
video_layout = kwargs.get("video_token_layout")
if x.dim() != 3 or x.shape[0] != 1:
raise ValueError(f"x must be [1, S, C], got {list(x.shape)}")
@@ -1145,6 +1163,7 @@ class MiniMaxH3DiTModel(nn.Module):
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
packed_total=seq_len,
video_layout=video_layout,
)
hidden = self.sp_gather(hidden)
@@ -236,6 +236,9 @@ def minimax_h3_packed_sequence(
"token_tags": token_tags,
"cu_seqlens": cu,
"document_id": doc,
# Extent of the video segment within the packed sequence.
"latent_grid": torch.tensor([latent_t, ph, pw], dtype=torch.int64),
"video_row_start": torch.tensor(video_sl.start, dtype=torch.int64),
}
@@ -554,6 +557,9 @@ def minimax_h3_packed_sequence_ref2va_blocks(
"token_tags": token_tags,
"cu_seqlens": cu,
"document_id": doc,
# Extent of the video segment within the packed sequence.
"latent_grid": torch.tensor([latent_t, ph, pw], dtype=torch.int64),
"video_row_start": torch.tensor(video_sl.start, dtype=torch.int64),
}
+8 -1
View File
@@ -51,7 +51,14 @@ def _load_remote_component(
class_reference,
component_path,
)
return component_cls.from_pretrained(component_path)
# Build on the host regardless of the ambient default device. Online
# quantization wraps pipeline construction in a `with torch.device(<accel>)`
# block for the DiT's quantized linears, and the checkpoint's own VAE code
# builds constants with ops that have no accelerator kernel (BigVGAN's
# anti-aliasing filters call torch.kaiser_window). Callers place the module
# explicitly right after this returns, so nothing depends on the context.
with torch.device("cpu"):
return component_cls.from_pretrained(component_path)
class _AudioVAEDeterminismContext(AbstractContextManager):