[Attention] [P1] Keep H3 VSA policy in the model and share sparse primitives (#7535)
Signed-off-by: lishunyang12 <lishunyang12@users.noreply.github.com> Co-authored-by: lishunyang12 <lishunyang12@users.noreply.github.com>
This commit is contained in:
1 parent
99ff4f3070
commit
507cb1d834
19 files changed
+1117
-473
No files matched your search
@@ -0,0 +1,115 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Shared pooling, routing and provider calls for explicit block-sparse attention."""
|
||||
|
||||
import os
|
||||
|
||||
import torch
|
||||
from vllm.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
if not hasattr(torch.ops.vllm_omni, "fastvideo_block_sparse_attn_bshd"):
|
||||
|
||||
@torch.library.custom_op("vllm_omni::fastvideo_block_sparse_attn_bshd", mutates_args=())
|
||||
def fastvideo_block_sparse_attn_bshd(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
block_map: torch.Tensor,
|
||||
variable_block_sizes: torch.Tensor,
|
||||
logical_blocks: int,
|
||||
) -> torch.Tensor:
|
||||
"""Run explicit block-sparse attention on BSHD tensors in 64-row blocks.
|
||||
|
||||
Inputs and the block map may include transport-only blocks after
|
||||
``logical_blocks``. The Triton provider sees only logical blocks and
|
||||
the wrapper restores the original row count. Native provider selection
|
||||
and its supported-input checks remain owned by FastVideo.
|
||||
"""
|
||||
q = query.transpose(1, 2).contiguous()
|
||||
k = key.transpose(1, 2).contiguous()
|
||||
v = value.transpose(1, 2).contiguous()
|
||||
|
||||
# Prefer the explicitly selected native provider when it supports
|
||||
# these tensors; retain the existing Triton provider otherwise.
|
||||
if os.environ.get("FASTVIDEO_VSA_SM100A", "0") == "1":
|
||||
try:
|
||||
from fastvideo_kernel import block_sparse_attn_sm100a
|
||||
from fastvideo_kernel.triton_kernels.index import map_to_index
|
||||
|
||||
if block_sparse_attn_sm100a.is_supported(q, variable_block_sizes):
|
||||
q2k_idx, q2k_num = map_to_index(block_map)
|
||||
out, _ = block_sparse_attn_sm100a.block_sparse_attn_sm100a(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
q2k_idx.to(torch.int32).contiguous(),
|
||||
q2k_num.to(torch.int32).contiguous(),
|
||||
variable_block_sizes.to(torch.int32).contiguous(),
|
||||
need_lse=False,
|
||||
)
|
||||
return out.transpose(1, 2).contiguous()
|
||||
except torch.AcceleratorError:
|
||||
# A device fault can poison the context; do not launch another kernel.
|
||||
raise
|
||||
except (ImportError, RuntimeError) as exc:
|
||||
logger.warning_once(
|
||||
"FASTVIDEO_VSA_SM100A=1 requested but the native Blackwell forward is "
|
||||
"unavailable (%s); using the Triton block-sparse route instead.",
|
||||
exc,
|
||||
)
|
||||
|
||||
from fastvideo_kernel.block_sparse_attn import block_sparse_attn
|
||||
|
||||
logical_len = logical_blocks * 64
|
||||
out, _ = block_sparse_attn(
|
||||
q[:, :, :logical_len].contiguous(),
|
||||
k[:, :, :logical_len].contiguous(),
|
||||
v[:, :, :logical_len].contiguous(),
|
||||
block_map[..., :logical_blocks, :logical_blocks].contiguous(),
|
||||
variable_block_sizes[:logical_blocks].to(torch.int32).contiguous(),
|
||||
)
|
||||
out = out.transpose(1, 2).contiguous()
|
||||
if out.shape[1] != query.shape[1]:
|
||||
out = torch.nn.functional.pad(out, (0, 0, 0, 0, 0, query.shape[1] - out.shape[1]))
|
||||
return out
|
||||
|
||||
@fastvideo_block_sparse_attn_bshd.register_fake
|
||||
def _(query, key, value, block_map, variable_block_sizes, logical_blocks):
|
||||
del key, value, block_map, variable_block_sizes, logical_blocks
|
||||
return torch.empty_like(query)
|
||||
|
||||
|
||||
fastvideo_block_sparse_attn_bshd = torch.ops.vllm_omni.fastvideo_block_sparse_attn_bshd
|
||||
|
||||
|
||||
def mean_pool_tiles(x: torch.Tensor, sizes: torch.Tensor, block_size: int) -> torch.Tensor:
|
||||
"""Mean-pool zero-padded BSHD tiles with FP32 accumulation.
|
||||
|
||||
``sizes`` gives the number of valid rows in each tile.
|
||||
"""
|
||||
batch, seq_len, heads, dim = x.shape
|
||||
blocks = seq_len // block_size
|
||||
pooled = x.view(batch, blocks, block_size, heads, dim).sum(dim=2, dtype=torch.float32)
|
||||
pooled = pooled / sizes.view(1, -1, 1, 1).clamp_min(1)
|
||||
return pooled.permute(0, 2, 1, 3)
|
||||
|
||||
|
||||
def build_prefix_dense_block_map(
|
||||
scores: torch.Tensor,
|
||||
num_prefix_blocks: int,
|
||||
num_sparse_blocks: int,
|
||||
topk: int,
|
||||
) -> torch.Tensor:
|
||||
"""Keep prefix queries/keys dense and select top-k non-prefix keys per row."""
|
||||
keep_sparse = min(topk, num_sparse_blocks)
|
||||
if keep_sparse == num_sparse_blocks:
|
||||
return torch.ones_like(scores, dtype=torch.bool)
|
||||
block_map = torch.zeros_like(scores, dtype=torch.bool)
|
||||
indices = scores[..., num_prefix_blocks:].topk(keep_sparse, dim=-1).indices + num_prefix_blocks
|
||||
block_map.scatter_(-1, indices, True)
|
||||
block_map[..., :num_prefix_blocks] = True
|
||||
block_map[:, :, :num_prefix_blocks, :] = True
|
||||
return block_map
|
||||
@@ -1,338 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Fused MiniMax H3 modulation with FP32 accumulation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
# Ascend CANN limits the launch coreDim to uint16.
|
||||
_MAX_1D_GRID_SIZE = 65535
|
||||
|
||||
|
||||
def _iter_row_chunks(rows: int):
|
||||
for row_offset in range(0, rows, _MAX_1D_GRID_SIZE):
|
||||
yield row_offset, min(rows - row_offset, _MAX_1D_GRID_SIZE)
|
||||
|
||||
|
||||
def _launch_row_chunks(kernel, rows: int, device_type: str, *args, **kwargs) -> None:
|
||||
if device_type != "npu":
|
||||
kernel[(rows,)](*args, 0, **kwargs)
|
||||
return
|
||||
for row_offset, chunk_rows in _iter_row_chunks(rows):
|
||||
kernel[(chunk_rows,)](*args, row_offset, **kwargs)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _indexed_scale_shift_kernel(
|
||||
output_ptr,
|
||||
x_ptr,
|
||||
shift_ptr,
|
||||
scale_ptr,
|
||||
indices_ptr,
|
||||
hidden_size,
|
||||
stride_x_row,
|
||||
stride_shift_row,
|
||||
stride_scale_row,
|
||||
stride_indices,
|
||||
row_offset,
|
||||
block_n: tl.constexpr,
|
||||
):
|
||||
row = tl.program_id(0) + row_offset
|
||||
columns = tl.arange(0, block_n)
|
||||
mask = columns < hidden_size
|
||||
index = tl.load(indices_ptr + row * stride_indices)
|
||||
|
||||
x = tl.load(x_ptr + row * stride_x_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
shift = tl.load(shift_ptr + index * stride_shift_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
scale = tl.load(scale_ptr + index * stride_scale_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
|
||||
tl.store(
|
||||
output_ptr + row * stride_x_row + columns,
|
||||
x * (1.0 + scale) + shift,
|
||||
mask=mask,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _indexed_gate_kernel(
|
||||
output_ptr,
|
||||
x_ptr,
|
||||
gate_ptr,
|
||||
other_ptr,
|
||||
indices_ptr,
|
||||
hidden_size,
|
||||
stride_output_row,
|
||||
stride_x_row,
|
||||
stride_gate_row,
|
||||
stride_other_row,
|
||||
stride_indices,
|
||||
row_offset,
|
||||
block_n: tl.constexpr,
|
||||
):
|
||||
row = tl.program_id(0) + row_offset
|
||||
columns = tl.arange(0, block_n)
|
||||
mask = columns < hidden_size
|
||||
index = tl.load(indices_ptr + row * stride_indices)
|
||||
|
||||
x = tl.load(x_ptr + row * stride_x_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
gate = tl.load(gate_ptr + index * stride_gate_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
other = tl.load(other_ptr + row * stride_other_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
|
||||
tl.store(
|
||||
output_ptr + row * stride_output_row + columns,
|
||||
x + gate * other,
|
||||
mask=mask,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _rms_norm_indexed_scale_shift_kernel(
|
||||
output_ptr,
|
||||
x_ptr,
|
||||
weight_ptr,
|
||||
shift_ptr,
|
||||
scale_ptr,
|
||||
indices_ptr,
|
||||
hidden_size: tl.constexpr,
|
||||
eps: tl.constexpr,
|
||||
stride_x_row,
|
||||
stride_shift_row,
|
||||
stride_scale_row,
|
||||
stride_indices,
|
||||
row_offset,
|
||||
block_n: tl.constexpr,
|
||||
):
|
||||
row = tl.program_id(0) + row_offset
|
||||
columns = tl.arange(0, block_n)
|
||||
mask = columns < hidden_size
|
||||
index = tl.load(indices_ptr + row * stride_indices)
|
||||
|
||||
x = tl.load(x_ptr + row * stride_x_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
weight = tl.load(weight_ptr + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
variance = tl.sum(x * x, axis=0) / hidden_size
|
||||
normalized = x * tl.rsqrt(variance + eps) * weight
|
||||
|
||||
shift = tl.load(shift_ptr + index * stride_shift_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
scale = tl.load(scale_ptr + index * stride_scale_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
tl.store(
|
||||
output_ptr + row * hidden_size + columns,
|
||||
normalized * (1.0 + scale) + shift,
|
||||
mask=mask,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _indexed_gate_rms_norm_scale_shift_kernel(
|
||||
residual_out_ptr,
|
||||
modulated_out_ptr,
|
||||
residual_ptr,
|
||||
gate_ptr,
|
||||
branch_ptr,
|
||||
weight_ptr,
|
||||
shift_ptr,
|
||||
scale_ptr,
|
||||
indices_ptr,
|
||||
hidden_size: tl.constexpr,
|
||||
eps: tl.constexpr,
|
||||
stride_residual_row,
|
||||
stride_gate_row,
|
||||
stride_branch_row,
|
||||
stride_shift_row,
|
||||
stride_scale_row,
|
||||
stride_indices,
|
||||
row_offset,
|
||||
block_n: tl.constexpr,
|
||||
):
|
||||
row = tl.program_id(0) + row_offset
|
||||
columns = tl.arange(0, block_n)
|
||||
mask = columns < hidden_size
|
||||
index = tl.load(indices_ptr + row * stride_indices)
|
||||
|
||||
residual = tl.load(residual_ptr + row * stride_residual_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
gate = tl.load(gate_ptr + index * stride_gate_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
branch = tl.load(branch_ptr + row * stride_branch_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
# Match the BF16 residual value consumed by the unfused RMSNorm path.
|
||||
updated = (residual + gate * branch).to(tl.bfloat16).to(tl.float32)
|
||||
tl.store(residual_out_ptr + row * hidden_size + columns, updated, mask=mask)
|
||||
|
||||
weight = tl.load(weight_ptr + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
variance = tl.sum(updated * updated, axis=0) / hidden_size
|
||||
normalized = updated * tl.rsqrt(variance + eps) * weight
|
||||
shift = tl.load(shift_ptr + index * stride_shift_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
scale = tl.load(scale_ptr + index * stride_scale_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
tl.store(
|
||||
modulated_out_ptr + row * hidden_size + columns,
|
||||
normalized * (1.0 + scale) + shift,
|
||||
mask=mask,
|
||||
)
|
||||
|
||||
|
||||
def indexed_scale_shift_(
|
||||
x: torch.Tensor,
|
||||
shift: torch.Tensor,
|
||||
scale: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Apply indexed scale/shift in-place to a disposable contiguous input."""
|
||||
if x.is_cpu:
|
||||
x.copy_((x * (1.0 + scale.index_select(0, indices)) + shift.index_select(0, indices)).to(x.dtype))
|
||||
return x
|
||||
rows, hidden_size = x.shape
|
||||
if rows == 0:
|
||||
return x
|
||||
_launch_row_chunks(
|
||||
_indexed_scale_shift_kernel,
|
||||
rows,
|
||||
x.device.type,
|
||||
x,
|
||||
x,
|
||||
shift,
|
||||
scale,
|
||||
indices,
|
||||
hidden_size,
|
||||
x.stride(0),
|
||||
shift.stride(0),
|
||||
scale.stride(0),
|
||||
indices.stride(0),
|
||||
block_n=triton.next_power_of_2(hidden_size),
|
||||
num_warps=8,
|
||||
)
|
||||
return x
|
||||
|
||||
|
||||
def indexed_gate(
|
||||
x: torch.Tensor,
|
||||
gate: torch.Tensor,
|
||||
other: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Return ``x + gate[indices] * other`` without indexed temporaries."""
|
||||
if x.is_cpu:
|
||||
return (x + gate.index_select(0, indices) * other).to(x.dtype)
|
||||
output = torch.empty_like(x)
|
||||
rows, hidden_size = x.shape
|
||||
if rows == 0:
|
||||
return output
|
||||
_launch_row_chunks(
|
||||
_indexed_gate_kernel,
|
||||
rows,
|
||||
x.device.type,
|
||||
output,
|
||||
x,
|
||||
gate,
|
||||
other,
|
||||
indices,
|
||||
hidden_size,
|
||||
output.stride(0),
|
||||
x.stride(0),
|
||||
gate.stride(0),
|
||||
other.stride(0),
|
||||
indices.stride(0),
|
||||
block_n=triton.next_power_of_2(hidden_size),
|
||||
num_warps=8,
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
def rms_norm_indexed_scale_shift(
|
||||
x: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
shift: torch.Tensor,
|
||||
scale: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
eps: float,
|
||||
) -> torch.Tensor:
|
||||
"""Fuse H3 RMSNorm with its indexed AdaLN affine transform."""
|
||||
if x.is_cpu:
|
||||
input_dtype = x.dtype
|
||||
normalized = x.float()
|
||||
variance = normalized.pow(2).mean(-1, keepdim=True)
|
||||
normalized = normalized * torch.rsqrt(variance + eps)
|
||||
normalized = (weight.float() * normalized).to(input_dtype)
|
||||
return (normalized * (1.0 + scale.index_select(0, indices)) + shift.index_select(0, indices)).to(input_dtype)
|
||||
output = torch.empty_like(x)
|
||||
rows, hidden_size = x.shape
|
||||
if rows:
|
||||
_launch_row_chunks(
|
||||
_rms_norm_indexed_scale_shift_kernel,
|
||||
rows,
|
||||
x.device.type,
|
||||
output,
|
||||
x,
|
||||
weight,
|
||||
shift,
|
||||
scale,
|
||||
indices,
|
||||
hidden_size,
|
||||
eps,
|
||||
x.stride(0),
|
||||
shift.stride(0),
|
||||
scale.stride(0),
|
||||
indices.stride(0),
|
||||
block_n=triton.next_power_of_2(hidden_size),
|
||||
num_warps=8,
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
def indexed_gate_rms_norm_scale_shift(
|
||||
residual: torch.Tensor,
|
||||
gate: torch.Tensor,
|
||||
branch: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
shift: torch.Tensor,
|
||||
scale: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
eps: float,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Fuse gated residual, the following RMSNorm, and AdaLN affine."""
|
||||
if residual.is_cpu:
|
||||
input_dtype = residual.dtype
|
||||
residual_out = (residual + gate.index_select(0, indices) * branch).to(input_dtype)
|
||||
normalized = residual_out.float()
|
||||
variance = normalized.pow(2).mean(-1, keepdim=True)
|
||||
normalized = normalized * torch.rsqrt(variance + eps)
|
||||
normalized = (weight.float() * normalized).to(input_dtype)
|
||||
modulated_out = (normalized * (1.0 + scale.index_select(0, indices)) + shift.index_select(0, indices)).to(
|
||||
input_dtype
|
||||
)
|
||||
return residual_out, modulated_out
|
||||
residual_out = torch.empty_like(residual)
|
||||
modulated_out = torch.empty_like(residual)
|
||||
rows, hidden_size = residual.shape
|
||||
if rows:
|
||||
_launch_row_chunks(
|
||||
_indexed_gate_rms_norm_scale_shift_kernel,
|
||||
rows,
|
||||
residual.device.type,
|
||||
residual_out,
|
||||
modulated_out,
|
||||
residual,
|
||||
gate,
|
||||
branch,
|
||||
weight,
|
||||
shift,
|
||||
scale,
|
||||
indices,
|
||||
hidden_size,
|
||||
eps,
|
||||
residual.stride(0),
|
||||
gate.stride(0),
|
||||
branch.stride(0),
|
||||
shift.stride(0),
|
||||
scale.stride(0),
|
||||
indices.stride(0),
|
||||
block_n=triton.next_power_of_2(hidden_size),
|
||||
num_warps=8,
|
||||
)
|
||||
return residual_out, modulated_out
|
||||
|
||||
|
||||
__all__ = [
|
||||
"indexed_gate",
|
||||
"indexed_gate_rms_norm_scale_shift",
|
||||
"indexed_scale_shift_",
|
||||
"rms_norm_indexed_scale_shift",
|
||||
]
|
||||
Reference in new issue
Block a user