[Minimax-M3][Perf] Use triton_mrope for vision tower + int64 offset fix for triton_mrope (#58526)
Signed-off-by: Thien Tran <gau.nernst@yahoo.com.sg> Co-authored-by: Kimi <noreply@moonshot.cn> Co-authored-by: Isotr0py <Isotr0py@outlook.com>
This commit is contained in:
co-authored by
Kimi
Isotr0py
parent
ade1056ee5
commit
16070ed7e9
@@ -21,20 +21,16 @@ from vllm.model_executor.layers.linear import (
|
||||
RowParallelLinear,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization import QuantizationConfig
|
||||
from vllm.model_executor.layers.rotary_embedding.common import ApplyRotaryEmb
|
||||
from vllm.model_executor.layers.rotary_embedding.mrope import triton_mrope
|
||||
from vllm.model_executor.layers.rotary_embedding.mrope_vit_setup import (
|
||||
vit_mrope_setup,
|
||||
)
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
from vllm.model_executor.models.utils import maybe_prefix
|
||||
from vllm.model_executor.models.vision import (
|
||||
get_vit_attn_backend,
|
||||
is_vit_use_data_parallel,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
# ROCm caps a kernel-launch gridDim.y at 65536. The HIP flash-attn Triton
|
||||
# rotary kernel launches grid.y = cdiv(seqlen, BLOCK_M), so it fails with
|
||||
# hipErrorInvalidValue once cdiv(seqlen, BLOCK_M) > 65536. Used below to decide
|
||||
# when RoPE must be applied per video segment instead of in one launch.
|
||||
_HIP_MAX_GRID_DIM_Y = 65536
|
||||
|
||||
|
||||
class MiniMaxVLPatchEmbed(nn.Module):
|
||||
@@ -125,56 +121,13 @@ class MiniMaxVLAttention(nn.Module):
|
||||
head_size=self.head_dim,
|
||||
prefix=f"{prefix}.attn",
|
||||
)
|
||||
# ApplyRotaryEmb handles the internal cos/sin repeat and partial
|
||||
# rotation (ro_dim = half_rot_dim * 2 < head_dim for MiniMax).
|
||||
# enable_fp32_compute=True runs the rotation in fp32 (q/k upcast,
|
||||
# fp32 cos/sin), matching the reference ``_minimax_rope_applier``.
|
||||
self.apply_rotary_emb = ApplyRotaryEmb(
|
||||
enforce_enable=True, enable_fp32_compute=True
|
||||
)
|
||||
|
||||
def _apply_rotary_emb(
|
||||
self,
|
||||
qk_reshaped: torch.Tensor,
|
||||
rotary_cos: torch.Tensor,
|
||||
rotary_sin: torch.Tensor,
|
||||
seq_len: int,
|
||||
rotary_segment_lengths: list[int] | None,
|
||||
) -> torch.Tensor:
|
||||
# Default fast path (all NVIDIA inputs, and ROCm short clips/images):
|
||||
# a single rotary kernel launch. ``rotary_segment_lengths`` is only
|
||||
# populated on ROCm (see ``MiniMaxVLVisionTransformer.forward``), so
|
||||
# the per-segment path below is ROCm-only and never touches the
|
||||
# NVIDIA/CUDA code path.
|
||||
if not current_platform.is_rocm() or rotary_segment_lengths is None:
|
||||
return self.apply_rotary_emb(qk_reshaped, rotary_cos, rotary_sin)
|
||||
|
||||
# ROCm only: the HIP flash-attn Triton rotary kernel fails with
|
||||
# hipErrorInvalidValue once grid.y = cdiv(seqlen, BLOCK_M) exceeds
|
||||
# _HIP_MAX_GRID_DIM_Y (65536). BLOCK_M is 8 for rotary_dim <= 128
|
||||
# (MiniMax-M3 vision: rotary_dim=78), giving a hard limit of
|
||||
# 65536 * BLOCK_M tokens — measured exactly as 524288 OK / 524289 fail.
|
||||
# Only long videos cross it; since vision_segment_max_frames caps each
|
||||
# segment at a few frames (<< limit), applying RoPE per segment keeps
|
||||
# every sub-call in range. Splitting on segment boundaries is
|
||||
# mathematically exact because rotary_cos/sin are precomputed per token.
|
||||
# Images and short clips stay on the single-kernel fast path above.
|
||||
rotary_dim = rotary_cos.shape[-1] * 2
|
||||
block_m = 8 if rotary_dim <= 128 else 4
|
||||
hip_rotary_max_seqlen = _HIP_MAX_GRID_DIM_Y * block_m
|
||||
if seq_len <= hip_rotary_max_seqlen or len(rotary_segment_lengths) <= 1:
|
||||
return self.apply_rotary_emb(qk_reshaped, rotary_cos, rotary_sin)
|
||||
|
||||
qk_segments = qk_reshaped.split(rotary_segment_lengths, dim=1)
|
||||
cos_segments = rotary_cos.split(rotary_segment_lengths, dim=0)
|
||||
sin_segments = rotary_sin.split(rotary_segment_lengths, dim=0)
|
||||
return torch.cat(
|
||||
[
|
||||
self.apply_rotary_emb(qk_s, cos_s, sin_s)
|
||||
for qk_s, cos_s, sin_s in zip(qk_segments, cos_segments, sin_segments)
|
||||
],
|
||||
dim=1,
|
||||
)
|
||||
# Partial 3D RoPE geometry: rot_dim is split evenly across t/h/w
|
||||
# (same formula as MiniMaxVLVisionTransformer; rot_dim may be <
|
||||
# head_dim). mrope_section is in half-dim units for triton_mrope.
|
||||
rope_dims = 2 * (self.head_dim // 2)
|
||||
axis_dim = 2 * ((rope_dims // 3) // 2)
|
||||
self.rotary_dim = 3 * axis_dim
|
||||
self.mrope_section = [axis_dim // 2] * 3
|
||||
|
||||
def forward(
|
||||
self,
|
||||
@@ -183,33 +136,34 @@ class MiniMaxVLAttention(nn.Module):
|
||||
rotary_cos: torch.Tensor,
|
||||
rotary_sin: torch.Tensor,
|
||||
max_seqlen: torch.Tensor,
|
||||
rotary_segment_lengths: list[int] | None = None,
|
||||
sequence_lengths: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
# x: (N, 1, embed_dim) [seq=N, batch=1, chan=embed_dim]
|
||||
x_qkv, _ = self.qkv_proj(x) # (N, 1, 3 * heads_per_part * head_dim)
|
||||
seq_len, batch_size, _ = x_qkv.shape
|
||||
|
||||
# Rearrange to (b=1, N, 3, heads, head_dim) — same as Qwen2_5_VisionAttention
|
||||
qkv = rearrange(
|
||||
x_qkv,
|
||||
"s b (three head d) -> b s three head d",
|
||||
three=3,
|
||||
head=self.num_heads_per_partition,
|
||||
)
|
||||
qk, v = qkv[:, :, :2], qkv[:, :, 2] # (b,N,2,h,d) and (b,N,h,d)
|
||||
qkv = x_qkv.view(seq_len, 3, self.num_heads_per_partition, self.head_dim)
|
||||
v = qkv[:, 2].unsqueeze(0) # (b=1, N, heads, head_dim) strided view
|
||||
|
||||
# Stack q/k → (2*b, N, heads, head_dim) for joint RoPE application.
|
||||
# rotary_cos/sin: (N, half_rot_dim) — ApplyRotaryEmb expands internally
|
||||
# and rotates only the first 2*half_rot_dim dims, passing the rest through.
|
||||
qk_reshaped = rearrange(qk, "b s two h d -> (two b) s h d", two=2).contiguous()
|
||||
qk_rotated = self._apply_rotary_emb(
|
||||
qk_reshaped, rotary_cos, rotary_sin, seq_len, rotary_segment_lengths
|
||||
# In-place partial 3D RoPE on strided q/k views of the packed qkv
|
||||
# tensor: one kernel launch, no repack/upcast copies. fp32 cos/sin
|
||||
# make the kernel compute in fp32, matching the reference
|
||||
# ``_minimax_rope_applier`` precision.
|
||||
q = qkv[:, 0].reshape(seq_len, -1)
|
||||
k = qkv[:, 1].reshape(seq_len, -1)
|
||||
triton_mrope(
|
||||
q,
|
||||
k,
|
||||
rotary_cos,
|
||||
rotary_sin,
|
||||
self.mrope_section,
|
||||
self.head_dim,
|
||||
self.rotary_dim,
|
||||
mrope_interleaved=False,
|
||||
is_neox_style=True,
|
||||
)
|
||||
qk_rotated = qk_rotated.view(
|
||||
2, batch_size, seq_len, self.num_heads_per_partition, self.head_dim
|
||||
)
|
||||
q, k = qk_rotated.unbind(dim=0) # each (b=1, N, heads, head_dim)
|
||||
q = q.view(batch_size, seq_len, self.num_heads_per_partition, self.head_dim)
|
||||
k = k.view(batch_size, seq_len, self.num_heads_per_partition, self.head_dim)
|
||||
|
||||
# Flash attention → (b, N, heads, head_dim)
|
||||
context = self.attn(
|
||||
@@ -272,7 +226,6 @@ class MiniMaxVLEncoderLayer(nn.Module):
|
||||
rotary_cos: torch.Tensor,
|
||||
rotary_sin: torch.Tensor,
|
||||
max_seqlen: torch.Tensor,
|
||||
rotary_segment_lengths: list[int] | None = None,
|
||||
sequence_lengths: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
# x: (N, 1, hidden_size)
|
||||
@@ -282,7 +235,6 @@ class MiniMaxVLEncoderLayer(nn.Module):
|
||||
rotary_cos,
|
||||
rotary_sin,
|
||||
max_seqlen,
|
||||
rotary_segment_lengths,
|
||||
sequence_lengths,
|
||||
)
|
||||
residual = x
|
||||
@@ -324,7 +276,6 @@ class MiniMaxVLEncoder(nn.Module):
|
||||
rotary_cos: torch.Tensor,
|
||||
rotary_sin: torch.Tensor,
|
||||
max_seqlen: torch.Tensor,
|
||||
rotary_segment_lengths: list[int] | None = None,
|
||||
sequence_lengths: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
for layer in self.layers:
|
||||
@@ -334,7 +285,6 @@ class MiniMaxVLEncoder(nn.Module):
|
||||
rotary_cos,
|
||||
rotary_sin,
|
||||
max_seqlen,
|
||||
rotary_segment_lengths,
|
||||
sequence_lengths,
|
||||
)
|
||||
return x
|
||||
@@ -427,82 +377,6 @@ class MiniMaxVLVisionTransformer(nn.Module):
|
||||
# out_hidden_size needed by run_dp_sharded_mrope_vision_model
|
||||
self.out_hidden_size = embed_dim
|
||||
|
||||
# ── RoPE helpers ─────────────────────────────────────────────────────
|
||||
|
||||
def _get_3d_rope_embed(
|
||||
self, grid_t: int, grid_h: int, grid_w: int, spatial_merge_size: int
|
||||
) -> torch.Tensor:
|
||||
"""Compute 3D RoPE frequencies for a single (T, H, W) grid.
|
||||
|
||||
Returns (T*H*W, half_rot_dim) on the same device as inv_freq buffers.
|
||||
Mirrors the reference ``_get_3d_rope_embed`` exactly.
|
||||
"""
|
||||
tokens_per_frame = grid_h * grid_w
|
||||
|
||||
tpos_ids = (
|
||||
torch.arange(grid_t, device=self.inv_freq_t.device)
|
||||
.unsqueeze(1)
|
||||
.expand(-1, tokens_per_frame)
|
||||
.flatten()
|
||||
)
|
||||
|
||||
hpos_ids = (
|
||||
torch.arange(grid_h, device=self.inv_freq_h.device)
|
||||
.unsqueeze(1)
|
||||
.expand(-1, grid_w)
|
||||
.reshape(
|
||||
grid_h // spatial_merge_size,
|
||||
spatial_merge_size,
|
||||
grid_w // spatial_merge_size,
|
||||
spatial_merge_size,
|
||||
)
|
||||
.permute(0, 2, 1, 3)
|
||||
.unsqueeze(0)
|
||||
.expand(grid_t, -1, -1, -1, -1)
|
||||
.flatten()
|
||||
)
|
||||
wpos_ids = (
|
||||
torch.arange(grid_w, device=self.inv_freq_w.device)
|
||||
.unsqueeze(0)
|
||||
.expand(grid_h, -1)
|
||||
.reshape(
|
||||
grid_h // spatial_merge_size,
|
||||
spatial_merge_size,
|
||||
grid_w // spatial_merge_size,
|
||||
spatial_merge_size,
|
||||
)
|
||||
.permute(0, 2, 1, 3)
|
||||
.unsqueeze(0)
|
||||
.expand(grid_t, -1, -1, -1, -1)
|
||||
.flatten()
|
||||
)
|
||||
|
||||
max_t = max(grid_t, 1)
|
||||
max_hw = max(grid_h, grid_w)
|
||||
|
||||
seq_t = torch.arange(
|
||||
max_t, device=self.inv_freq_t.device, dtype=self.inv_freq_t.dtype
|
||||
)
|
||||
seq_hw = torch.arange(
|
||||
max_hw, device=self.inv_freq_h.device, dtype=self.inv_freq_h.dtype
|
||||
)
|
||||
|
||||
freqs_t = torch.outer(seq_t, self.inv_freq_t) # (max_t, t_dim/2)
|
||||
freqs_h = torch.outer(seq_hw, self.inv_freq_h) # (max_hw, h_dim/2)
|
||||
freqs_w = torch.outer(seq_hw, self.inv_freq_w) # (max_hw, w_dim/2)
|
||||
|
||||
return torch.cat(
|
||||
[freqs_t[tpos_ids], freqs_h[hpos_ids], freqs_w[wpos_ids]], dim=-1
|
||||
) # (T*H*W, half_rot_dim)
|
||||
|
||||
def _get_rope_embed_3d(
|
||||
self, grid_thw: list[list[int]], spatial_merge_size: int
|
||||
) -> torch.Tensor:
|
||||
embeds = [
|
||||
self._get_3d_rope_embed(t, h, w, spatial_merge_size) for t, h, w in grid_thw
|
||||
]
|
||||
return torch.cat(embeds, dim=0) # (total_N, half_rot_dim)
|
||||
|
||||
# ── Frame-limit helper (mirrors the reference) ───────────────────────
|
||||
|
||||
def _apply_max_frames_limit(self, grid_thw: list[list[int]]) -> list[list[int]]:
|
||||
@@ -557,21 +431,19 @@ class MiniMaxVLVisionTransformer(nn.Module):
|
||||
hidden.device,
|
||||
)
|
||||
|
||||
# 3D RoPE: (total_N, half_rot_dim); ApplyRotaryEmb expands internally
|
||||
freqs = self._get_rope_embed_3d(limited, self.spatial_merge_size)
|
||||
freqs = freqs.to(device=hidden.device)
|
||||
# Keep cos/sin in fp32; ApplyRotaryEmb(enable_fp32_compute=True) runs the
|
||||
# rotation in fp32 to match the reference precision.
|
||||
rotary_cos, rotary_sin = freqs.cos(), freqs.sin()
|
||||
# 3D RoPE cos/sin: (3, total_N, half_rot_dim) fp32 t/h/w planes for
|
||||
# triton_mrope from one fused setup kernel. Kept fp32 so the kernel
|
||||
# computes the rotation in fp32, matching the reference.
|
||||
rotary_cos, rotary_sin = vit_mrope_setup(
|
||||
self.inv_freq_t,
|
||||
self.inv_freq_h,
|
||||
self.inv_freq_w,
|
||||
limited,
|
||||
self.spatial_merge_size,
|
||||
)
|
||||
|
||||
# Encoder expects (N, 1, hidden_size) — add batch dim
|
||||
hidden = hidden.unsqueeze(1)
|
||||
# On ROCm, the flash_attn Triton rotary kernel can fail with
|
||||
# hipErrorInvalidValue when seqlen is very large, e.g. 192k video
|
||||
# tokens; pass per-segment lengths so RoPE can be applied in chunks.
|
||||
# On other platforms leave it None -> single-kernel fast path, so the
|
||||
# NVIDIA/CUDA code path is unchanged.
|
||||
rotary_segment_lengths = lens if current_platform.is_rocm() else None
|
||||
|
||||
hidden = self.encoder(
|
||||
hidden,
|
||||
@@ -579,7 +451,6 @@ class MiniMaxVLVisionTransformer(nn.Module):
|
||||
rotary_cos,
|
||||
rotary_sin,
|
||||
max_seqlen,
|
||||
rotary_segment_lengths,
|
||||
sequence_lengths=sequence_lengths,
|
||||
)
|
||||
hidden = hidden.squeeze(1) # back to (total_N, hidden_size)
|
||||
|
||||
Reference in New Issue
Block a user